Example: Interfacing Eigen

ViennaCL objects can directly initialized with data of objects from the Eigen library. The necessary wrappers are provided with ViennaCL, but must be enabled explicitly via the preprocessor constant VIENNACL_HAVE_EIGEN. The following code snippet shows how transfer from Eigen to ViennaCL and vice versa is triggered:

Transfer from Eigen to ViennaCL and back
// other ViennaCL and Eigen includes here
// main code:
Eigen::MatrixXd                                 eigen_densematrix(dim, dim);
Eigen::SparseMatrix<double, Eigen::RowMajor>    eigen_sparsematrix(dim, dim);
Eigen::VectorXd                                 eigen_vector(dim);
// fill Eigen objects in a very sophisticated way with numbers here
viennacl::matrix<double>                viennacl_densematrix(dim, dim);
viennacl::compressed_matrix<double>     viennacl_sparsematrix(dim, dim);
viennacl::vector<double>                viennacl_vector(dim);
// copy data from Eigen objects to ViennaCL objects
viennacl::copy(eigen_densematrix,  viennacl_densematrix);
viennacl::copy(eigen_sparsematrix, viennacl_sparsematrix);
viennacl::copy(eigen_vector,       viennacl_vector);
// do some heavy linear algebra with ViennaCL here 
// (iterative solvers, BLAS 3 routines, etc.)
// copy back to Eigen:
viennacl::copy(viennacl_densematrix,  eigen_densematrix);
viennacl::copy(viennacl_sparsematrix, eigen_sparsematrix);
viennacl::copy(viennacl_vector,       eigen_vector);

In addition to initializing ViennaCL objects directly with Eigen, the iterative solvers can directly be used with Eigen objects. This is especially useful if no OpenCL library is installed on the target machine.

Iterative Solvers from ViennaCL with Eigen objects
//other ViennaCL and Eigen includes here
//main code:
using namespace viennacl::linalg;
Eigen::SparseMatrix<double, Eigen::RowMajor> eigen_matrix(dim, dim);
Eigen::VectorXd eigen_rhs(dim);
Eigen::VectorXd eigen_result(dim);
// fill eigen_matrix and eigen_rhs here (e.g. by Finite Element Methods)
// Solve system using Conjugate Gradients from ViennaCL
eigen_result = solve(eigen_matrix, eigen_rhs, cg_tag());
// Solve system using Stabilized BiConjugate Gradients from ViennaCL
eigen_result = solve(eigen_matrix, eigen_rhs, bicgstab_tag());
// Solve system using Generalized Minimum Residual Method from ViennaCL
eigen_result = solve(eigen_matrix, eigen_rhs, gmres_tag());