FML
Loading...
Searching...
No Matches
Matplotlibcpp.h
Go to the documentation of this file.
1#ifndef MATPLOTLIBCXX_HEADER
2#define MATPLOTLIBCXX_HEADER
3// #pragma once
4// Old Python and numpy headers use the keyword register (removed in C++17): define it away while including them
5#if __cplusplus > 199711L
6#define FML_MATPLOTLIBCPP_UNDEF_REGISTER
7#define register
8#endif
9
10//====================================================================
11//
12// Make plots with matplotlib from within C++
13// Works with Python 3 (and 2.7), with or without numpy (-DWITHOUT_NUMPY)
14//
15// Slightly modified from the library at: https://github.com/lava/matplotlib-cpp
16// Licence: https://github.com/lava/matplotlib-cpp/blob/master/LICENSE
17//
18//====================================================================
19
20#include <Python.h>
21#include <algorithm>
22#include <array>
23#include <cstdint> // <cstdint> requires c++11 support
24#include <functional>
25#include <iostream>
26#include <map>
27#include <numeric>
28#include <stdexcept>
29#include <unordered_map>
30#include <vector>
31
32#ifndef WITHOUT_NUMPY
33#ifdef WITH_OPENCV
34#include <opencv2/opencv.hpp>
35#endif // WITH_OPENCV
36
37#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
38#include <numpy/arrayobject.h>
39
40/*
41 * A bunch of constants were removed in OpenCV 4 in favour of enum classes, so
42 * define the ones we need here.
43 */
44#if CV_MAJOR_VERSION > 3
45#define CV_BGR2RGB cv::COLOR_BGR2RGB
46#define CV_BGRA2RGBA cv::COLOR_BGRA2RGBA
47#endif
48#endif // WITHOUT_NUMPY
49
50#ifdef FML_MATPLOTLIBCPP_UNDEF_REGISTER
51#undef register
52#undef FML_MATPLOTLIBCPP_UNDEF_REGISTER
53#endif
54
55#if PY_MAJOR_VERSION >= 3
56#define PyString_FromString PyUnicode_FromString
57#define PyInt_FromLong PyLong_FromLong
58#endif
59
60namespace FML {
61 namespace UTILS {
62 /// Make plots with matplotlib from within C++
63 namespace Matplotlib {
64 namespace detail {
65
66 static std::string s_backend;
67
68 struct _interpreter {
69 PyObject * s_python_function_show;
70 PyObject * s_python_function_close;
71 PyObject * s_python_function_draw;
72 PyObject * s_python_function_pause;
73 PyObject * s_python_function_save;
74 PyObject * s_python_function_figure;
75 PyObject * s_python_function_fignum_exists;
76 PyObject * s_python_function_plot;
77 PyObject * s_python_function_quiver;
78 PyObject * s_python_function_semilogx;
79 PyObject * s_python_function_semilogy;
80 PyObject * s_python_function_loglog;
81 PyObject * s_python_function_fill;
82 PyObject * s_python_function_fill_between;
83 PyObject * s_python_function_hist;
84 PyObject * s_python_function_imshow;
85 PyObject * s_python_function_scatter;
86 PyObject * s_python_function_subplot;
87 PyObject * s_python_function_subplot2grid;
88 PyObject * s_python_function_legend;
89 PyObject * s_python_function_xlim;
90 PyObject * s_python_function_ion;
91 PyObject * s_python_function_ginput;
92 PyObject * s_python_function_ylim;
93 PyObject * s_python_function_title;
94 PyObject * s_python_function_axis;
95 PyObject * s_python_function_xscale;
96 PyObject * s_python_function_yscale;
97 PyObject * s_python_function_xlabel;
98 PyObject * s_python_function_ylabel;
99 PyObject * s_python_function_xticks;
100 PyObject * s_python_function_yticks;
101 PyObject * s_python_function_tick_params;
102 PyObject * s_python_function_grid;
103 PyObject * s_python_function_clf;
104 PyObject * s_python_function_errorbar;
105 PyObject * s_python_function_annotate;
106 PyObject * s_python_function_tight_layout;
107 PyObject * s_python_colormap;
108 PyObject * s_python_empty_tuple;
109 PyObject * s_python_function_stem;
110 PyObject * s_python_function_xkcd;
111 PyObject * s_python_function_text;
112 PyObject * s_python_function_suptitle;
113 PyObject * s_python_function_bar;
114 PyObject * s_python_function_subplots_adjust;
115
116 /* For now, _interpreter is implemented as a singleton since its currently not
117 possible to have multiple independent embedded python interpreters without
118 patching the python source code or starting a separate process for each.
119 http://bytes.com/topic/python/answers/793370-multiple-independent-python-interpreters-c-c-program
120 */
121
122 static _interpreter & get() {
123 static _interpreter ctx;
124 return ctx;
125 }
126
127 PyObject * safe_import(PyObject * module, std::string fname) {
128 PyObject * fn = PyObject_GetAttrString(module, fname.c_str());
129
130 if (!fn)
131 throw std::runtime_error(std::string("Couldn't find required function: ") + fname);
132
133 if (!PyFunction_Check(fn))
134 throw std::runtime_error(fname + std::string(" is unexpectedly not a PyFunction."));
135
136 return fn;
137 }
138
139 private:
140#ifndef WITHOUT_NUMPY
141#if PY_MAJOR_VERSION >= 3
142
143 void * import_numpy() {
144 import_array(); // initialize C-API
145 return nullptr;
146 }
147
148#else
149
150 void import_numpy() {
151 import_array(); // initialize C-API
152 }
153
154#endif
155#endif
156
157 _interpreter() {
158 // Set the program name (optional; Py_SetProgramName is deprecated from Python 3.11)
159#if PY_MAJOR_VERSION >= 3
160#if PY_VERSION_HEX < 0x030B0000
161 wchar_t name[] = L"plotting";
162 Py_SetProgramName(name);
163#endif
164#else
165 char name[] = "plotting";
166 Py_SetProgramName(name);
167#endif
168 Py_Initialize();
169
170#ifndef WITHOUT_NUMPY
171 import_numpy(); // initialize numpy C-API
172#endif
173
174 PyObject * matplotlibname = PyString_FromString("matplotlib");
175 PyObject * pyplotname = PyString_FromString("matplotlib.pyplot");
176 PyObject * cmname = PyString_FromString("matplotlib.cm");
177 PyObject * pylabname = PyString_FromString("pylab");
178 if (!pyplotname || !pylabname || !matplotlibname || !cmname) {
179 throw std::runtime_error("couldnt create string");
180 }
181
182 PyObject * matplotlib = PyImport_Import(matplotlibname);
183 Py_DECREF(matplotlibname);
184 if (!matplotlib) {
185 PyErr_Print();
186 throw std::runtime_error("Error loading module matplotlib!");
187 }
188
189 // matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
190 // or matplotlib.backends is imported for the first time
191 if (!s_backend.empty()) {
192 PyObject_CallMethod(matplotlib,
193 const_cast<char *>("use"),
194 const_cast<char *>("s"),
195 s_backend.c_str());
196 }
197
198 PyObject * pymod = PyImport_Import(pyplotname);
199 Py_DECREF(pyplotname);
200 if (!pymod) {
201 throw std::runtime_error("Error loading module matplotlib.pyplot!");
202 }
203
204 s_python_colormap = PyImport_Import(cmname);
205 Py_DECREF(cmname);
206 if (!s_python_colormap) {
207 throw std::runtime_error("Error loading module matplotlib.cm!");
208 }
209
210 PyObject * pylabmod = PyImport_Import(pylabname);
211 Py_DECREF(pylabname);
212 if (!pylabmod) {
213 throw std::runtime_error("Error loading module pylab!");
214 }
215
216 s_python_function_show = safe_import(pymod, "show");
217 s_python_function_close = safe_import(pymod, "close");
218 s_python_function_draw = safe_import(pymod, "draw");
219 s_python_function_pause = safe_import(pymod, "pause");
220 s_python_function_figure = safe_import(pymod, "figure");
221 s_python_function_fignum_exists = safe_import(pymod, "fignum_exists");
222 s_python_function_plot = safe_import(pymod, "plot");
223 s_python_function_quiver = safe_import(pymod, "quiver");
224 s_python_function_semilogx = safe_import(pymod, "semilogx");
225 s_python_function_semilogy = safe_import(pymod, "semilogy");
226 s_python_function_loglog = safe_import(pymod, "loglog");
227 s_python_function_fill = safe_import(pymod, "fill");
228 s_python_function_fill_between = safe_import(pymod, "fill_between");
229 s_python_function_hist = safe_import(pymod, "hist");
230 s_python_function_scatter = safe_import(pymod, "scatter");
231 s_python_function_subplot = safe_import(pymod, "subplot");
232 s_python_function_subplot2grid = safe_import(pymod, "subplot2grid");
233 s_python_function_legend = safe_import(pymod, "legend");
234 s_python_function_ylim = safe_import(pymod, "ylim");
235 s_python_function_title = safe_import(pymod, "title");
236 s_python_function_axis = safe_import(pymod, "axis");
237 s_python_function_xscale = safe_import(pymod, "xscale");
238 s_python_function_yscale = safe_import(pymod, "yscale");
239 s_python_function_xlabel = safe_import(pymod, "xlabel");
240 s_python_function_ylabel = safe_import(pymod, "ylabel");
241 s_python_function_xticks = safe_import(pymod, "xticks");
242 s_python_function_yticks = safe_import(pymod, "yticks");
243 s_python_function_tick_params = safe_import(pymod, "tick_params");
244 s_python_function_grid = safe_import(pymod, "grid");
245 s_python_function_xlim = safe_import(pymod, "xlim");
246 s_python_function_ion = safe_import(pymod, "ion");
247 s_python_function_ginput = safe_import(pymod, "ginput");
248 s_python_function_save = safe_import(pylabmod, "savefig");
249 s_python_function_annotate = safe_import(pymod, "annotate");
250 s_python_function_clf = safe_import(pymod, "clf");
251 s_python_function_errorbar = safe_import(pymod, "errorbar");
252 s_python_function_tight_layout = safe_import(pymod, "tight_layout");
253 s_python_function_stem = safe_import(pymod, "stem");
254 s_python_function_xkcd = safe_import(pymod, "xkcd");
255 s_python_function_text = safe_import(pymod, "text");
256 s_python_function_suptitle = safe_import(pymod, "suptitle");
257 s_python_function_bar = safe_import(pymod, "bar");
258 s_python_function_subplots_adjust = safe_import(pymod, "subplots_adjust");
259#ifndef WITHOUT_NUMPY
260 s_python_function_imshow = safe_import(pymod, "imshow");
261#endif
262
263 s_python_empty_tuple = PyTuple_New(0);
264 }
265
266 ~_interpreter() { Py_Finalize(); }
267 };
268
269 } // end namespace detail
270
271 // must be called before the first regular call to matplotlib to have any effect
272 inline void backend(const std::string & name) { detail::s_backend = name; }
273
274 inline bool annotate(std::string annotation, double x, double y) {
275 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
276 PyObject * xy = PyTuple_New(2);
277 PyObject * str = PyString_FromString(annotation.c_str());
278
279 PyTuple_SetItem(xy, 0, PyFloat_FromDouble(x));
280 PyTuple_SetItem(xy, 1, PyFloat_FromDouble(y));
281
282 PyObject * kwargs = PyDict_New();
283 PyDict_SetItemString(kwargs, "xy", xy);
284
285 PyObject * args = PyTuple_New(1);
286 PyTuple_SetItem(args, 0, str);
287
288 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_annotate, args, kwargs);
289
290 Py_DECREF(args);
291 Py_DECREF(kwargs);
292
293 if (res)
294 Py_DECREF(res);
295
296 return res;
297 }
298
299#ifndef WITHOUT_NUMPY
300 // Type selector for numpy array conversion
301 template <typename T>
302 struct select_npy_type {
303 const static NPY_TYPES type = NPY_NOTYPE;
304 }; // Default
305 template <>
306 struct select_npy_type<double> {
307 const static NPY_TYPES type = NPY_DOUBLE;
308 };
309 template <>
310 struct select_npy_type<float> {
311 const static NPY_TYPES type = NPY_FLOAT;
312 };
313 template <>
314 struct select_npy_type<bool> {
315 const static NPY_TYPES type = NPY_BOOL;
316 };
317 template <>
318 struct select_npy_type<int8_t> {
319 const static NPY_TYPES type = NPY_INT8;
320 };
321 template <>
322 struct select_npy_type<int16_t> {
323 const static NPY_TYPES type = NPY_SHORT;
324 };
325 template <>
326 struct select_npy_type<int32_t> {
327 const static NPY_TYPES type = NPY_INT;
328 };
329 template <>
330 struct select_npy_type<int64_t> {
331 const static NPY_TYPES type = NPY_INT64;
332 };
333 template <>
334 struct select_npy_type<uint8_t> {
335 const static NPY_TYPES type = NPY_UINT8;
336 };
337 template <>
338 struct select_npy_type<uint16_t> {
339 const static NPY_TYPES type = NPY_USHORT;
340 };
341 template <>
342 struct select_npy_type<uint32_t> {
343 const static NPY_TYPES type = NPY_ULONG;
344 };
345 template <>
346 struct select_npy_type<uint64_t> {
347 const static NPY_TYPES type = NPY_UINT64;
348 };
349
350 template <typename Numeric>
351 PyObject * get_array(const std::vector<Numeric> & v) {
352 detail::_interpreter::get(); // interpreter needs to be initialized for the
353 // numpy commands to work
354 NPY_TYPES type = select_npy_type<Numeric>::type;
355 if (type == NPY_NOTYPE) {
356 std::vector<double> vd(v.size());
357 npy_intp vsize = v.size();
358 std::copy(v.begin(), v.end(), vd.begin());
359 PyObject * varray = PyArray_SimpleNewFromData(1, &vsize, NPY_DOUBLE, (void *)(vd.data()));
360 return varray;
361 }
362
363 npy_intp vsize = v.size();
364 PyObject * varray = PyArray_SimpleNewFromData(1, &vsize, type, (void *)(v.data()));
365 return varray;
366 }
367
368 template <typename Numeric>
369 PyObject * get_2darray(const std::vector<::std::vector<Numeric>> & v) {
370 detail::_interpreter::get(); // interpreter needs to be initialized for the
371 // numpy commands to work
372 if (v.size() < 1)
373 throw std::runtime_error("get_2d_array v too small");
374
375 npy_intp vsize[2] = {static_cast<npy_intp>(v.size()), static_cast<npy_intp>(v[0].size())};
376
377 PyArrayObject * varray = (PyArrayObject *)PyArray_SimpleNew(2, vsize, NPY_DOUBLE);
378
379 double * vd_begin = static_cast<double *>(PyArray_DATA(varray));
380
381 for (const ::std::vector<Numeric> & v_row : v) {
382 if (v_row.size() != static_cast<size_t>(vsize[1]))
383 throw std::runtime_error("Missmatched array size");
384 std::copy(v_row.begin(), v_row.end(), vd_begin);
385 vd_begin += vsize[1];
386 }
387
388 return reinterpret_cast<PyObject *>(varray);
389 }
390
391#else
392 // fallback if we don't have numpy: copy every element of the given vector
393
394 template <typename Numeric>
395 PyObject * get_array(const std::vector<Numeric> & v) {
396 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
397 PyObject * list = PyList_New(v.size());
398 for (size_t i = 0; i < v.size(); ++i) {
399 PyList_SetItem(list, i, PyFloat_FromDouble(v.at(i)));
400 }
401 return list;
402 }
403
404#endif // WITHOUT_NUMPY
405
406 template <typename Numeric>
407 bool plot(const std::vector<Numeric> & x,
408 const std::vector<Numeric> & y,
409 const std::map<std::string, std::string> & keywords) {
410 assert(x.size() == y.size());
411
412 // using numpy arrays
413 PyObject * xarray = get_array(x);
414 PyObject * yarray = get_array(y);
415
416 // construct positional args
417 PyObject * args = PyTuple_New(2);
418 PyTuple_SetItem(args, 0, xarray);
419 PyTuple_SetItem(args, 1, yarray);
420
421 // construct keyword args
422 PyObject * kwargs = PyDict_New();
423 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
424 ++it) {
425 PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
426 }
427
428 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, args, kwargs);
429
430 Py_DECREF(args);
431 Py_DECREF(kwargs);
432 if (res)
433 Py_DECREF(res);
434
435 return res;
436 }
437
438 // TODO - it should be possible to make this work by implementing
439 // a non-numpy alternative for `get_2darray()`.
440#ifndef WITHOUT_NUMPY
441 template <typename Numeric>
442 void
443 plot_surface(const std::vector<::std::vector<Numeric>> & x,
444 const std::vector<::std::vector<Numeric>> & y,
445 const std::vector<::std::vector<Numeric>> & z,
446 const std::map<std::string, std::string> & keywords = std::map<std::string, std::string>()) {
447 // We lazily load the modules here the first time this function is called
448 // because I'm not sure that we can assume "matplotlib installed" implies
449 // "mpl_toolkits installed" on all platforms, and we don't want to require
450 // it for people who don't need 3d plots.
451 static PyObject *mpl_toolkitsmod = nullptr, *axis3dmod = nullptr;
452 if (!mpl_toolkitsmod) {
453 detail::_interpreter::get();
454
455 PyObject * mpl_toolkits = PyString_FromString("mpl_toolkits");
456 PyObject * axis3d = PyString_FromString("mpl_toolkits.mplot3d");
457 if (!mpl_toolkits || !axis3d) {
458 throw std::runtime_error("couldnt create string");
459 }
460
461 mpl_toolkitsmod = PyImport_Import(mpl_toolkits);
462 Py_DECREF(mpl_toolkits);
463 if (!mpl_toolkitsmod) {
464 throw std::runtime_error("Error loading module mpl_toolkits!");
465 }
466
467 axis3dmod = PyImport_Import(axis3d);
468 Py_DECREF(axis3d);
469 if (!axis3dmod) {
470 throw std::runtime_error("Error loading module mpl_toolkits.mplot3d!");
471 }
472 }
473
474 assert(x.size() == y.size());
475 assert(y.size() == z.size());
476
477 // using numpy arrays
478 PyObject * xarray = get_2darray(x);
479 PyObject * yarray = get_2darray(y);
480 PyObject * zarray = get_2darray(z);
481
482 // construct positional args
483 PyObject * args = PyTuple_New(3);
484 PyTuple_SetItem(args, 0, xarray);
485 PyTuple_SetItem(args, 1, yarray);
486 PyTuple_SetItem(args, 2, zarray);
487
488 // Build up the kw args.
489 PyObject * kwargs = PyDict_New();
490 PyDict_SetItemString(kwargs, "rstride", PyInt_FromLong(1));
491 PyDict_SetItemString(kwargs, "cstride", PyInt_FromLong(1));
492
493 PyObject * python_colormap_coolwarm =
494 PyObject_GetAttrString(detail::_interpreter::get().s_python_colormap, "coolwarm");
495
496 PyDict_SetItemString(kwargs, "cmap", python_colormap_coolwarm);
497
498 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
499 ++it) {
500 PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
501 }
502
503 PyObject * fig = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure,
504 detail::_interpreter::get().s_python_empty_tuple);
505 if (!fig)
506 throw std::runtime_error("Call to figure() failed.");
507
508 PyObject * gca_kwargs = PyDict_New();
509 PyDict_SetItemString(gca_kwargs, "projection", PyString_FromString("3d"));
510
511 PyObject * gca = PyObject_GetAttrString(fig, "gca");
512 if (!gca)
513 throw std::runtime_error("No gca");
514 Py_INCREF(gca);
515 PyObject * axis = PyObject_Call(gca, detail::_interpreter::get().s_python_empty_tuple, gca_kwargs);
516
517 if (!axis)
518 throw std::runtime_error("No axis");
519 Py_INCREF(axis);
520
521 Py_DECREF(gca);
522 Py_DECREF(gca_kwargs);
523
524 PyObject * plot_surface = PyObject_GetAttrString(axis, "plot_surface");
525 if (!plot_surface)
526 throw std::runtime_error("No surface");
527 Py_INCREF(plot_surface);
528 PyObject * res = PyObject_Call(plot_surface, args, kwargs);
529 if (!res)
530 throw std::runtime_error("failed surface");
531 Py_DECREF(plot_surface);
532
533 Py_DECREF(axis);
534 Py_DECREF(args);
535 Py_DECREF(kwargs);
536 if (res)
537 Py_DECREF(res);
538 }
539#endif // WITHOUT_NUMPY
540
541 template <typename Numeric>
542 bool stem(const std::vector<Numeric> & x,
543 const std::vector<Numeric> & y,
544 const std::map<std::string, std::string> & keywords) {
545 assert(x.size() == y.size());
546
547 // using numpy arrays
548 PyObject * xarray = get_array(x);
549 PyObject * yarray = get_array(y);
550
551 // construct positional args
552 PyObject * args = PyTuple_New(2);
553 PyTuple_SetItem(args, 0, xarray);
554 PyTuple_SetItem(args, 1, yarray);
555
556 // construct keyword args
557 PyObject * kwargs = PyDict_New();
558 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
559 ++it) {
560 PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
561 }
562
563 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_stem, args, kwargs);
564
565 Py_DECREF(args);
566 Py_DECREF(kwargs);
567 if (res)
568 Py_DECREF(res);
569
570 return res;
571 }
572
573 template <typename Numeric>
574 bool fill(const std::vector<Numeric> & x,
575 const std::vector<Numeric> & y,
576 const std::map<std::string, std::string> & keywords) {
577 assert(x.size() == y.size());
578
579 // using numpy arrays
580 PyObject * xarray = get_array(x);
581 PyObject * yarray = get_array(y);
582
583 // construct positional args
584 PyObject * args = PyTuple_New(2);
585 PyTuple_SetItem(args, 0, xarray);
586 PyTuple_SetItem(args, 1, yarray);
587
588 // construct keyword args
589 PyObject * kwargs = PyDict_New();
590 for (auto it = keywords.begin(); it != keywords.end(); ++it) {
591 PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
592 }
593
594 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_fill, args, kwargs);
595
596 Py_DECREF(args);
597 Py_DECREF(kwargs);
598
599 if (res)
600 Py_DECREF(res);
601
602 return res;
603 }
604
605 template <typename Numeric>
606 bool fill_between(const std::vector<Numeric> & x,
607 const std::vector<Numeric> & y1,
608 const std::vector<Numeric> & y2,
609 const std::map<std::string, std::string> & keywords) {
610 assert(x.size() == y1.size());
611 assert(x.size() == y2.size());
612
613 // using numpy arrays
614 PyObject * xarray = get_array(x);
615 PyObject * y1array = get_array(y1);
616 PyObject * y2array = get_array(y2);
617
618 // construct positional args
619 PyObject * args = PyTuple_New(3);
620 PyTuple_SetItem(args, 0, xarray);
621 PyTuple_SetItem(args, 1, y1array);
622 PyTuple_SetItem(args, 2, y2array);
623
624 // construct keyword args
625 PyObject * kwargs = PyDict_New();
626 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
627 ++it) {
628 PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
629 }
630
631 PyObject * res =
632 PyObject_Call(detail::_interpreter::get().s_python_function_fill_between, args, kwargs);
633
634 Py_DECREF(args);
635 Py_DECREF(kwargs);
636 if (res)
637 Py_DECREF(res);
638
639 return res;
640 }
641
642 template <typename Numeric>
643 bool hist(const std::vector<Numeric> & y,
644 long bins = 10,
645 std::string color = "b",
646 double alpha = 1.0,
647 bool cumulative = false) {
648 PyObject * yarray = get_array(y);
649
650 PyObject * kwargs = PyDict_New();
651 PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins));
652 PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str()));
653 PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha));
654 PyDict_SetItemString(kwargs, "cumulative", cumulative ? Py_True : Py_False);
655
656 PyObject * plot_args = PyTuple_New(1);
657
658 PyTuple_SetItem(plot_args, 0, yarray);
659
660 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);
661
662 Py_DECREF(plot_args);
663 Py_DECREF(kwargs);
664 if (res)
665 Py_DECREF(res);
666
667 return res;
668 }
669
670#ifndef WITHOUT_NUMPY
671 namespace internal {
672 inline void imshow(void * ptr,
673 const NPY_TYPES type,
674 const int rows,
675 const int columns,
676 const int colors,
677 const std::map<std::string, std::string> & keywords) {
678 assert(type == NPY_UINT8 || type == NPY_FLOAT);
679 assert(colors == 1 || colors == 3 || colors == 4);
680
681 detail::_interpreter::get(); // interpreter needs to be initialized for the
682 // numpy commands to work
683
684 // construct args
685 npy_intp dims[3] = {rows, columns, colors};
686 PyObject * args = PyTuple_New(1);
687 PyTuple_SetItem(args, 0, PyArray_SimpleNewFromData(colors == 1 ? 2 : 3, dims, type, ptr));
688
689 // construct keyword args
690 PyObject * kwargs = PyDict_New();
691 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
692 ++it) {
693 PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
694 }
695
696 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_imshow, args, kwargs);
697 Py_DECREF(args);
698 Py_DECREF(kwargs);
699 if (!res)
700 throw std::runtime_error("Call to imshow() failed");
701 Py_DECREF(res);
702 }
703 } // namespace internal
704
705 inline void imshow(const unsigned char * ptr,
706 const int rows,
707 const int columns,
708 const int colors,
709 const std::map<std::string, std::string> & keywords = {}) {
710 internal::imshow((void *)ptr, NPY_UINT8, rows, columns, colors, keywords);
711 }
712
713 inline void imshow(const float * ptr,
714 const int rows,
715 const int columns,
716 const int colors,
717 const std::map<std::string, std::string> & keywords = {}) {
718 internal::imshow((void *)ptr, NPY_FLOAT, rows, columns, colors, keywords);
719 }
720
721#ifdef WITH_OPENCV
722 void imshow(const cv::Mat & image, const std::map<std::string, std::string> & keywords = {}) {
723 // Convert underlying type of matrix, if needed
724 cv::Mat image2;
725 NPY_TYPES npy_type = NPY_UINT8;
726 switch (image.type() & CV_MAT_DEPTH_MASK) {
727 case CV_8U:
728 image2 = image;
729 break;
730 case CV_32F:
731 image2 = image;
732 npy_type = NPY_FLOAT;
733 break;
734 default:
735 image.convertTo(image2, CV_MAKETYPE(CV_8U, image.channels()));
736 }
737
738 // If color image, convert from BGR to RGB
739 switch (image2.channels()) {
740 case 3:
741 cv::cvtColor(image2, image2, CV_BGR2RGB);
742 break;
743 case 4:
744 cv::cvtColor(image2, image2, CV_BGRA2RGBA);
745 }
746
747 internal::imshow(image2.data, npy_type, image2.rows, image2.cols, image2.channels(), keywords);
748 }
749#endif // WITH_OPENCV
750#endif // WITHOUT_NUMPY
751
752 template <typename NumericX, typename NumericY>
753 bool scatter(const std::vector<NumericX> & x,
754 const std::vector<NumericY> & y,
755 const double s = 1.0, // The marker size in points**2
756 const std::unordered_map<std::string, std::string> & keywords = {}) {
757 assert(x.size() == y.size());
758
759 PyObject * xarray = get_array(x);
760 PyObject * yarray = get_array(y);
761
762 PyObject * kwargs = PyDict_New();
763 PyDict_SetItemString(kwargs, "s", PyLong_FromLong(s));
764 for (const auto & it : keywords) {
765 PyDict_SetItemString(kwargs, it.first.c_str(), PyString_FromString(it.second.c_str()));
766 }
767
768 PyObject * plot_args = PyTuple_New(2);
769 PyTuple_SetItem(plot_args, 0, xarray);
770 PyTuple_SetItem(plot_args, 1, yarray);
771
772 PyObject * res =
773 PyObject_Call(detail::_interpreter::get().s_python_function_scatter, plot_args, kwargs);
774
775 Py_DECREF(plot_args);
776 Py_DECREF(kwargs);
777 if (res)
778 Py_DECREF(res);
779
780 return res;
781 }
782
783 template <typename Numeric>
784 bool bar(const std::vector<Numeric> & x,
785 const std::vector<Numeric> & y,
786 std::string ec = "black",
787 std::string ls = "-",
788 double lw = 1.0,
789 const std::map<std::string, std::string> & keywords = {}) {
790 PyObject * xarray = get_array(x);
791 PyObject * yarray = get_array(y);
792
793 PyObject * kwargs = PyDict_New();
794
795 PyDict_SetItemString(kwargs, "ec", PyString_FromString(ec.c_str()));
796 PyDict_SetItemString(kwargs, "ls", PyString_FromString(ls.c_str()));
797 PyDict_SetItemString(kwargs, "lw", PyFloat_FromDouble(lw));
798
799 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
800 ++it) {
801 PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
802 }
803
804 PyObject * plot_args = PyTuple_New(2);
805 PyTuple_SetItem(plot_args, 0, xarray);
806 PyTuple_SetItem(plot_args, 1, yarray);
807
808 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_bar, plot_args, kwargs);
809
810 Py_DECREF(plot_args);
811 Py_DECREF(kwargs);
812 if (res)
813 Py_DECREF(res);
814
815 return res;
816 }
817
818 template <typename Numeric>
819 bool bar(const std::vector<Numeric> & y,
820 std::string ec = "black",
821 std::string ls = "-",
822 double lw = 1.0,
823 const std::map<std::string, std::string> & keywords = {}) {
824 using T = typename std::remove_reference<decltype(y)>::type::value_type;
825
826 std::vector<T> x;
827 for (std::size_t i = 0; i < y.size(); i++) {
828 x.push_back(i);
829 }
830
831 return bar(x, y, ec, ls, lw, keywords);
832 }
833
834 inline bool subplots_adjust(const std::map<std::string, double> & keywords = {}) {
835 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
836 PyObject * kwargs = PyDict_New();
837 for (std::map<std::string, double>::const_iterator it = keywords.begin(); it != keywords.end(); ++it) {
838 PyDict_SetItemString(kwargs, it->first.c_str(), PyFloat_FromDouble(it->second));
839 }
840
841 PyObject * plot_args = PyTuple_New(0);
842
843 PyObject * res =
844 PyObject_Call(detail::_interpreter::get().s_python_function_subplots_adjust, plot_args, kwargs);
845
846 Py_DECREF(plot_args);
847 Py_DECREF(kwargs);
848 if (res)
849 Py_DECREF(res);
850
851 return res;
852 }
853
854 template <typename Numeric>
855 bool named_hist(std::string label,
856 const std::vector<Numeric> & y,
857 long bins = 10,
858 std::string color = "b",
859 double alpha = 1.0) {
860 PyObject * yarray = get_array(y);
861
862 PyObject * kwargs = PyDict_New();
863 PyDict_SetItemString(kwargs, "label", PyString_FromString(label.c_str()));
864 PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins));
865 PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str()));
866 PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha));
867
868 PyObject * plot_args = PyTuple_New(1);
869 PyTuple_SetItem(plot_args, 0, yarray);
870
871 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);
872
873 Py_DECREF(plot_args);
874 Py_DECREF(kwargs);
875 if (res)
876 Py_DECREF(res);
877
878 return res;
879 }
880
881 template <typename NumericX, typename NumericY>
882 bool plot(const std::vector<NumericX> & x, const std::vector<NumericY> & y, const std::string & s = "") {
883 assert(x.size() == y.size());
884
885 PyObject * xarray = get_array(x);
886 PyObject * yarray = get_array(y);
887
888 PyObject * pystring = PyString_FromString(s.c_str());
889
890 PyObject * plot_args = PyTuple_New(3);
891 PyTuple_SetItem(plot_args, 0, xarray);
892 PyTuple_SetItem(plot_args, 1, yarray);
893 PyTuple_SetItem(plot_args, 2, pystring);
894
895 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);
896
897 Py_DECREF(plot_args);
898 if (res)
899 Py_DECREF(res);
900
901 return res;
902 }
903
904 template <typename NumericX, typename NumericY, typename NumericU, typename NumericW>
905 bool quiver(const std::vector<NumericX> & x,
906 const std::vector<NumericY> & y,
907 const std::vector<NumericU> & u,
908 const std::vector<NumericW> & w,
909 const std::map<std::string, std::string> & keywords = {}) {
910 assert(x.size() == y.size() and x.size() == u.size() and u.size() == w.size());
911
912 PyObject * xarray = get_array(x);
913 PyObject * yarray = get_array(y);
914 PyObject * uarray = get_array(u);
915 PyObject * warray = get_array(w);
916
917 PyObject * plot_args = PyTuple_New(4);
918 PyTuple_SetItem(plot_args, 0, xarray);
919 PyTuple_SetItem(plot_args, 1, yarray);
920 PyTuple_SetItem(plot_args, 2, uarray);
921 PyTuple_SetItem(plot_args, 3, warray);
922
923 // construct keyword args
924 PyObject * kwargs = PyDict_New();
925 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
926 ++it) {
927 PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
928 }
929
930 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_quiver, plot_args, kwargs);
931
932 Py_DECREF(kwargs);
933 Py_DECREF(plot_args);
934 if (res)
935 Py_DECREF(res);
936
937 return res;
938 }
939
940 template <typename NumericX, typename NumericY>
941 bool stem(const std::vector<NumericX> & x, const std::vector<NumericY> & y, const std::string & s = "") {
942 assert(x.size() == y.size());
943
944 PyObject * xarray = get_array(x);
945 PyObject * yarray = get_array(y);
946
947 PyObject * pystring = PyString_FromString(s.c_str());
948
949 PyObject * plot_args = PyTuple_New(3);
950 PyTuple_SetItem(plot_args, 0, xarray);
951 PyTuple_SetItem(plot_args, 1, yarray);
952 PyTuple_SetItem(plot_args, 2, pystring);
953
954 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_stem, plot_args);
955
956 Py_DECREF(plot_args);
957 if (res)
958 Py_DECREF(res);
959
960 return res;
961 }
962
963 template <typename NumericX, typename NumericY>
964 bool
965 semilogx(const std::vector<NumericX> & x, const std::vector<NumericY> & y, const std::string & s = "") {
966 assert(x.size() == y.size());
967
968 PyObject * xarray = get_array(x);
969 PyObject * yarray = get_array(y);
970
971 PyObject * pystring = PyString_FromString(s.c_str());
972
973 PyObject * plot_args = PyTuple_New(3);
974 PyTuple_SetItem(plot_args, 0, xarray);
975 PyTuple_SetItem(plot_args, 1, yarray);
976 PyTuple_SetItem(plot_args, 2, pystring);
977
978 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogx, plot_args);
979
980 Py_DECREF(plot_args);
981 if (res)
982 Py_DECREF(res);
983
984 return res;
985 }
986
987 template <typename NumericX, typename NumericY>
988 bool
989 semilogy(const std::vector<NumericX> & x, const std::vector<NumericY> & y, const std::string & s = "") {
990 assert(x.size() == y.size());
991
992 PyObject * xarray = get_array(x);
993 PyObject * yarray = get_array(y);
994
995 PyObject * pystring = PyString_FromString(s.c_str());
996
997 PyObject * plot_args = PyTuple_New(3);
998 PyTuple_SetItem(plot_args, 0, xarray);
999 PyTuple_SetItem(plot_args, 1, yarray);
1000 PyTuple_SetItem(plot_args, 2, pystring);
1001
1002 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogy, plot_args);
1003
1004 Py_DECREF(plot_args);
1005 if (res)
1006 Py_DECREF(res);
1007
1008 return res;
1009 }
1010
1011 template <typename NumericX, typename NumericY>
1012 bool loglog(const std::vector<NumericX> & x, const std::vector<NumericY> & y, const std::string & s = "") {
1013 assert(x.size() == y.size());
1014
1015 PyObject * xarray = get_array(x);
1016 PyObject * yarray = get_array(y);
1017
1018 PyObject * pystring = PyString_FromString(s.c_str());
1019
1020 PyObject * plot_args = PyTuple_New(3);
1021 PyTuple_SetItem(plot_args, 0, xarray);
1022 PyTuple_SetItem(plot_args, 1, yarray);
1023 PyTuple_SetItem(plot_args, 2, pystring);
1024
1025 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_loglog, plot_args);
1026
1027 Py_DECREF(plot_args);
1028 if (res)
1029 Py_DECREF(res);
1030
1031 return res;
1032 }
1033
1034 template <typename NumericX, typename NumericY>
1035 bool errorbar(const std::vector<NumericX> & x,
1036 const std::vector<NumericY> & y,
1037 const std::vector<NumericX> & yerr,
1038 const std::map<std::string, std::string> & keywords = {}) {
1039 assert(x.size() == y.size());
1040
1041 PyObject * xarray = get_array(x);
1042 PyObject * yarray = get_array(y);
1043 PyObject * yerrarray = get_array(yerr);
1044
1045 // construct keyword args
1046 PyObject * kwargs = PyDict_New();
1047 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
1048 ++it) {
1049 PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
1050 }
1051
1052 PyDict_SetItemString(kwargs, "yerr", yerrarray);
1053
1054 PyObject * plot_args = PyTuple_New(2);
1055 PyTuple_SetItem(plot_args, 0, xarray);
1056 PyTuple_SetItem(plot_args, 1, yarray);
1057
1058 PyObject * res =
1059 PyObject_Call(detail::_interpreter::get().s_python_function_errorbar, plot_args, kwargs);
1060
1061 Py_DECREF(kwargs);
1062 Py_DECREF(plot_args);
1063
1064 if (res)
1065 Py_DECREF(res);
1066 else
1067 throw std::runtime_error("Call to errorbar() failed.");
1068
1069 return res;
1070 }
1071
1072 template <typename Numeric>
1073 bool named_plot(const std::string & name, const std::vector<Numeric> & y, const std::string & format = "") {
1074 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1075 PyObject * kwargs = PyDict_New();
1076 PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
1077
1078 PyObject * yarray = get_array(y);
1079
1080 PyObject * pystring = PyString_FromString(format.c_str());
1081
1082 PyObject * plot_args = PyTuple_New(2);
1083
1084 PyTuple_SetItem(plot_args, 0, yarray);
1085 PyTuple_SetItem(plot_args, 1, pystring);
1086
1087 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
1088
1089 Py_DECREF(kwargs);
1090 Py_DECREF(plot_args);
1091 if (res)
1092 Py_DECREF(res);
1093
1094 return res;
1095 }
1096
1097 template <typename Numeric>
1098 bool named_plot(const std::string & name,
1099 const std::vector<Numeric> & x,
1100 const std::vector<Numeric> & y,
1101 const std::string & format = "") {
1102 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1103 PyObject * kwargs = PyDict_New();
1104 PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
1105
1106 PyObject * xarray = get_array(x);
1107 PyObject * yarray = get_array(y);
1108
1109 PyObject * pystring = PyString_FromString(format.c_str());
1110
1111 PyObject * plot_args = PyTuple_New(3);
1112 PyTuple_SetItem(plot_args, 0, xarray);
1113 PyTuple_SetItem(plot_args, 1, yarray);
1114 PyTuple_SetItem(plot_args, 2, pystring);
1115
1116 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
1117
1118 Py_DECREF(kwargs);
1119 Py_DECREF(plot_args);
1120 if (res)
1121 Py_DECREF(res);
1122
1123 return res;
1124 }
1125
1126 template <typename Numeric>
1127 bool named_semilogx(const std::string & name,
1128 const std::vector<Numeric> & x,
1129 const std::vector<Numeric> & y,
1130 const std::string & format = "") {
1131 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1132 PyObject * kwargs = PyDict_New();
1133 PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
1134
1135 PyObject * xarray = get_array(x);
1136 PyObject * yarray = get_array(y);
1137
1138 PyObject * pystring = PyString_FromString(format.c_str());
1139
1140 PyObject * plot_args = PyTuple_New(3);
1141 PyTuple_SetItem(plot_args, 0, xarray);
1142 PyTuple_SetItem(plot_args, 1, yarray);
1143 PyTuple_SetItem(plot_args, 2, pystring);
1144
1145 PyObject * res =
1146 PyObject_Call(detail::_interpreter::get().s_python_function_semilogx, plot_args, kwargs);
1147
1148 Py_DECREF(kwargs);
1149 Py_DECREF(plot_args);
1150 if (res)
1151 Py_DECREF(res);
1152
1153 return res;
1154 }
1155
1156 template <typename Numeric>
1157 bool named_semilogy(const std::string & name,
1158 const std::vector<Numeric> & x,
1159 const std::vector<Numeric> & y,
1160 const std::string & format = "") {
1161 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1162 PyObject * kwargs = PyDict_New();
1163 PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
1164
1165 PyObject * xarray = get_array(x);
1166 PyObject * yarray = get_array(y);
1167
1168 PyObject * pystring = PyString_FromString(format.c_str());
1169
1170 PyObject * plot_args = PyTuple_New(3);
1171 PyTuple_SetItem(plot_args, 0, xarray);
1172 PyTuple_SetItem(plot_args, 1, yarray);
1173 PyTuple_SetItem(plot_args, 2, pystring);
1174
1175 PyObject * res =
1176 PyObject_Call(detail::_interpreter::get().s_python_function_semilogy, plot_args, kwargs);
1177
1178 Py_DECREF(kwargs);
1179 Py_DECREF(plot_args);
1180 if (res)
1181 Py_DECREF(res);
1182
1183 return res;
1184 }
1185
1186 template <typename Numeric>
1187 bool named_loglog(const std::string & name,
1188 const std::vector<Numeric> & x,
1189 const std::vector<Numeric> & y,
1190 const std::string & format = "") {
1191 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1192 PyObject * kwargs = PyDict_New();
1193 PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
1194
1195 PyObject * xarray = get_array(x);
1196 PyObject * yarray = get_array(y);
1197
1198 PyObject * pystring = PyString_FromString(format.c_str());
1199
1200 PyObject * plot_args = PyTuple_New(3);
1201 PyTuple_SetItem(plot_args, 0, xarray);
1202 PyTuple_SetItem(plot_args, 1, yarray);
1203 PyTuple_SetItem(plot_args, 2, pystring);
1204 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_loglog, plot_args, kwargs);
1205
1206 Py_DECREF(kwargs);
1207 Py_DECREF(plot_args);
1208 if (res)
1209 Py_DECREF(res);
1210
1211 return res;
1212 }
1213
1214 template <typename Numeric>
1215 bool plot(const std::vector<Numeric> & y, const std::string & format = "") {
1216 std::vector<Numeric> x(y.size());
1217 for (size_t i = 0; i < x.size(); ++i)
1218 x.at(i) = i;
1219 return plot(x, y, format);
1220 }
1221
1222 template <typename Numeric>
1223 bool plot(const std::vector<Numeric> & y, const std::map<std::string, std::string> & keywords) {
1224 std::vector<Numeric> x(y.size());
1225 for (size_t i = 0; i < x.size(); ++i)
1226 x.at(i) = i;
1227 return plot(x, y, keywords);
1228 }
1229
1230 template <typename Numeric>
1231 bool stem(const std::vector<Numeric> & y, const std::string & format = "") {
1232 std::vector<Numeric> x(y.size());
1233 for (size_t i = 0; i < x.size(); ++i)
1234 x.at(i) = i;
1235 return stem(x, y, format);
1236 }
1237
1238 template <typename Numeric>
1239 void text(Numeric x, Numeric y, const std::string & s = "") {
1240 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1241 PyObject * args = PyTuple_New(3);
1242 PyTuple_SetItem(args, 0, PyFloat_FromDouble(x));
1243 PyTuple_SetItem(args, 1, PyFloat_FromDouble(y));
1244 PyTuple_SetItem(args, 2, PyString_FromString(s.c_str()));
1245
1246 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_text, args);
1247 if (!res)
1248 throw std::runtime_error("Call to text() failed.");
1249
1250 Py_DECREF(args);
1251 Py_DECREF(res);
1252 }
1253
1254 inline long figure(long number = -1) {
1255 PyObject * res;
1256 if (number == -1)
1257 res = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure,
1258 detail::_interpreter::get().s_python_empty_tuple);
1259 else {
1260 assert(number > 0);
1261
1262 // Make sure interpreter is initialised
1263 detail::_interpreter::get();
1264
1265 PyObject * args = PyTuple_New(1);
1266 PyTuple_SetItem(args, 0, PyLong_FromLong(number));
1267 res = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure, args);
1268 Py_DECREF(args);
1269 }
1270
1271 if (!res)
1272 throw std::runtime_error("Call to figure() failed.");
1273
1274 PyObject * num = PyObject_GetAttrString(res, "number");
1275 if (!num)
1276 throw std::runtime_error("Could not get number attribute of figure object");
1277 const long figureNumber = PyLong_AsLong(num);
1278
1279 Py_DECREF(num);
1280 Py_DECREF(res);
1281
1282 return figureNumber;
1283 }
1284
1285 inline bool fignum_exists(long number) {
1286 // Make sure interpreter is initialised
1287 detail::_interpreter::get();
1288
1289 PyObject * args = PyTuple_New(1);
1290 PyTuple_SetItem(args, 0, PyLong_FromLong(number));
1291 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_fignum_exists, args);
1292 if (!res)
1293 throw std::runtime_error("Call to fignum_exists() failed.");
1294
1295 bool ret = PyObject_IsTrue(res);
1296 Py_DECREF(res);
1297 Py_DECREF(args);
1298
1299 return ret;
1300 }
1301
1302 inline void figure_size(size_t w, size_t h) {
1303 // Make sure interpreter is initialised
1304 detail::_interpreter::get();
1305
1306 const size_t dpi = 100;
1307 PyObject * size = PyTuple_New(2);
1308 PyTuple_SetItem(size, 0, PyFloat_FromDouble((double)w / dpi));
1309 PyTuple_SetItem(size, 1, PyFloat_FromDouble((double)h / dpi));
1310
1311 PyObject * kwargs = PyDict_New();
1312 PyDict_SetItemString(kwargs, "figsize", size);
1313 PyDict_SetItemString(kwargs, "dpi", PyLong_FromSize_t(dpi));
1314
1315 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_figure,
1316 detail::_interpreter::get().s_python_empty_tuple,
1317 kwargs);
1318
1319 Py_DECREF(kwargs);
1320
1321 if (!res)
1322 throw std::runtime_error("Call to figure_size() failed.");
1323 Py_DECREF(res);
1324 }
1325
1326 inline void legend() {
1327 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_legend,
1328 detail::_interpreter::get().s_python_empty_tuple);
1329 if (!res)
1330 throw std::runtime_error("Call to legend() failed.");
1331
1332 Py_DECREF(res);
1333 }
1334
1335 template <typename Numeric>
1336 void ylim(Numeric left, Numeric right) {
1337 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1338 PyObject * list = PyList_New(2);
1339 PyList_SetItem(list, 0, PyFloat_FromDouble(left));
1340 PyList_SetItem(list, 1, PyFloat_FromDouble(right));
1341
1342 PyObject * args = PyTuple_New(1);
1343 PyTuple_SetItem(args, 0, list);
1344
1345 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);
1346 if (!res)
1347 throw std::runtime_error("Call to ylim() failed.");
1348
1349 Py_DECREF(args);
1350 Py_DECREF(res);
1351 }
1352
1353 template <typename Numeric>
1354 void xlim(Numeric left, Numeric right) {
1355 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1356 PyObject * list = PyList_New(2);
1357 PyList_SetItem(list, 0, PyFloat_FromDouble(left));
1358 PyList_SetItem(list, 1, PyFloat_FromDouble(right));
1359
1360 PyObject * args = PyTuple_New(1);
1361 PyTuple_SetItem(args, 0, list);
1362
1363 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);
1364 if (!res)
1365 throw std::runtime_error("Call to xlim() failed.");
1366
1367 Py_DECREF(args);
1368 Py_DECREF(res);
1369 }
1370
1371 inline double * xlim() {
1372 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1373 PyObject * args = PyTuple_New(0);
1374 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);
1375 PyObject * left = PyTuple_GetItem(res, 0);
1376 PyObject * right = PyTuple_GetItem(res, 1);
1377
1378 double * arr = new double[2];
1379 arr[0] = PyFloat_AsDouble(left);
1380 arr[1] = PyFloat_AsDouble(right);
1381
1382 if (!res)
1383 throw std::runtime_error("Call to xlim() failed.");
1384
1385 Py_DECREF(res);
1386 return arr;
1387 }
1388
1389 inline double * ylim() {
1390 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1391 PyObject * args = PyTuple_New(0);
1392 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);
1393 PyObject * left = PyTuple_GetItem(res, 0);
1394 PyObject * right = PyTuple_GetItem(res, 1);
1395
1396 double * arr = new double[2];
1397 arr[0] = PyFloat_AsDouble(left);
1398 arr[1] = PyFloat_AsDouble(right);
1399
1400 if (!res)
1401 throw std::runtime_error("Call to ylim() failed.");
1402
1403 Py_DECREF(res);
1404 return arr;
1405 }
1406
1407 template <typename Numeric>
1408 inline void xticks(const std::vector<Numeric> & ticks,
1409 const std::vector<std::string> & labels = {},
1410 const std::map<std::string, std::string> & keywords = {}) {
1411 assert(labels.size() == 0 || ticks.size() == labels.size());
1412
1413 // using numpy array
1414 PyObject * ticksarray = get_array(ticks);
1415
1416 PyObject * args;
1417 if (labels.size() == 0) {
1418 // construct positional args
1419 args = PyTuple_New(1);
1420 PyTuple_SetItem(args, 0, ticksarray);
1421 } else {
1422 // make tuple of tick labels
1423 PyObject * labelstuple = PyTuple_New(labels.size());
1424 for (size_t i = 0; i < labels.size(); i++)
1425 PyTuple_SetItem(labelstuple, i, PyUnicode_FromString(labels[i].c_str()));
1426
1427 // construct positional args
1428 args = PyTuple_New(2);
1429 PyTuple_SetItem(args, 0, ticksarray);
1430 PyTuple_SetItem(args, 1, labelstuple);
1431 }
1432
1433 // construct keyword args
1434 PyObject * kwargs = PyDict_New();
1435 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
1436 ++it) {
1437 PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
1438 }
1439
1440 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_xticks, args, kwargs);
1441
1442 Py_DECREF(args);
1443 Py_DECREF(kwargs);
1444 if (!res)
1445 throw std::runtime_error("Call to xticks() failed");
1446
1447 Py_DECREF(res);
1448 }
1449
1450 template <typename Numeric>
1451 inline void xticks(const std::vector<Numeric> & ticks,
1452 const std::map<std::string, std::string> & keywords) {
1453 xticks(ticks, {}, keywords);
1454 }
1455
1456 template <typename Numeric>
1457 inline void yticks(const std::vector<Numeric> & ticks,
1458 const std::vector<std::string> & labels = {},
1459 const std::map<std::string, std::string> & keywords = {}) {
1460 assert(labels.size() == 0 || ticks.size() == labels.size());
1461
1462 // using numpy array
1463 PyObject * ticksarray = get_array(ticks);
1464
1465 PyObject * args;
1466 if (labels.size() == 0) {
1467 // construct positional args
1468 args = PyTuple_New(1);
1469 PyTuple_SetItem(args, 0, ticksarray);
1470 } else {
1471 // make tuple of tick labels
1472 PyObject * labelstuple = PyTuple_New(labels.size());
1473 for (size_t i = 0; i < labels.size(); i++)
1474 PyTuple_SetItem(labelstuple, i, PyUnicode_FromString(labels[i].c_str()));
1475
1476 // construct positional args
1477 args = PyTuple_New(2);
1478 PyTuple_SetItem(args, 0, ticksarray);
1479 PyTuple_SetItem(args, 1, labelstuple);
1480 }
1481
1482 // construct keyword args
1483 PyObject * kwargs = PyDict_New();
1484 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
1485 ++it) {
1486 PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
1487 }
1488
1489 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_yticks, args, kwargs);
1490
1491 Py_DECREF(args);
1492 Py_DECREF(kwargs);
1493 if (!res)
1494 throw std::runtime_error("Call to yticks() failed");
1495
1496 Py_DECREF(res);
1497 }
1498
1499 template <typename Numeric>
1500 inline void yticks(const std::vector<Numeric> & ticks,
1501 const std::map<std::string, std::string> & keywords) {
1502 yticks(ticks, {}, keywords);
1503 }
1504
1505 inline void tick_params(const std::map<std::string, std::string> & keywords,
1506 const std::string axis = "both") {
1507 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1508 // construct positional args
1509 PyObject * args;
1510 args = PyTuple_New(1);
1511 PyTuple_SetItem(args, 0, PyString_FromString(axis.c_str()));
1512
1513 // construct keyword args
1514 PyObject * kwargs = PyDict_New();
1515 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
1516 ++it) {
1517 PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
1518 }
1519
1520 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_tick_params, args, kwargs);
1521
1522 Py_DECREF(args);
1523 Py_DECREF(kwargs);
1524 if (!res)
1525 throw std::runtime_error("Call to tick_params() failed");
1526
1527 Py_DECREF(res);
1528 }
1529
1530 inline void subplot(long nrows, long ncols, long plot_number) {
1531 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1532 // construct positional args
1533 PyObject * args = PyTuple_New(3);
1534 PyTuple_SetItem(args, 0, PyFloat_FromDouble(nrows));
1535 PyTuple_SetItem(args, 1, PyFloat_FromDouble(ncols));
1536 PyTuple_SetItem(args, 2, PyFloat_FromDouble(plot_number));
1537
1538 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_subplot, args);
1539 if (!res)
1540 throw std::runtime_error("Call to subplot() failed.");
1541
1542 Py_DECREF(args);
1543 Py_DECREF(res);
1544 }
1545
1546 inline void
1547 subplot2grid(long nrows, long ncols, long rowid = 0, long colid = 0, long rowspan = 1, long colspan = 1) {
1548 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1549 PyObject * shape = PyTuple_New(2);
1550 PyTuple_SetItem(shape, 0, PyLong_FromLong(nrows));
1551 PyTuple_SetItem(shape, 1, PyLong_FromLong(ncols));
1552
1553 PyObject * loc = PyTuple_New(2);
1554 PyTuple_SetItem(loc, 0, PyLong_FromLong(rowid));
1555 PyTuple_SetItem(loc, 1, PyLong_FromLong(colid));
1556
1557 PyObject * args = PyTuple_New(4);
1558 PyTuple_SetItem(args, 0, shape);
1559 PyTuple_SetItem(args, 1, loc);
1560 PyTuple_SetItem(args, 2, PyLong_FromLong(rowspan));
1561 PyTuple_SetItem(args, 3, PyLong_FromLong(colspan));
1562
1563 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_subplot2grid, args);
1564 if (!res)
1565 throw std::runtime_error("Call to subplot2grid() failed.");
1566
1567 Py_DECREF(shape);
1568 Py_DECREF(loc);
1569 Py_DECREF(args);
1570 Py_DECREF(res);
1571 }
1572
1573 inline void title(const std::string & titlestr, const std::map<std::string, std::string> & keywords = {}) {
1574 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1575 PyObject * pytitlestr = PyString_FromString(titlestr.c_str());
1576 PyObject * args = PyTuple_New(1);
1577 PyTuple_SetItem(args, 0, pytitlestr);
1578
1579 PyObject * kwargs = PyDict_New();
1580 for (auto it = keywords.begin(); it != keywords.end(); ++it) {
1581 PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
1582 }
1583
1584 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_title, args, kwargs);
1585 if (!res)
1586 throw std::runtime_error("Call to title() failed.");
1587
1588 Py_DECREF(args);
1589 Py_DECREF(kwargs);
1590 Py_DECREF(res);
1591 }
1592
1593 inline void suptitle(const std::string & suptitlestr,
1594 const std::map<std::string, std::string> & keywords = {}) {
1595 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1596 PyObject * pysuptitlestr = PyString_FromString(suptitlestr.c_str());
1597 PyObject * args = PyTuple_New(1);
1598 PyTuple_SetItem(args, 0, pysuptitlestr);
1599
1600 PyObject * kwargs = PyDict_New();
1601 for (auto it = keywords.begin(); it != keywords.end(); ++it) {
1602 PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
1603 }
1604
1605 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_suptitle, args, kwargs);
1606 if (!res)
1607 throw std::runtime_error("Call to suptitle() failed.");
1608
1609 Py_DECREF(args);
1610 Py_DECREF(kwargs);
1611 Py_DECREF(res);
1612 }
1613
1614 inline void axis(const std::string & axisstr) {
1615 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1616 PyObject * str = PyString_FromString(axisstr.c_str());
1617 PyObject * args = PyTuple_New(1);
1618 PyTuple_SetItem(args, 0, str);
1619
1620 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_axis, args);
1621 if (!res)
1622 throw std::runtime_error("Call to title() failed.");
1623
1624 Py_DECREF(args);
1625 Py_DECREF(res);
1626 }
1627
1628 inline void xscale(const std::string & xscale) {
1629 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1630 PyObject * str = PyString_FromString(xscale.c_str());
1631 PyObject * args = PyTuple_New(1);
1632 PyTuple_SetItem(args, 0, str);
1633
1634 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xscale, args);
1635 if (!res)
1636 throw std::runtime_error("Call to title() failed.");
1637
1638 Py_DECREF(args);
1639 Py_DECREF(res);
1640 }
1641
1642 inline void yscale(const std::string & yscale) {
1643 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1644 PyObject * str = PyString_FromString(yscale.c_str());
1645 PyObject * args = PyTuple_New(1);
1646 PyTuple_SetItem(args, 0, str);
1647
1648 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_yscale, args);
1649 if (!res)
1650 throw std::runtime_error("Call to title() failed.");
1651
1652 Py_DECREF(args);
1653 Py_DECREF(res);
1654 }
1655
1656 inline void xlabel(const std::string & str, const std::map<std::string, std::string> & keywords = {}) {
1657 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1658 PyObject * pystr = PyString_FromString(str.c_str());
1659 PyObject * args = PyTuple_New(1);
1660 PyTuple_SetItem(args, 0, pystr);
1661
1662 PyObject * kwargs = PyDict_New();
1663 for (auto it = keywords.begin(); it != keywords.end(); ++it) {
1664 PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
1665 }
1666
1667 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_xlabel, args, kwargs);
1668 if (!res)
1669 throw std::runtime_error("Call to xlabel() failed.");
1670
1671 Py_DECREF(args);
1672 Py_DECREF(kwargs);
1673 Py_DECREF(res);
1674 }
1675
1676 inline void ylabel(const std::string & str, const std::map<std::string, std::string> & keywords = {}) {
1677 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1678 PyObject * pystr = PyString_FromString(str.c_str());
1679 PyObject * args = PyTuple_New(1);
1680 PyTuple_SetItem(args, 0, pystr);
1681
1682 PyObject * kwargs = PyDict_New();
1683 for (auto it = keywords.begin(); it != keywords.end(); ++it) {
1684 PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
1685 }
1686
1687 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_ylabel, args, kwargs);
1688 if (!res)
1689 throw std::runtime_error("Call to ylabel() failed.");
1690
1691 Py_DECREF(args);
1692 Py_DECREF(kwargs);
1693 Py_DECREF(res);
1694 }
1695
1696 inline void grid(bool flag) {
1697 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1698 PyObject * pyflag = flag ? Py_True : Py_False;
1699 Py_INCREF(pyflag);
1700
1701 PyObject * args = PyTuple_New(1);
1702 PyTuple_SetItem(args, 0, pyflag);
1703
1704 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_grid, args);
1705 if (!res)
1706 throw std::runtime_error("Call to grid() failed.");
1707
1708 Py_DECREF(args);
1709 Py_DECREF(res);
1710 }
1711
1712 inline void show(const bool block = true) {
1713 PyObject * res;
1714 if (block) {
1715 res = PyObject_CallObject(detail::_interpreter::get().s_python_function_show,
1716 detail::_interpreter::get().s_python_empty_tuple);
1717 } else {
1718 PyObject * kwargs = PyDict_New();
1719 PyDict_SetItemString(kwargs, "block", Py_False);
1720 res = PyObject_Call(detail::_interpreter::get().s_python_function_show,
1721 detail::_interpreter::get().s_python_empty_tuple,
1722 kwargs);
1723 Py_DECREF(kwargs);
1724 }
1725
1726 if (!res)
1727 throw std::runtime_error("Call to show() failed.");
1728
1729 Py_DECREF(res);
1730 }
1731
1732 inline void close() {
1733 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_close,
1734 detail::_interpreter::get().s_python_empty_tuple);
1735
1736 if (!res)
1737 throw std::runtime_error("Call to close() failed.");
1738
1739 Py_DECREF(res);
1740 }
1741
1742 inline void xkcd() {
1743 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1744 PyObject * res;
1745 PyObject * kwargs = PyDict_New();
1746
1747 res = PyObject_Call(detail::_interpreter::get().s_python_function_xkcd,
1748 detail::_interpreter::get().s_python_empty_tuple,
1749 kwargs);
1750
1751 Py_DECREF(kwargs);
1752
1753 if (!res)
1754 throw std::runtime_error("Call to show() failed.");
1755
1756 Py_DECREF(res);
1757 }
1758
1759 inline void draw() {
1760 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_draw,
1761 detail::_interpreter::get().s_python_empty_tuple);
1762
1763 if (!res)
1764 throw std::runtime_error("Call to draw() failed.");
1765
1766 Py_DECREF(res);
1767 }
1768
1769 template <typename Numeric>
1770 inline void pause(Numeric interval) {
1771 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1772 PyObject * args = PyTuple_New(1);
1773 PyTuple_SetItem(args, 0, PyFloat_FromDouble(interval));
1774
1775 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_pause, args);
1776 if (!res)
1777 throw std::runtime_error("Call to pause() failed.");
1778
1779 Py_DECREF(args);
1780 Py_DECREF(res);
1781 }
1782
1783 inline void save(const std::string & filename) {
1784 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1785 PyObject * pyfilename = PyString_FromString(filename.c_str());
1786
1787 PyObject * args = PyTuple_New(1);
1788 PyTuple_SetItem(args, 0, pyfilename);
1789
1790 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_save, args);
1791 if (!res)
1792 throw std::runtime_error("Call to save() failed.");
1793
1794 Py_DECREF(args);
1795 Py_DECREF(res);
1796 }
1797
1798 inline void clf() {
1799 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_clf,
1800 detail::_interpreter::get().s_python_empty_tuple);
1801
1802 if (!res)
1803 throw std::runtime_error("Call to clf() failed.");
1804
1805 Py_DECREF(res);
1806 }
1807
1808 inline void ion() {
1809 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ion,
1810 detail::_interpreter::get().s_python_empty_tuple);
1811
1812 if (!res)
1813 throw std::runtime_error("Call to ion() failed.");
1814
1815 Py_DECREF(res);
1816 }
1817
1818 inline std::vector<std::array<double, 2>> ginput(const int numClicks = 1,
1819 const std::map<std::string, std::string> & keywords = {}) {
1820 detail::_interpreter::get(); // the interpreter must be initialized before calling Python
1821 PyObject * args = PyTuple_New(1);
1822 PyTuple_SetItem(args, 0, PyLong_FromLong(numClicks));
1823
1824 // construct keyword args
1825 PyObject * kwargs = PyDict_New();
1826 for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end();
1827 ++it) {
1828 PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
1829 }
1830
1831 PyObject * res = PyObject_Call(detail::_interpreter::get().s_python_function_ginput, args, kwargs);
1832
1833 Py_DECREF(kwargs);
1834 Py_DECREF(args);
1835 if (!res)
1836 throw std::runtime_error("Call to ginput() failed.");
1837
1838 const size_t len = PyList_Size(res);
1839 std::vector<std::array<double, 2>> out;
1840 out.reserve(len);
1841 for (size_t i = 0; i < len; i++) {
1842 PyObject * current = PyList_GetItem(res, i);
1843 std::array<double, 2> position;
1844 position[0] = PyFloat_AsDouble(PyTuple_GetItem(current, 0));
1845 position[1] = PyFloat_AsDouble(PyTuple_GetItem(current, 1));
1846 out.push_back(position);
1847 }
1848 Py_DECREF(res);
1849
1850 return out;
1851 }
1852
1853 // Actually, is there any reason not to call this automatically for every plot?
1854 inline void tight_layout() {
1855 PyObject * res = PyObject_CallObject(detail::_interpreter::get().s_python_function_tight_layout,
1856 detail::_interpreter::get().s_python_empty_tuple);
1857
1858 if (!res)
1859 throw std::runtime_error("Call to tight_layout() failed.");
1860
1861 Py_DECREF(res);
1862 }
1863
1864 // Support for variadic plot() and initializer lists:
1865
1866 namespace detail {
1867
1868 template <typename T>
1869 using is_function = typename std::is_function<std::remove_pointer<std::remove_reference<T>>>::type;
1870
1871 template <bool obj, typename T>
1872 struct is_callable_impl;
1873
1874 template <typename T>
1875 struct is_callable_impl<false, T> {
1876 typedef is_function<T> type;
1877 }; // a non-object is callable iff it is a function
1878
1879 template <typename T>
1880 struct is_callable_impl<true, T> {
1881 struct Fallback {
1882 void operator()();
1883 };
1884 struct Derived : T, Fallback {};
1885
1886 template <typename U, U>
1887 struct Check;
1888
1889 template <typename U>
1890 static std::true_type test(...); // use a variadic function to make sure (1) it accepts everything
1891 // and (2) its always the worst match
1892
1893 template <typename U>
1894 static std::false_type test(Check<void (Fallback::*)(), &U::operator()> *);
1895
1896 public:
1897 typedef decltype(test<Derived>(nullptr)) type;
1898 typedef decltype(&Fallback::operator()) dtype;
1899 static constexpr bool value = type::value;
1900 }; // an object is callable iff it defines operator()
1901
1902 template <typename T>
1903 struct is_callable {
1904 // dispatch to is_callable_impl<true, T> or is_callable_impl<false, T>
1905 // depending on whether T is of class type or not
1906 typedef typename is_callable_impl<std::is_class<T>::value, T>::type type;
1907 };
1908
1909 template <typename IsYDataCallable>
1910 struct plot_impl {};
1911
1912 template <>
1913 struct plot_impl<std::false_type> {
1914 template <typename IterableX, typename IterableY>
1915 bool operator()(const IterableX & x, const IterableY & y, const std::string & format) {
1916 // 2-phase lookup for distance, begin, end
1917 using std::begin;
1918 using std::distance;
1919 using std::end;
1920
1921 auto xs = distance(begin(x), end(x));
1922 auto ys = distance(begin(y), end(y));
1923 assert(xs == ys and "x and y data must have the same number of elements!");
1924
1925 PyObject * xlist = PyList_New(xs);
1926 PyObject * ylist = PyList_New(ys);
1927 PyObject * pystring = PyString_FromString(format.c_str());
1928
1929 auto itx = begin(x), ity = begin(y);
1930 for (size_t i = 0; i < xs; ++i) {
1931 PyList_SetItem(xlist, i, PyFloat_FromDouble(*itx++));
1932 PyList_SetItem(ylist, i, PyFloat_FromDouble(*ity++));
1933 }
1934
1935 PyObject * plot_args = PyTuple_New(3);
1936 PyTuple_SetItem(plot_args, 0, xlist);
1937 PyTuple_SetItem(plot_args, 1, ylist);
1938 PyTuple_SetItem(plot_args, 2, pystring);
1939
1940 PyObject * res =
1941 PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);
1942
1943 Py_DECREF(plot_args);
1944 if (res)
1945 Py_DECREF(res);
1946
1947 return res;
1948 }
1949 };
1950
1951 template <>
1952 struct plot_impl<std::true_type> {
1953 template <typename Iterable, typename Callable>
1954 bool operator()(const Iterable & ticks, const Callable & f, const std::string & format) {
1955 if (begin(ticks) == end(ticks))
1956 return true;
1957
1958 // We could use additional meta-programming to deduce the correct element
1959 // type of y, but all values have to be convertible to double anyways
1960 std::vector<double> y;
1961 for (auto x : ticks)
1962 y.push_back(f(x));
1963 return plot_impl<std::false_type>()(ticks, y, format);
1964 }
1965 };
1966
1967 } // end namespace detail
1968
1969 // recursion stop for the above
1970 template <typename... Args>
1971 bool plot() {
1972 return true;
1973 }
1974
1975 template <typename A, typename B, typename... Args>
1976 bool plot(const A & a, const B & b, const std::string & format, Args... args) {
1977 return detail::plot_impl<typename detail::is_callable<B>::type>()(a, b, format) && plot(args...);
1978 }
1979
1980 /*
1981 * This group of plot() functions is needed to support initializer lists, i.e.
1982 * calling plot( {1,2,3,4} )
1983 */
1984 inline bool
1985 plot(const std::vector<double> & x, const std::vector<double> & y, const std::string & format = "") {
1986 return plot<double, double>(x, y, format);
1987 }
1988
1989 inline bool plot(const std::vector<double> & y, const std::string & format = "") {
1990 return plot<double>(y, format);
1991 }
1992
1993 inline bool plot(const std::vector<double> & x,
1994 const std::vector<double> & y,
1995 const std::map<std::string, std::string> & keywords) {
1996 return plot<double>(x, y, keywords);
1997 }
1998
1999 /*
2000 * This class allows dynamic plots, ie changing the plotted data without
2001 * clearing and re-plotting
2002 */
2003
2004 class Plot {
2005 public:
2006 // default initialization with plot label, some data and format
2007 template <typename Numeric>
2008 Plot(const std::string & name,
2009 const std::vector<Numeric> & x,
2010 const std::vector<Numeric> & y,
2011 const std::string & format = "") {
2012 assert(x.size() == y.size());
2013
2014 PyObject * kwargs = PyDict_New();
2015 if (name != "")
2016 PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
2017
2018 PyObject * xarray = get_array(x);
2019 PyObject * yarray = get_array(y);
2020
2021 PyObject * pystring = PyString_FromString(format.c_str());
2022
2023 PyObject * plot_args = PyTuple_New(3);
2024 PyTuple_SetItem(plot_args, 0, xarray);
2025 PyTuple_SetItem(plot_args, 1, yarray);
2026 PyTuple_SetItem(plot_args, 2, pystring);
2027
2028 PyObject * res =
2029 PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
2030
2031 Py_DECREF(kwargs);
2032 Py_DECREF(plot_args);
2033
2034 if (res) {
2035 line = PyList_GetItem(res, 0);
2036
2037 if (line)
2038 set_data_fct = PyObject_GetAttrString(line, "set_data");
2039 else
2040 Py_DECREF(line); // NOLINT
2041 Py_DECREF(res);
2042 }
2043 }
2044
2045 // shorter initialization with name or format only
2046 // basically calls line, = plot([], [])
2047 Plot(const std::string & name = "", const std::string & format = "")
2048 : Plot(name, std::vector<double>(), std::vector<double>(), format) {}
2049
2050 template <typename Numeric>
2051 bool update(const std::vector<Numeric> & x, const std::vector<Numeric> & y) {
2052 assert(x.size() == y.size());
2053 if (set_data_fct) {
2054 PyObject * xarray = get_array(x);
2055 PyObject * yarray = get_array(y);
2056
2057 PyObject * plot_args = PyTuple_New(2);
2058 PyTuple_SetItem(plot_args, 0, xarray);
2059 PyTuple_SetItem(plot_args, 1, yarray);
2060
2061 PyObject * res = PyObject_CallObject(set_data_fct, plot_args);
2062 if (res)
2063 Py_DECREF(res);
2064 return res;
2065 }
2066 return false;
2067 }
2068
2069 // clears the plot but keep it available
2070 bool clear() { return update(std::vector<double>(), std::vector<double>()); }
2071
2072 // definitely remove this line
2073 void remove() {
2074 if (line) {
2075 auto remove_fct = PyObject_GetAttrString(line, "remove");
2076 PyObject * args = PyTuple_New(0);
2077 PyObject * res = PyObject_CallObject(remove_fct, args);
2078 if (res)
2079 Py_DECREF(res);
2080 }
2081 decref();
2082 }
2083
2084 ~Plot() { decref(); }
2085
2086 private:
2087 void decref() {
2088 if (line)
2089 Py_DECREF(line);
2090 if (set_data_fct)
2091 Py_DECREF(set_data_fct);
2092 }
2093
2094 PyObject * line = nullptr;
2095 PyObject * set_data_fct = nullptr;
2096 };
2097
2098 } // end namespace Matplotlib
2099 } // namespace UTILS
2100} // namespace FML
2101#endif
std::vector< std::vector< std::string > > rows
Vec u
Definition Minimizer.cpp:27
double f
Definition Minimizer.cpp:28
const std::string filename
Definition Main.cpp:63
const double h
Definition Main.cpp:66
std::string name
std::function< std::string(const RunSettings &)> get
Plot(const std::string &name, const std::vector< Numeric > &x, const std::vector< Numeric > &y, const std::string &format="")
Plot(const std::string &name="", const std::string &format="")
bool update(const std::vector< Numeric > &x, const std::vector< Numeric > &y)
void title(const std::string &titlestr, const std::map< std::string, std::string > &keywords={})
void text(Numeric x, Numeric y, const std::string &s="")
bool named_semilogx(const std::string &name, const std::vector< Numeric > &x, const std::vector< Numeric > &y, const std::string &format="")
PyObject * get_array(const std::vector< Numeric > &v)
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)
void show(const bool block=true)
std::vector< std::array< double, 2 > > ginput(const int numClicks=1, const std::map< std::string, std::string > &keywords={})
bool annotate(std::string annotation, double x, double y)
void ylabel(const std::string &str, const std::map< std::string, std::string > &keywords={})
void yscale(const std::string &yscale)
void xticks(const std::vector< Numeric > &ticks, const std::vector< std::string > &labels={}, const std::map< std::string, std::string > &keywords={})
void tick_params(const std::map< std::string, std::string > &keywords, const std::string axis="both")
bool stem(const std::vector< Numeric > &x, const std::vector< Numeric > &y, const std::map< std::string, std::string > &keywords)
void figure_size(size_t w, size_t h)
bool hist(const std::vector< Numeric > &y, long bins=10, std::string color="b", double alpha=1.0, bool cumulative=false)
void subplot(long nrows, long ncols, long plot_number)
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={})
void yticks(const std::vector< Numeric > &ticks, const std::vector< std::string > &labels={}, const std::map< std::string, std::string > &keywords={})
bool named_plot(const std::string &name, const std::vector< Numeric > &y, const std::string &format="")
void xlabel(const std::string &str, const std::map< std::string, std::string > &keywords={})
void save(const std::string &filename)
void imshow(const unsigned char *ptr, const int rows, const int columns, const int colors, const std::map< std::string, std::string > &keywords={})
bool named_hist(std::string label, const std::vector< Numeric > &y, long bins=10, std::string color="b", double alpha=1.0)
bool fill(const std::vector< Numeric > &x, const std::vector< Numeric > &y, const std::map< std::string, std::string > &keywords)
void subplot2grid(long nrows, long ncols, long rowid=0, long colid=0, long rowspan=1, long colspan=1)
bool loglog(const std::vector< NumericX > &x, const std::vector< NumericY > &y, const std::string &s="")
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={})
bool subplots_adjust(const std::map< std::string, double > &keywords={})
void axis(const std::string &axisstr)
void plot_surface(const std::vector<::std::vector< Numeric > > &x, const std::vector<::std::vector< Numeric > > &y, const std::vector<::std::vector< Numeric > > &z, const std::map< std::string, std::string > &keywords=std::map< std::string, std::string >())
bool semilogy(const std::vector< NumericX > &x, const std::vector< NumericY > &y, const std::string &s="")
bool fignum_exists(long number)
long figure(long number=-1)
void suptitle(const std::string &suptitlestr, const std::map< std::string, std::string > &keywords={})
void backend(const std::string &name)
void pause(Numeric interval)
bool bar(const std::vector< Numeric > &x, const std::vector< Numeric > &y, std::string ec="black", std::string ls="-", double lw=1.0, const std::map< std::string, std::string > &keywords={})
void xscale(const std::string &xscale)
bool scatter(const std::vector< NumericX > &x, const std::vector< NumericY > &y, const double s=1.0, const std::unordered_map< std::string, std::string > &keywords={})
bool semilogx(const std::vector< NumericX > &x, const std::vector< NumericY > &y, const std::string &s="")
bool named_semilogy(const std::string &name, const std::vector< Numeric > &x, const std::vector< Numeric > &y, const std::string &format="")
bool named_loglog(const std::string &name, const std::vector< Numeric > &x, const std::vector< Numeric > &y, const std::string &format="")
PyObject * get_2darray(const std::vector<::std::vector< Numeric > > &v)
return y
Definition Global.h:365
Definition test.py:1
std::string num(double x)
Definition test_camb.cpp:34
double distance(const Sample &a, const Sample &b, double L)
ComplexType value(const std::array< int, N > &wave, int generation)
void shape(const std::set< Cell > &cells, Boundary b, double volume, double area, double h, int chi, const std::string &label)
double alpha(V3 a, V3 b)