matplotlibcpp.h 42 KB

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