matplotlibcpp.h 96 KB

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