8#ifndef __eigenpy_utils_std_vector_hpp__ 9#define __eigenpy_utils_std_vector_hpp__ 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> 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" 29template <
typename vector_type,
bool NoProxy = false>
36bool from_python_list(PyObject* obj_ptr, T*) {
38 if (!PyList_Check(obj_ptr))
return false;
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);
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;
54template <
typename vector_type,
bool NoProxy>
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);
60 for (
size_t k = 0; k < vec.size(); ++k) {
61 bp_list.append(boost::ref(vec[k]));
67template <
typename vector_type>
69 static bp::list run(vector_type& vec,
const bool) {
70 typedef bp::iterator<vector_type> iterator;
71 return bp::list(iterator()(vec));
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;
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>);
94 static bp::object base_get_item_int(bp::back_reference<Container&> container,
96 index_type idx = convert_index(container.get(), i_);
97 typename Container::iterator i = container.get().begin();
99 if (i == container.get().end()) {
100 PyErr_SetString(PyExc_KeyError,
"Invalid index");
101 bp::throw_error_already_set();
104 typename bp::to_python_indirect<data_type&,
105 bp::detail::make_reference_holder>
107 return bp::object(bp::handle<>(convert(*i)));
110 static bp::object base_get_item_slice(
111 bp::back_reference<Container&> container, bp::slice slice) {
115 slice.get_indices(container.get().begin(), container.get().end());
118 typename bp::to_python_indirect<value_type&,
119 bp::detail::make_reference_holder>
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;
127 }
catch (
const std::invalid_argument&) {
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);
140 for (Py_ssize_t k = 0; k < m; ++k) {
141 bp::object obj = idxs[k];
142 bp::extract<long> ei(obj);
144 PyErr_SetString(PyExc_TypeError,
"Indices must be integers");
145 bp::throw_error_already_set();
147 auto idx = normalize_index(c.get().size(), ei());
148 out.append(elem_ref(c.get(), idx));
153 static index_type normalize_index(std::size_t n,
long 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();
160 return static_cast<index_type
>(idx);
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>
167 return bp::object(bp::handle<>(conv(c[i])));
170 static index_type convert_index(Container& container, PyObject* i_) {
171 bp::extract<long> i(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();
179 return (index_type)index;
182 PyErr_SetString(PyExc_TypeError,
"Invalid index type");
183 bp::throw_error_already_set();
193template <
typename MatrixType>
194struct extract_to_eigen_ref
195 : converter::extract_rvalue<Eigen::Ref<MatrixType>> {
196 typedef Eigen::Ref<MatrixType> RefType;
199 typedef converter::extract_rvalue<RefType> base;
202 typedef RefType result_type;
204 operator result_type()
const {
return (*
this)(); }
206 extract_to_eigen_ref(PyObject* o) : base(o) {}
207 extract_to_eigen_ref(api::object
const& o) : base(o.ptr()) {}
212template <
typename Scalar,
int Rows,
int Cols,
int Options,
int MaxRows,
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>
219 typedef extract_to_eigen_ref<MatrixType> base;
220 extract(PyObject* o) : base(o) {}
221 extract(api::object
const& o) : base(o.ptr()) {}
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()) {}
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()) {}
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;
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)),
263 bool is_convertible =
264 ::eigenpy::details::from_python_list(py_obj, (Type*)(0));
265 if (!is_convertible)
return;
267 typedef ::eigenpy::StdContainerFromPythonList<vector_type> Constructor;
268 Constructor::construct(py_obj, &m_data.stage1);
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);
275 result_type operator()()
const {
276 return ::boost::python::detail::void_ptr_to_reference(result(),
277 (result_type (*)())0);
280 ~reference_arg_from_python() {
281 if (m_data.stage1.convertible == m_data.storage.bytes) {
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]);
293 rvalue_from_python_data<ref_vector_type> m_data;
295 vector_type* vec_ptr;
306template <
class Container>
309 typedef typename Container::allocator_type Allocator;
312template <
typename _Tp, std::
size_t Size>
323template <
typename vector_type,
bool NoProxy>
325 typedef typename vector_type::value_type T;
326 typedef typename details::container_traits<vector_type>::Allocator Allocator;
330 namespace bp = boost::python;
333 if (!PyList_Check(obj_ptr))
return 0;
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);
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;
352 bp::converter::rvalue_from_python_stage1_data* memory) {
354 bp::object bp_obj(bp::handle<>(bp::borrowed(obj_ptr)));
355 bp::list bp_list(bp_obj);
359 bp::converter::rvalue_from_python_storage<vector_type>*
>(
360 reinterpret_cast<void*
>(memory))
363 typedef bp::stl_input_iterator<T> iterator;
366 new (storage) vector_type(iterator(bp_list), iterator());
369 memory->convertible = storage;
372 static void register_converter() {
374 bp::type_id<vector_type>());
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);
385 bool has_operator_equal_value =
386 std::is_base_of<std::true_type, has_operator_equal<T>>::value>
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) !=
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;
409template <
class Container,
bool NoProxy>
410struct contains_vector_derived_policies
411 :
public bp::vector_indexing_suite<
413 contains_vector_derived_policies<Container, NoProxy>> {
414 typedef typename Container::value_type key_type;
416 static bool contains(Container& container, key_type
const& key) {
417 return contains_algo<key_type>::run(container, key);
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;
433 ExposeStdMethodToStdVector(
const CoVisitor& co_visitor)
434 : m_co_visitor(co_visitor) {}
436 template <
class Class>
437 void visit(Class& cl)
const {
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>());
449 const CoVisitor& m_co_visitor;
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);
462template <
typename vector_type,
bool T_picklable = false>
463struct def_pickle_std_vector {
464 static void run(bp::class_<vector_type>&) {}
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>());
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;
490 static void expose(
const std::string& class_name,
491 const std::string& doc_string =
"") {
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);
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) {
507 auto add_std_visitor =
508 internal::createExposeStdMethodToStdVector<vector_type, NoProxy>(
512 bp::class_<vector_type> cl(class_name.c_str(), doc_string.c_str());
516 bp::vector_indexing_suite<
517 vector_type, NoProxy,
518 internal::contains_vector_derived_policies<vector_type, NoProxy>>
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"),
527 .def(vector_indexing)
528 .def(add_std_visitor);
530 internal::def_pickle_std_vector<vector_type, pickable>::run(cl);
532 if (EnableFromPythonListConverter) {
534 FromPythonListConverter::register_converter();
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_";
549 StdVectorPythonVisitor<VecMatType>::expose(
void expose()
Call the expose function of a given type T.
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....
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...