matplotlibcpp.h 54 KB

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