Drake
eigen_pybind.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <Eigen/Dense>
4 #include "pybind11/eigen.h"
5 
7 
8 namespace drake {
9 namespace pydrake {
10 
11 /// Provides a mutable Ref<> for a pointer.
12 /// Meant to be used for decorating methods passed to `pybind11` (e.g. virtual
13 /// function dispatch).
14 // TODO(eric.cousineau): Ensure that all C++ mutator call sites use `EigenPtr`.
15 template <typename Derived>
16 auto ToEigenRef(Eigen::VectorBlock<Derived>* derived) {
17  return Eigen::Ref<Derived>(*derived);
18 }
19 
20 /// Converts a raw array to a numpy array.
21 template <typename T>
22 py::object ToArray(T* ptr, int size, py::tuple shape) {
23  // Create flat array to be reshaped in numpy.
24  using Vector = VectorX<T>;
25  Eigen::Map<Vector> data(ptr, size);
26  return py::cast(
27  Eigen::Ref<Vector>(data), py_reference).attr("reshape")(shape);
28 }
29 
30 /// Converts a raw array to a numpy array (`const` variant).
31 template <typename T>
32 py::object ToArray(const T* ptr, int size, py::tuple shape) {
33  // Create flat array to be reshaped in numpy.
34  using Vector = const VectorX<T>;
35  Eigen::Map<Vector> data(ptr, size);
36  return py::cast(
37  Eigen::Ref<Vector>(data), py_reference).attr("reshape")(shape);
38 }
39 
40 } // namespace pydrake
41 } // namespace drake
py::object ToArray(T *ptr, int size, py::tuple shape)
Converts a raw array to a numpy array.
Definition: eigen_pybind.h:22
This file contains abbreviated definitions for certain specializations of Eigen::Matrix that are comm...
Definition: bullet_model.cc:22
Eigen::Matrix< Scalar, Eigen::Dynamic, 1 > VectorX
A column vector of any size, templated on scalar type.
Definition: eigen_types.h:46
double T
Definition: benchmarks_py.cc:14
const auto py_reference
Used when returning T& orconst T&`, as pybind&#39;s default behavior is to copy lvalue references.
Definition: pydrake_pybind.h:227
auto ToEigenRef(Eigen::VectorBlock< Derived > *derived)
Provides a mutable Ref<> for a pointer.
Definition: eigen_pybind.h:16
int data
Definition: value_test.cc:20