matplotlibcpp.h 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. #pragma once
  2. #include <vector>
  3. #include <map>
  4. #include <numeric>
  5. #include <algorithm>
  6. #include <stdexcept>
  7. #include <iostream>
  8. #include <cstdint> // <cstdint> requires c++11 support
  9. #include <functional>
  10. #include <Python.h>
  11. #ifndef WITHOUT_NUMPY
  12. # define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
  13. # include <numpy/arrayobject.h>
  14. #endif // WITHOUT_NUMPY
  15. #if PY_MAJOR_VERSION >= 3
  16. # define PyString_FromString PyUnicode_FromString
  17. #endif
  18. namespace matplotlibcpp {
  19. namespace detail {
  20. static std::string s_backend;
  21. struct _interpreter {
  22. PyObject *s_python_function_show;
  23. PyObject *s_python_function_close;
  24. PyObject *s_python_function_draw;
  25. PyObject *s_python_function_pause;
  26. PyObject *s_python_function_save;
  27. PyObject *s_python_function_figure;
  28. PyObject *s_python_function_fignum_exists;
  29. PyObject *s_python_function_plot;
  30. PyObject *s_python_function_quiver;
  31. PyObject *s_python_function_semilogx;
  32. PyObject *s_python_function_semilogy;
  33. PyObject *s_python_function_loglog;
  34. PyObject *s_python_function_fill;
  35. PyObject *s_python_function_fill_between;
  36. PyObject *s_python_function_hist;
  37. PyObject *s_python_function_scatter;
  38. PyObject *s_python_function_subplot;
  39. PyObject *s_python_function_legend;
  40. PyObject *s_python_function_xlim;
  41. PyObject *s_python_function_ion;
  42. PyObject *s_python_function_ginput;
  43. PyObject *s_python_function_ylim;
  44. PyObject *s_python_function_title;
  45. PyObject *s_python_function_axis;
  46. PyObject *s_python_function_xlabel;
  47. PyObject *s_python_function_ylabel;
  48. PyObject *s_python_function_xticks;
  49. PyObject *s_python_function_yticks;
  50. PyObject *s_python_function_grid;
  51. PyObject *s_python_function_clf;
  52. PyObject *s_python_function_errorbar;
  53. PyObject *s_python_function_annotate;
  54. PyObject *s_python_function_tight_layout;
  55. PyObject *s_python_colormap;
  56. PyObject *s_python_empty_tuple;
  57. PyObject *s_python_function_stem;
  58. PyObject *s_python_function_xkcd;
  59. PyObject *s_python_function_text;
  60. PyObject *s_python_function_suptitle;
  61. PyObject *s_python_function_bar;
  62. PyObject *s_python_function_subplots_adjust;
  63. /* For now, _interpreter is implemented as a singleton since its currently not possible to have
  64. multiple independent embedded python interpreters without patching the python source code
  65. or starting a separate process for each.
  66. http://bytes.com/topic/python/answers/793370-multiple-independent-python-interpreters-c-c-program
  67. */
  68. static _interpreter& get() {
  69. static _interpreter ctx;
  70. return ctx;
  71. }
  72. private:
  73. #ifndef WITHOUT_NUMPY
  74. # if PY_MAJOR_VERSION >= 3
  75. void *import_numpy() {
  76. import_array(); // initialize C-API
  77. return NULL;
  78. }
  79. # else
  80. void import_numpy() {
  81. import_array(); // initialize C-API
  82. }
  83. # endif
  84. #endif
  85. _interpreter() {
  86. // optional but recommended
  87. #if PY_MAJOR_VERSION >= 3
  88. wchar_t name[] = L"plotting";
  89. #else
  90. char name[] = "plotting";
  91. #endif
  92. Py_SetProgramName(name);
  93. Py_Initialize();
  94. #ifndef WITHOUT_NUMPY
  95. import_numpy(); // initialize numpy C-API
  96. #endif
  97. PyObject* matplotlibname = PyString_FromString("matplotlib");
  98. PyObject* pyplotname = PyString_FromString("matplotlib.pyplot");
  99. PyObject* cmname = PyString_FromString("matplotlib.cm");
  100. PyObject* pylabname = PyString_FromString("pylab");
  101. if (!pyplotname || !pylabname || !matplotlibname || !cmname) {
  102. throw std::runtime_error("couldnt create string");
  103. }
  104. PyObject* matplotlib = PyImport_Import(matplotlibname);
  105. Py_DECREF(matplotlibname);
  106. if (!matplotlib) { throw std::runtime_error("Error loading module matplotlib!"); }
  107. // matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  108. // or matplotlib.backends is imported for the first time
  109. if (!s_backend.empty()) {
  110. PyObject_CallMethod(matplotlib, const_cast<char*>("use"), const_cast<char*>("s"), s_backend.c_str());
  111. }
  112. PyObject* pymod = PyImport_Import(pyplotname);
  113. Py_DECREF(pyplotname);
  114. if (!pymod) { throw std::runtime_error("Error loading module matplotlib.pyplot!"); }
  115. s_python_colormap = PyImport_Import(cmname);
  116. Py_DECREF(cmname);
  117. if (!s_python_colormap) { throw std::runtime_error("Error loading module matplotlib.cm!"); }
  118. PyObject* pylabmod = PyImport_Import(pylabname);
  119. Py_DECREF(pylabname);
  120. if (!pylabmod) { throw std::runtime_error("Error loading module pylab!"); }
  121. s_python_function_show = PyObject_GetAttrString(pymod, "show");
  122. s_python_function_close = PyObject_GetAttrString(pymod, "close");
  123. s_python_function_draw = PyObject_GetAttrString(pymod, "draw");
  124. s_python_function_pause = PyObject_GetAttrString(pymod, "pause");
  125. s_python_function_figure = PyObject_GetAttrString(pymod, "figure");
  126. s_python_function_fignum_exists = PyObject_GetAttrString(pymod, "fignum_exists");
  127. s_python_function_plot = PyObject_GetAttrString(pymod, "plot");
  128. s_python_function_quiver = PyObject_GetAttrString(pymod, "quiver");
  129. s_python_function_semilogx = PyObject_GetAttrString(pymod, "semilogx");
  130. s_python_function_semilogy = PyObject_GetAttrString(pymod, "semilogy");
  131. s_python_function_loglog = PyObject_GetAttrString(pymod, "loglog");
  132. s_python_function_fill = PyObject_GetAttrString(pymod, "fill");
  133. s_python_function_fill_between = PyObject_GetAttrString(pymod, "fill_between");
  134. s_python_function_hist = PyObject_GetAttrString(pymod,"hist");
  135. s_python_function_scatter = PyObject_GetAttrString(pymod,"scatter");
  136. s_python_function_subplot = PyObject_GetAttrString(pymod, "subplot");
  137. s_python_function_legend = PyObject_GetAttrString(pymod, "legend");
  138. s_python_function_ylim = PyObject_GetAttrString(pymod, "ylim");
  139. s_python_function_title = PyObject_GetAttrString(pymod, "title");
  140. s_python_function_axis = PyObject_GetAttrString(pymod, "axis");
  141. s_python_function_xlabel = PyObject_GetAttrString(pymod, "xlabel");
  142. s_python_function_ylabel = PyObject_GetAttrString(pymod, "ylabel");
  143. s_python_function_xticks = PyObject_GetAttrString(pymod, "xticks");
  144. s_python_function_yticks = PyObject_GetAttrString(pymod, "yticks");
  145. s_python_function_grid = PyObject_GetAttrString(pymod, "grid");
  146. s_python_function_xlim = PyObject_GetAttrString(pymod, "xlim");
  147. s_python_function_ion = PyObject_GetAttrString(pymod, "ion");
  148. s_python_function_ginput = PyObject_GetAttrString(pymod, "ginput");
  149. s_python_function_save = PyObject_GetAttrString(pylabmod, "savefig");
  150. s_python_function_annotate = PyObject_GetAttrString(pymod,"annotate");
  151. s_python_function_clf = PyObject_GetAttrString(pymod, "clf");
  152. s_python_function_errorbar = PyObject_GetAttrString(pymod, "errorbar");
  153. s_python_function_tight_layout = PyObject_GetAttrString(pymod, "tight_layout");
  154. s_python_function_stem = PyObject_GetAttrString(pymod, "stem");
  155. s_python_function_xkcd = PyObject_GetAttrString(pymod, "xkcd");
  156. s_python_function_text = PyObject_GetAttrString(pymod, "text");
  157. s_python_function_suptitle = PyObject_GetAttrString(pymod, "suptitle");
  158. s_python_function_bar = PyObject_GetAttrString(pymod,"bar");
  159. s_python_function_subplots_adjust = PyObject_GetAttrString(pymod,"subplots_adjust");
  160. if( !s_python_function_show
  161. || !s_python_function_close
  162. || !s_python_function_draw
  163. || !s_python_function_pause
  164. || !s_python_function_figure
  165. || !s_python_function_fignum_exists
  166. || !s_python_function_plot
  167. || !s_python_function_quiver
  168. || !s_python_function_semilogx
  169. || !s_python_function_semilogy
  170. || !s_python_function_loglog
  171. || !s_python_function_fill
  172. || !s_python_function_fill_between
  173. || !s_python_function_subplot
  174. || !s_python_function_legend
  175. || !s_python_function_ylim
  176. || !s_python_function_title
  177. || !s_python_function_axis
  178. || !s_python_function_xlabel
  179. || !s_python_function_ylabel
  180. || !s_python_function_grid
  181. || !s_python_function_xlim
  182. || !s_python_function_ion
  183. || !s_python_function_ginput
  184. || !s_python_function_save
  185. || !s_python_function_clf
  186. || !s_python_function_annotate
  187. || !s_python_function_errorbar
  188. || !s_python_function_errorbar
  189. || !s_python_function_tight_layout
  190. || !s_python_function_stem
  191. || !s_python_function_xkcd
  192. || !s_python_function_text
  193. || !s_python_function_suptitle
  194. || !s_python_function_bar
  195. || !s_python_function_subplots_adjust
  196. ) { throw std::runtime_error("Couldn't find required function!"); }
  197. if ( !PyFunction_Check(s_python_function_show)
  198. || !PyFunction_Check(s_python_function_close)
  199. || !PyFunction_Check(s_python_function_draw)
  200. || !PyFunction_Check(s_python_function_pause)
  201. || !PyFunction_Check(s_python_function_figure)
  202. || !PyFunction_Check(s_python_function_fignum_exists)
  203. || !PyFunction_Check(s_python_function_plot)
  204. || !PyFunction_Check(s_python_function_quiver)
  205. || !PyFunction_Check(s_python_function_semilogx)
  206. || !PyFunction_Check(s_python_function_semilogy)
  207. || !PyFunction_Check(s_python_function_loglog)
  208. || !PyFunction_Check(s_python_function_fill)
  209. || !PyFunction_Check(s_python_function_fill_between)
  210. || !PyFunction_Check(s_python_function_subplot)
  211. || !PyFunction_Check(s_python_function_legend)
  212. || !PyFunction_Check(s_python_function_annotate)
  213. || !PyFunction_Check(s_python_function_ylim)
  214. || !PyFunction_Check(s_python_function_title)
  215. || !PyFunction_Check(s_python_function_axis)
  216. || !PyFunction_Check(s_python_function_xlabel)
  217. || !PyFunction_Check(s_python_function_ylabel)
  218. || !PyFunction_Check(s_python_function_grid)
  219. || !PyFunction_Check(s_python_function_xlim)
  220. || !PyFunction_Check(s_python_function_ion)
  221. || !PyFunction_Check(s_python_function_ginput)
  222. || !PyFunction_Check(s_python_function_save)
  223. || !PyFunction_Check(s_python_function_clf)
  224. || !PyFunction_Check(s_python_function_tight_layout)
  225. || !PyFunction_Check(s_python_function_errorbar)
  226. || !PyFunction_Check(s_python_function_stem)
  227. || !PyFunction_Check(s_python_function_xkcd)
  228. || !PyFunction_Check(s_python_function_text)
  229. || !PyFunction_Check(s_python_function_suptitle)
  230. || !PyFunction_Check(s_python_function_bar)
  231. || !PyFunction_Check(s_python_function_subplots_adjust)
  232. ) { throw std::runtime_error("Python object is unexpectedly not a PyFunction."); }
  233. s_python_empty_tuple = PyTuple_New(0);
  234. }
  235. ~_interpreter() {
  236. Py_Finalize();
  237. }
  238. };
  239. } // end namespace detail
  240. // must be called before the first regular call to matplotlib to have any effect
  241. inline void backend(const std::string& name)
  242. {
  243. detail::s_backend = name;
  244. }
  245. inline bool annotate(std::string annotation, double x, double y)
  246. {
  247. PyObject * xy = PyTuple_New(2);
  248. PyObject * str = PyString_FromString(annotation.c_str());
  249. PyTuple_SetItem(xy,0,PyFloat_FromDouble(x));
  250. PyTuple_SetItem(xy,1,PyFloat_FromDouble(y));
  251. PyObject* kwargs = PyDict_New();
  252. PyDict_SetItemString(kwargs, "xy", xy);
  253. PyObject* args = PyTuple_New(1);
  254. PyTuple_SetItem(args, 0, str);
  255. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_annotate, args, kwargs);
  256. Py_DECREF(args);
  257. Py_DECREF(kwargs);
  258. if(res) Py_DECREF(res);
  259. return res;
  260. }
  261. #ifndef WITHOUT_NUMPY
  262. // Type selector for numpy array conversion
  263. template <typename T> struct select_npy_type { const static NPY_TYPES type = NPY_NOTYPE; }; //Default
  264. template <> struct select_npy_type<double> { const static NPY_TYPES type = NPY_DOUBLE; };
  265. template <> struct select_npy_type<float> { const static NPY_TYPES type = NPY_FLOAT; };
  266. template <> struct select_npy_type<bool> { const static NPY_TYPES type = NPY_BOOL; };
  267. template <> struct select_npy_type<int8_t> { const static NPY_TYPES type = NPY_INT8; };
  268. template <> struct select_npy_type<int16_t> { const static NPY_TYPES type = NPY_SHORT; };
  269. template <> struct select_npy_type<int32_t> { const static NPY_TYPES type = NPY_INT; };
  270. template <> struct select_npy_type<int64_t> { const static NPY_TYPES type = NPY_INT64; };
  271. template <> struct select_npy_type<uint8_t> { const static NPY_TYPES type = NPY_UINT8; };
  272. template <> struct select_npy_type<uint16_t> { const static NPY_TYPES type = NPY_USHORT; };
  273. template <> struct select_npy_type<uint32_t> { const static NPY_TYPES type = NPY_ULONG; };
  274. template <> struct select_npy_type<uint64_t> { const static NPY_TYPES type = NPY_UINT64; };
  275. template<typename Numeric>
  276. PyObject* get_array(const std::vector<Numeric>& v)
  277. {
  278. detail::_interpreter::get(); //interpreter needs to be initialized for the numpy commands to work
  279. NPY_TYPES type = select_npy_type<Numeric>::type;
  280. if (type == NPY_NOTYPE)
  281. {
  282. std::vector<double> vd(v.size());
  283. npy_intp vsize = v.size();
  284. std::copy(v.begin(),v.end(),vd.begin());
  285. PyObject* varray = PyArray_SimpleNewFromData(1, &vsize, NPY_DOUBLE, (void*)(vd.data()));
  286. return varray;
  287. }
  288. npy_intp vsize = v.size();
  289. PyObject* varray = PyArray_SimpleNewFromData(1, &vsize, type, (void*)(v.data()));
  290. return varray;
  291. }
  292. template<typename Numeric>
  293. PyObject* get_2darray(const std::vector<::std::vector<Numeric>>& v)
  294. {
  295. detail::_interpreter::get(); //interpreter needs to be initialized for the numpy commands to work
  296. if (v.size() < 1) throw std::runtime_error("get_2d_array v too small");
  297. npy_intp vsize[2] = {static_cast<npy_intp>(v.size()),
  298. static_cast<npy_intp>(v[0].size())};
  299. PyArrayObject *varray =
  300. (PyArrayObject *)PyArray_SimpleNew(2, vsize, NPY_DOUBLE);
  301. double *vd_begin = static_cast<double *>(PyArray_DATA(varray));
  302. for (const ::std::vector<Numeric> &v_row : v) {
  303. if (v_row.size() != static_cast<size_t>(vsize[1]))
  304. throw std::runtime_error("Missmatched array size");
  305. std::copy(v_row.begin(), v_row.end(), vd_begin);
  306. vd_begin += vsize[1];
  307. }
  308. return reinterpret_cast<PyObject *>(varray);
  309. }
  310. #else // fallback if we don't have numpy: copy every element of the given vector
  311. template<typename Numeric>
  312. PyObject* get_array(const std::vector<Numeric>& v)
  313. {
  314. PyObject* list = PyList_New(v.size());
  315. for(size_t i = 0; i < v.size(); ++i) {
  316. PyList_SetItem(list, i, PyFloat_FromDouble(v.at(i)));
  317. }
  318. return list;
  319. }
  320. #endif // WITHOUT_NUMPY
  321. template<typename Numeric>
  322. bool plot(const std::vector<Numeric> &x, const std::vector<Numeric> &y, const std::map<std::string, std::string>& keywords)
  323. {
  324. assert(x.size() == y.size());
  325. // using numpy arrays
  326. PyObject* xarray = get_array(x);
  327. PyObject* yarray = get_array(y);
  328. // construct positional args
  329. PyObject* args = PyTuple_New(2);
  330. PyTuple_SetItem(args, 0, xarray);
  331. PyTuple_SetItem(args, 1, yarray);
  332. // construct keyword args
  333. PyObject* kwargs = PyDict_New();
  334. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  335. {
  336. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  337. }
  338. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, args, kwargs);
  339. Py_DECREF(args);
  340. Py_DECREF(kwargs);
  341. if(res) Py_DECREF(res);
  342. return res;
  343. }
  344. template <typename Numeric>
  345. void plot_surface(const std::vector<::std::vector<Numeric>> &x,
  346. const std::vector<::std::vector<Numeric>> &y,
  347. const std::vector<::std::vector<Numeric>> &z,
  348. const std::map<std::string, std::string> &keywords =
  349. std::map<std::string, std::string>())
  350. {
  351. // We lazily load the modules here the first time this function is called
  352. // because I'm not sure that we can assume "matplotlib installed" implies
  353. // "mpl_toolkits installed" on all platforms, and we don't want to require
  354. // it for people who don't need 3d plots.
  355. static PyObject *mpl_toolkitsmod = nullptr, *axis3dmod = nullptr;
  356. if (!mpl_toolkitsmod) {
  357. detail::_interpreter::get();
  358. PyObject* mpl_toolkits = PyString_FromString("mpl_toolkits");
  359. PyObject* axis3d = PyString_FromString("mpl_toolkits.mplot3d");
  360. if (!mpl_toolkits || !axis3d) { throw std::runtime_error("couldnt create string"); }
  361. mpl_toolkitsmod = PyImport_Import(mpl_toolkits);
  362. Py_DECREF(mpl_toolkits);
  363. if (!mpl_toolkitsmod) { throw std::runtime_error("Error loading module mpl_toolkits!"); }
  364. axis3dmod = PyImport_Import(axis3d);
  365. Py_DECREF(axis3d);
  366. if (!axis3dmod) { throw std::runtime_error("Error loading module mpl_toolkits.mplot3d!"); }
  367. }
  368. assert(x.size() == y.size());
  369. assert(y.size() == z.size());
  370. // using numpy arrays
  371. PyObject *xarray = get_2darray(x);
  372. PyObject *yarray = get_2darray(y);
  373. PyObject *zarray = get_2darray(z);
  374. // construct positional args
  375. PyObject *args = PyTuple_New(3);
  376. PyTuple_SetItem(args, 0, xarray);
  377. PyTuple_SetItem(args, 1, yarray);
  378. PyTuple_SetItem(args, 2, zarray);
  379. // Build up the kw args.
  380. PyObject *kwargs = PyDict_New();
  381. PyDict_SetItemString(kwargs, "rstride", PyInt_FromLong(1));
  382. PyDict_SetItemString(kwargs, "cstride", PyInt_FromLong(1));
  383. PyObject *python_colormap_coolwarm = PyObject_GetAttrString(
  384. detail::_interpreter::get().s_python_colormap, "coolwarm");
  385. PyDict_SetItemString(kwargs, "cmap", python_colormap_coolwarm);
  386. for (std::map<std::string, std::string>::const_iterator it = keywords.begin();
  387. it != keywords.end(); ++it) {
  388. PyDict_SetItemString(kwargs, it->first.c_str(),
  389. PyString_FromString(it->second.c_str()));
  390. }
  391. PyObject *fig =
  392. PyObject_CallObject(detail::_interpreter::get().s_python_function_figure,
  393. detail::_interpreter::get().s_python_empty_tuple);
  394. if (!fig) throw std::runtime_error("Call to figure() failed.");
  395. PyObject *gca_kwargs = PyDict_New();
  396. PyDict_SetItemString(gca_kwargs, "projection", PyString_FromString("3d"));
  397. PyObject *gca = PyObject_GetAttrString(fig, "gca");
  398. if (!gca) throw std::runtime_error("No gca");
  399. Py_INCREF(gca);
  400. PyObject *axis = PyObject_Call(
  401. gca, detail::_interpreter::get().s_python_empty_tuple, gca_kwargs);
  402. if (!axis) throw std::runtime_error("No axis");
  403. Py_INCREF(axis);
  404. Py_DECREF(gca);
  405. Py_DECREF(gca_kwargs);
  406. PyObject *plot_surface = PyObject_GetAttrString(axis, "plot_surface");
  407. if (!plot_surface) throw std::runtime_error("No surface");
  408. Py_INCREF(plot_surface);
  409. PyObject *res = PyObject_Call(plot_surface, args, kwargs);
  410. if (!res) throw std::runtime_error("failed surface");
  411. Py_DECREF(plot_surface);
  412. Py_DECREF(axis);
  413. Py_DECREF(args);
  414. Py_DECREF(kwargs);
  415. if (res) Py_DECREF(res);
  416. }
  417. template<typename Numeric>
  418. bool stem(const std::vector<Numeric> &x, const std::vector<Numeric> &y, const std::map<std::string, std::string>& keywords)
  419. {
  420. assert(x.size() == y.size());
  421. // using numpy arrays
  422. PyObject* xarray = get_array(x);
  423. PyObject* yarray = get_array(y);
  424. // construct positional args
  425. PyObject* args = PyTuple_New(2);
  426. PyTuple_SetItem(args, 0, xarray);
  427. PyTuple_SetItem(args, 1, yarray);
  428. // construct keyword args
  429. PyObject* kwargs = PyDict_New();
  430. for (std::map<std::string, std::string>::const_iterator it =
  431. keywords.begin(); it != keywords.end(); ++it) {
  432. PyDict_SetItemString(kwargs, it->first.c_str(),
  433. PyString_FromString(it->second.c_str()));
  434. }
  435. PyObject* res = PyObject_Call(
  436. detail::_interpreter::get().s_python_function_stem, args, kwargs);
  437. Py_DECREF(args);
  438. Py_DECREF(kwargs);
  439. if (res)
  440. Py_DECREF(res);
  441. return res;
  442. }
  443. template< typename Numeric >
  444. bool fill(const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::map<std::string, std::string>& keywords)
  445. {
  446. assert(x.size() == y.size());
  447. // using numpy arrays
  448. PyObject* xarray = get_array(x);
  449. PyObject* yarray = get_array(y);
  450. // construct positional args
  451. PyObject* args = PyTuple_New(2);
  452. PyTuple_SetItem(args, 0, xarray);
  453. PyTuple_SetItem(args, 1, yarray);
  454. // construct keyword args
  455. PyObject* kwargs = PyDict_New();
  456. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  457. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  458. }
  459. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_fill, args, kwargs);
  460. Py_DECREF(args);
  461. Py_DECREF(kwargs);
  462. if (res) Py_DECREF(res);
  463. return res;
  464. }
  465. template< typename Numeric >
  466. 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)
  467. {
  468. assert(x.size() == y1.size());
  469. assert(x.size() == y2.size());
  470. // using numpy arrays
  471. PyObject* xarray = get_array(x);
  472. PyObject* y1array = get_array(y1);
  473. PyObject* y2array = get_array(y2);
  474. // construct positional args
  475. PyObject* args = PyTuple_New(3);
  476. PyTuple_SetItem(args, 0, xarray);
  477. PyTuple_SetItem(args, 1, y1array);
  478. PyTuple_SetItem(args, 2, y2array);
  479. // construct keyword args
  480. PyObject* kwargs = PyDict_New();
  481. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it) {
  482. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  483. }
  484. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_fill_between, args, kwargs);
  485. Py_DECREF(args);
  486. Py_DECREF(kwargs);
  487. if(res) Py_DECREF(res);
  488. return res;
  489. }
  490. template< typename Numeric>
  491. bool hist(const std::vector<Numeric>& y, long bins=10,std::string color="b", double alpha=1.0)
  492. {
  493. PyObject* yarray = get_array(y);
  494. PyObject* kwargs = PyDict_New();
  495. PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins));
  496. PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str()));
  497. PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha));
  498. PyObject* plot_args = PyTuple_New(1);
  499. PyTuple_SetItem(plot_args, 0, yarray);
  500. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);
  501. Py_DECREF(plot_args);
  502. Py_DECREF(kwargs);
  503. if(res) Py_DECREF(res);
  504. return res;
  505. }
  506. template<typename NumericX, typename NumericY>
  507. bool scatter(const std::vector<NumericX>& x,
  508. const std::vector<NumericY>& y,
  509. const double s=1.0) // The marker size in points**2
  510. {
  511. assert(x.size() == y.size());
  512. PyObject* xarray = get_array(x);
  513. PyObject* yarray = get_array(y);
  514. PyObject* kwargs = PyDict_New();
  515. PyDict_SetItemString(kwargs, "s", PyLong_FromLong(s));
  516. PyObject* plot_args = PyTuple_New(2);
  517. PyTuple_SetItem(plot_args, 0, xarray);
  518. PyTuple_SetItem(plot_args, 1, yarray);
  519. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_scatter, plot_args, kwargs);
  520. Py_DECREF(plot_args);
  521. Py_DECREF(kwargs);
  522. if(res) Py_DECREF(res);
  523. return res;
  524. }
  525. template< typename Numeric>
  526. bool bar(const std::vector<Numeric>& y, std::string ec = "black", std::string ls = "-", double lw = 1.0,
  527. const std::map<std::string, std::string>& keywords = {})
  528. {
  529. PyObject* yarray = get_array(y);
  530. std::vector<int> x;
  531. for (int i = 0; i < y.size(); i++)
  532. x.push_back(i);
  533. PyObject* xarray = get_array(x);
  534. PyObject* kwargs = PyDict_New();
  535. PyDict_SetItemString(kwargs, "ec", PyString_FromString(ec.c_str()));
  536. PyDict_SetItemString(kwargs, "ls", PyString_FromString(ls.c_str()));
  537. PyDict_SetItemString(kwargs, "lw", PyFloat_FromDouble(lw));
  538. PyObject* plot_args = PyTuple_New(2);
  539. PyTuple_SetItem(plot_args, 0, xarray);
  540. PyTuple_SetItem(plot_args, 1, yarray);
  541. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_bar, plot_args, kwargs);
  542. Py_DECREF(plot_args);
  543. Py_DECREF(kwargs);
  544. if(res) Py_DECREF(res);
  545. return res;
  546. }
  547. inline bool subplots_adjust(const std::map<std::string, double>& keywords = {})
  548. {
  549. PyObject* kwargs = PyDict_New();
  550. for (std::map<std::string, double>::const_iterator it =
  551. keywords.begin(); it != keywords.end(); ++it) {
  552. PyDict_SetItemString(kwargs, it->first.c_str(),
  553. PyFloat_FromDouble(it->second));
  554. }
  555. PyObject* plot_args = PyTuple_New(0);
  556. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_subplots_adjust, plot_args, kwargs);
  557. Py_DECREF(plot_args);
  558. Py_DECREF(kwargs);
  559. if(res) Py_DECREF(res);
  560. return res;
  561. }
  562. template< typename Numeric>
  563. bool named_hist(std::string label,const std::vector<Numeric>& y, long bins=10, std::string color="b", double alpha=1.0)
  564. {
  565. PyObject* yarray = get_array(y);
  566. PyObject* kwargs = PyDict_New();
  567. PyDict_SetItemString(kwargs, "label", PyString_FromString(label.c_str()));
  568. PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins));
  569. PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str()));
  570. PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha));
  571. PyObject* plot_args = PyTuple_New(1);
  572. PyTuple_SetItem(plot_args, 0, yarray);
  573. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);
  574. Py_DECREF(plot_args);
  575. Py_DECREF(kwargs);
  576. if(res) Py_DECREF(res);
  577. return res;
  578. }
  579. template<typename NumericX, typename NumericY>
  580. bool plot(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  581. {
  582. assert(x.size() == y.size());
  583. PyObject* xarray = get_array(x);
  584. PyObject* yarray = get_array(y);
  585. PyObject* pystring = PyString_FromString(s.c_str());
  586. PyObject* plot_args = PyTuple_New(3);
  587. PyTuple_SetItem(plot_args, 0, xarray);
  588. PyTuple_SetItem(plot_args, 1, yarray);
  589. PyTuple_SetItem(plot_args, 2, pystring);
  590. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);
  591. Py_DECREF(plot_args);
  592. if(res) Py_DECREF(res);
  593. return res;
  594. }
  595. template<typename NumericX, typename NumericY, typename NumericU, typename NumericW>
  596. 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 = {})
  597. {
  598. assert(x.size() == y.size() && x.size() == u.size() && u.size() == w.size());
  599. PyObject* xarray = get_array(x);
  600. PyObject* yarray = get_array(y);
  601. PyObject* uarray = get_array(u);
  602. PyObject* warray = get_array(w);
  603. PyObject* plot_args = PyTuple_New(4);
  604. PyTuple_SetItem(plot_args, 0, xarray);
  605. PyTuple_SetItem(plot_args, 1, yarray);
  606. PyTuple_SetItem(plot_args, 2, uarray);
  607. PyTuple_SetItem(plot_args, 3, warray);
  608. // construct keyword args
  609. PyObject* kwargs = PyDict_New();
  610. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  611. {
  612. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  613. }
  614. PyObject* res = PyObject_Call(
  615. detail::_interpreter::get().s_python_function_quiver, plot_args, kwargs);
  616. Py_DECREF(kwargs);
  617. Py_DECREF(plot_args);
  618. if (res)
  619. Py_DECREF(res);
  620. return res;
  621. }
  622. template<typename NumericX, typename NumericY>
  623. bool stem(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  624. {
  625. assert(x.size() == y.size());
  626. PyObject* xarray = get_array(x);
  627. PyObject* yarray = get_array(y);
  628. PyObject* pystring = PyString_FromString(s.c_str());
  629. PyObject* plot_args = PyTuple_New(3);
  630. PyTuple_SetItem(plot_args, 0, xarray);
  631. PyTuple_SetItem(plot_args, 1, yarray);
  632. PyTuple_SetItem(plot_args, 2, pystring);
  633. PyObject* res = PyObject_CallObject(
  634. detail::_interpreter::get().s_python_function_stem, plot_args);
  635. Py_DECREF(plot_args);
  636. if (res)
  637. Py_DECREF(res);
  638. return res;
  639. }
  640. template<typename NumericX, typename NumericY>
  641. bool semilogx(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  642. {
  643. assert(x.size() == y.size());
  644. PyObject* xarray = get_array(x);
  645. PyObject* yarray = get_array(y);
  646. PyObject* pystring = PyString_FromString(s.c_str());
  647. PyObject* plot_args = PyTuple_New(3);
  648. PyTuple_SetItem(plot_args, 0, xarray);
  649. PyTuple_SetItem(plot_args, 1, yarray);
  650. PyTuple_SetItem(plot_args, 2, pystring);
  651. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogx, plot_args);
  652. Py_DECREF(plot_args);
  653. if(res) Py_DECREF(res);
  654. return res;
  655. }
  656. template<typename NumericX, typename NumericY>
  657. bool semilogy(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  658. {
  659. assert(x.size() == y.size());
  660. PyObject* xarray = get_array(x);
  661. PyObject* yarray = get_array(y);
  662. PyObject* pystring = PyString_FromString(s.c_str());
  663. PyObject* plot_args = PyTuple_New(3);
  664. PyTuple_SetItem(plot_args, 0, xarray);
  665. PyTuple_SetItem(plot_args, 1, yarray);
  666. PyTuple_SetItem(plot_args, 2, pystring);
  667. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogy, plot_args);
  668. Py_DECREF(plot_args);
  669. if(res) Py_DECREF(res);
  670. return res;
  671. }
  672. template<typename NumericX, typename NumericY>
  673. bool loglog(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  674. {
  675. assert(x.size() == y.size());
  676. PyObject* xarray = get_array(x);
  677. PyObject* yarray = get_array(y);
  678. PyObject* pystring = PyString_FromString(s.c_str());
  679. PyObject* plot_args = PyTuple_New(3);
  680. PyTuple_SetItem(plot_args, 0, xarray);
  681. PyTuple_SetItem(plot_args, 1, yarray);
  682. PyTuple_SetItem(plot_args, 2, pystring);
  683. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_loglog, plot_args);
  684. Py_DECREF(plot_args);
  685. if(res) Py_DECREF(res);
  686. return res;
  687. }
  688. template<typename NumericX, typename NumericY>
  689. 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 = {})
  690. {
  691. assert(x.size() == y.size());
  692. PyObject* xarray = get_array(x);
  693. PyObject* yarray = get_array(y);
  694. PyObject* yerrarray = get_array(yerr);
  695. // construct keyword args
  696. PyObject* kwargs = PyDict_New();
  697. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  698. {
  699. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  700. }
  701. PyDict_SetItemString(kwargs, "yerr", yerrarray);
  702. PyObject *plot_args = PyTuple_New(2);
  703. PyTuple_SetItem(plot_args, 0, xarray);
  704. PyTuple_SetItem(plot_args, 1, yarray);
  705. PyObject *res = PyObject_Call(detail::_interpreter::get().s_python_function_errorbar, plot_args, kwargs);
  706. Py_DECREF(kwargs);
  707. Py_DECREF(plot_args);
  708. if (res)
  709. Py_DECREF(res);
  710. else
  711. throw std::runtime_error("Call to errorbar() failed.");
  712. return res;
  713. }
  714. template<typename Numeric>
  715. bool named_plot(const std::string& name, const std::vector<Numeric>& y, const std::string& format = "")
  716. {
  717. PyObject* kwargs = PyDict_New();
  718. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  719. PyObject* yarray = get_array(y);
  720. PyObject* pystring = PyString_FromString(format.c_str());
  721. PyObject* plot_args = PyTuple_New(2);
  722. PyTuple_SetItem(plot_args, 0, yarray);
  723. PyTuple_SetItem(plot_args, 1, pystring);
  724. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
  725. Py_DECREF(kwargs);
  726. Py_DECREF(plot_args);
  727. if (res) Py_DECREF(res);
  728. return res;
  729. }
  730. template<typename Numeric>
  731. bool named_plot(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  732. {
  733. PyObject* kwargs = PyDict_New();
  734. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  735. PyObject* xarray = get_array(x);
  736. PyObject* yarray = get_array(y);
  737. PyObject* pystring = PyString_FromString(format.c_str());
  738. PyObject* plot_args = PyTuple_New(3);
  739. PyTuple_SetItem(plot_args, 0, xarray);
  740. PyTuple_SetItem(plot_args, 1, yarray);
  741. PyTuple_SetItem(plot_args, 2, pystring);
  742. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
  743. Py_DECREF(kwargs);
  744. Py_DECREF(plot_args);
  745. if (res) Py_DECREF(res);
  746. return res;
  747. }
  748. template<typename Numeric>
  749. bool named_semilogx(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  750. {
  751. PyObject* kwargs = PyDict_New();
  752. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  753. PyObject* xarray = get_array(x);
  754. PyObject* yarray = get_array(y);
  755. PyObject* pystring = PyString_FromString(format.c_str());
  756. PyObject* plot_args = PyTuple_New(3);
  757. PyTuple_SetItem(plot_args, 0, xarray);
  758. PyTuple_SetItem(plot_args, 1, yarray);
  759. PyTuple_SetItem(plot_args, 2, pystring);
  760. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogx, plot_args, kwargs);
  761. Py_DECREF(kwargs);
  762. Py_DECREF(plot_args);
  763. if (res) Py_DECREF(res);
  764. return res;
  765. }
  766. template<typename Numeric>
  767. bool named_semilogy(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  768. {
  769. PyObject* kwargs = PyDict_New();
  770. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  771. PyObject* xarray = get_array(x);
  772. PyObject* yarray = get_array(y);
  773. PyObject* pystring = PyString_FromString(format.c_str());
  774. PyObject* plot_args = PyTuple_New(3);
  775. PyTuple_SetItem(plot_args, 0, xarray);
  776. PyTuple_SetItem(plot_args, 1, yarray);
  777. PyTuple_SetItem(plot_args, 2, pystring);
  778. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogy, plot_args, kwargs);
  779. Py_DECREF(kwargs);
  780. Py_DECREF(plot_args);
  781. if (res) Py_DECREF(res);
  782. return res;
  783. }
  784. template<typename Numeric>
  785. bool named_loglog(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  786. {
  787. PyObject* kwargs = PyDict_New();
  788. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  789. PyObject* xarray = get_array(x);
  790. PyObject* yarray = get_array(y);
  791. PyObject* pystring = PyString_FromString(format.c_str());
  792. PyObject* plot_args = PyTuple_New(3);
  793. PyTuple_SetItem(plot_args, 0, xarray);
  794. PyTuple_SetItem(plot_args, 1, yarray);
  795. PyTuple_SetItem(plot_args, 2, pystring);
  796. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_loglog, plot_args, kwargs);
  797. Py_DECREF(kwargs);
  798. Py_DECREF(plot_args);
  799. if (res) Py_DECREF(res);
  800. return res;
  801. }
  802. template<typename Numeric>
  803. bool plot(const std::vector<Numeric>& y, const std::string& format = "")
  804. {
  805. std::vector<Numeric> x(y.size());
  806. for(size_t i=0; i<x.size(); ++i) x.at(i) = i;
  807. return plot(x,y,format);
  808. }
  809. template<typename Numeric>
  810. bool stem(const std::vector<Numeric>& y, const std::string& format = "")
  811. {
  812. std::vector<Numeric> x(y.size());
  813. for (size_t i = 0; i < x.size(); ++i) x.at(i) = i;
  814. return stem(x, y, format);
  815. }
  816. template<typename Numeric>
  817. void text(Numeric x, Numeric y, const std::string& s = "")
  818. {
  819. PyObject* args = PyTuple_New(3);
  820. PyTuple_SetItem(args, 0, PyFloat_FromDouble(x));
  821. PyTuple_SetItem(args, 1, PyFloat_FromDouble(y));
  822. PyTuple_SetItem(args, 2, PyString_FromString(s.c_str()));
  823. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_text, args);
  824. if(!res) throw std::runtime_error("Call to text() failed.");
  825. Py_DECREF(args);
  826. Py_DECREF(res);
  827. }
  828. inline long figure(long number = -1)
  829. {
  830. PyObject *res;
  831. if (number == -1)
  832. res = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure, detail::_interpreter::get().s_python_empty_tuple);
  833. else {
  834. assert(number > 0);
  835. // Make sure interpreter is initialised
  836. detail::_interpreter::get();
  837. PyObject *args = PyTuple_New(1);
  838. PyTuple_SetItem(args, 0, PyLong_FromLong(number));
  839. res = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure, args);
  840. Py_DECREF(args);
  841. }
  842. if(!res) throw std::runtime_error("Call to figure() failed.");
  843. PyObject* num = PyObject_GetAttrString(res, "number");
  844. if (!num) throw std::runtime_error("Could not get number attribute of figure object");
  845. const long figureNumber = PyLong_AsLong(num);
  846. Py_DECREF(num);
  847. Py_DECREF(res);
  848. return figureNumber;
  849. }
  850. inline bool fignum_exists(long number)
  851. {
  852. // Make sure interpreter is initialised
  853. detail::_interpreter::get();
  854. PyObject *args = PyTuple_New(1);
  855. PyTuple_SetItem(args, 0, PyLong_FromLong(number));
  856. PyObject *res = PyObject_CallObject(detail::_interpreter::get().s_python_function_fignum_exists, args);
  857. if(!res) throw std::runtime_error("Call to fignum_exists() failed.");
  858. bool ret = PyObject_IsTrue(res);
  859. Py_DECREF(res);
  860. Py_DECREF(args);
  861. return ret;
  862. }
  863. inline void figure_size(size_t w, size_t h)
  864. {
  865. const size_t dpi = 100;
  866. PyObject* size = PyTuple_New(2);
  867. PyTuple_SetItem(size, 0, PyFloat_FromDouble((double)w / dpi));
  868. PyTuple_SetItem(size, 1, PyFloat_FromDouble((double)h / dpi));
  869. PyObject* kwargs = PyDict_New();
  870. PyDict_SetItemString(kwargs, "figsize", size);
  871. PyDict_SetItemString(kwargs, "dpi", PyLong_FromSize_t(dpi));
  872. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_figure,
  873. detail::_interpreter::get().s_python_empty_tuple, kwargs);
  874. Py_DECREF(kwargs);
  875. if(!res) throw std::runtime_error("Call to figure_size() failed.");
  876. Py_DECREF(res);
  877. }
  878. inline void legend()
  879. {
  880. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_legend, detail::_interpreter::get().s_python_empty_tuple);
  881. if(!res) throw std::runtime_error("Call to legend() failed.");
  882. Py_DECREF(res);
  883. }
  884. template<typename Numeric>
  885. void ylim(Numeric left, Numeric right)
  886. {
  887. PyObject* list = PyList_New(2);
  888. PyList_SetItem(list, 0, PyFloat_FromDouble(left));
  889. PyList_SetItem(list, 1, PyFloat_FromDouble(right));
  890. PyObject* args = PyTuple_New(1);
  891. PyTuple_SetItem(args, 0, list);
  892. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);
  893. if(!res) throw std::runtime_error("Call to ylim() failed.");
  894. Py_DECREF(args);
  895. Py_DECREF(res);
  896. }
  897. template<typename Numeric>
  898. void xlim(Numeric left, Numeric right)
  899. {
  900. PyObject* list = PyList_New(2);
  901. PyList_SetItem(list, 0, PyFloat_FromDouble(left));
  902. PyList_SetItem(list, 1, PyFloat_FromDouble(right));
  903. PyObject* args = PyTuple_New(1);
  904. PyTuple_SetItem(args, 0, list);
  905. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);
  906. if(!res) throw std::runtime_error("Call to xlim() failed.");
  907. Py_DECREF(args);
  908. Py_DECREF(res);
  909. }
  910. inline double* xlim()
  911. {
  912. PyObject* args = PyTuple_New(0);
  913. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);
  914. PyObject* left = PyTuple_GetItem(res,0);
  915. PyObject* right = PyTuple_GetItem(res,1);
  916. double* arr = new double[2];
  917. arr[0] = PyFloat_AsDouble(left);
  918. arr[1] = PyFloat_AsDouble(right);
  919. if(!res) throw std::runtime_error("Call to xlim() failed.");
  920. Py_DECREF(res);
  921. return arr;
  922. }
  923. inline double* ylim()
  924. {
  925. PyObject* args = PyTuple_New(0);
  926. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);
  927. PyObject* left = PyTuple_GetItem(res,0);
  928. PyObject* right = PyTuple_GetItem(res,1);
  929. double* arr = new double[2];
  930. arr[0] = PyFloat_AsDouble(left);
  931. arr[1] = PyFloat_AsDouble(right);
  932. if(!res) throw std::runtime_error("Call to ylim() failed.");
  933. Py_DECREF(res);
  934. return arr;
  935. }
  936. template<typename Numeric>
  937. inline void xticks(const std::vector<Numeric> &ticks, const std::vector<std::string> &labels = {}, const std::map<std::string, std::string>& keywords = {})
  938. {
  939. assert(labels.size() == 0 || ticks.size() == labels.size());
  940. // using numpy array
  941. PyObject* ticksarray = get_array(ticks);
  942. PyObject* args;
  943. if(labels.size() == 0) {
  944. // construct positional args
  945. args = PyTuple_New(1);
  946. PyTuple_SetItem(args, 0, ticksarray);
  947. } else {
  948. // make tuple of tick labels
  949. PyObject* labelstuple = PyTuple_New(labels.size());
  950. for (size_t i = 0; i < labels.size(); i++)
  951. PyTuple_SetItem(labelstuple, i, PyUnicode_FromString(labels[i].c_str()));
  952. // construct positional args
  953. args = PyTuple_New(2);
  954. PyTuple_SetItem(args, 0, ticksarray);
  955. PyTuple_SetItem(args, 1, labelstuple);
  956. }
  957. // construct keyword args
  958. PyObject* kwargs = PyDict_New();
  959. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  960. {
  961. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  962. }
  963. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_xticks, args, kwargs);
  964. Py_DECREF(args);
  965. Py_DECREF(kwargs);
  966. if(!res) throw std::runtime_error("Call to xticks() failed");
  967. Py_DECREF(res);
  968. }
  969. template<typename Numeric>
  970. inline void xticks(const std::vector<Numeric> &ticks, const std::map<std::string, std::string>& keywords)
  971. {
  972. xticks(ticks, {}, keywords);
  973. }
  974. template<typename Numeric>
  975. inline void yticks(const std::vector<Numeric> &ticks, const std::vector<std::string> &labels = {}, const std::map<std::string, std::string>& keywords = {})
  976. {
  977. assert(labels.size() == 0 || ticks.size() == labels.size());
  978. // using numpy array
  979. PyObject* ticksarray = get_array(ticks);
  980. PyObject* args;
  981. if(labels.size() == 0) {
  982. // construct positional args
  983. args = PyTuple_New(1);
  984. PyTuple_SetItem(args, 0, ticksarray);
  985. } else {
  986. // make tuple of tick labels
  987. PyObject* labelstuple = PyTuple_New(labels.size());
  988. for (size_t i = 0; i < labels.size(); i++)
  989. PyTuple_SetItem(labelstuple, i, PyUnicode_FromString(labels[i].c_str()));
  990. // construct positional args
  991. args = PyTuple_New(2);
  992. PyTuple_SetItem(args, 0, ticksarray);
  993. PyTuple_SetItem(args, 1, labelstuple);
  994. }
  995. // construct keyword args
  996. PyObject* kwargs = PyDict_New();
  997. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  998. {
  999. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1000. }
  1001. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_yticks, args, kwargs);
  1002. Py_DECREF(args);
  1003. Py_DECREF(kwargs);
  1004. if(!res) throw std::runtime_error("Call to yticks() failed");
  1005. Py_DECREF(res);
  1006. }
  1007. template<typename Numeric>
  1008. inline void yticks(const std::vector<Numeric> &ticks, const std::map<std::string, std::string>& keywords)
  1009. {
  1010. yticks(ticks, {}, keywords);
  1011. }
  1012. inline void subplot(long nrows, long ncols, long plot_number)
  1013. {
  1014. // construct positional args
  1015. PyObject* args = PyTuple_New(3);
  1016. PyTuple_SetItem(args, 0, PyFloat_FromDouble(nrows));
  1017. PyTuple_SetItem(args, 1, PyFloat_FromDouble(ncols));
  1018. PyTuple_SetItem(args, 2, PyFloat_FromDouble(plot_number));
  1019. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_subplot, args);
  1020. if(!res) throw std::runtime_error("Call to subplot() failed.");
  1021. Py_DECREF(args);
  1022. Py_DECREF(res);
  1023. }
  1024. inline void title(const std::string &titlestr)
  1025. {
  1026. PyObject* pytitlestr = PyString_FromString(titlestr.c_str());
  1027. PyObject* args = PyTuple_New(1);
  1028. PyTuple_SetItem(args, 0, pytitlestr);
  1029. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_title, args);
  1030. if(!res) throw std::runtime_error("Call to title() failed.");
  1031. Py_DECREF(args);
  1032. Py_DECREF(res);
  1033. }
  1034. inline void suptitle(const std::string &suptitlestr)
  1035. {
  1036. PyObject* pysuptitlestr = PyString_FromString(suptitlestr.c_str());
  1037. PyObject* args = PyTuple_New(1);
  1038. PyTuple_SetItem(args, 0, pysuptitlestr);
  1039. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_suptitle, args);
  1040. if(!res) throw std::runtime_error("Call to suptitle() failed.");
  1041. Py_DECREF(args);
  1042. Py_DECREF(res);
  1043. }
  1044. inline void axis(const std::string &axisstr)
  1045. {
  1046. PyObject* str = PyString_FromString(axisstr.c_str());
  1047. PyObject* args = PyTuple_New(1);
  1048. PyTuple_SetItem(args, 0, str);
  1049. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_axis, args);
  1050. if(!res) throw std::runtime_error("Call to title() failed.");
  1051. Py_DECREF(args);
  1052. Py_DECREF(res);
  1053. }
  1054. inline void xlabel(const std::string &str)
  1055. {
  1056. PyObject* pystr = PyString_FromString(str.c_str());
  1057. PyObject* args = PyTuple_New(1);
  1058. PyTuple_SetItem(args, 0, pystr);
  1059. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlabel, args);
  1060. if(!res) throw std::runtime_error("Call to xlabel() failed.");
  1061. Py_DECREF(args);
  1062. Py_DECREF(res);
  1063. }
  1064. inline void ylabel(const std::string &str)
  1065. {
  1066. PyObject* pystr = PyString_FromString(str.c_str());
  1067. PyObject* args = PyTuple_New(1);
  1068. PyTuple_SetItem(args, 0, pystr);
  1069. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylabel, args);
  1070. if(!res) throw std::runtime_error("Call to ylabel() failed.");
  1071. Py_DECREF(args);
  1072. Py_DECREF(res);
  1073. }
  1074. inline void grid(bool flag)
  1075. {
  1076. PyObject* pyflag = flag ? Py_True : Py_False;
  1077. Py_INCREF(pyflag);
  1078. PyObject* args = PyTuple_New(1);
  1079. PyTuple_SetItem(args, 0, pyflag);
  1080. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_grid, args);
  1081. if(!res) throw std::runtime_error("Call to grid() failed.");
  1082. Py_DECREF(args);
  1083. Py_DECREF(res);
  1084. }
  1085. inline void show(const bool block = true)
  1086. {
  1087. PyObject* res;
  1088. if(block)
  1089. {
  1090. res = PyObject_CallObject(
  1091. detail::_interpreter::get().s_python_function_show,
  1092. detail::_interpreter::get().s_python_empty_tuple);
  1093. }
  1094. else
  1095. {
  1096. PyObject *kwargs = PyDict_New();
  1097. PyDict_SetItemString(kwargs, "block", Py_False);
  1098. res = PyObject_Call( detail::_interpreter::get().s_python_function_show, detail::_interpreter::get().s_python_empty_tuple, kwargs);
  1099. Py_DECREF(kwargs);
  1100. }
  1101. if (!res) throw std::runtime_error("Call to show() failed.");
  1102. Py_DECREF(res);
  1103. }
  1104. inline void close()
  1105. {
  1106. PyObject* res = PyObject_CallObject(
  1107. detail::_interpreter::get().s_python_function_close,
  1108. detail::_interpreter::get().s_python_empty_tuple);
  1109. if (!res) throw std::runtime_error("Call to close() failed.");
  1110. Py_DECREF(res);
  1111. }
  1112. inline void xkcd() {
  1113. PyObject* res;
  1114. PyObject *kwargs = PyDict_New();
  1115. res = PyObject_Call(detail::_interpreter::get().s_python_function_xkcd,
  1116. detail::_interpreter::get().s_python_empty_tuple, kwargs);
  1117. Py_DECREF(kwargs);
  1118. if (!res)
  1119. throw std::runtime_error("Call to show() failed.");
  1120. Py_DECREF(res);
  1121. }
  1122. inline void draw()
  1123. {
  1124. PyObject* res = PyObject_CallObject(
  1125. detail::_interpreter::get().s_python_function_draw,
  1126. detail::_interpreter::get().s_python_empty_tuple);
  1127. if (!res) throw std::runtime_error("Call to draw() failed.");
  1128. Py_DECREF(res);
  1129. }
  1130. template<typename Numeric>
  1131. inline void pause(Numeric interval)
  1132. {
  1133. PyObject* args = PyTuple_New(1);
  1134. PyTuple_SetItem(args, 0, PyFloat_FromDouble(interval));
  1135. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_pause, args);
  1136. if(!res) throw std::runtime_error("Call to pause() failed.");
  1137. Py_DECREF(args);
  1138. Py_DECREF(res);
  1139. }
  1140. inline void save(const std::string& filename)
  1141. {
  1142. PyObject* pyfilename = PyString_FromString(filename.c_str());
  1143. PyObject* args = PyTuple_New(1);
  1144. PyTuple_SetItem(args, 0, pyfilename);
  1145. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_save, args);
  1146. if (!res) throw std::runtime_error("Call to save() failed.");
  1147. Py_DECREF(args);
  1148. Py_DECREF(res);
  1149. }
  1150. inline void clf() {
  1151. PyObject *res = PyObject_CallObject(
  1152. detail::_interpreter::get().s_python_function_clf,
  1153. detail::_interpreter::get().s_python_empty_tuple);
  1154. if (!res) throw std::runtime_error("Call to clf() failed.");
  1155. Py_DECREF(res);
  1156. }
  1157. inline void ion() {
  1158. PyObject *res = PyObject_CallObject(
  1159. detail::_interpreter::get().s_python_function_ion,
  1160. detail::_interpreter::get().s_python_empty_tuple);
  1161. if (!res) throw std::runtime_error("Call to ion() failed.");
  1162. Py_DECREF(res);
  1163. }
  1164. inline std::vector<std::array<double, 2>> ginput(const int numClicks = 1, const std::map<std::string, std::string>& keywords = {})
  1165. {
  1166. PyObject *args = PyTuple_New(1);
  1167. PyTuple_SetItem(args, 0, PyLong_FromLong(numClicks));
  1168. // construct keyword args
  1169. PyObject* kwargs = PyDict_New();
  1170. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1171. {
  1172. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1173. }
  1174. PyObject* res = PyObject_Call(
  1175. detail::_interpreter::get().s_python_function_ginput, args, kwargs);
  1176. Py_DECREF(kwargs);
  1177. Py_DECREF(args);
  1178. if (!res) throw std::runtime_error("Call to ginput() failed.");
  1179. const size_t len = PyList_Size(res);
  1180. std::vector<std::array<double, 2>> out;
  1181. out.reserve(len);
  1182. for (size_t i = 0; i < len; i++) {
  1183. PyObject *current = PyList_GetItem(res, i);
  1184. std::array<double, 2> position;
  1185. position[0] = PyFloat_AsDouble(PyTuple_GetItem(current, 0));
  1186. position[1] = PyFloat_AsDouble(PyTuple_GetItem(current, 1));
  1187. out.push_back(position);
  1188. }
  1189. Py_DECREF(res);
  1190. return out;
  1191. }
  1192. // Actually, is there any reason not to call this automatically for every plot?
  1193. inline void tight_layout() {
  1194. PyObject *res = PyObject_CallObject(
  1195. detail::_interpreter::get().s_python_function_tight_layout,
  1196. detail::_interpreter::get().s_python_empty_tuple);
  1197. if (!res) throw std::runtime_error("Call to tight_layout() failed.");
  1198. Py_DECREF(res);
  1199. }
  1200. // Support for variadic plot() and initializer lists:
  1201. namespace detail {
  1202. template<typename T>
  1203. using is_function = typename std::is_function<std::remove_pointer<std::remove_reference<T>>>::type;
  1204. template<bool obj, typename T>
  1205. struct is_callable_impl;
  1206. template<typename T>
  1207. struct is_callable_impl<false, T>
  1208. {
  1209. typedef is_function<T> type;
  1210. }; // a non-object is callable iff it is a function
  1211. template<typename T>
  1212. struct is_callable_impl<true, T>
  1213. {
  1214. struct Fallback { void operator()(); };
  1215. struct Derived : T, Fallback { };
  1216. template<typename U, U> struct Check;
  1217. template<typename U>
  1218. static std::true_type test( ... ); // use a variadic function to make sure (1) it accepts everything and (2) its always the worst match
  1219. template<typename U>
  1220. static std::false_type test( Check<void(Fallback::*)(), &U::operator()>* );
  1221. public:
  1222. typedef decltype(test<Derived>(nullptr)) type;
  1223. typedef decltype(&Fallback::operator()) dtype;
  1224. static constexpr bool value = type::value;
  1225. }; // an object is callable iff it defines operator()
  1226. template<typename T>
  1227. struct is_callable
  1228. {
  1229. // dispatch to is_callable_impl<true, T> or is_callable_impl<false, T> depending on whether T is of class type or not
  1230. typedef typename is_callable_impl<std::is_class<T>::value, T>::type type;
  1231. };
  1232. template<typename IsYDataCallable>
  1233. struct plot_impl { };
  1234. template<>
  1235. struct plot_impl<std::false_type>
  1236. {
  1237. template<typename IterableX, typename IterableY>
  1238. bool operator()(const IterableX& x, const IterableY& y, const std::string& format)
  1239. {
  1240. // 2-phase lookup for distance, begin, end
  1241. using std::distance;
  1242. using std::begin;
  1243. using std::end;
  1244. auto xs = distance(begin(x), end(x));
  1245. auto ys = distance(begin(y), end(y));
  1246. assert(xs == ys && "x and y data must have the same number of elements!");
  1247. PyObject* xlist = PyList_New(xs);
  1248. PyObject* ylist = PyList_New(ys);
  1249. PyObject* pystring = PyString_FromString(format.c_str());
  1250. auto itx = begin(x), ity = begin(y);
  1251. for(size_t i = 0; i < xs; ++i) {
  1252. PyList_SetItem(xlist, i, PyFloat_FromDouble(*itx++));
  1253. PyList_SetItem(ylist, i, PyFloat_FromDouble(*ity++));
  1254. }
  1255. PyObject* plot_args = PyTuple_New(3);
  1256. PyTuple_SetItem(plot_args, 0, xlist);
  1257. PyTuple_SetItem(plot_args, 1, ylist);
  1258. PyTuple_SetItem(plot_args, 2, pystring);
  1259. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);
  1260. Py_DECREF(plot_args);
  1261. if(res) Py_DECREF(res);
  1262. return res;
  1263. }
  1264. };
  1265. template<>
  1266. struct plot_impl<std::true_type>
  1267. {
  1268. template<typename Iterable, typename Callable>
  1269. bool operator()(const Iterable& ticks, const Callable& f, const std::string& format)
  1270. {
  1271. if(begin(ticks) == end(ticks)) return true;
  1272. // We could use additional meta-programming to deduce the correct element type of y,
  1273. // but all values have to be convertible to double anyways
  1274. std::vector<double> y;
  1275. for(auto x : ticks) y.push_back(f(x));
  1276. return plot_impl<std::false_type>()(ticks,y,format);
  1277. }
  1278. };
  1279. } // end namespace detail
  1280. // recursion stop for the above
  1281. template<typename... Args>
  1282. bool plot() { return true; }
  1283. template<typename A, typename B, typename... Args>
  1284. bool plot(const A& a, const B& b, const std::string& format, Args... args)
  1285. {
  1286. return detail::plot_impl<typename detail::is_callable<B>::type>()(a,b,format) && plot(args...);
  1287. }
  1288. /*
  1289. * This group of plot() functions is needed to support initializer lists, i.e. calling
  1290. * plot( {1,2,3,4} )
  1291. */
  1292. inline bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::string& format = "") {
  1293. return plot<double,double>(x,y,format);
  1294. }
  1295. inline bool plot(const std::vector<double>& y, const std::string& format = "") {
  1296. return plot<double>(y,format);
  1297. }
  1298. inline bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::map<std::string, std::string>& keywords) {
  1299. return plot<double>(x,y,keywords);
  1300. }
  1301. } // end namespace matplotlibcpp