1
0

matplotlibcpp.h 49 KB

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