Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame^] | 1 | Eigen |
| 2 | ===== |
| 3 | |
| 4 | `Eigen <http://eigen.tuxfamily.org>`_ is C++ header-based library for dense and |
| 5 | sparse linear algebra. Due to its popularity and widespread adoption, pybind11 |
| 6 | provides transparent conversion support between Eigen and Scientific Python linear |
| 7 | algebra data types. |
| 8 | |
| 9 | Specifically, when including the optional header file :file:`pybind11/eigen.h`, |
| 10 | pybind11 will automatically and transparently convert |
| 11 | |
| 12 | 1. Static and dynamic Eigen dense vectors and matrices to instances of |
| 13 | ``numpy.ndarray`` (and vice versa). |
| 14 | |
| 15 | 2. Returned matrix expressions such as blocks (including columns or rows) and |
| 16 | diagonals will be converted to ``numpy.ndarray`` of the expression |
| 17 | values. |
| 18 | |
| 19 | 3. Returned matrix-like objects such as Eigen::DiagonalMatrix or |
| 20 | Eigen::SelfAdjointView will be converted to ``numpy.ndarray`` containing the |
| 21 | expressed value. |
| 22 | |
| 23 | 4. Eigen sparse vectors and matrices to instances of |
| 24 | ``scipy.sparse.csr_matrix``/``scipy.sparse.csc_matrix`` (and vice versa). |
| 25 | |
| 26 | This makes it possible to bind most kinds of functions that rely on these types. |
| 27 | One major caveat are functions that take Eigen matrices *by reference* and modify |
| 28 | them somehow, in which case the information won't be propagated to the caller. |
| 29 | |
| 30 | .. code-block:: cpp |
| 31 | |
| 32 | /* The Python bindings of these functions won't replicate |
| 33 | the intended effect of modifying the function arguments */ |
| 34 | void scale_by_2(Eigen::Vector3f &v) { |
| 35 | v *= 2; |
| 36 | } |
| 37 | void scale_by_2(Eigen::Ref<Eigen::MatrixXd> &v) { |
| 38 | v *= 2; |
| 39 | } |
| 40 | |
| 41 | To see why this is, refer to the section on :ref:`opaque` (although that |
| 42 | section specifically covers STL data types, the underlying issue is the same). |
| 43 | The :ref:`numpy` sections discuss an efficient alternative for exposing the |
| 44 | underlying native Eigen types as opaque objects in a way that still integrates |
| 45 | with NumPy and SciPy. |
| 46 | |
| 47 | .. seealso:: |
| 48 | |
| 49 | The file :file:`tests/test_eigen.cpp` contains a complete example that |
| 50 | shows how to pass Eigen sparse and dense data types in more detail. |