OISEAU
A modern DGTD framework
Loading...
Searching...
No Matches
pyplot.hpp
1// Copyright (C) 2026 Tiago V. L. Amorim (@tiagovla)
2//
3// This file is part of oiseau (https://github.com/tiagovla/oiseau)
4//
5// SPDX-License-Identifier: GPL-3.0-or-later
6
7#pragma once
8
9#include <nanobind/nanobind.h>
10#include <nanobind/ndarray.h>
11#include <nanobind/stl/array.h>
12#include <nanobind/stl/string.h>
13#include <nanobind/stl/vector.h>
14
15#include <memory>
16#include <utility>
17#include <xtensor/containers/xarray.hpp>
18#include <xtensor/core/xexpression.hpp>
19
20namespace py = nanobind;
21using namespace py::literals;
22
23namespace nanobind::detail {
24
25template <typename E>
26 requires xt::is_xexpression<E>::value
27struct type_caster<E> {
28 using value_type = typename E::value_type;
29 using array_type = xt::xarray<value_type>;
30
31 NB_TYPE_CASTER(array_type, const_name("numpy.ndarray"));
32 static handle from_cpp(const E& expr, rv_policy, cleanup_list*) {
33 auto data = std::make_unique<array_type>(expr);
34 py::capsule owner(data.get(),
35 [](void* pointer) noexcept { delete static_cast<array_type*>(pointer); });
36 auto* array = data.release();
37 return py::ndarray<py::numpy, value_type>(array->data(), array->dimension(),
38 array->shape().data(), owner)
39 .cast()
40 .release();
41 }
42};
43
44} // namespace nanobind::detail
45
46namespace plt {
47
48class scoped_interpreter {
49 public:
50 NB_INLINE scoped_interpreter() {
51 // Register nanobind state in the calling binary as well as the plotting library.
52 if (!py::register_module(initialize())) fail_initialization();
53 }
54 ~scoped_interpreter();
55
56 scoped_interpreter(const scoped_interpreter&) = delete;
57 scoped_interpreter& operator=(const scoped_interpreter&) = delete;
58 scoped_interpreter(scoped_interpreter&& other) noexcept
59 : m_active(std::exchange(other.m_active, false)) {}
60
61 private:
62 static NB_EXPORT py::module_ initialize();
63 [[noreturn]] static void fail_initialization();
64 bool m_active = true;
65};
66
67inline auto plt() { return py::module_::import_("matplotlib.pyplot"); }
68
69#define DEFINE_PYPLOT_FUNC(name) \
70 template <typename... Args> \
71 auto name(Args&&... args) { \
72 return plt().attr(#name)(std::forward<Args>(args)...); \
73 }
74
75#define DEFINE_PYPLOT_FUNC_WRAPPED(WrapperClass, name) \
76 template <typename... Args> \
77 WrapperClass name(Args&&... args) { \
78 return WrapperClass(plt().attr(#name)(std::forward<Args>(args)...)); \
79 }
80
81#define DEFINE_PY_CLASS_METHOD_AUTO(name) \
82 template <typename... Args> \
83 auto name(Args&&... args) { \
84 return m_obj.attr(#name)(std::forward<Args>(args)...); \
85 }
86
87#define DEFINE_PY_CLASS_METHOD_WRAPPED(WrapperClass, name) \
88 template <typename... Args> \
89 WrapperClass name(Args&&... args) { \
90 return WrapperClass(m_obj.attr(#name)(std::forward<Args>(args)...)); \
91 }
92
93// --- Classes using the simplified macros ---
94
95class NB_EXPORT AxesSubPlot {
96 public:
97 explicit AxesSubPlot(py::object axes) : m_obj(std::move(axes)) {}
98
99 DEFINE_PY_CLASS_METHOD_AUTO(scatter)
100 DEFINE_PY_CLASS_METHOD_AUTO(triplot)
101 DEFINE_PY_CLASS_METHOD_AUTO(tripcolor)
102 DEFINE_PY_CLASS_METHOD_AUTO(plot)
103 DEFINE_PY_CLASS_METHOD_AUTO(quiver)
104 DEFINE_PY_CLASS_METHOD_AUTO(text)
105 DEFINE_PY_CLASS_METHOD_AUTO(set_xlabel)
106 DEFINE_PY_CLASS_METHOD_AUTO(set_ylabel)
107 DEFINE_PY_CLASS_METHOD_AUTO(set_zlabel)
108 DEFINE_PY_CLASS_METHOD_AUTO(set_title)
109 DEFINE_PY_CLASS_METHOD_AUTO(set_aspect)
110 DEFINE_PY_CLASS_METHOD_AUTO(grid)
111 DEFINE_PY_CLASS_METHOD_AUTO(legend)
112 DEFINE_PY_CLASS_METHOD_AUTO(set_xlim)
113 DEFINE_PY_CLASS_METHOD_AUTO(set_ylim)
114 DEFINE_PY_CLASS_METHOD_AUTO(set_zlim)
115
116 private:
117 py::object m_obj;
118};
119
120class NB_EXPORT Figure {
121 public:
122 explicit Figure(py::object fig) : m_obj(std::move(fig)) {}
123
124 DEFINE_PY_CLASS_METHOD_WRAPPED(AxesSubPlot, add_subplot)
125 DEFINE_PY_CLASS_METHOD_AUTO(savefig)
126 DEFINE_PY_CLASS_METHOD_AUTO(show)
127
128 private:
129 py::object m_obj;
130};
131
132// --- Free functions using the simplified macros ---
133
134DEFINE_PYPLOT_FUNC(scatter)
135DEFINE_PYPLOT_FUNC(show)
136DEFINE_PYPLOT_FUNC(plot)
137DEFINE_PYPLOT_FUNC(xlabel)
138DEFINE_PYPLOT_FUNC(ylabel)
139DEFINE_PYPLOT_FUNC(title)
140DEFINE_PYPLOT_FUNC(grid)
141DEFINE_PYPLOT_FUNC(legend)
142DEFINE_PYPLOT_FUNC(savefig)
143
144DEFINE_PYPLOT_FUNC_WRAPPED(Figure, figure)
145
146template <typename... Args>
147std::pair<Figure, AxesSubPlot> subplots(Args&&... args) {
148 auto res = py::cast<py::tuple>(plt().attr("subplots")(std::forward<Args>(args)...));
149 return {Figure(res[0]), AxesSubPlot(res[1])};
150}
151
152// --- Undefine all macros ---
153
154#undef DEFINE_PYPLOT_FUNC
155#undef DEFINE_PYPLOT_FUNC_WRAPPED
156#undef DEFINE_PY_CLASS_METHOD_AUTO
157#undef DEFINE_PY_CLASS_METHOD_WRAPPED
158
159} // namespace plt
Definition pyplot.hpp:95
Definition pyplot.hpp:120