Package: rmjarvis.eigency
[![Build Status](https://travis-ci.org/wouterboomsma/eigency.svg?branch=master)](https://travis-ci.org/wouterboomsma/eigency)# EigencyEigency is a Cython interface between Numpy arrays and Matrix/Arrayobjects from the Eigen C++ library. It is intended to simplify theprocess of writing C++ extensions using the Eigen library. Eigency isdesigned to reuse the underlying storage of the arrays when passingdata back and forth, and will thus avoid making unnecessary copieswhenever possible. Only in cases where copies are explicitly requestedby your C++ code will they be made.Below is a description of a range of common usage scenarios. A full workingexample of both setup and these different use cases is available in the`test` directory distributed with the this package.## SetupTo import eigency functionality, add the following to your `.pyx` file:```from eigency.core cimport *```In addition, in the `setup.py` file, the include directories must beset up to include the eigency includes. This can be done by callingthe `get_includes` function in the `eigency` module:```import eigency...extensions = [Extension("module-dir-name/module-name", ["module-dir-name/module-name.pyx"],include_dirs = [".", "module-dir-name"] + eigency.get_includes()),]```Eigency includes a version of the Eigen library, and the `get_includes` function will include the path to this directory. If youhave your own version of Eigen, just set the `include_eigen` option to False, and add your own path instead:```include_dirs = [".", "module-dir-name", 'path-to-own-eigen'] + eigency.get_includes(include_eigen=False)```## From Numpy to EigenAssume we are writing a Cython interface to the following C++ function:```c++void function_w_mat_arg(const Eigen::Map<Eigen::MatrixXd> &mat) {std::cout << mat << "\n";}```Note that we use `Eigen::Map` to ensure that we can reuse the storageof the numpy array, thus avoiding making a copy. Assuming the C++ codeis in a file called `functions.h`, the corresponding `.pyx` entry could look like this:```cdef extern from "functions.h":cdef void _function_w_mat_arg "function_w_mat_arg"(Map[MatrixXd] &)# This will be exposed to Pythondef function_w_mat_arg(np.ndarray array):return _function_w_mat_arg(Map[MatrixXd](array))```The last line contains the actual conversion. `Map` is an Eigencytype that derives from the real Eigen map, and will take care ofthe conversion from the numpy array to the corresponding Eigen type.We can now call the C++ function directly from Python:```python>>> import numpy as np>>> import eigency_tests>>> x = np.array([[1.1, 2.2], [3.3, 4.4]])>>> eigency_tests.function_w_mat_arg(x)1.1 3.32.2 4.4```(if you are wondering about why the matrix is transposed, pleasesee the Storage layout section below).## Types matterThe basic idea behind eigency is to share the underlying representation of anumpy array between Python and C++. This means that somewhere in the process,we need to make explicit which numerical types we are dealing with. In thefunction above, we specify that we expect an Eigen MatrixXd, which meansthat the numpy array must also contain double (i.e. float64) values. If we instead providea numpy array of ints, we will get strange results.```python>>> import numpy as np>>> import eigency_tests>>> x = np.array([[1, 2], [3, 4]])>>> eigency_tests.function_w_mat_arg(x)4.94066e-324  1.4822e-3239.88131e-324 1.97626e-323```This is because we are explicitly asking C++ to interpret out python integervalues as floats.To avoid this type of error, you can force your cython function toaccept only numpy arrays of a specific type:```cdef extern from "functions.h":cdef void _function_w_mat_arg "function_w_mat_arg"(Map[MatrixXd] &)# This will be exposed to Pythondef function_w_mat_arg(np.ndarray[np.float64_t, ndim=2] array):return _function_w_mat_arg(Map[MatrixXd](array))```(Note that when using this technique to select the type, you also need to specifythe dimensions of the array (this will default to 1)). Using this new definition,users will get an error when passing arrays of the wrong type:```python>>> import numpy as np>>> import eigency_tests>>> x = np.array([[1, 2], [3, 4]])>>> eigency_tests.function_w_mat_arg(x)Traceback (most recent call last):File "<stdin>", line 1, in <module>File "eigency_tests/eigency_tests.pyx", line 87, in eigency_tests.eigency_tests.function_w_mat_argValueError: Buffer dtype mismatch, expected 'float64_t' but got 'long'```Since it avoids many surprises, it is strongly recommended to use this techniqueto specify the full types of numpy arrays in your cython code wheneverpossible.## Writing Eigen Map types in CythonSince Cython does not support nested fused types, you cannot write types like `Map[Matrix[double, 2, 2]]`. In most cases, you won't need to, since you can just use Eigens convenience typedefs, such as `Map[VectorXd]`. If you need the additional flexibility of the full specification, you can use the `FlattenedMap` type, where all type arguments can be specified at top level, for instance `FlattenedMap[Matrix, double, _2, _3]` or `FlattenedMap[Matrix, double, _2, Dynamic]`. Note that dimensions must be prefixed with an underscore.Using full specifications of the Eigen types, the previous example would look like this:```cdef extern from "functions.h":cdef void _function_w_mat_arg "function_w_mat_arg" (FlattenedMap[Matrix, double, Dynamic, Dynamic] &)# This will be exposed to Pythondef function_w_mat_arg(np.ndarray[np.float64_t, ndim=2] array):return _function_w_mat_arg(FlattenedMap[Matrix, double, Dynamic, Dynamic](array))````FlattenedType` takes four template parameters: arraytype, scalartype,rows and cols.  Eigen supports a few other template arguments forsetting the storage layout and Map strides. Since cython does notsupport default template arguments for fused types, we have insteaddefined separate types for this purpose. These are called`FlattenedMapWithOrder` and `FlattenedMapWithStride` with five and eighttemplate arguments, respectively. For details on their use, see the sectionabout storage layout below.## From Numpy to Eigen (insisting on a copy)Eigency will not complain if the C++ function you interface with doesnot take a Eigen Map object, but instead a regular Eigen Matrix orArray. However, in such cases, a copy will be made. Actually, theprocedure is exactly the same as above. In the `.pyx` file, you stilldefine everything exactly the same way as for the Map case described above.For instance, given the following C++ function:```c++void function_w_vec_arg_no_map(const Eigen::VectorXd &vec);```The Cython definitions would still look like this:```cdef extern from "functions.h":cdef void _function_w_vec_arg_no_map "function_w_vec_arg_no_map"(Map[VectorXd] &)# This will be exposed to Pythondef function_w_vec_arg_no_map(np.ndarray[np.float64_t] array):return _function_w_vec_arg_no_map(Map[VectorXd](array))```Cython will not mind the fact that the argument type in the externdeclaration (a Map type) differs from the actual one in the `.h` file,as long as one can be assigned to the other. Since Map objects can beassigned to their corresponding Matrix/Array types this worksseemlessly. But keep in mind that this assignment will make a copy ofthe underlying data.## Eigen to NumpyC++ functions returning a reference to an Eigen Matrix/Array can alsobe transferred to numpy arrays without copying their content.  Assumewe have a class with a single getter function that returns an Eigenmatrix member:```c++class MyClass {public:MyClass():matrix(Eigen::Matrix3d::Constant(3.)) {}Eigen::MatrixXd &get_matrix() {return this->matrix;}private:Eigen::Matrix3d matrix;};```The Cython C++ class interface is specified as usual:```cdef cppclass _MyClass "MyClass":_MyClass "MyClass"() except +Matrix3d &get_matrix()```And the corresponding Python wrapper:```pythoncdef class MyClass:cdef _MyClass *thisptr;def __cinit__(self):self.thisptr = new _MyClass()def __dealloc__(self):del self.thisptrdef get_matrix(self):return ndarray(self.thisptr.get_matrix())```This last line contains the actual conversion. Again, eigency has itsown version of `ndarray`, that will take care of the conversion foryou.Due to limitations in Cython, Eigency cannot deal with fullMatrix/Array template specifications as return types(e.g. `Matrix[double, 4, 2]`). However, as a workaround, you can use`PlainObjectBase` as a return type in such cases (or in all cases ifyou prefer):```PlainObjectBase &get_matrix()```## Overriding default behaviorThe `ndarray` conversion type specifier will attempt do guess whether you want a copyor a view, depending on the return type. Most of the time, this isprobably what you want. However, there might be cases where you wantto override this behavior. For instance, functions returning constreferences will result in a copy of the array, since the const-nesscannot be enforced in Python. However, you can always override thedefault behavior by using the `ndarray_copy` or `ndarray_view`functions.Expanding the `MyClass` example from before:```c++class MyClass {public:...const Eigen::MatrixXd &get_const_matrix() {return this->matrix;}...};```With the corresponding cython interface specificationThe Cython C++ class interface is specified as usual:```cdef cppclass _MyClass "MyClass":...const Matrix3d &get_const_matrix()```The following would return a copy```pythoncdef class MyClass:...def get_const_matrix(self):return ndarray(self.thisptr.get_const_matrix())```while the following would force it to return a view```pythoncdef class MyClass:...def get_const_matrix(self):return ndarray_view(self.thisptr.get_const_matrix())```## Eigen to Numpy (non-reference return values)Functions returning an Eigen object (not a reference), are specifiedin a similar way. For instance, given the following C++ function:```c++Eigen::Matrix3d function_w_mat_retval();```The Cython code could be written as:```cdef extern from "functions.h":cdef Matrix3d _function_w_mat_retval "function_w_mat_retval" ()# This will be exposed to Pythondef function_w_mat_retval():return ndarray_copy(_function_w_mat_retval())```As mentioned above, you can replace `Matrix3d` (or any other Eigen return type) with`PlainObjectBase`, which is especially relevant when working withEigen object that do not have an associated convenience typedef.Note that we use `ndarray_copy` instead of `ndarray` to explicitlystate that a copy should be made. In c++11 compliant compilers, itwill detect the rvalue reference and automatically make a copy even ifyou just use `ndarray` (see next section), but to ensure that it worksalso with older compilers it is recommended to always use`ndarray_copy` when returning newly constructed eigen values.## Corrupt data when returning non-map typesThe tendency of Eigency to avoid copies whenever possible can leadto corrupted data when returning non-map Eigen arrays. For instance,in the `function_w_mat_retval` from the previous section, a temporaryvalue will be returned from C++, and we have to take care to makea copy of this data instead of letting the resulting numpy arrayrefer directly to this memory. In C++11, this situation can bedetected directly using rvalue references, and it will thereforeautomatically make a copy:```def function_w_mat_retval():# This works in C++11, because it detects the rvalue referencereturn ndarray(_function_w_mat_retval())```However, to make sure it works with older compilers,it is recommended to use the `ndarray_copy` conversion:```def function_w_mat_retval():# Explicit request for copy - this always worksreturn ndarray_copy(_function_w_mat_retval())```## Storage layout - why arrays are sometimes transposedThe default storage layout used in numpy and Eigen differ. Numpy usesa row-major layout (C-style) per default while Eigen uses acolumn-major layout (Fortran style) by default.  In Eigency, we prioritize toavoid copying of data whenever possible, which can have unexpectedconsequences in some cases: There is no problem when passing valuesfrom C++ to Python - we just adjust the storage layout of the returnednumpy array to match that of Eigen. However, since the storage layoutis encoded into the _type_ of the Eigen array (or the type of theMap), we cannot automatically change the layout in the Python to C++ direction. InEigency, we have therefore opted to return the transposed array/matrixin such cases. This provides the user with the flexibility to dealwith the problem either in Python (use order="F" when constructingyour numpy array), or on the C++ side: (1) explicitly define yourargument to have the row-major storage layout, 2) manually set the Mapstride, or 3) just call `.transpose()` on the receivedarray/matrix).As an example, consider the case of a C++ function that both receivesand returns a Eigen Map type, thus acting as a filter:```c++Eigen::Map<Eigen::ArrayXXd> function_filter(Eigen::Map<Eigen::ArrayXXd> &mat) {return mat;}```The Cython code could be:```cdef extern from "functions.h":...cdef Map[ArrayXXd] &_function_filter1 "function_filter1" (Map[ArrayXXd] &)def function_filter1(np.ndarray[np.float64_t, ndim=2] array):return ndarray(_function_filter1(Map[ArrayXXd](array)))```If we call this function from Python in the standard way, we willsee that the array is transposed on the way from Python to C++, andremains that way when it is again returned to Python:```python>>> x = np.array([[1., 2., 3., 4.], [5., 6., 7., 8.]])>>> y = function_filter1(x)>>> print x[[ 1.  2.  3.  4.][ 5.  6.  7.  8.]]>>> print y[[ 1.  5.][ 2.  6.][ 3.  7.][ 4.  8.]]```The simplest way to avoid this is to tell numpy to use acolumn-major array layout instead of the default row-majorlayout. This can be done using the order='F' option:```python>>> x = np.array([[1., 2., 3., 4.], [5., 6., 7., 8.]], order='F')>>> y = function_filter1(x)>>> print x[[ 1.  2.  3.  4.][ 5.  6.  7.  8.]]>>> print y[[ 1.  2.  3.  4.][ 5.  6.  7.  8.]]```The other alternative is to tell Eigen to use RowMajor layout. Thisrequires changing the C++ function definition:```c++typedef Eigen::Map<Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > RowMajorArrayMap;RowMajorArrayMap &function_filter2(RowMajorArrayMap &mat) {return mat;}```To write the corresponding Cython definition, we need the expanded version of`FlattenedMap` called `FlattenedMapWithOrder`, which allows us to specifythe storage order:```cdef extern from "functions.h":...cdef PlainObjectBase _function_filter2 "function_filter2" (FlattenedMapWithOrder[Array, double, Dynamic, Dynamic, RowMajor])def function_filter2(np.ndarray[np.float64_t, ndim=2] array):return ndarray(_function_filter2(FlattenedMapWithOrder[Array, double, Dynamic, Dynamic, RowMajor](array)))```Another alternative is to keep the array itself in RowMajor format,but use different stride values for the Map type:```c++typedef Eigen::Map<Eigen::ArrayXXd, Eigen::Unaligned, Eigen::Stride<1, Eigen::Dynamic> > CustomStrideMap;CustomStrideMap &function_filter3(CustomStrideMap &);```In this case, in Cython, we need to use the even more extended`FlattenedMap` type called `FlattenedMapWithStride`, taking eightarguments:```cdef extern from "functions.h":...cdef PlainObjectBase _function_filter3 "function_filter3" (FlattenedMapWithStride[Array, double, Dynamic, Dynamic, ColMajor, Unaligned, _1, Dynamic])def function_filter3(np.ndarray[np.float64_t, ndim=2] array):return ndarray(_function_filter3(FlattenedMapWithStride[Array, double, Dynamic, Dynamic, ColMajor, Unaligned, _1, Dynamic](array)))```In all three cases, the returned array will now be of the same shapeas the original.