matplotlibcpp.h 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918
  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_xlim = safe_import(pymod, "xlim");
  208. s_python_function_ylim = safe_import(pymod, "ylim");
  209. s_python_function_title = safe_import(pymod, "title");
  210. s_python_function_axis = safe_import(pymod, "axis");
  211. s_python_function_axhline = safe_import(pymod, "axhline");
  212. s_python_function_axvline = safe_import(pymod, "axvline");
  213. s_python_function_axvspan = safe_import(pymod, "axvspan");
  214. s_python_function_xlabel = safe_import(pymod, "xlabel");
  215. s_python_function_ylabel = safe_import(pymod, "ylabel");
  216. s_python_function_gca = safe_import(pymod, "gca");
  217. s_python_function_xticks = safe_import(pymod, "xticks");
  218. s_python_function_yticks = safe_import(pymod, "yticks");
  219. s_python_function_margins = safe_import(pymod, "margins");
  220. s_python_function_tick_params = safe_import(pymod, "tick_params");
  221. s_python_function_grid = safe_import(pymod, "grid");
  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. template <typename Numeric>
  488. void contour(const std::vector<::std::vector<Numeric>> &x,
  489. const std::vector<::std::vector<Numeric>> &y,
  490. const std::vector<::std::vector<Numeric>> &z,
  491. const std::map<std::string, std::string> &keywords = {})
  492. {
  493. detail::_interpreter::get();
  494. // using numpy arrays
  495. PyObject *xarray = detail::get_2darray(x);
  496. PyObject *yarray = detail::get_2darray(y);
  497. PyObject *zarray = detail::get_2darray(z);
  498. // construct positional args
  499. PyObject *args = PyTuple_New(3);
  500. PyTuple_SetItem(args, 0, xarray);
  501. PyTuple_SetItem(args, 1, yarray);
  502. PyTuple_SetItem(args, 2, zarray);
  503. // Build up the kw args.
  504. PyObject *kwargs = PyDict_New();
  505. PyObject *python_colormap_coolwarm = PyObject_GetAttrString(
  506. detail::_interpreter::get().s_python_colormap, "coolwarm");
  507. PyDict_SetItemString(kwargs, "cmap", python_colormap_coolwarm);
  508. for (std::map<std::string, std::string>::const_iterator it = keywords.begin();
  509. it != keywords.end(); ++it) {
  510. PyDict_SetItemString(kwargs, it->first.c_str(),
  511. PyString_FromString(it->second.c_str()));
  512. }
  513. PyObject *res = PyObject_Call(detail::_interpreter::get().s_python_function_contour, args, kwargs);
  514. if (!res)
  515. throw std::runtime_error("failed contour");
  516. Py_DECREF(args);
  517. Py_DECREF(kwargs);
  518. if (res)
  519. Py_DECREF(res);
  520. }
  521. #endif // WITHOUT_NUMPY
  522. template <typename Numeric>
  523. void plot3(const std::vector<Numeric> &x,
  524. const std::vector<Numeric> &y,
  525. const std::vector<Numeric> &z,
  526. const std::map<std::string, std::string> &keywords =
  527. std::map<std::string, std::string>(),
  528. const long fig_number=0)
  529. {
  530. detail::_interpreter::get();
  531. // Same as with plot_surface: We lazily load the modules here the first time
  532. // this function is called because I'm not sure that we can assume "matplotlib
  533. // installed" implies "mpl_toolkits installed" on all platforms, and we don't
  534. // want to require it for people who don't need 3d plots.
  535. static PyObject *mpl_toolkitsmod = nullptr, *axis3dmod = nullptr;
  536. if (!mpl_toolkitsmod) {
  537. detail::_interpreter::get();
  538. PyObject* mpl_toolkits = PyString_FromString("mpl_toolkits");
  539. PyObject* axis3d = PyString_FromString("mpl_toolkits.mplot3d");
  540. if (!mpl_toolkits || !axis3d) { throw std::runtime_error("couldnt create string"); }
  541. mpl_toolkitsmod = PyImport_Import(mpl_toolkits);
  542. Py_DECREF(mpl_toolkits);
  543. if (!mpl_toolkitsmod) { throw std::runtime_error("Error loading module mpl_toolkits!"); }
  544. axis3dmod = PyImport_Import(axis3d);
  545. Py_DECREF(axis3d);
  546. if (!axis3dmod) { throw std::runtime_error("Error loading module mpl_toolkits.mplot3d!"); }
  547. }
  548. assert(x.size() == y.size());
  549. assert(y.size() == z.size());
  550. PyObject *xarray = detail::get_array(x);
  551. PyObject *yarray = detail::get_array(y);
  552. PyObject *zarray = detail::get_array(z);
  553. // construct positional args
  554. PyObject *args = PyTuple_New(3);
  555. PyTuple_SetItem(args, 0, xarray);
  556. PyTuple_SetItem(args, 1, yarray);
  557. PyTuple_SetItem(args, 2, zarray);
  558. // Build up the kw args.
  559. PyObject *kwargs = PyDict_New();
  560. for (std::map<std::string, std::string>::const_iterator it = keywords.begin();
  561. it != keywords.end(); ++it) {
  562. PyDict_SetItemString(kwargs, it->first.c_str(),
  563. PyString_FromString(it->second.c_str()));
  564. }
  565. PyObject *fig_args = PyTuple_New(1);
  566. PyObject* fig = nullptr;
  567. PyTuple_SetItem(fig_args, 0, PyLong_FromLong(fig_number));
  568. PyObject *fig_exists =
  569. PyObject_CallObject(detail::_interpreter::get().s_python_function_fignum_exists, fig_args);
  570. if (!PyObject_IsTrue(fig_exists)) {
  571. fig = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure,
  572. detail::_interpreter::get().s_python_empty_tuple);
  573. } else {
  574. fig = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure,
  575. fig_args);
  576. }
  577. if (!fig) throw std::runtime_error("Call to figure() failed.");
  578. PyObject *gca_kwargs = PyDict_New();
  579. PyDict_SetItemString(gca_kwargs, "projection", PyString_FromString("3d"));
  580. PyObject *gca = PyObject_GetAttrString(fig, "gca");
  581. if (!gca) throw std::runtime_error("No gca");
  582. Py_INCREF(gca);
  583. PyObject *axis = PyObject_Call(
  584. gca, detail::_interpreter::get().s_python_empty_tuple, gca_kwargs);
  585. if (!axis) throw std::runtime_error("No axis");
  586. Py_INCREF(axis);
  587. Py_DECREF(gca);
  588. Py_DECREF(gca_kwargs);
  589. PyObject *plot3 = PyObject_GetAttrString(axis, "plot");
  590. if (!plot3) throw std::runtime_error("No 3D line plot");
  591. Py_INCREF(plot3);
  592. PyObject *res = PyObject_Call(plot3, args, kwargs);
  593. if (!res) throw std::runtime_error("Failed 3D line plot");
  594. Py_DECREF(plot3);
  595. Py_DECREF(axis);
  596. Py_DECREF(args);
  597. Py_DECREF(kwargs);
  598. if (res) Py_DECREF(res);
  599. }
  600. template<typename Numeric>
  601. bool stem(const std::vector<Numeric> &x, const std::vector<Numeric> &y, const std::map<std::string, std::string>& keywords)
  602. {
  603. assert(x.size() == y.size());
  604. detail::_interpreter::get();
  605. // using numpy arrays
  606. PyObject* xarray = detail::get_array(x);
  607. PyObject* yarray = detail::get_array(y);
  608. // construct positional args
  609. PyObject* args = PyTuple_New(2);
  610. PyTuple_SetItem(args, 0, xarray);
  611. PyTuple_SetItem(args, 1, yarray);
  612. // construct keyword args
  613. PyObject* kwargs = PyDict_New();
  614. for (std::map<std::string, std::string>::const_iterator it =
  615. keywords.begin(); it != keywords.end(); ++it) {
  616. PyDict_SetItemString(kwargs, it->first.c_str(),
  617. PyString_FromString(it->second.c_str()));
  618. }
  619. PyObject* res = PyObject_Call(
  620. detail::_interpreter::get().s_python_function_stem, args, kwargs);
  621. Py_DECREF(args);
  622. Py_DECREF(kwargs);
  623. if (res)
  624. Py_DECREF(res);
  625. return res;
  626. }
  627. template< typename Numeric >
  628. bool fill(const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::map<std::string, std::string>& keywords)
  629. {
  630. assert(x.size() == y.size());
  631. detail::_interpreter::get();
  632. // using numpy arrays
  633. PyObject* xarray = detail::get_array(x);
  634. PyObject* yarray = detail::get_array(y);
  635. // construct positional args
  636. PyObject* args = PyTuple_New(2);
  637. PyTuple_SetItem(args, 0, xarray);
  638. PyTuple_SetItem(args, 1, yarray);
  639. // construct keyword args
  640. PyObject* kwargs = PyDict_New();
  641. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  642. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  643. }
  644. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_fill, args, kwargs);
  645. Py_DECREF(args);
  646. Py_DECREF(kwargs);
  647. if (res) Py_DECREF(res);
  648. return res;
  649. }
  650. template< typename Numeric >
  651. 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)
  652. {
  653. assert(x.size() == y1.size());
  654. assert(x.size() == y2.size());
  655. detail::_interpreter::get();
  656. // using numpy arrays
  657. PyObject* xarray = detail::get_array(x);
  658. PyObject* y1array = detail::get_array(y1);
  659. PyObject* y2array = detail::get_array(y2);
  660. // construct positional args
  661. PyObject* args = PyTuple_New(3);
  662. PyTuple_SetItem(args, 0, xarray);
  663. PyTuple_SetItem(args, 1, y1array);
  664. PyTuple_SetItem(args, 2, y2array);
  665. // construct keyword args
  666. PyObject* kwargs = PyDict_New();
  667. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it) {
  668. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  669. }
  670. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_fill_between, args, kwargs);
  671. Py_DECREF(args);
  672. Py_DECREF(kwargs);
  673. if(res) Py_DECREF(res);
  674. return res;
  675. }
  676. template <typename Numeric>
  677. bool arrow(Numeric x, Numeric y, Numeric end_x, Numeric end_y, const std::string& fc = "r",
  678. const std::string ec = "k", Numeric head_length = 0.25, Numeric head_width = 0.1625) {
  679. PyObject* obj_x = PyFloat_FromDouble(x);
  680. PyObject* obj_y = PyFloat_FromDouble(y);
  681. PyObject* obj_end_x = PyFloat_FromDouble(end_x);
  682. PyObject* obj_end_y = PyFloat_FromDouble(end_y);
  683. PyObject* kwargs = PyDict_New();
  684. PyDict_SetItemString(kwargs, "fc", PyString_FromString(fc.c_str()));
  685. PyDict_SetItemString(kwargs, "ec", PyString_FromString(ec.c_str()));
  686. PyDict_SetItemString(kwargs, "head_width", PyFloat_FromDouble(head_width));
  687. PyDict_SetItemString(kwargs, "head_length", PyFloat_FromDouble(head_length));
  688. PyObject* plot_args = PyTuple_New(4);
  689. PyTuple_SetItem(plot_args, 0, obj_x);
  690. PyTuple_SetItem(plot_args, 1, obj_y);
  691. PyTuple_SetItem(plot_args, 2, obj_end_x);
  692. PyTuple_SetItem(plot_args, 3, obj_end_y);
  693. PyObject* res =
  694. PyObject_Call(detail::_interpreter::get().s_python_function_arrow, plot_args, kwargs);
  695. Py_DECREF(plot_args);
  696. Py_DECREF(kwargs);
  697. if (res)
  698. Py_DECREF(res);
  699. return res;
  700. }
  701. template< typename Numeric>
  702. bool hist(const std::vector<Numeric>& y, long bins=10,std::string color="b",
  703. double alpha=1.0, bool cumulative=false)
  704. {
  705. detail::_interpreter::get();
  706. PyObject* yarray = detail::get_array(y);
  707. PyObject* kwargs = PyDict_New();
  708. PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins));
  709. PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str()));
  710. PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha));
  711. PyDict_SetItemString(kwargs, "cumulative", cumulative ? Py_True : Py_False);
  712. PyObject* plot_args = PyTuple_New(1);
  713. PyTuple_SetItem(plot_args, 0, yarray);
  714. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);
  715. Py_DECREF(plot_args);
  716. Py_DECREF(kwargs);
  717. if(res) Py_DECREF(res);
  718. return res;
  719. }
  720. #ifndef WITHOUT_NUMPY
  721. namespace detail {
  722. 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)
  723. {
  724. assert(type == NPY_UINT8 || type == NPY_FLOAT);
  725. assert(colors == 1 || colors == 3 || colors == 4);
  726. detail::_interpreter::get();
  727. // construct args
  728. npy_intp dims[3] = { rows, columns, colors };
  729. PyObject *args = PyTuple_New(1);
  730. PyTuple_SetItem(args, 0, PyArray_SimpleNewFromData(colors == 1 ? 2 : 3, dims, type, ptr));
  731. // construct keyword args
  732. PyObject* kwargs = PyDict_New();
  733. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  734. {
  735. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  736. }
  737. PyObject *res = PyObject_Call(detail::_interpreter::get().s_python_function_imshow, args, kwargs);
  738. Py_DECREF(args);
  739. Py_DECREF(kwargs);
  740. if (!res)
  741. throw std::runtime_error("Call to imshow() failed");
  742. if (out)
  743. *out = res;
  744. else
  745. Py_DECREF(res);
  746. }
  747. } // namespace detail
  748. 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)
  749. {
  750. detail::imshow((void *) ptr, NPY_UINT8, rows, columns, colors, keywords, out);
  751. }
  752. 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)
  753. {
  754. detail::imshow((void *) ptr, NPY_FLOAT, rows, columns, colors, keywords, out);
  755. }
  756. #ifdef WITH_OPENCV
  757. void imshow(const cv::Mat &image, const std::map<std::string, std::string> &keywords = {})
  758. {
  759. // Convert underlying type of matrix, if needed
  760. cv::Mat image2;
  761. NPY_TYPES npy_type = NPY_UINT8;
  762. switch (image.type() & CV_MAT_DEPTH_MASK) {
  763. case CV_8U:
  764. image2 = image;
  765. break;
  766. case CV_32F:
  767. image2 = image;
  768. npy_type = NPY_FLOAT;
  769. break;
  770. default:
  771. image.convertTo(image2, CV_MAKETYPE(CV_8U, image.channels()));
  772. }
  773. // If color image, convert from BGR to RGB
  774. switch (image2.channels()) {
  775. case 3:
  776. cv::cvtColor(image2, image2, CV_BGR2RGB);
  777. break;
  778. case 4:
  779. cv::cvtColor(image2, image2, CV_BGRA2RGBA);
  780. }
  781. detail::imshow(image2.data, npy_type, image2.rows, image2.cols, image2.channels(), keywords);
  782. }
  783. #endif // WITH_OPENCV
  784. #endif // WITHOUT_NUMPY
  785. template<typename NumericX, typename NumericY>
  786. bool scatter(const std::vector<NumericX>& x,
  787. const std::vector<NumericY>& y,
  788. const double s=1.0, // The marker size in points**2
  789. const std::map<std::string, std::string> & keywords = {})
  790. {
  791. detail::_interpreter::get();
  792. assert(x.size() == y.size());
  793. PyObject* xarray = detail::get_array(x);
  794. PyObject* yarray = detail::get_array(y);
  795. PyObject* kwargs = PyDict_New();
  796. PyDict_SetItemString(kwargs, "s", PyLong_FromLong(s));
  797. for (const auto& it : keywords)
  798. {
  799. PyDict_SetItemString(kwargs, it.first.c_str(), PyString_FromString(it.second.c_str()));
  800. }
  801. PyObject* plot_args = PyTuple_New(2);
  802. PyTuple_SetItem(plot_args, 0, xarray);
  803. PyTuple_SetItem(plot_args, 1, yarray);
  804. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_scatter, plot_args, kwargs);
  805. Py_DECREF(plot_args);
  806. Py_DECREF(kwargs);
  807. if(res) Py_DECREF(res);
  808. return res;
  809. }
  810. template<typename NumericX, typename NumericY, typename NumericZ>
  811. bool scatter(const std::vector<NumericX>& x,
  812. const std::vector<NumericY>& y,
  813. const std::vector<NumericZ>& z,
  814. const double s=1.0, // The marker size in points**2
  815. const std::map<std::string, std::string> & keywords = {},
  816. const long fig_number=0) {
  817. detail::_interpreter::get();
  818. // Same as with plot_surface: We lazily load the modules here the first time
  819. // this function is called because I'm not sure that we can assume "matplotlib
  820. // installed" implies "mpl_toolkits installed" on all platforms, and we don't
  821. // want to require it for people who don't need 3d plots.
  822. static PyObject *mpl_toolkitsmod = nullptr, *axis3dmod = nullptr;
  823. if (!mpl_toolkitsmod) {
  824. detail::_interpreter::get();
  825. PyObject* mpl_toolkits = PyString_FromString("mpl_toolkits");
  826. PyObject* axis3d = PyString_FromString("mpl_toolkits.mplot3d");
  827. if (!mpl_toolkits || !axis3d) { throw std::runtime_error("couldnt create string"); }
  828. mpl_toolkitsmod = PyImport_Import(mpl_toolkits);
  829. Py_DECREF(mpl_toolkits);
  830. if (!mpl_toolkitsmod) { throw std::runtime_error("Error loading module mpl_toolkits!"); }
  831. axis3dmod = PyImport_Import(axis3d);
  832. Py_DECREF(axis3d);
  833. if (!axis3dmod) { throw std::runtime_error("Error loading module mpl_toolkits.mplot3d!"); }
  834. }
  835. assert(x.size() == y.size());
  836. assert(y.size() == z.size());
  837. PyObject *xarray = detail::get_array(x);
  838. PyObject *yarray = detail::get_array(y);
  839. PyObject *zarray = detail::get_array(z);
  840. // construct positional args
  841. PyObject *args = PyTuple_New(3);
  842. PyTuple_SetItem(args, 0, xarray);
  843. PyTuple_SetItem(args, 1, yarray);
  844. PyTuple_SetItem(args, 2, zarray);
  845. // Build up the kw args.
  846. PyObject *kwargs = PyDict_New();
  847. for (std::map<std::string, std::string>::const_iterator it = keywords.begin();
  848. it != keywords.end(); ++it) {
  849. PyDict_SetItemString(kwargs, it->first.c_str(),
  850. PyString_FromString(it->second.c_str()));
  851. }
  852. PyObject *fig_args = PyTuple_New(1);
  853. PyObject* fig = nullptr;
  854. PyTuple_SetItem(fig_args, 0, PyLong_FromLong(fig_number));
  855. PyObject *fig_exists =
  856. PyObject_CallObject(detail::_interpreter::get().s_python_function_fignum_exists, fig_args);
  857. if (!PyObject_IsTrue(fig_exists)) {
  858. fig = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure,
  859. detail::_interpreter::get().s_python_empty_tuple);
  860. } else {
  861. fig = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure,
  862. fig_args);
  863. }
  864. Py_DECREF(fig_exists);
  865. if (!fig) throw std::runtime_error("Call to figure() failed.");
  866. PyObject *gca_kwargs = PyDict_New();
  867. PyDict_SetItemString(gca_kwargs, "projection", PyString_FromString("3d"));
  868. PyObject *gca = PyObject_GetAttrString(fig, "gca");
  869. if (!gca) throw std::runtime_error("No gca");
  870. Py_INCREF(gca);
  871. PyObject *axis = PyObject_Call(
  872. gca, detail::_interpreter::get().s_python_empty_tuple, gca_kwargs);
  873. if (!axis) throw std::runtime_error("No axis");
  874. Py_INCREF(axis);
  875. Py_DECREF(gca);
  876. Py_DECREF(gca_kwargs);
  877. PyObject *plot3 = PyObject_GetAttrString(axis, "scatter");
  878. if (!plot3) throw std::runtime_error("No 3D line plot");
  879. Py_INCREF(plot3);
  880. PyObject *res = PyObject_Call(plot3, args, kwargs);
  881. if (!res) throw std::runtime_error("Failed 3D line plot");
  882. Py_DECREF(plot3);
  883. Py_DECREF(axis);
  884. Py_DECREF(args);
  885. Py_DECREF(kwargs);
  886. Py_DECREF(fig);
  887. if (res) Py_DECREF(res);
  888. return res;
  889. }
  890. template<typename Numeric>
  891. bool boxplot(const std::vector<std::vector<Numeric>>& data,
  892. const std::vector<std::string>& labels = {},
  893. const std::map<std::string, std::string> & keywords = {})
  894. {
  895. detail::_interpreter::get();
  896. PyObject* listlist = detail::get_listlist(data);
  897. PyObject* args = PyTuple_New(1);
  898. PyTuple_SetItem(args, 0, listlist);
  899. PyObject* kwargs = PyDict_New();
  900. // kwargs needs the labels, if there are (the correct number of) labels
  901. if (!labels.empty() && labels.size() == data.size()) {
  902. PyDict_SetItemString(kwargs, "labels", detail::get_array(labels));
  903. }
  904. // take care of the remaining keywords
  905. for (const auto& it : keywords)
  906. {
  907. PyDict_SetItemString(kwargs, it.first.c_str(), PyString_FromString(it.second.c_str()));
  908. }
  909. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_boxplot, args, kwargs);
  910. Py_DECREF(args);
  911. Py_DECREF(kwargs);
  912. if(res) Py_DECREF(res);
  913. return res;
  914. }
  915. template<typename Numeric>
  916. bool boxplot(const std::vector<Numeric>& data,
  917. const std::map<std::string, std::string> & keywords = {})
  918. {
  919. detail::_interpreter::get();
  920. PyObject* vector = detail::get_array(data);
  921. PyObject* args = PyTuple_New(1);
  922. PyTuple_SetItem(args, 0, vector);
  923. PyObject* kwargs = PyDict_New();
  924. for (const auto& it : keywords)
  925. {
  926. PyDict_SetItemString(kwargs, it.first.c_str(), PyString_FromString(it.second.c_str()));
  927. }
  928. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_boxplot, args, kwargs);
  929. Py_DECREF(args);
  930. Py_DECREF(kwargs);
  931. if(res) Py_DECREF(res);
  932. return res;
  933. }
  934. template <typename Numeric>
  935. bool bar(const std::vector<Numeric> & x,
  936. const std::vector<Numeric> & y,
  937. std::string ec = "black",
  938. std::string ls = "-",
  939. double lw = 1.0,
  940. const std::map<std::string, std::string> & keywords = {})
  941. {
  942. detail::_interpreter::get();
  943. PyObject * xarray = detail::get_array(x);
  944. PyObject * yarray = detail::get_array(y);
  945. PyObject * kwargs = PyDict_New();
  946. PyDict_SetItemString(kwargs, "ec", PyString_FromString(ec.c_str()));
  947. PyDict_SetItemString(kwargs, "ls", PyString_FromString(ls.c_str()));
  948. PyDict_SetItemString(kwargs, "lw", PyFloat_FromDouble(lw));
  949. for (std::map<std::string, std::string>::const_iterator it =
  950. keywords.begin();
  951. it != keywords.end();
  952. ++it) {
  953. PyDict_SetItemString(
  954. 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(
  960. detail::_interpreter::get().s_python_function_bar, plot_args, kwargs);
  961. Py_DECREF(plot_args);
  962. Py_DECREF(kwargs);
  963. if (res) Py_DECREF(res);
  964. return res;
  965. }
  966. template <typename Numeric>
  967. bool bar(const std::vector<Numeric> & y,
  968. std::string ec = "black",
  969. std::string ls = "-",
  970. double lw = 1.0,
  971. const std::map<std::string, std::string> & keywords = {})
  972. {
  973. using T = typename std::remove_reference<decltype(y)>::type::value_type;
  974. detail::_interpreter::get();
  975. std::vector<T> x;
  976. for (std::size_t i = 0; i < y.size(); i++) { x.push_back(i); }
  977. return bar(x, y, ec, ls, lw, keywords);
  978. }
  979. template<typename Numeric>
  980. 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 = { }) {
  981. PyObject *xarray = detail::get_array(x);
  982. PyObject *yarray = detail::get_array(y);
  983. PyObject *kwargs = PyDict_New();
  984. PyDict_SetItemString(kwargs, "ec", PyString_FromString(ec.c_str()));
  985. PyDict_SetItemString(kwargs, "ls", PyString_FromString(ls.c_str()));
  986. PyDict_SetItemString(kwargs, "lw", PyFloat_FromDouble(lw));
  987. for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it) {
  988. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  989. }
  990. PyObject *plot_args = PyTuple_New(2);
  991. PyTuple_SetItem(plot_args, 0, xarray);
  992. PyTuple_SetItem(plot_args, 1, yarray);
  993. PyObject *res = PyObject_Call(detail::_interpreter::get().s_python_function_barh, plot_args, kwargs);
  994. Py_DECREF(plot_args);
  995. Py_DECREF(kwargs);
  996. if (res) Py_DECREF(res);
  997. return res;
  998. }
  999. inline bool subplots_adjust(const std::map<std::string, double>& keywords = {})
  1000. {
  1001. detail::_interpreter::get();
  1002. PyObject* kwargs = PyDict_New();
  1003. for (std::map<std::string, double>::const_iterator it =
  1004. keywords.begin(); it != keywords.end(); ++it) {
  1005. PyDict_SetItemString(kwargs, it->first.c_str(),
  1006. PyFloat_FromDouble(it->second));
  1007. }
  1008. PyObject* plot_args = PyTuple_New(0);
  1009. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_subplots_adjust, plot_args, kwargs);
  1010. Py_DECREF(plot_args);
  1011. Py_DECREF(kwargs);
  1012. if(res) Py_DECREF(res);
  1013. return res;
  1014. }
  1015. template< typename Numeric>
  1016. bool named_hist(std::string label,const std::vector<Numeric>& y, long bins=10, std::string color="b", double alpha=1.0)
  1017. {
  1018. detail::_interpreter::get();
  1019. PyObject* yarray = detail::get_array(y);
  1020. PyObject* kwargs = PyDict_New();
  1021. PyDict_SetItemString(kwargs, "label", PyString_FromString(label.c_str()));
  1022. PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins));
  1023. PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str()));
  1024. PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha));
  1025. PyObject* plot_args = PyTuple_New(1);
  1026. PyTuple_SetItem(plot_args, 0, yarray);
  1027. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);
  1028. Py_DECREF(plot_args);
  1029. Py_DECREF(kwargs);
  1030. if(res) Py_DECREF(res);
  1031. return res;
  1032. }
  1033. template<typename NumericX, typename NumericY>
  1034. bool plot(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  1035. {
  1036. assert(x.size() == y.size());
  1037. detail::_interpreter::get();
  1038. PyObject* xarray = detail::get_array(x);
  1039. PyObject* yarray = detail::get_array(y);
  1040. PyObject* pystring = PyString_FromString(s.c_str());
  1041. PyObject* plot_args = PyTuple_New(3);
  1042. PyTuple_SetItem(plot_args, 0, xarray);
  1043. PyTuple_SetItem(plot_args, 1, yarray);
  1044. PyTuple_SetItem(plot_args, 2, pystring);
  1045. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);
  1046. Py_DECREF(plot_args);
  1047. if(res) Py_DECREF(res);
  1048. return res;
  1049. }
  1050. template <typename NumericX, typename NumericY, typename NumericZ>
  1051. bool contour(const std::vector<NumericX>& x, const std::vector<NumericY>& y,
  1052. const std::vector<NumericZ>& z,
  1053. const std::map<std::string, std::string>& keywords = {}) {
  1054. assert(x.size() == y.size() && x.size() == z.size());
  1055. PyObject* xarray = detail::get_array(x);
  1056. PyObject* yarray = detail::get_array(y);
  1057. PyObject* zarray = detail::get_array(z);
  1058. PyObject* plot_args = PyTuple_New(3);
  1059. PyTuple_SetItem(plot_args, 0, xarray);
  1060. PyTuple_SetItem(plot_args, 1, yarray);
  1061. PyTuple_SetItem(plot_args, 2, zarray);
  1062. // construct keyword args
  1063. PyObject* kwargs = PyDict_New();
  1064. for (std::map<std::string, std::string>::const_iterator it = keywords.begin();
  1065. it != keywords.end(); ++it) {
  1066. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1067. }
  1068. PyObject* res =
  1069. PyObject_Call(detail::_interpreter::get().s_python_function_contour, plot_args, kwargs);
  1070. Py_DECREF(kwargs);
  1071. Py_DECREF(plot_args);
  1072. if (res)
  1073. Py_DECREF(res);
  1074. return res;
  1075. }
  1076. template<typename NumericX, typename NumericY, typename NumericU, typename NumericW>
  1077. 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 = {})
  1078. {
  1079. assert(x.size() == y.size() && x.size() == u.size() && u.size() == w.size());
  1080. detail::_interpreter::get();
  1081. PyObject* xarray = detail::get_array(x);
  1082. PyObject* yarray = detail::get_array(y);
  1083. PyObject* uarray = detail::get_array(u);
  1084. PyObject* warray = detail::get_array(w);
  1085. PyObject* plot_args = PyTuple_New(4);
  1086. PyTuple_SetItem(plot_args, 0, xarray);
  1087. PyTuple_SetItem(plot_args, 1, yarray);
  1088. PyTuple_SetItem(plot_args, 2, uarray);
  1089. PyTuple_SetItem(plot_args, 3, warray);
  1090. // construct keyword args
  1091. PyObject* kwargs = PyDict_New();
  1092. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1093. {
  1094. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1095. }
  1096. PyObject* res = PyObject_Call(
  1097. detail::_interpreter::get().s_python_function_quiver, plot_args, kwargs);
  1098. Py_DECREF(kwargs);
  1099. Py_DECREF(plot_args);
  1100. if (res)
  1101. Py_DECREF(res);
  1102. return res;
  1103. }
  1104. template<typename NumericX, typename NumericY, typename NumericZ, typename NumericU, typename NumericW, typename NumericV>
  1105. 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 = {})
  1106. {
  1107. //set up 3d axes stuff
  1108. static PyObject *mpl_toolkitsmod = nullptr, *axis3dmod = nullptr;
  1109. if (!mpl_toolkitsmod) {
  1110. detail::_interpreter::get();
  1111. PyObject* mpl_toolkits = PyString_FromString("mpl_toolkits");
  1112. PyObject* axis3d = PyString_FromString("mpl_toolkits.mplot3d");
  1113. if (!mpl_toolkits || !axis3d) { throw std::runtime_error("couldnt create string"); }
  1114. mpl_toolkitsmod = PyImport_Import(mpl_toolkits);
  1115. Py_DECREF(mpl_toolkits);
  1116. if (!mpl_toolkitsmod) { throw std::runtime_error("Error loading module mpl_toolkits!"); }
  1117. axis3dmod = PyImport_Import(axis3d);
  1118. Py_DECREF(axis3d);
  1119. if (!axis3dmod) { throw std::runtime_error("Error loading module mpl_toolkits.mplot3d!"); }
  1120. }
  1121. //assert sizes match up
  1122. 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());
  1123. //set up parameters
  1124. detail::_interpreter::get();
  1125. PyObject* xarray = detail::get_array(x);
  1126. PyObject* yarray = detail::get_array(y);
  1127. PyObject* zarray = detail::get_array(z);
  1128. PyObject* uarray = detail::get_array(u);
  1129. PyObject* warray = detail::get_array(w);
  1130. PyObject* varray = detail::get_array(v);
  1131. PyObject* plot_args = PyTuple_New(6);
  1132. PyTuple_SetItem(plot_args, 0, xarray);
  1133. PyTuple_SetItem(plot_args, 1, yarray);
  1134. PyTuple_SetItem(plot_args, 2, zarray);
  1135. PyTuple_SetItem(plot_args, 3, uarray);
  1136. PyTuple_SetItem(plot_args, 4, warray);
  1137. PyTuple_SetItem(plot_args, 5, varray);
  1138. // construct keyword args
  1139. PyObject* kwargs = PyDict_New();
  1140. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1141. {
  1142. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1143. }
  1144. //get figure gca to enable 3d projection
  1145. PyObject *fig =
  1146. PyObject_CallObject(detail::_interpreter::get().s_python_function_figure,
  1147. detail::_interpreter::get().s_python_empty_tuple);
  1148. if (!fig) throw std::runtime_error("Call to figure() failed.");
  1149. PyObject *gca_kwargs = PyDict_New();
  1150. PyDict_SetItemString(gca_kwargs, "projection", PyString_FromString("3d"));
  1151. PyObject *gca = PyObject_GetAttrString(fig, "gca");
  1152. if (!gca) throw std::runtime_error("No gca");
  1153. Py_INCREF(gca);
  1154. PyObject *axis = PyObject_Call(
  1155. gca, detail::_interpreter::get().s_python_empty_tuple, gca_kwargs);
  1156. if (!axis) throw std::runtime_error("No axis");
  1157. Py_INCREF(axis);
  1158. Py_DECREF(gca);
  1159. Py_DECREF(gca_kwargs);
  1160. //plot our boys bravely, plot them strongly, plot them with a wink and clap
  1161. PyObject *plot3 = PyObject_GetAttrString(axis, "quiver");
  1162. if (!plot3) throw std::runtime_error("No 3D line plot");
  1163. Py_INCREF(plot3);
  1164. PyObject* res = PyObject_Call(
  1165. plot3, plot_args, kwargs);
  1166. if (!res) throw std::runtime_error("Failed 3D plot");
  1167. Py_DECREF(plot3);
  1168. Py_DECREF(axis);
  1169. Py_DECREF(kwargs);
  1170. Py_DECREF(plot_args);
  1171. if (res)
  1172. Py_DECREF(res);
  1173. return res;
  1174. }
  1175. template<typename NumericX, typename NumericY>
  1176. bool stem(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  1177. {
  1178. assert(x.size() == y.size());
  1179. detail::_interpreter::get();
  1180. PyObject* xarray = detail::get_array(x);
  1181. PyObject* yarray = detail::get_array(y);
  1182. PyObject* pystring = PyString_FromString(s.c_str());
  1183. PyObject* plot_args = PyTuple_New(3);
  1184. PyTuple_SetItem(plot_args, 0, xarray);
  1185. PyTuple_SetItem(plot_args, 1, yarray);
  1186. PyTuple_SetItem(plot_args, 2, pystring);
  1187. PyObject* res = PyObject_CallObject(
  1188. detail::_interpreter::get().s_python_function_stem, plot_args);
  1189. Py_DECREF(plot_args);
  1190. if (res)
  1191. Py_DECREF(res);
  1192. return res;
  1193. }
  1194. template<typename NumericX, typename NumericY>
  1195. bool semilogx(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_semilogx, 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 semilogy(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  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* pystring = PyString_FromString(s.c_str());
  1219. PyObject* plot_args = PyTuple_New(3);
  1220. PyTuple_SetItem(plot_args, 0, xarray);
  1221. PyTuple_SetItem(plot_args, 1, yarray);
  1222. PyTuple_SetItem(plot_args, 2, pystring);
  1223. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogy, plot_args);
  1224. Py_DECREF(plot_args);
  1225. if(res) Py_DECREF(res);
  1226. return res;
  1227. }
  1228. template<typename NumericX, typename NumericY>
  1229. bool loglog(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  1230. {
  1231. assert(x.size() == y.size());
  1232. detail::_interpreter::get();
  1233. PyObject* xarray = detail::get_array(x);
  1234. PyObject* yarray = detail::get_array(y);
  1235. PyObject* pystring = PyString_FromString(s.c_str());
  1236. PyObject* plot_args = PyTuple_New(3);
  1237. PyTuple_SetItem(plot_args, 0, xarray);
  1238. PyTuple_SetItem(plot_args, 1, yarray);
  1239. PyTuple_SetItem(plot_args, 2, pystring);
  1240. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_loglog, plot_args);
  1241. Py_DECREF(plot_args);
  1242. if(res) Py_DECREF(res);
  1243. return res;
  1244. }
  1245. template<typename NumericX, typename NumericY>
  1246. 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 = {})
  1247. {
  1248. assert(x.size() == y.size());
  1249. detail::_interpreter::get();
  1250. PyObject* xarray = detail::get_array(x);
  1251. PyObject* yarray = detail::get_array(y);
  1252. PyObject* yerrarray = detail::get_array(yerr);
  1253. // construct keyword args
  1254. PyObject* kwargs = PyDict_New();
  1255. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1256. {
  1257. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1258. }
  1259. PyDict_SetItemString(kwargs, "yerr", yerrarray);
  1260. PyObject *plot_args = PyTuple_New(2);
  1261. PyTuple_SetItem(plot_args, 0, xarray);
  1262. PyTuple_SetItem(plot_args, 1, yarray);
  1263. PyObject *res = PyObject_Call(detail::_interpreter::get().s_python_function_errorbar, plot_args, kwargs);
  1264. Py_DECREF(kwargs);
  1265. Py_DECREF(plot_args);
  1266. if (res)
  1267. Py_DECREF(res);
  1268. else
  1269. throw std::runtime_error("Call to errorbar() failed.");
  1270. return res;
  1271. }
  1272. template<typename Numeric>
  1273. bool named_plot(const std::string& name, const std::vector<Numeric>& y, const std::string& format = "")
  1274. {
  1275. detail::_interpreter::get();
  1276. PyObject* kwargs = PyDict_New();
  1277. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  1278. PyObject* yarray = detail::get_array(y);
  1279. PyObject* pystring = PyString_FromString(format.c_str());
  1280. PyObject* plot_args = PyTuple_New(2);
  1281. PyTuple_SetItem(plot_args, 0, yarray);
  1282. PyTuple_SetItem(plot_args, 1, pystring);
  1283. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
  1284. Py_DECREF(kwargs);
  1285. Py_DECREF(plot_args);
  1286. if (res) Py_DECREF(res);
  1287. return res;
  1288. }
  1289. template<typename Numeric>
  1290. bool named_plot(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  1291. {
  1292. detail::_interpreter::get();
  1293. PyObject* kwargs = PyDict_New();
  1294. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  1295. PyObject* xarray = detail::get_array(x);
  1296. PyObject* yarray = detail::get_array(y);
  1297. PyObject* pystring = PyString_FromString(format.c_str());
  1298. PyObject* plot_args = PyTuple_New(3);
  1299. PyTuple_SetItem(plot_args, 0, xarray);
  1300. PyTuple_SetItem(plot_args, 1, yarray);
  1301. PyTuple_SetItem(plot_args, 2, pystring);
  1302. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
  1303. Py_DECREF(kwargs);
  1304. Py_DECREF(plot_args);
  1305. if (res) Py_DECREF(res);
  1306. return res;
  1307. }
  1308. template<typename Numeric>
  1309. bool named_semilogx(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  1310. {
  1311. detail::_interpreter::get();
  1312. PyObject* kwargs = PyDict_New();
  1313. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  1314. PyObject* xarray = detail::get_array(x);
  1315. PyObject* yarray = detail::get_array(y);
  1316. PyObject* pystring = PyString_FromString(format.c_str());
  1317. PyObject* plot_args = PyTuple_New(3);
  1318. PyTuple_SetItem(plot_args, 0, xarray);
  1319. PyTuple_SetItem(plot_args, 1, yarray);
  1320. PyTuple_SetItem(plot_args, 2, pystring);
  1321. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogx, plot_args, kwargs);
  1322. Py_DECREF(kwargs);
  1323. Py_DECREF(plot_args);
  1324. if (res) Py_DECREF(res);
  1325. return res;
  1326. }
  1327. template<typename Numeric>
  1328. bool named_semilogy(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  1329. {
  1330. detail::_interpreter::get();
  1331. PyObject* kwargs = PyDict_New();
  1332. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  1333. PyObject* xarray = detail::get_array(x);
  1334. PyObject* yarray = detail::get_array(y);
  1335. PyObject* pystring = PyString_FromString(format.c_str());
  1336. PyObject* plot_args = PyTuple_New(3);
  1337. PyTuple_SetItem(plot_args, 0, xarray);
  1338. PyTuple_SetItem(plot_args, 1, yarray);
  1339. PyTuple_SetItem(plot_args, 2, pystring);
  1340. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogy, plot_args, kwargs);
  1341. Py_DECREF(kwargs);
  1342. Py_DECREF(plot_args);
  1343. if (res) Py_DECREF(res);
  1344. return res;
  1345. }
  1346. template<typename Numeric>
  1347. bool named_loglog(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  1348. {
  1349. detail::_interpreter::get();
  1350. PyObject* kwargs = PyDict_New();
  1351. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  1352. PyObject* xarray = detail::get_array(x);
  1353. PyObject* yarray = detail::get_array(y);
  1354. PyObject* pystring = PyString_FromString(format.c_str());
  1355. PyObject* plot_args = PyTuple_New(3);
  1356. PyTuple_SetItem(plot_args, 0, xarray);
  1357. PyTuple_SetItem(plot_args, 1, yarray);
  1358. PyTuple_SetItem(plot_args, 2, pystring);
  1359. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_loglog, plot_args, kwargs);
  1360. Py_DECREF(kwargs);
  1361. Py_DECREF(plot_args);
  1362. if (res) Py_DECREF(res);
  1363. return res;
  1364. }
  1365. template<typename Numeric>
  1366. bool plot(const std::vector<Numeric>& y, const std::string& format = "")
  1367. {
  1368. std::vector<Numeric> x(y.size());
  1369. for(size_t i=0; i<x.size(); ++i) x.at(i) = i;
  1370. return plot(x,y,format);
  1371. }
  1372. template<typename Numeric>
  1373. bool plot(const std::vector<Numeric>& y, const std::map<std::string, std::string>& keywords)
  1374. {
  1375. std::vector<Numeric> x(y.size());
  1376. for(size_t i=0; i<x.size(); ++i) x.at(i) = i;
  1377. return plot(x,y,keywords);
  1378. }
  1379. template<typename Numeric>
  1380. bool stem(const std::vector<Numeric>& y, const std::string& format = "")
  1381. {
  1382. std::vector<Numeric> x(y.size());
  1383. for (size_t i = 0; i < x.size(); ++i) x.at(i) = i;
  1384. return stem(x, y, format);
  1385. }
  1386. template<typename Numeric>
  1387. void text(Numeric x, Numeric y, const std::string& s = "")
  1388. {
  1389. detail::_interpreter::get();
  1390. PyObject* args = PyTuple_New(3);
  1391. PyTuple_SetItem(args, 0, PyFloat_FromDouble(x));
  1392. PyTuple_SetItem(args, 1, PyFloat_FromDouble(y));
  1393. PyTuple_SetItem(args, 2, PyString_FromString(s.c_str()));
  1394. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_text, args);
  1395. if(!res) throw std::runtime_error("Call to text() failed.");
  1396. Py_DECREF(args);
  1397. Py_DECREF(res);
  1398. }
  1399. inline void colorbar(PyObject* mappable = NULL, const std::map<std::string, float>& keywords = {})
  1400. {
  1401. if (mappable == NULL)
  1402. throw std::runtime_error("Must call colorbar with PyObject* returned from an image, contour, surface, etc.");
  1403. detail::_interpreter::get();
  1404. PyObject* args = PyTuple_New(1);
  1405. PyTuple_SetItem(args, 0, mappable);
  1406. PyObject* kwargs = PyDict_New();
  1407. for(std::map<std::string, float>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1408. {
  1409. PyDict_SetItemString(kwargs, it->first.c_str(), PyFloat_FromDouble(it->second));
  1410. }
  1411. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_colorbar, args, kwargs);
  1412. if(!res) throw std::runtime_error("Call to colorbar() failed.");
  1413. Py_DECREF(args);
  1414. Py_DECREF(kwargs);
  1415. Py_DECREF(res);
  1416. }
  1417. inline long figure(long number = -1)
  1418. {
  1419. detail::_interpreter::get();
  1420. PyObject *res;
  1421. if (number == -1)
  1422. res = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure, detail::_interpreter::get().s_python_empty_tuple);
  1423. else {
  1424. assert(number > 0);
  1425. // Make sure interpreter is initialised
  1426. detail::_interpreter::get();
  1427. PyObject *args = PyTuple_New(1);
  1428. PyTuple_SetItem(args, 0, PyLong_FromLong(number));
  1429. res = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure, args);
  1430. Py_DECREF(args);
  1431. }
  1432. if(!res) throw std::runtime_error("Call to figure() failed.");
  1433. PyObject* num = PyObject_GetAttrString(res, "number");
  1434. if (!num) throw std::runtime_error("Could not get number attribute of figure object");
  1435. const long figureNumber = PyLong_AsLong(num);
  1436. Py_DECREF(num);
  1437. Py_DECREF(res);
  1438. return figureNumber;
  1439. }
  1440. inline bool fignum_exists(long number)
  1441. {
  1442. detail::_interpreter::get();
  1443. PyObject *args = PyTuple_New(1);
  1444. PyTuple_SetItem(args, 0, PyLong_FromLong(number));
  1445. PyObject *res = PyObject_CallObject(detail::_interpreter::get().s_python_function_fignum_exists, args);
  1446. if(!res) throw std::runtime_error("Call to fignum_exists() failed.");
  1447. bool ret = PyObject_IsTrue(res);
  1448. Py_DECREF(res);
  1449. Py_DECREF(args);
  1450. return ret;
  1451. }
  1452. inline void figure_size(size_t w, size_t h)
  1453. {
  1454. detail::_interpreter::get();
  1455. const size_t dpi = 100;
  1456. PyObject* size = PyTuple_New(2);
  1457. PyTuple_SetItem(size, 0, PyFloat_FromDouble((double)w / dpi));
  1458. PyTuple_SetItem(size, 1, PyFloat_FromDouble((double)h / dpi));
  1459. PyObject* kwargs = PyDict_New();
  1460. PyDict_SetItemString(kwargs, "figsize", size);
  1461. PyDict_SetItemString(kwargs, "dpi", PyLong_FromSize_t(dpi));
  1462. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_figure,
  1463. detail::_interpreter::get().s_python_empty_tuple, kwargs);
  1464. Py_DECREF(kwargs);
  1465. if(!res) throw std::runtime_error("Call to figure_size() failed.");
  1466. Py_DECREF(res);
  1467. }
  1468. inline void legend()
  1469. {
  1470. detail::_interpreter::get();
  1471. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_legend, detail::_interpreter::get().s_python_empty_tuple);
  1472. if(!res) throw std::runtime_error("Call to legend() failed.");
  1473. Py_DECREF(res);
  1474. }
  1475. inline void legend(const std::map<std::string, std::string>& keywords)
  1476. {
  1477. detail::_interpreter::get();
  1478. // construct keyword args
  1479. PyObject* kwargs = PyDict_New();
  1480. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1481. {
  1482. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1483. }
  1484. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_legend, detail::_interpreter::get().s_python_empty_tuple, kwargs);
  1485. if(!res) throw std::runtime_error("Call to legend() failed.");
  1486. Py_DECREF(kwargs);
  1487. Py_DECREF(res);
  1488. }
  1489. template<typename Numeric>
  1490. inline void set_aspect(Numeric ratio)
  1491. {
  1492. detail::_interpreter::get();
  1493. PyObject* args = PyTuple_New(1);
  1494. PyTuple_SetItem(args, 0, PyFloat_FromDouble(ratio));
  1495. PyObject* kwargs = PyDict_New();
  1496. PyObject *ax =
  1497. PyObject_CallObject(detail::_interpreter::get().s_python_function_gca,
  1498. detail::_interpreter::get().s_python_empty_tuple);
  1499. if (!ax) throw std::runtime_error("Call to gca() failed.");
  1500. Py_INCREF(ax);
  1501. PyObject *set_aspect = PyObject_GetAttrString(ax, "set_aspect");
  1502. if (!set_aspect) throw std::runtime_error("Attribute set_aspect not found.");
  1503. Py_INCREF(set_aspect);
  1504. PyObject *res = PyObject_Call(set_aspect, args, kwargs);
  1505. if (!res) throw std::runtime_error("Call to set_aspect() failed.");
  1506. Py_DECREF(set_aspect);
  1507. Py_DECREF(ax);
  1508. Py_DECREF(args);
  1509. Py_DECREF(kwargs);
  1510. }
  1511. inline void set_aspect_equal()
  1512. {
  1513. // expect ratio == "equal". Leaving error handling to matplotlib.
  1514. detail::_interpreter::get();
  1515. PyObject* args = PyTuple_New(1);
  1516. PyTuple_SetItem(args, 0, PyString_FromString("equal"));
  1517. PyObject* kwargs = PyDict_New();
  1518. PyObject *ax =
  1519. PyObject_CallObject(detail::_interpreter::get().s_python_function_gca,
  1520. detail::_interpreter::get().s_python_empty_tuple);
  1521. if (!ax) throw std::runtime_error("Call to gca() failed.");
  1522. Py_INCREF(ax);
  1523. PyObject *set_aspect = PyObject_GetAttrString(ax, "set_aspect");
  1524. if (!set_aspect) throw std::runtime_error("Attribute set_aspect not found.");
  1525. Py_INCREF(set_aspect);
  1526. PyObject *res = PyObject_Call(set_aspect, args, kwargs);
  1527. if (!res) throw std::runtime_error("Call to set_aspect() failed.");
  1528. Py_DECREF(set_aspect);
  1529. Py_DECREF(ax);
  1530. Py_DECREF(args);
  1531. Py_DECREF(kwargs);
  1532. }
  1533. template<typename Numeric>
  1534. void ylim(Numeric left, Numeric right)
  1535. {
  1536. detail::_interpreter::get();
  1537. PyObject* list = PyList_New(2);
  1538. PyList_SetItem(list, 0, PyFloat_FromDouble(left));
  1539. PyList_SetItem(list, 1, PyFloat_FromDouble(right));
  1540. PyObject* args = PyTuple_New(1);
  1541. PyTuple_SetItem(args, 0, list);
  1542. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);
  1543. if(!res) throw std::runtime_error("Call to ylim() failed.");
  1544. Py_DECREF(args);
  1545. Py_DECREF(res);
  1546. }
  1547. template<typename Numeric>
  1548. void xlim(Numeric left, Numeric right)
  1549. {
  1550. detail::_interpreter::get();
  1551. PyObject* list = PyList_New(2);
  1552. PyList_SetItem(list, 0, PyFloat_FromDouble(left));
  1553. PyList_SetItem(list, 1, PyFloat_FromDouble(right));
  1554. PyObject* args = PyTuple_New(1);
  1555. PyTuple_SetItem(args, 0, list);
  1556. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);
  1557. if(!res) throw std::runtime_error("Call to xlim() failed.");
  1558. Py_DECREF(args);
  1559. Py_DECREF(res);
  1560. }
  1561. inline std::array<double, 2> xlim()
  1562. {
  1563. PyObject* args = PyTuple_New(0);
  1564. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);
  1565. if(!res) throw std::runtime_error("Call to xlim() failed.");
  1566. Py_DECREF(res);
  1567. PyObject* left = PyTuple_GetItem(res,0);
  1568. PyObject* right = PyTuple_GetItem(res,1);
  1569. return { PyFloat_AsDouble(left), PyFloat_AsDouble(right) };
  1570. }
  1571. inline std::array<double, 2> ylim()
  1572. {
  1573. PyObject* args = PyTuple_New(0);
  1574. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);
  1575. if(!res) throw std::runtime_error("Call to ylim() failed.");
  1576. Py_DECREF(res);
  1577. PyObject* left = PyTuple_GetItem(res,0);
  1578. PyObject* right = PyTuple_GetItem(res,1);
  1579. return { PyFloat_AsDouble(left), PyFloat_AsDouble(right) };
  1580. }
  1581. template<typename Numeric>
  1582. inline void xticks(const std::vector<Numeric> &ticks, const std::vector<std::string> &labels = {}, const std::map<std::string, std::string>& keywords = {})
  1583. {
  1584. assert(labels.size() == 0 || ticks.size() == labels.size());
  1585. detail::_interpreter::get();
  1586. // using numpy array
  1587. PyObject* ticksarray = detail::get_array(ticks);
  1588. PyObject* args;
  1589. if(labels.size() == 0) {
  1590. // construct positional args
  1591. args = PyTuple_New(1);
  1592. PyTuple_SetItem(args, 0, ticksarray);
  1593. } else {
  1594. // make tuple of tick labels
  1595. PyObject* labelstuple = PyTuple_New(labels.size());
  1596. for (size_t i = 0; i < labels.size(); i++)
  1597. PyTuple_SetItem(labelstuple, i, PyUnicode_FromString(labels[i].c_str()));
  1598. // construct positional args
  1599. args = PyTuple_New(2);
  1600. PyTuple_SetItem(args, 0, ticksarray);
  1601. PyTuple_SetItem(args, 1, labelstuple);
  1602. }
  1603. // construct keyword args
  1604. PyObject* kwargs = PyDict_New();
  1605. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1606. {
  1607. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1608. }
  1609. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_xticks, args, kwargs);
  1610. Py_DECREF(args);
  1611. Py_DECREF(kwargs);
  1612. if(!res) throw std::runtime_error("Call to xticks() failed");
  1613. Py_DECREF(res);
  1614. }
  1615. template<typename Numeric>
  1616. inline void xticks(const std::vector<Numeric> &ticks, const std::map<std::string, std::string>& keywords)
  1617. {
  1618. xticks(ticks, {}, keywords);
  1619. }
  1620. template<typename Numeric>
  1621. inline void yticks(const std::vector<Numeric> &ticks, const std::vector<std::string> &labels = {}, const std::map<std::string, std::string>& keywords = {})
  1622. {
  1623. assert(labels.size() == 0 || ticks.size() == labels.size());
  1624. detail::_interpreter::get();
  1625. // using numpy array
  1626. PyObject* ticksarray = detail::get_array(ticks);
  1627. PyObject* args;
  1628. if(labels.size() == 0) {
  1629. // construct positional args
  1630. args = PyTuple_New(1);
  1631. PyTuple_SetItem(args, 0, ticksarray);
  1632. } else {
  1633. // make tuple of tick labels
  1634. PyObject* labelstuple = PyTuple_New(labels.size());
  1635. for (size_t i = 0; i < labels.size(); i++)
  1636. PyTuple_SetItem(labelstuple, i, PyUnicode_FromString(labels[i].c_str()));
  1637. // construct positional args
  1638. args = PyTuple_New(2);
  1639. PyTuple_SetItem(args, 0, ticksarray);
  1640. PyTuple_SetItem(args, 1, labelstuple);
  1641. }
  1642. // construct keyword args
  1643. PyObject* kwargs = PyDict_New();
  1644. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1645. {
  1646. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1647. }
  1648. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_yticks, args, kwargs);
  1649. Py_DECREF(args);
  1650. Py_DECREF(kwargs);
  1651. if(!res) throw std::runtime_error("Call to yticks() failed");
  1652. Py_DECREF(res);
  1653. }
  1654. template<typename Numeric>
  1655. inline void yticks(const std::vector<Numeric> &ticks, const std::map<std::string, std::string>& keywords)
  1656. {
  1657. yticks(ticks, {}, keywords);
  1658. }
  1659. template <typename Numeric> inline void margins(Numeric margin)
  1660. {
  1661. // construct positional args
  1662. PyObject* args = PyTuple_New(1);
  1663. PyTuple_SetItem(args, 0, PyFloat_FromDouble(margin));
  1664. PyObject* res =
  1665. PyObject_CallObject(detail::_interpreter::get().s_python_function_margins, args);
  1666. if (!res)
  1667. throw std::runtime_error("Call to margins() failed.");
  1668. Py_DECREF(args);
  1669. Py_DECREF(res);
  1670. }
  1671. template <typename Numeric> inline void margins(Numeric margin_x, Numeric margin_y)
  1672. {
  1673. // construct positional args
  1674. PyObject* args = PyTuple_New(2);
  1675. PyTuple_SetItem(args, 0, PyFloat_FromDouble(margin_x));
  1676. PyTuple_SetItem(args, 1, PyFloat_FromDouble(margin_y));
  1677. PyObject* res =
  1678. PyObject_CallObject(detail::_interpreter::get().s_python_function_margins, args);
  1679. if (!res)
  1680. throw std::runtime_error("Call to margins() failed.");
  1681. Py_DECREF(args);
  1682. Py_DECREF(res);
  1683. }
  1684. inline void tick_params(const std::map<std::string, std::string>& keywords, const std::string axis = "both")
  1685. {
  1686. detail::_interpreter::get();
  1687. // construct positional args
  1688. PyObject* args;
  1689. args = PyTuple_New(1);
  1690. PyTuple_SetItem(args, 0, PyString_FromString(axis.c_str()));
  1691. // construct keyword args
  1692. PyObject* kwargs = PyDict_New();
  1693. for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1694. {
  1695. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1696. }
  1697. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_tick_params, args, kwargs);
  1698. Py_DECREF(args);
  1699. Py_DECREF(kwargs);
  1700. if (!res) throw std::runtime_error("Call to tick_params() failed");
  1701. Py_DECREF(res);
  1702. }
  1703. inline void subplot(long nrows, long ncols, long plot_number)
  1704. {
  1705. detail::_interpreter::get();
  1706. // construct positional args
  1707. PyObject* args = PyTuple_New(3);
  1708. PyTuple_SetItem(args, 0, PyFloat_FromDouble(nrows));
  1709. PyTuple_SetItem(args, 1, PyFloat_FromDouble(ncols));
  1710. PyTuple_SetItem(args, 2, PyFloat_FromDouble(plot_number));
  1711. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_subplot, args);
  1712. if(!res) throw std::runtime_error("Call to subplot() failed.");
  1713. Py_DECREF(args);
  1714. Py_DECREF(res);
  1715. }
  1716. inline void subplot2grid(long nrows, long ncols, long rowid=0, long colid=0, long rowspan=1, long colspan=1)
  1717. {
  1718. detail::_interpreter::get();
  1719. PyObject* shape = PyTuple_New(2);
  1720. PyTuple_SetItem(shape, 0, PyLong_FromLong(nrows));
  1721. PyTuple_SetItem(shape, 1, PyLong_FromLong(ncols));
  1722. PyObject* loc = PyTuple_New(2);
  1723. PyTuple_SetItem(loc, 0, PyLong_FromLong(rowid));
  1724. PyTuple_SetItem(loc, 1, PyLong_FromLong(colid));
  1725. PyObject* args = PyTuple_New(4);
  1726. PyTuple_SetItem(args, 0, shape);
  1727. PyTuple_SetItem(args, 1, loc);
  1728. PyTuple_SetItem(args, 2, PyLong_FromLong(rowspan));
  1729. PyTuple_SetItem(args, 3, PyLong_FromLong(colspan));
  1730. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_subplot2grid, args);
  1731. if(!res) throw std::runtime_error("Call to subplot2grid() failed.");
  1732. Py_DECREF(shape);
  1733. Py_DECREF(loc);
  1734. Py_DECREF(args);
  1735. Py_DECREF(res);
  1736. }
  1737. inline void title(const std::string &titlestr, const std::map<std::string, std::string> &keywords = {})
  1738. {
  1739. detail::_interpreter::get();
  1740. PyObject* pytitlestr = PyString_FromString(titlestr.c_str());
  1741. PyObject* args = PyTuple_New(1);
  1742. PyTuple_SetItem(args, 0, pytitlestr);
  1743. PyObject* kwargs = PyDict_New();
  1744. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  1745. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1746. }
  1747. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_title, args, kwargs);
  1748. if(!res) throw std::runtime_error("Call to title() failed.");
  1749. Py_DECREF(args);
  1750. Py_DECREF(kwargs);
  1751. Py_DECREF(res);
  1752. }
  1753. inline void suptitle(const std::string &suptitlestr, const std::map<std::string, std::string> &keywords = {})
  1754. {
  1755. detail::_interpreter::get();
  1756. PyObject* pysuptitlestr = PyString_FromString(suptitlestr.c_str());
  1757. PyObject* args = PyTuple_New(1);
  1758. PyTuple_SetItem(args, 0, pysuptitlestr);
  1759. PyObject* kwargs = PyDict_New();
  1760. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  1761. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1762. }
  1763. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_suptitle, args, kwargs);
  1764. if(!res) throw std::runtime_error("Call to suptitle() failed.");
  1765. Py_DECREF(args);
  1766. Py_DECREF(kwargs);
  1767. Py_DECREF(res);
  1768. }
  1769. inline void axis(const std::string &axisstr)
  1770. {
  1771. detail::_interpreter::get();
  1772. PyObject* str = PyString_FromString(axisstr.c_str());
  1773. PyObject* args = PyTuple_New(1);
  1774. PyTuple_SetItem(args, 0, str);
  1775. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_axis, args);
  1776. if(!res) throw std::runtime_error("Call to title() failed.");
  1777. Py_DECREF(args);
  1778. Py_DECREF(res);
  1779. }
  1780. 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>())
  1781. {
  1782. detail::_interpreter::get();
  1783. // construct positional args
  1784. PyObject* args = PyTuple_New(3);
  1785. PyTuple_SetItem(args, 0, PyFloat_FromDouble(y));
  1786. PyTuple_SetItem(args, 1, PyFloat_FromDouble(xmin));
  1787. PyTuple_SetItem(args, 2, PyFloat_FromDouble(xmax));
  1788. // construct keyword args
  1789. PyObject* kwargs = PyDict_New();
  1790. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1791. {
  1792. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1793. }
  1794. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_axhline, args, kwargs);
  1795. Py_DECREF(args);
  1796. Py_DECREF(kwargs);
  1797. if(res) Py_DECREF(res);
  1798. }
  1799. 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>())
  1800. {
  1801. detail::_interpreter::get();
  1802. // construct positional args
  1803. PyObject* args = PyTuple_New(3);
  1804. PyTuple_SetItem(args, 0, PyFloat_FromDouble(x));
  1805. PyTuple_SetItem(args, 1, PyFloat_FromDouble(ymin));
  1806. PyTuple_SetItem(args, 2, PyFloat_FromDouble(ymax));
  1807. // construct keyword args
  1808. PyObject* kwargs = PyDict_New();
  1809. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1810. {
  1811. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1812. }
  1813. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_axvline, args, kwargs);
  1814. Py_DECREF(args);
  1815. Py_DECREF(kwargs);
  1816. if(res) Py_DECREF(res);
  1817. }
  1818. 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>())
  1819. {
  1820. // construct positional args
  1821. PyObject* args = PyTuple_New(4);
  1822. PyTuple_SetItem(args, 0, PyFloat_FromDouble(xmin));
  1823. PyTuple_SetItem(args, 1, PyFloat_FromDouble(xmax));
  1824. PyTuple_SetItem(args, 2, PyFloat_FromDouble(ymin));
  1825. PyTuple_SetItem(args, 3, PyFloat_FromDouble(ymax));
  1826. // construct keyword args
  1827. PyObject* kwargs = PyDict_New();
  1828. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  1829. if (it->first == "linewidth" || it->first == "alpha") {
  1830. PyDict_SetItemString(kwargs, it->first.c_str(),
  1831. PyFloat_FromDouble(std::stod(it->second)));
  1832. } else {
  1833. PyDict_SetItemString(kwargs, it->first.c_str(),
  1834. PyString_FromString(it->second.c_str()));
  1835. }
  1836. }
  1837. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_axvspan, args, kwargs);
  1838. Py_DECREF(args);
  1839. Py_DECREF(kwargs);
  1840. if(res) Py_DECREF(res);
  1841. }
  1842. inline void xlabel(const std::string &str, const std::map<std::string, std::string> &keywords = {})
  1843. {
  1844. detail::_interpreter::get();
  1845. PyObject* pystr = PyString_FromString(str.c_str());
  1846. PyObject* args = PyTuple_New(1);
  1847. PyTuple_SetItem(args, 0, pystr);
  1848. PyObject* kwargs = PyDict_New();
  1849. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  1850. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1851. }
  1852. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_xlabel, args, kwargs);
  1853. if(!res) throw std::runtime_error("Call to xlabel() failed.");
  1854. Py_DECREF(args);
  1855. Py_DECREF(kwargs);
  1856. Py_DECREF(res);
  1857. }
  1858. inline void ylabel(const std::string &str, const std::map<std::string, std::string>& keywords = {})
  1859. {
  1860. detail::_interpreter::get();
  1861. PyObject* pystr = PyString_FromString(str.c_str());
  1862. PyObject* args = PyTuple_New(1);
  1863. PyTuple_SetItem(args, 0, pystr);
  1864. PyObject* kwargs = PyDict_New();
  1865. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  1866. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1867. }
  1868. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_ylabel, args, kwargs);
  1869. if(!res) throw std::runtime_error("Call to ylabel() failed.");
  1870. Py_DECREF(args);
  1871. Py_DECREF(kwargs);
  1872. Py_DECREF(res);
  1873. }
  1874. inline void set_zlabel(const std::string &str, const std::map<std::string, std::string>& keywords = {})
  1875. {
  1876. detail::_interpreter::get();
  1877. // Same as with plot_surface: We lazily load the modules here the first time
  1878. // this function is called because I'm not sure that we can assume "matplotlib
  1879. // installed" implies "mpl_toolkits installed" on all platforms, and we don't
  1880. // want to require it for people who don't need 3d plots.
  1881. static PyObject *mpl_toolkitsmod = nullptr, *axis3dmod = nullptr;
  1882. if (!mpl_toolkitsmod) {
  1883. PyObject* mpl_toolkits = PyString_FromString("mpl_toolkits");
  1884. PyObject* axis3d = PyString_FromString("mpl_toolkits.mplot3d");
  1885. if (!mpl_toolkits || !axis3d) { throw std::runtime_error("couldnt create string"); }
  1886. mpl_toolkitsmod = PyImport_Import(mpl_toolkits);
  1887. Py_DECREF(mpl_toolkits);
  1888. if (!mpl_toolkitsmod) { throw std::runtime_error("Error loading module mpl_toolkits!"); }
  1889. axis3dmod = PyImport_Import(axis3d);
  1890. Py_DECREF(axis3d);
  1891. if (!axis3dmod) { throw std::runtime_error("Error loading module mpl_toolkits.mplot3d!"); }
  1892. }
  1893. PyObject* pystr = PyString_FromString(str.c_str());
  1894. PyObject* args = PyTuple_New(1);
  1895. PyTuple_SetItem(args, 0, pystr);
  1896. PyObject* kwargs = PyDict_New();
  1897. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  1898. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1899. }
  1900. PyObject *ax =
  1901. PyObject_CallObject(detail::_interpreter::get().s_python_function_gca,
  1902. detail::_interpreter::get().s_python_empty_tuple);
  1903. if (!ax) throw std::runtime_error("Call to gca() failed.");
  1904. Py_INCREF(ax);
  1905. PyObject *zlabel = PyObject_GetAttrString(ax, "set_zlabel");
  1906. if (!zlabel) throw std::runtime_error("Attribute set_zlabel not found.");
  1907. Py_INCREF(zlabel);
  1908. PyObject *res = PyObject_Call(zlabel, args, kwargs);
  1909. if (!res) throw std::runtime_error("Call to set_zlabel() failed.");
  1910. Py_DECREF(zlabel);
  1911. Py_DECREF(ax);
  1912. Py_DECREF(args);
  1913. Py_DECREF(kwargs);
  1914. if (res) Py_DECREF(res);
  1915. }
  1916. inline void grid(bool flag)
  1917. {
  1918. detail::_interpreter::get();
  1919. PyObject* pyflag = flag ? Py_True : Py_False;
  1920. Py_INCREF(pyflag);
  1921. PyObject* args = PyTuple_New(1);
  1922. PyTuple_SetItem(args, 0, pyflag);
  1923. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_grid, args);
  1924. if(!res) throw std::runtime_error("Call to grid() failed.");
  1925. Py_DECREF(args);
  1926. Py_DECREF(res);
  1927. }
  1928. inline void show(const bool block = true)
  1929. {
  1930. detail::_interpreter::get();
  1931. PyObject* res;
  1932. if(block)
  1933. {
  1934. res = PyObject_CallObject(
  1935. detail::_interpreter::get().s_python_function_show,
  1936. detail::_interpreter::get().s_python_empty_tuple);
  1937. }
  1938. else
  1939. {
  1940. PyObject *kwargs = PyDict_New();
  1941. PyDict_SetItemString(kwargs, "block", Py_False);
  1942. res = PyObject_Call( detail::_interpreter::get().s_python_function_show, detail::_interpreter::get().s_python_empty_tuple, kwargs);
  1943. Py_DECREF(kwargs);
  1944. }
  1945. if (!res) throw std::runtime_error("Call to show() failed.");
  1946. Py_DECREF(res);
  1947. }
  1948. inline void close()
  1949. {
  1950. detail::_interpreter::get();
  1951. PyObject* res = PyObject_CallObject(
  1952. detail::_interpreter::get().s_python_function_close,
  1953. detail::_interpreter::get().s_python_empty_tuple);
  1954. if (!res) throw std::runtime_error("Call to close() failed.");
  1955. Py_DECREF(res);
  1956. }
  1957. inline void xkcd() {
  1958. detail::_interpreter::get();
  1959. PyObject* res;
  1960. PyObject *kwargs = PyDict_New();
  1961. res = PyObject_Call(detail::_interpreter::get().s_python_function_xkcd,
  1962. detail::_interpreter::get().s_python_empty_tuple, kwargs);
  1963. Py_DECREF(kwargs);
  1964. if (!res)
  1965. throw std::runtime_error("Call to show() failed.");
  1966. Py_DECREF(res);
  1967. }
  1968. inline void draw()
  1969. {
  1970. detail::_interpreter::get();
  1971. PyObject* res = PyObject_CallObject(
  1972. detail::_interpreter::get().s_python_function_draw,
  1973. detail::_interpreter::get().s_python_empty_tuple);
  1974. if (!res) throw std::runtime_error("Call to draw() failed.");
  1975. Py_DECREF(res);
  1976. }
  1977. template<typename Numeric>
  1978. inline void pause(Numeric interval)
  1979. {
  1980. detail::_interpreter::get();
  1981. PyObject* args = PyTuple_New(1);
  1982. PyTuple_SetItem(args, 0, PyFloat_FromDouble(interval));
  1983. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_pause, args);
  1984. if(!res) throw std::runtime_error("Call to pause() failed.");
  1985. Py_DECREF(args);
  1986. Py_DECREF(res);
  1987. }
  1988. inline void save(const std::string& filename, const int dpi=0)
  1989. {
  1990. detail::_interpreter::get();
  1991. PyObject* pyfilename = PyString_FromString(filename.c_str());
  1992. PyObject* args = PyTuple_New(1);
  1993. PyTuple_SetItem(args, 0, pyfilename);
  1994. PyObject* kwargs = PyDict_New();
  1995. if(dpi > 0)
  1996. {
  1997. PyDict_SetItemString(kwargs, "dpi", PyLong_FromLong(dpi));
  1998. }
  1999. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_save, args, kwargs);
  2000. if (!res) throw std::runtime_error("Call to save() failed.");
  2001. Py_DECREF(args);
  2002. Py_DECREF(kwargs);
  2003. Py_DECREF(res);
  2004. }
  2005. inline void rcparams(const std::map<std::string, std::string>& keywords = {}) {
  2006. detail::_interpreter::get();
  2007. PyObject* args = PyTuple_New(0);
  2008. PyObject* kwargs = PyDict_New();
  2009. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  2010. if ("text.usetex" == it->first)
  2011. PyDict_SetItemString(kwargs, it->first.c_str(), PyLong_FromLong(std::stoi(it->second.c_str())));
  2012. else PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  2013. }
  2014. PyObject * update = PyObject_GetAttrString(detail::_interpreter::get().s_python_function_rcparams, "update");
  2015. PyObject * res = PyObject_Call(update, args, kwargs);
  2016. if(!res) throw std::runtime_error("Call to rcParams.update() failed.");
  2017. Py_DECREF(args);
  2018. Py_DECREF(kwargs);
  2019. Py_DECREF(update);
  2020. Py_DECREF(res);
  2021. }
  2022. inline void clf() {
  2023. detail::_interpreter::get();
  2024. PyObject *res = PyObject_CallObject(
  2025. detail::_interpreter::get().s_python_function_clf,
  2026. detail::_interpreter::get().s_python_empty_tuple);
  2027. if (!res) throw std::runtime_error("Call to clf() failed.");
  2028. Py_DECREF(res);
  2029. }
  2030. inline void cla() {
  2031. detail::_interpreter::get();
  2032. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_cla,
  2033. detail::_interpreter::get().s_python_empty_tuple);
  2034. if (!res)
  2035. throw std::runtime_error("Call to cla() failed.");
  2036. Py_DECREF(res);
  2037. }
  2038. inline void ion() {
  2039. detail::_interpreter::get();
  2040. PyObject *res = PyObject_CallObject(
  2041. detail::_interpreter::get().s_python_function_ion,
  2042. detail::_interpreter::get().s_python_empty_tuple);
  2043. if (!res) throw std::runtime_error("Call to ion() failed.");
  2044. Py_DECREF(res);
  2045. }
  2046. inline std::vector<std::array<double, 2>> ginput(const int numClicks = 1, const std::map<std::string, std::string>& keywords = {})
  2047. {
  2048. detail::_interpreter::get();
  2049. PyObject *args = PyTuple_New(1);
  2050. PyTuple_SetItem(args, 0, PyLong_FromLong(numClicks));
  2051. // construct keyword args
  2052. PyObject* kwargs = PyDict_New();
  2053. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  2054. {
  2055. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  2056. }
  2057. PyObject* res = PyObject_Call(
  2058. detail::_interpreter::get().s_python_function_ginput, args, kwargs);
  2059. Py_DECREF(kwargs);
  2060. Py_DECREF(args);
  2061. if (!res) throw std::runtime_error("Call to ginput() failed.");
  2062. const size_t len = PyList_Size(res);
  2063. std::vector<std::array<double, 2>> out;
  2064. out.reserve(len);
  2065. for (size_t i = 0; i < len; i++) {
  2066. PyObject *current = PyList_GetItem(res, i);
  2067. std::array<double, 2> position;
  2068. position[0] = PyFloat_AsDouble(PyTuple_GetItem(current, 0));
  2069. position[1] = PyFloat_AsDouble(PyTuple_GetItem(current, 1));
  2070. out.push_back(position);
  2071. }
  2072. Py_DECREF(res);
  2073. return out;
  2074. }
  2075. // Actually, is there any reason not to call this automatically for every plot?
  2076. inline void tight_layout() {
  2077. detail::_interpreter::get();
  2078. PyObject *res = PyObject_CallObject(
  2079. detail::_interpreter::get().s_python_function_tight_layout,
  2080. detail::_interpreter::get().s_python_empty_tuple);
  2081. if (!res) throw std::runtime_error("Call to tight_layout() failed.");
  2082. Py_DECREF(res);
  2083. }
  2084. // Support for variadic plot() and initializer lists:
  2085. namespace detail {
  2086. template<typename T>
  2087. using is_function = typename std::is_function<std::remove_pointer<std::remove_reference<T>>>::type;
  2088. template<bool obj, typename T>
  2089. struct is_callable_impl;
  2090. template<typename T>
  2091. struct is_callable_impl<false, T>
  2092. {
  2093. typedef is_function<T> type;
  2094. }; // a non-object is callable iff it is a function
  2095. template<typename T>
  2096. struct is_callable_impl<true, T>
  2097. {
  2098. struct Fallback { void operator()(); };
  2099. struct Derived : T, Fallback { };
  2100. template<typename U, U> struct Check;
  2101. template<typename U>
  2102. static std::true_type test( ... ); // use a variadic function to make sure (1) it accepts everything and (2) its always the worst match
  2103. template<typename U>
  2104. static std::false_type test( Check<void(Fallback::*)(), &U::operator()>* );
  2105. public:
  2106. typedef decltype(test<Derived>(nullptr)) type;
  2107. typedef decltype(&Fallback::operator()) dtype;
  2108. static constexpr bool value = type::value;
  2109. }; // an object is callable iff it defines operator()
  2110. template<typename T>
  2111. struct is_callable
  2112. {
  2113. // dispatch to is_callable_impl<true, T> or is_callable_impl<false, T> depending on whether T is of class type or not
  2114. typedef typename is_callable_impl<std::is_class<T>::value, T>::type type;
  2115. };
  2116. template<typename IsYDataCallable>
  2117. struct plot_impl { };
  2118. template<>
  2119. struct plot_impl<std::false_type>
  2120. {
  2121. template<typename IterableX, typename IterableY>
  2122. bool operator()(const IterableX& x, const IterableY& y, const std::string& format)
  2123. {
  2124. detail::_interpreter::get();
  2125. // 2-phase lookup for distance, begin, end
  2126. using std::distance;
  2127. using std::begin;
  2128. using std::end;
  2129. auto xs = distance(begin(x), end(x));
  2130. auto ys = distance(begin(y), end(y));
  2131. assert(xs == ys && "x and y data must have the same number of elements!");
  2132. PyObject* xlist = PyList_New(xs);
  2133. PyObject* ylist = PyList_New(ys);
  2134. PyObject* pystring = PyString_FromString(format.c_str());
  2135. auto itx = begin(x), ity = begin(y);
  2136. for(size_t i = 0; i < xs; ++i) {
  2137. PyList_SetItem(xlist, i, PyFloat_FromDouble(*itx++));
  2138. PyList_SetItem(ylist, i, PyFloat_FromDouble(*ity++));
  2139. }
  2140. PyObject* plot_args = PyTuple_New(3);
  2141. PyTuple_SetItem(plot_args, 0, xlist);
  2142. PyTuple_SetItem(plot_args, 1, ylist);
  2143. PyTuple_SetItem(plot_args, 2, pystring);
  2144. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);
  2145. Py_DECREF(plot_args);
  2146. if(res) Py_DECREF(res);
  2147. return res;
  2148. }
  2149. };
  2150. template<>
  2151. struct plot_impl<std::true_type>
  2152. {
  2153. template<typename Iterable, typename Callable>
  2154. bool operator()(const Iterable& ticks, const Callable& f, const std::string& format)
  2155. {
  2156. if(begin(ticks) == end(ticks)) return true;
  2157. // We could use additional meta-programming to deduce the correct element type of y,
  2158. // but all values have to be convertible to double anyways
  2159. std::vector<double> y;
  2160. for(auto x : ticks) y.push_back(f(x));
  2161. return plot_impl<std::false_type>()(ticks,y,format);
  2162. }
  2163. };
  2164. } // end namespace detail
  2165. // recursion stop for the above
  2166. template<typename... Args>
  2167. bool plot() { return true; }
  2168. template<typename A, typename B, typename... Args>
  2169. bool plot(const A& a, const B& b, const std::string& format, Args... args)
  2170. {
  2171. return detail::plot_impl<typename detail::is_callable<B>::type>()(a,b,format) && plot(args...);
  2172. }
  2173. /*
  2174. * This group of plot() functions is needed to support initializer lists, i.e. calling
  2175. * plot( {1,2,3,4} )
  2176. */
  2177. inline bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::string& format = "") {
  2178. return plot<double,double>(x,y,format);
  2179. }
  2180. inline bool plot(const std::vector<double>& y, const std::string& format = "") {
  2181. return plot<double>(y,format);
  2182. }
  2183. inline bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::map<std::string, std::string>& keywords) {
  2184. return plot<double>(x,y,keywords);
  2185. }
  2186. /*
  2187. * This class allows dynamic plots, ie changing the plotted data without clearing and re-plotting
  2188. */
  2189. class Plot
  2190. {
  2191. public:
  2192. // default initialization with plot label, some data and format
  2193. template<typename Numeric>
  2194. Plot(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "") {
  2195. detail::_interpreter::get();
  2196. assert(x.size() == y.size());
  2197. PyObject* kwargs = PyDict_New();
  2198. if(name != "")
  2199. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  2200. PyObject* xarray = detail::get_array(x);
  2201. PyObject* yarray = detail::get_array(y);
  2202. PyObject* pystring = PyString_FromString(format.c_str());
  2203. PyObject* plot_args = PyTuple_New(3);
  2204. PyTuple_SetItem(plot_args, 0, xarray);
  2205. PyTuple_SetItem(plot_args, 1, yarray);
  2206. PyTuple_SetItem(plot_args, 2, pystring);
  2207. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
  2208. Py_DECREF(kwargs);
  2209. Py_DECREF(plot_args);
  2210. if(res)
  2211. {
  2212. line= PyList_GetItem(res, 0);
  2213. if(line)
  2214. set_data_fct = PyObject_GetAttrString(line,"set_data");
  2215. else
  2216. Py_DECREF(line);
  2217. Py_DECREF(res);
  2218. }
  2219. }
  2220. // shorter initialization with name or format only
  2221. // basically calls line, = plot([], [])
  2222. Plot(const std::string& name = "", const std::string& format = "")
  2223. : Plot(name, std::vector<double>(), std::vector<double>(), format) {}
  2224. template<typename Numeric>
  2225. bool update(const std::vector<Numeric>& x, const std::vector<Numeric>& y) {
  2226. assert(x.size() == y.size());
  2227. if(set_data_fct)
  2228. {
  2229. PyObject* xarray = detail::get_array(x);
  2230. PyObject* yarray = detail::get_array(y);
  2231. PyObject* plot_args = PyTuple_New(2);
  2232. PyTuple_SetItem(plot_args, 0, xarray);
  2233. PyTuple_SetItem(plot_args, 1, yarray);
  2234. PyObject* res = PyObject_CallObject(set_data_fct, plot_args);
  2235. if (res) Py_DECREF(res);
  2236. return res;
  2237. }
  2238. return false;
  2239. }
  2240. // clears the plot but keep it available
  2241. bool clear() {
  2242. return update(std::vector<double>(), std::vector<double>());
  2243. }
  2244. // definitely remove this line
  2245. void remove() {
  2246. if(line)
  2247. {
  2248. auto remove_fct = PyObject_GetAttrString(line,"remove");
  2249. PyObject* args = PyTuple_New(0);
  2250. PyObject* res = PyObject_CallObject(remove_fct, args);
  2251. if (res) Py_DECREF(res);
  2252. }
  2253. decref();
  2254. }
  2255. ~Plot() {
  2256. decref();
  2257. }
  2258. private:
  2259. void decref() {
  2260. if(line)
  2261. Py_DECREF(line);
  2262. if(set_data_fct)
  2263. Py_DECREF(set_data_fct);
  2264. }
  2265. PyObject* line = nullptr;
  2266. PyObject* set_data_fct = nullptr;
  2267. };
  2268. } // end namespace matplotlibcpp