eigen.rst revision 11986:c12e4625ab56
1Eigen
2=====
3
4`Eigen <http://eigen.tuxfamily.org>`_ is C++ header-based library for dense and
5sparse linear algebra. Due to its popularity and widespread adoption, pybind11
6provides transparent conversion support between Eigen and Scientific Python linear
7algebra data types.
8
9Specifically, when including the optional header file :file:`pybind11/eigen.h`,
10pybind11 will automatically and transparently convert
11
121. Static and dynamic Eigen dense vectors and matrices to instances of
13   ``numpy.ndarray`` (and vice versa).
14
152. 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
193. Returned matrix-like objects such as Eigen::DiagonalMatrix or
20   Eigen::SelfAdjointView will be converted to ``numpy.ndarray`` containing the
21   expressed value.
22
234. Eigen sparse vectors and matrices to instances of
24   ``scipy.sparse.csr_matrix``/``scipy.sparse.csc_matrix`` (and vice versa).
25
26This makes it possible to bind most kinds of functions that rely on these types.
27One major caveat are functions that take Eigen matrices *by reference* and modify
28them 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
41To see why this is, refer to the section on :ref:`opaque` (although that
42section specifically covers STL data types, the underlying issue is the same).
43The :ref:`numpy` sections discuss an efficient alternative for exposing the
44underlying native Eigen types as opaque objects in a way that still integrates
45with 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.
51