matplotlibcpp.h 37 KB

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