matplotlibcpp.h 91 KB

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