matplotlibcpp.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. #pragma once
  2. #include <vector>
  3. #include <map>
  4. #include <numeric>
  5. #include <stdexcept>
  6. #include <iostream>
  7. #if __cplusplus > 199711L
  8. #include <functional>
  9. #endif
  10. #include <python2.7/Python.h>
  11. namespace matplotlibcpp {
  12. namespace detail {
  13. struct _pyplot_global {
  14. PyObject *s_python_function_show;
  15. PyObject *s_python_function_figure;
  16. PyObject *s_python_function_plot;
  17. PyObject *s_python_function_legend;
  18. PyObject *s_python_function_xlim;
  19. PyObject *s_python_function_ylim;
  20. PyObject *s_python_empty_tuple;
  21. static _pyplot_global& get() {
  22. static _pyplot_global ctx;
  23. return ctx;
  24. }
  25. private:
  26. _pyplot_global() {
  27. char name[] = "plotting"; // silence compiler warning abount const strings
  28. Py_SetProgramName(name); // optional but recommended
  29. Py_Initialize();
  30. PyObject* pyname = PyString_FromString("matplotlib.pyplot");
  31. if(!pyname) { throw std::runtime_error("couldnt create string"); }
  32. PyObject* pymod = PyImport_Import(pyname);
  33. Py_DECREF(pyname);
  34. if(!pymod) { throw std::runtime_error("Error loading module!"); }
  35. s_python_function_show = PyObject_GetAttrString(pymod, "show");
  36. s_python_function_figure = PyObject_GetAttrString(pymod, "figure");
  37. s_python_function_plot = PyObject_GetAttrString(pymod, "plot");
  38. s_python_function_legend = PyObject_GetAttrString(pymod, "legend");
  39. s_python_function_ylim = PyObject_GetAttrString(pymod, "ylim");
  40. s_python_function_xlim = PyObject_GetAttrString(pymod, "xlim");
  41. if(!s_python_function_show
  42. || !s_python_function_figure
  43. || !s_python_function_plot
  44. || !s_python_function_legend
  45. || !s_python_function_xlim
  46. || !s_python_function_ylim)
  47. { throw std::runtime_error("Couldnt find required function!"); }
  48. if(!PyFunction_Check(s_python_function_show)
  49. || !PyFunction_Check(s_python_function_figure)
  50. || !PyFunction_Check(s_python_function_plot)
  51. || !PyFunction_Check(s_python_function_legend)
  52. || !PyFunction_Check(s_python_function_xlim)
  53. || !PyFunction_Check(s_python_function_ylim))
  54. { throw std::runtime_error("Python object is unexpectedly not a PyFunction."); }
  55. s_python_empty_tuple = PyTuple_New(0);
  56. }
  57. ~_pyplot_global() {
  58. Py_Finalize();
  59. }
  60. };
  61. }
  62. template<typename Numeric>
  63. bool plot(const std::vector<Numeric> &x, const std::vector<Numeric> &y, const std::map<std::string, std::string>& keywords)
  64. {
  65. assert(x.size() == y.size());
  66. // using python lists
  67. PyObject* xlist = PyList_New(x.size());
  68. PyObject* ylist = PyList_New(y.size());
  69. for(size_t i = 0; i < x.size(); ++i) {
  70. PyList_SetItem(xlist, i, PyFloat_FromDouble(x.at(i)));
  71. PyList_SetItem(ylist, i, PyFloat_FromDouble(y.at(i)));
  72. }
  73. // construct positional args
  74. PyObject* args = PyTuple_New(2);
  75. PyTuple_SetItem(args, 0, xlist);
  76. PyTuple_SetItem(args, 1, ylist);
  77. Py_DECREF(xlist);
  78. Py_DECREF(ylist);
  79. // construct keyword args
  80. PyObject* kwargs = PyDict_New();
  81. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  82. {
  83. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  84. }
  85. PyObject* res = PyObject_Call(detail::_pyplot_global::get().s_python_function_plot, args, kwargs);
  86. Py_DECREF(args);
  87. Py_DECREF(kwargs);
  88. if(res) Py_DECREF(res);
  89. return res;
  90. }
  91. template<typename NumericX, typename NumericY>
  92. bool plot(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  93. {
  94. assert(x.size() == y.size());
  95. //std::string format(s);
  96. PyObject* xlist = PyList_New(x.size());
  97. PyObject* ylist = PyList_New(y.size());
  98. PyObject* pystring = PyString_FromString(s.c_str());
  99. for(size_t i = 0; i < x.size(); ++i) {
  100. PyList_SetItem(xlist, i, PyFloat_FromDouble(x.at(i)));
  101. PyList_SetItem(ylist, i, PyFloat_FromDouble(y.at(i)));
  102. }
  103. PyObject* plot_args = PyTuple_New(3);
  104. PyTuple_SetItem(plot_args, 0, xlist);
  105. PyTuple_SetItem(plot_args, 1, ylist);
  106. PyTuple_SetItem(plot_args, 2, pystring);
  107. PyObject* res = PyObject_CallObject(detail::_pyplot_global::get().s_python_function_plot, plot_args);
  108. Py_DECREF(xlist);
  109. Py_DECREF(ylist);
  110. Py_DECREF(plot_args);
  111. if(res) Py_DECREF(res);
  112. return res;
  113. }
  114. template<typename Numeric>
  115. bool named_plot(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "") {
  116. PyObject* kwargs = PyDict_New();
  117. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  118. PyObject* xlist = PyList_New(x.size());
  119. PyObject* ylist = PyList_New(y.size());
  120. PyObject* pystring = PyString_FromString(format.c_str());
  121. for(size_t i = 0; i < x.size(); ++i) {
  122. PyList_SetItem(xlist, i, PyFloat_FromDouble(x.at(i)));
  123. PyList_SetItem(ylist, i, PyFloat_FromDouble(y.at(i)));
  124. }
  125. PyObject* plot_args = PyTuple_New(3);
  126. PyTuple_SetItem(plot_args, 0, xlist);
  127. PyTuple_SetItem(plot_args, 1, ylist);
  128. PyTuple_SetItem(plot_args, 2, pystring);
  129. PyObject* res = PyObject_Call(detail::_pyplot_global::get().s_python_function_plot, plot_args, kwargs);
  130. Py_DECREF(kwargs);
  131. Py_DECREF(xlist);
  132. Py_DECREF(ylist);
  133. Py_DECREF(plot_args);
  134. if(res) Py_DECREF(res);
  135. return res;
  136. }
  137. template<typename Numeric>
  138. bool plot(const std::vector<Numeric>& y, const std::string& format = "")
  139. {
  140. std::vector<Numeric> x(y.size());
  141. for(size_t i=0; i<x.size(); ++i) x.at(i) = i;
  142. return plot(x,y,format);
  143. }
  144. /*
  145. * This group of plot() functions is needed to support initializer lists, i.e. calling
  146. * plot( {1,2,3,4} )
  147. */
  148. bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::string& format = "") {
  149. return plot<double,double>(x,y,format);
  150. }
  151. bool plot(const std::vector<double>& y, const std::string& format = "") {
  152. return plot<double>(y,format);
  153. }
  154. bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::map<std::string, std::string>& keywords) {
  155. return plot<double>(x,y,keywords);
  156. }
  157. bool named_plot(const std::string& name, const std::vector<double>& x, const std::vector<double>& y, const std::string& format = "") {
  158. return named_plot<double>(name,x,y,format);
  159. }
  160. #if __cplusplus > 199711L
  161. template<typename T>
  162. using is_function = typename std::is_function<std::remove_pointer<std::remove_reference<T>>>::type;
  163. template<bool obj, typename T>
  164. struct is_callable_impl;
  165. template<typename T>
  166. struct is_callable_impl<false, T>
  167. {
  168. typedef is_function<T> type;
  169. }; // a non-object is callable iff it is a function
  170. template<typename T>
  171. struct is_callable_impl<true, T>
  172. {
  173. struct Fallback { void operator()(); };
  174. struct Derived : T, Fallback { };
  175. template<typename U, U> struct Check;
  176. template<typename U>
  177. static std::true_type test( ... ); // use a variadic function to make use (1) it accepts everything and (2) its always the worst match
  178. template<typename U>
  179. static std::false_type test( Check<void(Fallback::*)(), &U::operator()>* );
  180. public:
  181. typedef decltype(test<Derived>(nullptr)) type;
  182. typedef decltype(&Fallback::operator()) dtype;
  183. static constexpr bool value = type::value;
  184. }; // an object is callable iff it defines operator()
  185. template<typename T>
  186. struct is_callable
  187. {
  188. // dispatch to is_callable_impl<true, T> or is_callable_impl<false, T> depending on whether T is of class type or not
  189. typedef typename is_callable_impl<std::is_class<T>::value, T>::type type; // todo: restore remove_reference
  190. };
  191. template<typename IsYDataCallable>
  192. struct plot_impl { };
  193. template<>
  194. struct plot_impl<std::false_type>
  195. {
  196. template<typename IterableX, typename IterableY>
  197. bool operator()(const IterableX& x, const IterableY& y, const std::string& format)
  198. {
  199. // It's annoying that we have to repeat the code of plot() above
  200. auto xs = std::distance(std::begin(x), std::end(x));
  201. auto ys = std::distance(std::begin(y), std::end(y));
  202. assert(xs == ys && "x and y data must have the same number of elements!");
  203. PyObject* xlist = PyList_New(xs);
  204. PyObject* ylist = PyList_New(ys);
  205. PyObject* pystring = PyString_FromString(format.c_str());
  206. auto itx = std::begin(x), ity = std::begin(y);
  207. for(size_t i = 0; i < xs; ++i) {
  208. PyList_SetItem(xlist, i, PyFloat_FromDouble(*itx++));
  209. PyList_SetItem(ylist, i, PyFloat_FromDouble(*ity++));
  210. }
  211. PyObject* plot_args = PyTuple_New(3);
  212. PyTuple_SetItem(plot_args, 0, xlist);
  213. PyTuple_SetItem(plot_args, 1, ylist);
  214. PyTuple_SetItem(plot_args, 2, pystring);
  215. PyObject* res = PyObject_CallObject(detail::_pyplot_global::get().s_python_function_plot, plot_args);
  216. Py_DECREF(xlist);
  217. Py_DECREF(ylist);
  218. Py_DECREF(plot_args);
  219. if(res) Py_DECREF(res);
  220. return res;
  221. }
  222. };
  223. template<>
  224. struct plot_impl<std::true_type>
  225. {
  226. template<typename Iterable, typename Callable>
  227. bool operator()(const Iterable& ticks, const Callable& f, const std::string& format)
  228. {
  229. //std::cout << "Callable impl called" << std::endl;
  230. if(begin(ticks) == end(ticks)) return true;
  231. // We could use additional meta-programming to deduce the correct element type of y,
  232. // but all values have to be convertible to double anyways
  233. std::vector<double> y;
  234. for(auto x : ticks) y.push_back(f(x));
  235. return plot_impl<std::false_type>()(ticks,y,format);
  236. }
  237. };
  238. // recursion stop for the above
  239. template<typename... Args>
  240. bool plot() { return true; }
  241. template<typename A, typename B, typename... Args>
  242. bool plot(const A& a, const B& b, const std::string& format, Args... args)
  243. {
  244. return plot_impl<typename is_callable<B>::type>()(a,b,format) && plot(args...);
  245. }
  246. #endif
  247. inline void legend() {
  248. PyObject* res = PyObject_CallObject(detail::_pyplot_global::get().s_python_function_legend, detail::_pyplot_global::get().s_python_empty_tuple);
  249. if(!res) throw std::runtime_error("Call to legend() failed.");
  250. Py_DECREF(res);
  251. }
  252. template<typename Numeric>
  253. void ylim(Numeric left, Numeric right)
  254. {
  255. PyObject* list = PyList_New(2);
  256. PyList_SetItem(list, 0, PyFloat_FromDouble(left));
  257. PyList_SetItem(list, 1, PyFloat_FromDouble(right));
  258. PyObject* args = PyTuple_New(1);
  259. PyTuple_SetItem(args, 0, list);
  260. PyObject* res = PyObject_CallObject(detail::_pyplot_global::get().s_python_function_ylim, args);
  261. if(!res) throw std::runtime_error("Call to ylim() failed.");
  262. Py_DECREF(list);
  263. Py_DECREF(args);
  264. Py_DECREF(res);
  265. }
  266. template<typename Numeric>
  267. void xlim(Numeric left, Numeric right)
  268. {
  269. PyObject* list = PyList_New(2);
  270. PyList_SetItem(list, 0, PyFloat_FromDouble(left));
  271. PyList_SetItem(list, 1, PyFloat_FromDouble(right));
  272. PyObject* args = PyTuple_New(1);
  273. PyTuple_SetItem(args, 0, list);
  274. PyObject* res = PyObject_CallObject(detail::_pyplot_global::get().s_python_function_xlim, args);
  275. if(!res) throw std::runtime_error("Call to xlim() failed.");
  276. Py_DECREF(list);
  277. Py_DECREF(args);
  278. Py_DECREF(res);
  279. }
  280. inline void show() {
  281. PyObject* res = PyObject_CallObject(detail::_pyplot_global::get().s_python_function_show, detail::_pyplot_global::get().s_python_empty_tuple);
  282. if(!res) throw std::runtime_error("Call to show() failed.");
  283. Py_DECREF(res);
  284. }
  285. }