matplotlibcpp.h 46 KB

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