eigenpy 3.13.0
Bindings between Numpy and Eigen using Boost.Python
Loading...
Searching...
No Matches
std-vector.hpp
1
7
8#ifndef __eigenpy_utils_std_vector_hpp__
9#define __eigenpy_utils_std_vector_hpp__
10
11#include <boost/mpl/if.hpp>
12#include <boost/python.hpp>
13#include <boost/python/stl_iterator.hpp>
14#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
15#include <iterator>
16#include <string>
17#include <vector>
18
19#include "eigenpy/eigenpy.hpp"
20#include "eigenpy/config.hpp"
21#include "eigenpy/copyable.hpp"
22#include "eigenpy/eigen-to-python.hpp"
23#include "eigenpy/pickle-vector.hpp"
24#include "eigenpy/registration.hpp"
25#include "eigenpy/utils/empty-visitor.hpp"
26
27namespace eigenpy {
28// Forward declaration
29template <typename vector_type, bool NoProxy = false>
31
32namespace details {
33
35template <typename T>
36bool from_python_list(PyObject* obj_ptr, T*) {
37 // Check if it is a list
38 if (!PyList_Check(obj_ptr)) return false;
39
40 // Retrieve the underlying list
41 bp::object bp_obj(bp::handle<>(bp::borrowed(obj_ptr)));
42 bp::list bp_list(bp_obj);
43 bp::ssize_t list_size = bp::len(bp_list);
44
45 // Check if all the elements contained in the current vector is of type T
46 for (bp::ssize_t k = 0; k < list_size; ++k) {
47 bp::extract<T> elt(bp_list[k]);
48 if (!elt.check()) return false;
49 }
50
51 return true;
52}
53
54template <typename vector_type, bool NoProxy>
55struct build_list {
56 static bp::list run(vector_type& vec, const bool deep_copy) {
57 if (deep_copy) return build_list<vector_type, true>::run(vec, true);
58
59 bp::list bp_list;
60 for (size_t k = 0; k < vec.size(); ++k) {
61 bp_list.append(boost::ref(vec[k]));
62 }
63 return bp_list;
64 }
65};
66
67template <typename vector_type>
68struct build_list<vector_type, true> {
69 static bp::list run(vector_type& vec, const bool) {
70 typedef bp::iterator<vector_type> iterator;
71 return bp::list(iterator()(vec));
72 }
73};
74
78template <typename Container>
80 : public bp::def_visitor<overload_base_get_item_for_std_vector<Container>> {
81 typedef typename Container::value_type value_type;
82 typedef typename Container::value_type data_type;
83 typedef size_t index_type;
84
85 template <class Class>
86 void visit(Class& cl) const {
87 cl.def("__getitem__", &base_get_item_int)
88 .def("__getitem__", &base_get_item_slice)
89 .def("__getitem__", &base_get_item_list_or_tuple<bp::list>)
90 .def("__getitem__", &base_get_item_list_or_tuple<bp::tuple>);
91 }
92
93 private:
94 static bp::object base_get_item_int(bp::back_reference<Container&> container,
95 PyObject* i_) {
96 index_type idx = convert_index(container.get(), i_);
97 typename Container::iterator i = container.get().begin();
98 std::advance(i, idx);
99 if (i == container.get().end()) {
100 PyErr_SetString(PyExc_KeyError, "Invalid index");
101 bp::throw_error_already_set();
102 }
103
104 typename bp::to_python_indirect<data_type&,
105 bp::detail::make_reference_holder>
106 convert;
107 return bp::object(bp::handle<>(convert(*i)));
108 }
109
110 static bp::object base_get_item_slice(
111 bp::back_reference<Container&> container, bp::slice slice) {
112 bp::list out;
113 try {
114 auto rng =
115 slice.get_indices(container.get().begin(), container.get().end());
116 // rng.start, rng.stop are iterators; rng.step is int; [start, stop] is
117 // closed
118 typename bp::to_python_indirect<value_type&,
119 bp::detail::make_reference_holder>
120 convert;
121 // forward or backward
122 for (typename Container::iterator it = rng.start;;
123 std::advance(it, rng.step)) {
124 out.append(bp::object(bp::handle<>(convert(*it))));
125 if (it == rng.stop) break; // closed interval, include stop
126 }
127 } catch (const std::invalid_argument&) {
128 // Boost.Python specifies empty ranges throw invalid_argument.
129 // Return [] (matches Python's behavior for empty slices).
130 return bp::list();
131 }
132 return out;
133 }
134
135 template <typename list_or_tuple>
136 static bp::object base_get_item_list_or_tuple(
137 bp::back_reference<Container&> c, list_or_tuple idxs) {
138 const Py_ssize_t m = bp::len(idxs);
139 bp::list out;
140 for (Py_ssize_t k = 0; k < m; ++k) {
141 bp::object obj = idxs[k];
142 bp::extract<long> ei(obj);
143 if (!ei.check()) {
144 PyErr_SetString(PyExc_TypeError, "Indices must be integers");
145 bp::throw_error_already_set();
146 }
147 auto idx = normalize_index(c.get().size(), ei());
148 out.append(elem_ref(c.get(), idx));
149 }
150 return out;
151 }
152
153 static index_type normalize_index(std::size_t n, long i) {
154 long idx = i;
155 if (idx < 0) idx += static_cast<long>(n);
156 if (idx < 0 || idx >= static_cast<long>(n)) {
157 PyErr_SetString(PyExc_IndexError, "Index out of range");
158 bp::throw_error_already_set();
159 }
160 return static_cast<index_type>(idx);
161 }
162
163 static bp::object elem_ref(Container& c, index_type i) {
164 typename bp::to_python_indirect<value_type&,
165 bp::detail::make_reference_holder>
166 conv;
167 return bp::object(bp::handle<>(conv(c[i])));
168 }
169
170 static index_type convert_index(Container& container, PyObject* i_) {
171 bp::extract<long> i(i_);
172 if (i.check()) {
173 long index = i();
174 if (index < 0) index += (long)container.size();
175 if (index >= long(container.size()) || index < 0) {
176 PyErr_SetString(PyExc_IndexError, "Index out of range");
177 bp::throw_error_already_set();
178 }
179 return (index_type)index;
180 }
181
182 PyErr_SetString(PyExc_TypeError, "Invalid index type");
183 bp::throw_error_already_set();
184 return index_type();
185 }
186};
187} // namespace details
188} // namespace eigenpy
189
190namespace boost {
191namespace python {
192
193template <typename MatrixType>
194struct extract_to_eigen_ref
195 : converter::extract_rvalue<Eigen::Ref<MatrixType>> {
196 typedef Eigen::Ref<MatrixType> RefType;
197
198 protected:
199 typedef converter::extract_rvalue<RefType> base;
200
201 public:
202 typedef RefType result_type;
203
204 operator result_type() const { return (*this)(); }
205
206 extract_to_eigen_ref(PyObject* o) : base(o) {}
207 extract_to_eigen_ref(api::object const& o) : base(o.ptr()) {}
208};
209
212template <typename Scalar, int Rows, int Cols, int Options, int MaxRows,
213 int MaxCols>
214struct extract<Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>&>
215 : extract_to_eigen_ref<
216 Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>> {
217 typedef Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>
218 MatrixType;
219 typedef extract_to_eigen_ref<MatrixType> base;
220 extract(PyObject* o) : base(o) {}
221 extract(api::object const& o) : base(o.ptr()) {}
222};
223
224template <typename Derived>
225struct extract<Eigen::MatrixBase<Derived>&>
226 : extract_to_eigen_ref<Eigen::MatrixBase<Derived>> {
227 typedef Eigen::MatrixBase<Derived> MatrixType;
228 typedef extract_to_eigen_ref<MatrixType> base;
229 extract(PyObject* o) : base(o) {}
230 extract(api::object const& o) : base(o.ptr()) {}
231};
232
233template <typename Derived>
234struct extract<Eigen::RefBase<Derived>&>
235 : extract_to_eigen_ref<Eigen::RefBase<Derived>> {
236 typedef Eigen::RefBase<Derived> MatrixType;
237 typedef extract_to_eigen_ref<MatrixType> base;
238 extract(PyObject* o) : base(o) {}
239 extract(api::object const& o) : base(o.ptr()) {}
240};
241
242namespace converter {
243
244template <typename Type, class Allocator>
245struct reference_arg_from_python<std::vector<Type, Allocator>&>
246 : arg_lvalue_from_python_base {
247 typedef std::vector<Type, Allocator> vector_type;
248 typedef vector_type& ref_vector_type;
249 typedef ref_vector_type result_type;
250 typedef extract<Type&> extract_type;
251
252 reference_arg_from_python(PyObject* py_obj)
253 : arg_lvalue_from_python_base(converter::get_lvalue_from_python(
254 py_obj, registered<vector_type>::converters)),
255 m_data(NULL),
256 m_source(py_obj),
257 vec_ptr(NULL) {
258 if (result() != 0) // we have found a lvalue converter
259 return;
260
261 // Check if py_obj is a py_list, which can then be converted to an
262 // std::vector
263 bool is_convertible =
264 ::eigenpy::details::from_python_list(py_obj, (Type*)(0));
265 if (!is_convertible) return;
266
267 typedef ::eigenpy::StdContainerFromPythonList<vector_type> Constructor;
268 Constructor::construct(py_obj, &m_data.stage1);
269
270 void*& m_result = const_cast<void*&>(result());
271 m_result = m_data.stage1.convertible;
272 vec_ptr = reinterpret_cast<vector_type*>(m_data.storage.bytes);
273 }
274
275 result_type operator()() const {
276 return ::boost::python::detail::void_ptr_to_reference(result(),
277 (result_type (*)())0);
278 }
279
280 ~reference_arg_from_python() {
281 if (m_data.stage1.convertible == m_data.storage.bytes) {
282 // Copy back the reference
283 const vector_type& vec = *vec_ptr;
284 list bp_list(handle<>(borrowed(m_source)));
285 for (size_t i = 0; i < vec.size(); ++i) {
286 typename extract_type::result_type elt = extract_type(bp_list[i]);
287 elt = vec[i];
288 }
289 }
290 }
291
292 private:
293 rvalue_from_python_data<ref_vector_type> m_data;
294 PyObject* m_source;
295 vector_type* vec_ptr;
296};
297
298} // namespace converter
299} // namespace python
300} // namespace boost
301
302namespace eigenpy {
303
304namespace details {
306template <class Container>
308 // default behavior expects allocators
309 typedef typename Container::allocator_type Allocator;
310};
311
312template <typename _Tp, std::size_t Size>
313struct container_traits<std::array<_Tp, Size>> {
314 typedef void Allocator;
315};
316}; // namespace details
317
323template <typename vector_type, bool NoProxy>
325 typedef typename vector_type::value_type T;
326 typedef typename details::container_traits<vector_type>::Allocator Allocator;
327
329 static void* convertible(PyObject* obj_ptr) {
330 namespace bp = boost::python;
331
332 // Check if it is a list
333 if (!PyList_Check(obj_ptr)) return 0;
334
335 // Retrieve the underlying list
336 bp::object bp_obj(bp::handle<>(bp::borrowed(obj_ptr)));
337 bp::list bp_list(bp_obj);
338 bp::ssize_t list_size = bp::len(bp_list);
339
340 // Check if all the elements contained in the current vector is of type T
341 for (bp::ssize_t k = 0; k < list_size; ++k) {
342 bp::extract<T> elt(bp_list[k]);
343 if (!elt.check()) return 0;
344 }
345
346 return obj_ptr;
347 }
348
351 static void construct(PyObject* obj_ptr,
352 bp::converter::rvalue_from_python_stage1_data* memory) {
353 // Extract the list
354 bp::object bp_obj(bp::handle<>(bp::borrowed(obj_ptr)));
355 bp::list bp_list(bp_obj);
356
357 void* storage =
358 reinterpret_cast<
359 bp::converter::rvalue_from_python_storage<vector_type>*>(
360 reinterpret_cast<void*>(memory))
361 ->storage.bytes;
362
363 typedef bp::stl_input_iterator<T> iterator;
364
365 // Build the std::vector
366 new (storage) vector_type(iterator(bp_list), iterator());
367
368 // Validate the construction
369 memory->convertible = storage;
370 }
371
372 static void register_converter() {
373 bp::converter::registry::push_back(&convertible, &construct,
374 bp::type_id<vector_type>());
375 }
376
377 static bp::list tolist(vector_type& self, const bool deep_copy = false) {
378 return details::build_list<vector_type, NoProxy>::run(self, deep_copy);
379 }
380};
381
382namespace internal {
383
384template <typename T,
385 bool has_operator_equal_value =
386 std::is_base_of<std::true_type, has_operator_equal<T>>::value>
387struct contains_algo;
388
389template <typename T>
390struct contains_algo<T, true> {
391 template <class Container, typename key_type>
392 static bool run(const Container& container, key_type const& key) {
393 return std::find(container.begin(), container.end(), key) !=
394 container.end();
395 }
396};
397
398template <typename T>
399struct contains_algo<T, false> {
400 template <class Container, typename key_type>
401 static bool run(const Container& container, key_type const& key) {
402 for (size_t k = 0; k < container.size(); ++k) {
403 if (&container[k] == &key) return true;
404 }
405 return false;
406 }
407};
408
409template <class Container, bool NoProxy>
410struct contains_vector_derived_policies
411 : public bp::vector_indexing_suite<
412 Container, NoProxy,
413 contains_vector_derived_policies<Container, NoProxy>> {
414 typedef typename Container::value_type key_type;
415
416 static bool contains(Container& container, key_type const& key) {
417 return contains_algo<key_type>::run(container, key);
418 }
419};
420
426template <typename Container, bool NoProxy, typename CoVisitor>
427struct ExposeStdMethodToStdVector
428 : public bp::def_visitor<
429 ExposeStdMethodToStdVector<Container, NoProxy, CoVisitor>> {
430 typedef StdContainerFromPythonList<Container, NoProxy>
431 FromPythonListConverter;
432
433 ExposeStdMethodToStdVector(const CoVisitor& co_visitor)
434 : m_co_visitor(co_visitor) {}
435
436 template <class Class>
437 void visit(Class& cl) const {
438 cl.def(m_co_visitor)
439 .def("tolist", &FromPythonListConverter::tolist,
440 (bp::arg("self"), bp::arg("deep_copy") = false),
441 "Returns the std::vector as a Python list.")
442 .def("reserve", &Container::reserve,
443 (bp::arg("self"), bp::arg("new_cap")),
444 "Increase the capacity of the vector to a value that's greater "
445 "or equal to new_cap.")
446 .def(CopyableVisitor<Container>());
447 }
448
449 const CoVisitor& m_co_visitor;
450};
451
453template <typename Container, bool NoProxy, typename CoVisitor>
454static ExposeStdMethodToStdVector<Container, NoProxy, CoVisitor>
455createExposeStdMethodToStdVector(const CoVisitor& co_visitor) {
456 return ExposeStdMethodToStdVector<Container, NoProxy, CoVisitor>(co_visitor);
457}
458
459} // namespace internal
460
461namespace internal {
462template <typename vector_type, bool T_picklable = false>
463struct def_pickle_std_vector {
464 static void run(bp::class_<vector_type>&) {}
465};
466
467template <typename vector_type>
468struct def_pickle_std_vector<vector_type, true> {
469 static void run(bp::class_<vector_type>& cl) {
470 cl.def_pickle(PickleVector<vector_type>());
471 }
472};
473} // namespace internal
474
483template <class vector_type, bool NoProxy = false,
484 bool EnableFromPythonListConverter = true, bool pickable = true>
486 typedef typename vector_type::value_type value_type;
488 FromPythonListConverter;
489
490 static void expose(const std::string& class_name,
491 const std::string& doc_string = "") {
492 expose(class_name, doc_string, EmptyPythonVisitor());
493 }
494
495 template <typename DerivedVisitor>
496 static void expose(const std::string& class_name,
497 const bp::def_visitor<DerivedVisitor>& visitor) {
498 expose(class_name, "", visitor);
499 }
500
501 template <typename DerivedVisitor>
502 static void expose(const std::string& class_name,
503 const std::string& doc_string,
504 const bp::def_visitor<DerivedVisitor>& visitor) {
505 // Apply visitor on already registered type or if type is not already
506 // registered, we define and apply the visitor on it
507 auto add_std_visitor =
508 internal::createExposeStdMethodToStdVector<vector_type, NoProxy>(
509 visitor);
511 add_std_visitor)) {
512 bp::class_<vector_type> cl(class_name.c_str(), doc_string.c_str());
513 cl.def(IdVisitor<vector_type>());
514
515 // Standard vector indexing definition
516 bp::vector_indexing_suite<
517 vector_type, NoProxy,
518 internal::contains_vector_derived_policies<vector_type, NoProxy>>
519 vector_indexing;
520
521 cl.def(bp::init<size_t, const value_type&>(
522 bp::args("self", "size", "value"),
523 "Constructor from a given size and a given value."))
524 .def(bp::init<const vector_type&>(bp::args("self", "other"),
525 "Copy constructor"))
526
527 .def(vector_indexing)
528 .def(add_std_visitor);
529
530 internal::def_pickle_std_vector<vector_type, pickable>::run(cl);
531 }
532 if (EnableFromPythonListConverter) {
533 // Register conversion
534 FromPythonListConverter::register_converter();
535 }
536 }
537};
538
542void EIGENPY_DLLAPI exposeStdVector();
543
544template <typename MatType, typename Alloc = Eigen::aligned_allocator<MatType>>
545void exposeStdVectorEigenSpecificType(const char* name) {
546 typedef std::vector<MatType, Alloc> VecMatType;
547 std::string full_name = "StdVec_";
548 full_name += name;
549 StdVectorPythonVisitor<VecMatType>::expose(
550 full_name.c_str(),
552}
553
554} // namespace eigenpy
555
556#endif // ifndef __eigenpy_utils_std_vector_hpp__
void expose()
Call the expose function of a given type T.
Definition expose.hpp:23
void EIGENPY_DLLAPI exposeStdVector()
bool register_symbolic_link_to_registered_type()
Symlink to the current scope the already registered class T.
Add the Python method id to retrieving a unique id for a given object exposed with Boost....
Definition id.hpp:18
Register the conversion from a Python list to a std::vector.
static void construct(PyObject *obj_ptr, bp::converter::rvalue_from_python_stage1_data *memory)
Allocate the std::vector and fill it with the element contained in the list.
static void * convertible(PyObject *obj_ptr)
Check if obj_ptr can be converted.
Expose an std::vector from a type given as template argument.
Change the behavior of indexing (method getitem in Python). This is suitable for container of Eigen m...