This tutorial shows how to calculate the largest eigenvalues of a matrix using Lanczos' method.
The Lanczos method is particularly attractive for use with large, sparse matrices, since the only requirement on the matrix is to provide a matrix-vector product. Although less common, the method is sometimes also with dense matrices.
We start with including the necessary headers:
#include <iostream>
#ifndef NDEBUG
#define BOOST_UBLAS_NDEBUG
#endif
#define VIENNACL_WITH_UBLAS
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
#include <iomanip>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
We read a sparse matrix (from Boost.uBLAS) from a matrix-market file, then run the Lanczos method. Finally, the computed eigenvalues are printed.
Create the uBLAS-matrix and read the sparse matrix:
boost::numeric::ublas::compressed_matrix<ScalarType> ublas_A;
{
std::cout << "Error reading Matrix file" << std::endl;
return EXIT_FAILURE;
}
Create the configuration for the Lanczos method.
Run the Lanczos method by passing the tag to the routine viennacl::linalg::eig()
std::cout << "Running Lanczos algorithm (this might take a while)..." << std::endl;
Print the computed eigenvalues and exit:
for (std::size_t i = 0; i< lanczos_eigenvalues.size(); i++)
std::cout << "Eigenvalue " << i+1 << ": " << std::setprecision(10) << lanczos_eigenvalues[i] << std::endl;
return EXIT_SUCCESS;
}
Full Example Code
#include <iostream>
#ifndef NDEBUG
#define BOOST_UBLAS_NDEBUG
#endif
#define VIENNACL_WITH_UBLAS
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
#include <iomanip>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
{
boost::numeric::ublas::compressed_matrix<ScalarType> ublas_A;
{
std::cout << "Error reading Matrix file" << std::endl;
return EXIT_FAILURE;
}
10,
1700);
std::cout << "Running Lanczos algorithm (this might take a while)..." << std::endl;
for (std::size_t i = 0; i< lanczos_eigenvalues.size(); i++)
std::cout << "Eigenvalue " << i+1 << ": " << std::setprecision(10) << lanczos_eigenvalues[i] << std::endl;
return EXIT_SUCCESS;
}