matplotlibcpp.h 12 KB

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