matplotlibcpp.h 97 KB

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