1#ifndef LINEARALGEBRA_SRC_MOLPRO_LINALG_ITERATIVESOLVER_HELPER_IMPLEMENTATION_H_
2#define LINEARALGEBRA_SRC_MOLPRO_LINALG_ITERATIVESOLVER_HELPER_IMPLEMENTATION_H_
7#include <molpro/Profiler.h>
8#include <molpro/lapacke.h>
9#include <molpro/linalg/itsolv/helper.h>
13template <
typename value_type>
16 auto mat = Eigen::Map<const Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>>(m.
data(), nrows, ncols);
17 auto svd = Eigen::JacobiSVD<Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>, Eigen::NoQRPreconditioner>(
18 mat, Eigen::ComputeThinV);
19 auto svd_system = std::list<SVD<value_type>>{};
20 auto sv = svd.singularValues();
21 for (
int i =
int(ncols) - 1; i >= 0; --i) {
22 if (std::abs(sv(i)) < threshold) {
26 for (
size_t j = 0; j < ncols; ++j) {
27 t.v.emplace_back(svd.matrixV()(j, i));
35template <
typename value_type>
38 auto mat = Eigen::Map<const Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>>(m.
data(), nrows, ncols);
39 auto svd = Eigen::BDCSVD<Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>>(mat, Eigen::ComputeThinV);
40 auto svd_system = std::list<SVD<value_type>>{};
41 auto sv = svd.singularValues();
42 for (
int i =
int(ncols) - 1; i >= 0; --i) {
43 if (std::abs(sv(i)) < threshold) {
47 for (
size_t j = 0; j < ncols; ++j) {
48 t.v.emplace_back(svd.matrixV()(j, i));
57template <
typename value_type>
63 int sdim = std::min(m, n);
64 std::vector<double> sv(sdim), u(nrows * nrows), v(ncols * ncols);
65 info = LAPACKE_dgesdd(LAPACK_ROW_MAJOR,
'A',
int(nrows),
int(ncols),
const_cast<double*
>(mat.
data()),
int(ncols),
66 sv.data(), u.data(),
int(nrows), v.data(),
int(ncols));
67 auto svd_system = std::list<SVD<value_type>>{};
68 for (
int i =
int(ncols) - 1; i >= 0; --i) {
69 if (std::abs(sv[i]) < threshold) {
70 auto t = SVD<value_type>{};
73 for (
size_t j = 0; j < ncols; ++j) {
74 t.v.emplace_back(v[i * ncols + j]);
82template <
typename value_type>
83std::list<SVD<value_type>> svd_lapacke_dgesvd(
size_t nrows,
size_t ncols,
const array::Span<value_type>& mat,
88 int sdim = std::min(m, n);
89 std::vector<double> sv(sdim), u(nrows * nrows), v(ncols * ncols);
90 double superb[sdim - 1];
91 info = LAPACKE_dgesvd(LAPACK_ROW_MAJOR,
'N',
'A',
int(nrows),
int(ncols),
const_cast<double*
>(mat.data()),
int(ncols),
92 sv.data(), u.data(),
int(nrows), v.data(),
int(ncols), superb);
93 auto svd_system = std::list<SVD<value_type>>{};
94 for (
int i =
int(ncols) - 1; i >= 0; --i) {
95 if (std::abs(sv[i]) < threshold) {
96 auto t = SVD<value_type>{};
99 for (
size_t j = 0; j < ncols; ++j) {
100 t.v.emplace_back(v[i * ncols + j]);
111extern "C" int dsyev_c(
char,
char,
int,
double*,
int,
double*);
124 std::vector<double>& eigenvalues,
const size_t dimension) {
127 if (eigenvectors.size() != matrix.size()) {
128 throw std::runtime_error(
"Matrix of eigenvectors and input matrix are not the same size!");
131 if (eigenvectors.size() != dimension * dimension || eigenvalues.size() != dimension) {
132 throw std::runtime_error(
"Size of eigenvectors/eigenvlaues do not match dimension!");
137 static const char compute_eigenvalues_eigenvectors =
'V';
139 static const char store_lower_triangle =
'L';
142 std::copy(matrix.begin(), matrix.end(), eigenvectors.begin());
146 lapack_int leading_dimension = dimension;
147 lapack_int order = dimension;
151 status = dsyev_c(compute_eigenvalues_eigenvectors, store_lower_triangle, order, eigenvectors.data(),
152 leading_dimension, eigenvalues.data());
154 status = LAPACKE_dsyev(LAPACK_COL_MAJOR, compute_eigenvalues_eigenvectors, store_lower_triangle, order,
155 eigenvectors.data(), leading_dimension, eigenvalues.data());
169 std::vector<double> eigvecs(dimension * dimension);
170 std::vector<double> eigvals(dimension);
175 throw std::invalid_argument(
"Invalid argument of eigensolver_lapacke_dsyev: ");
178 throw std::runtime_error(
"Lapacke_dsyev (eigensolver) failed to converge. "
179 " elements of an intermediate tridiagonal form did not converge to zero.");
182 auto eigensystem = std::list<SVD<double>>{};
185 for (
int i = dimension - 1; i >= 0;
188 temp_eigenproblem.
value = eigvals[i];
189 for (
size_t j = 0; j < dimension; j++) {
190 temp_eigenproblem.v.emplace_back(eigvecs[j + (dimension * i)]);
192 eigensystem.emplace_back(temp_eigenproblem);
210 std::vector<double> v;
211 v.insert(v.begin(), matrix.
begin(), matrix.
end());
222template <
typename value_type>
223size_t get_rank(std::vector<value_type> eigenvalues, value_type threshold) {
224 if (eigenvalues.size() == 0) {
227 value_type max = *max_element(eigenvalues.begin(), eigenvalues.end());
228 value_type threshold_scaled = threshold * max;
230 std::count_if(eigenvalues.begin(), eigenvalues.end(), [&](
auto const& val) { return val >= threshold_scaled; });
241template <
typename value_type>
244 value_type max_value = 0;
245 std::list<SVD<double>>::iterator it;
247 if (it->value > max_value) {
248 max_value = it->value;
252 value_type threshold_scaled = threshold * max_value;
257 if (it->value > threshold_scaled) {
264template <
typename value_type,
typename std::enable_if_t<!is_complex<value_type>{}, std::
nullptr_t>>
266 bool hermitian,
bool reduce_to_rank) {
267 std::list<SVD<value_type>> svds;
268 assert(m.
size() == nrows * ncols);
272 assert(nrows == ncols);
274 for (
auto s = svds.begin(); s != svds.end();)
275 if (s->value > threshold)
285 svds = svd_eigen_jacobi<value_type>(nrows, ncols, m, threshold);
290 if (reduce_to_rank) {
291 int rank =
get_rank(svds, threshold);
292 for (
int i = ncols; i > rank; i--) {
299template <
typename value_type,
typename std::enable_if_t<is_complex<value_type>{},
int>>
301 bool hermitian,
bool reduce_to_rank) {
306template <
typename value_type>
307void printMatrix(
const std::vector<value_type>& m,
size_t rows,
size_t cols, std::string title, std::ostream& s) {
309 << Eigen::Map<const Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>>(m.data(), rows, cols) << std::endl;
312template <
typename value_type,
typename std::enable_if_t<is_complex<value_type>{},
int>>
313void eigenproblem(std::vector<value_type>& eigenvectors, std::vector<value_type>& eigenvalues,
314 const std::vector<value_type>& matrix,
const std::vector<value_type>& metric,
size_t dimension,
315 bool hermitian,
double svdThreshold,
int verbosity,
bool condone_complex) {
319template <
typename value_type,
typename std::enable_if_t<!is_complex<value_type>{}, std::
nullptr_t>>
320void eigenproblem(std::vector<value_type>& eigenvectors, std::vector<value_type>& eigenvalues,
321 const std::vector<value_type>& matrix,
const std::vector<value_type>& metric,
size_t dimension,
322 bool hermitian,
double svdThreshold,
int verbosity,
bool condone_complex) {
324 prof->start(
"itsolv::eigenproblem");
325 Eigen::Map<const Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> HrowMajor(
326 matrix.data(), dimension, dimension);
327 Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic> H(dimension, dimension);
329 Eigen::Map<const Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>> S(metric.data(), dimension, dimension);
330 Eigen::MatrixXcd subspaceEigenvectors;
331 Eigen::VectorXcd subspaceEigenvalues;
335 Eigen::VectorXd singularValues;
336 Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> matrixV;
337 Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> matrixU;
338 std::vector<double> eigvecs;
339 std::vector<double> eigvals;
344 eigvecs.resize(dimension * dimension);
345 eigvals.resize(dimension);
348 throw std::runtime_error(
"Eigensolver did not converge");
350 singularValues = Eigen::Map<Eigen::VectorXd>(eigvals.data(), dimension);
351 matrixV = Eigen::Map<Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>>(
352 eigvecs.data(), dimension, dimension);
353 matrixU = Eigen::Map<Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>>(
354 eigvecs.data(), dimension, dimension);
355 rank =
get_rank(eigvals, svdThreshold);
357 Eigen::JacobiSVD<Eigen::MatrixXd> svd(S, Eigen::ComputeThinU | Eigen::ComputeThinV);
358 singularValues = svd.singularValues();
359 matrixV = svd.matrixV();
360 matrixU = svd.matrixU();
367 if (verbosity > 1 && rank <
S.cols())
368 molpro::cout <<
"SVD rank " << rank <<
" in subspace of dimension " <<
S.cols() << std::endl;
369 if (verbosity > 2 && rank <
S.cols())
370 molpro::cout <<
"singular values " << singularValues.transpose() << std::endl;
371 auto svmh = singularValues.head(rank);
372 for (
auto k = 0; k < rank; k++)
373 svmh(k) = svmh(k) > 1e-14 ? 1 / std::sqrt(svmh(k)) : 0;
375 (svmh.asDiagonal()) * (matrixU.leftCols(rank).adjoint()) * H * matrixV.leftCols(rank) * (svmh.asDiagonal());
383 Eigen::EigenSolver<Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>> s(Hbar);
385 subspaceEigenvalues = s.eigenvalues();
386 if (s.eigenvalues().imag().norm() < 1e-10) {
388 subspaceEigenvalues = subspaceEigenvalues.real();
389 subspaceEigenvectors = s.eigenvectors();
392 for (
int i = 0; i < subspaceEigenvectors.cols(); i++) {
393 if (subspaceEigenvectors.col(i).imag().norm() > 1e-10) {
395 if (std::abs(subspaceEigenvalues(i) - subspaceEigenvalues(j)) < 1e-10 and
396 subspaceEigenvectors.col(j).imag().norm() > 1e-10) {
397 subspaceEigenvectors.col(j) = subspaceEigenvectors.col(i).imag() / subspaceEigenvectors.col(i).imag().norm();
398 subspaceEigenvectors.col(i) = subspaceEigenvectors.col(i).real() / subspaceEigenvectors.col(i).real().norm();
402 subspaceEigenvectors = matrixV.leftCols(rank) * svmh.asDiagonal() * subspaceEigenvectors;
406#ifdef __INTEL_COMPILER
407 molpro::cout <<
"Hbar\n" << Hbar << std::endl;
408 molpro::cout <<
"Eigenvalues\n" << s.eigenvalues() << std::endl;
409 molpro::cout <<
"Eigenvectors\n" << s.eigenvectors() << std::endl;
410 throw std::runtime_error(
"Intel compiler does not support working with complex eigen3 entities properly");
412 subspaceEigenvectors = matrixV.leftCols(rank) * svmh.asDiagonal() * s.eigenvectors();
418 auto eigval = subspaceEigenvalues;
419 auto eigvec = subspaceEigenvectors;
420 std::vector<Eigen::Index> map;
421 for (Eigen::Index k = 0; k < Hbar.cols(); k++) {
423 for (ll = 0; std::count(map.begin(), map.end(), ll) != 0; ll++)
425 for (Eigen::Index l = 0; l < Hbar.cols(); l++) {
426 if (std::count(map.begin(), map.end(), l) == 0) {
427 if (eigval(l).real() < eigval(ll).real())
432 subspaceEigenvalues(k) = eigval(ll);
435 subspaceEigenvectors.col(k) = eigvec.col(ll);
437 for (Eigen::Index l = 0; l < Hbar.cols(); l++) {
438 if (std::abs(subspaceEigenvectors.col(k)[l].real()) > std::abs(subspaceEigenvectors.col(k)[maxcomp].real()))
441 if (subspaceEigenvectors.col(k)[maxcomp].real() < 0)
442 subspaceEigenvectors.col(k) = - subspaceEigenvectors.col(k);
453 Eigen::MatrixXcd ovlTimesVec(subspaceEigenvectors.cols(), subspaceEigenvectors.rows());
454 for (
auto repeat = 0; repeat < 3; ++repeat)
455 for (Eigen::Index k = 0; k < subspaceEigenvectors.cols(); k++) {
456 if (std::abs(subspaceEigenvalues(k)) <
458 subspaceEigenvectors.col(k).real() += double(0.3256897) * subspaceEigenvectors.col(k).imag();
459 subspaceEigenvectors.col(k).imag().setZero();
462 for (Eigen::Index l = 0; l < k; l++) {
474 subspaceEigenvectors.col(k) -= subspaceEigenvectors.col(l) *
475 ovlTimesVec.row(l).dot(subspaceEigenvectors.col(k));
487 subspaceEigenvectors.col(k).adjoint().dot(S * subspaceEigenvectors.col(k));
488 subspaceEigenvectors.col(k) /= std::sqrt(ovl.real());
489 ovlTimesVec.row(k) = subspaceEigenvectors.col(k).adjoint() *
S;
495 Eigen::Index lmax = 0;
496 for (Eigen::Index l = 0; l < subspaceEigenvectors.rows(); l++) {
497 if (std::abs(subspaceEigenvectors(l, k)) > std::abs(subspaceEigenvectors(lmax, k)))
500 if (subspaceEigenvectors(lmax, k).real() < 0)
501 subspaceEigenvectors.col(k) = -subspaceEigenvectors.col(k);
512 if (condone_complex) {
513 for (Eigen::Index root = 0; root < Hbar.cols(); ++root) {
514 if (subspaceEigenvalues(root).imag() != 0) {
518 subspaceEigenvalues(root) = subspaceEigenvalues(root + 1) = subspaceEigenvalues(root).real();
519 subspaceEigenvectors.col(root) = subspaceEigenvectors.col(root).real();
520 subspaceEigenvectors.col(root + 1) = subspaceEigenvectors.col(root + 1).imag();
525 if ((subspaceEigenvectors - subspaceEigenvectors.real()).norm() > 1e-10 or
526 (subspaceEigenvalues - subspaceEigenvalues.real()).norm() > 1e-10) {
527 throw std::runtime_error(
"unexpected complex solution found");
529 eigenvectors.resize(dimension * Hbar.cols());
530 eigenvalues.resize(Hbar.cols());
532 Eigen::Map<Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>>(eigenvectors.data(), dimension, Hbar.cols()) =
533 subspaceEigenvectors.real();
534 Eigen::Map<Eigen::Matrix<value_type, Eigen::Dynamic, 1>> ev(eigenvalues.data(), Hbar.cols());
535 ev = subspaceEigenvalues.real();
546template <
typename value_type,
typename std::enable_if_t<is_complex<value_type>{},
int>>
548 const std::vector<value_type>& matrix,
const std::vector<value_type>& metric,
549 const std::vector<value_type>& rhs,
const size_t dimension,
size_t nroot,
550 double augmented_hessian,
double svdThreshold,
int verbosity) {
554template <
typename value_type,
typename std::enable_if_t<!is_complex<value_type>{}, std::
nullptr_t>>
556 const std::vector<value_type>& matrix,
const std::vector<value_type>& metric,
557 const std::vector<value_type>& rhs,
const size_t dimension,
size_t nroot,
558 double augmented_hessian,
double svdThreshold,
int verbosity) {
559 const Eigen::Index nX = dimension;
560 solution.resize(nX * nroot);
562 if (augmented_hessian > 0) {
563 Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic> subspaceMatrix;
564 Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic> subspaceOverlap;
565 subspaceMatrix.conservativeResize(nX + 1, nX + 1);
566 subspaceOverlap.conservativeResize(nX + 1, nX + 1);
567 subspaceMatrix.block(0, 0, nX, nX) =
568 Eigen::Map<const Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>>(matrix.data(), nX, nX);
569 subspaceOverlap.block(0, 0, nX, nX) =
570 Eigen::Map<const Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>>(metric.data(), nX, nX);
571 eigenvalues.resize(nroot);
572 for (
size_t root = 0; root < nroot; root++) {
573 for (Eigen::Index i = 0; i < nX; i++) {
574 subspaceMatrix(i, nX) = subspaceMatrix(nX, i) = -augmented_hessian * rhs[i + nX * root];
575 subspaceOverlap(i, nX) = subspaceOverlap(nX, i) = 0;
577 subspaceMatrix(nX, nX) = 0;
578 subspaceOverlap(nX, nX) = 1;
582 Eigen::GeneralizedEigenSolver<Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>> s(subspaceMatrix,
584 auto eval = s.eigenvalues();
585 auto evec = s.eigenvectors();
586 Eigen::Index imax = 0;
587 for (Eigen::Index i = 0; i < nX + 1; i++)
588 if (eval(i).real() < eval(imax).real())
590 eigenvalues[root] = eval(imax).real();
591 auto Solution = evec.col(imax).real().head(nX) / (augmented_hessian * evec.real()(nX, imax));
592 for (
auto k = 0; k < nX; k++)
593 solution[k + nX * root] = Solution(k);
597 Eigen::Map<const Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> subspaceMatrixR(
598 matrix.data(), nX, nX);
599 Eigen::Map<const Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> RHS_R(rhs.data(), nX,
601 Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic> subspaceMatrix = subspaceMatrixR;
602 Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic> RHS = RHS_R;
603 Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic> Solution;
612 Solution = subspaceMatrix.householderQr().solve(RHS);
614 for (
size_t root = 0; root < nroot; root++)
615 for (
auto k = 0; k < nX; k++)
616 solution[k + nX * root] = Solution(k, root);
620template <
typename value_type,
typename std::enable_if_t<!is_complex<value_type>{}, std::
nullptr_t>>
621void solve_DIIS(std::vector<value_type>& solution,
const std::vector<value_type>& matrix,
const size_t dimension,
622 double svdThreshold,
int verbosity) {
623 auto nAug = dimension + 1;
625 solution.resize(dimension);
627 Eigen::VectorXd Rhs(nAug), Coeffs(nAug);
628 Eigen::MatrixXd BAug(nAug, nAug);
632 Eigen::Map<const Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>> subspaceMatrix(matrix.data(), dimension,
634 BAug.block(0, 0, dimension, dimension) = subspaceMatrix;
635 for (
size_t i = 0; i < dimension; ++i) {
636 BAug(dimension, i) = BAug(i, dimension) = -1;
639 BAug(dimension, dimension) = 0;
646 Eigen::JacobiSVD<Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>> svd(BAug, Eigen::ComputeThinU |
647 Eigen::ComputeThinV);
651 svd.setThreshold(svdThreshold * svd.singularValues().maxCoeff() * 0);
656 Coeffs = svd.solve(Rhs).head(dimension);
660 molpro::cout <<
"Combination of iteration vectors: " << Coeffs.transpose() << std::endl;
661 for (
size_t k = 0; k < (size_t)Coeffs.rows(); k++) {
662 if (std::isnan(std::abs(Coeffs(k)))) {
663 molpro::cout <<
"B:" << std::endl << BAug << std::endl;
664 molpro::cout <<
"Rhs:" << std::endl << Rhs << std::endl;
665 molpro::cout <<
"Combination of iteration vectors: " << Coeffs.transpose() << std::endl;
666 throw std::overflow_error(
"NaN detected in DIIS submatrix solution");
668 solution[k] = Coeffs(k);
Non-owning container taking a pointer to the data buffer and its size and exposing routines for itera...
Definition: Span.h:30
bool empty() const
Definition: Span.h:78
iterator begin()
Definition: Span.h:68
size_type size() const
Definition: Span.h:76
iterator end()
Definition: Span.h:72
iterator data()
Definition: Span.h:65
static std::shared_ptr< Profiler > single()
4-parameter interpolation of a 1-dimensional function given two points for which function values and ...
Definition: helper.h:10
std::list< SVD< value_type > > svd_eigen_bdcsvd(size_t nrows, size_t ncols, const array::Span< value_type > &m, double threshold)
Definition: helper-implementation.h:36
std::list< SVD< value_type > > svd_system(size_t nrows, size_t ncols, const array::Span< value_type > &m, double threshold, bool hermitian=false, bool reduce_to_rank=false)
Performs singular value decomposition and returns SVD objects for singular values less than threshold...
Definition: helper-implementation.h:265
void solve_LinearEquations(std::vector< value_type > &solution, std::vector< value_type > &eigenvalues, const std::vector< value_type > &matrix, const std::vector< value_type > &metric, const std::vector< value_type > &rhs, size_t dimension, size_t nroot, double augmented_hessian, double svdThreshold, int verbosity)
Definition: helper-implementation.h:547
size_t get_rank(std::vector< value_type > eigenvalues, value_type threshold)
Definition: helper-implementation.h:223
void solve_DIIS(std::vector< value_type > &solution, const std::vector< value_type > &matrix, size_t dimension, double svdThreshold, int verbosity=0)
Definition: helper-implementation.h:621
void eigenproblem(std::vector< value_type > &eigenvectors, std::vector< value_type > &eigenvalues, const std::vector< value_type > &matrix, const std::vector< value_type > &metric, size_t dimension, bool hermitian, double svdThreshold, int verbosity, bool condone_complex)
Definition: helper-implementation.h:313
int eigensolver_lapacke_dsyev(const std::vector< double > &matrix, std::vector< double > &eigenvectors, std::vector< double > &eigenvalues, const size_t dimension)
Definition: helper-implementation.h:123
void printMatrix(const std::vector< value_type > &, size_t rows, size_t cols, std::string title="", std::ostream &s=molpro::cout)
Definition: helper-implementation.h:307
std::list< SVD< value_type > > svd_eigen_jacobi(size_t nrows, size_t ncols, const array::Span< value_type > &m, double threshold)
Definition: helper-implementation.h:14
Stores a singular value and corresponding left and right singular vectors.
Definition: helper.h:19
value_type value
Definition: helper.h:21