Eigen-Contrib  5.0.1
 
Loading...
Searching...
No Matches
ArpackSelfAdjointEigenSolver.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2012 David Harmon <dharmon@gmail.com>
5//
6// This Source Code Form is subject to the terms of the Mozilla
7// Public License v. 2.0. If a copy of the MPL was not distributed
8// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9// SPDX-License-Identifier: MPL-2.0
10
11#ifndef EIGEN_ARPACKSELFADJOINTEIGENSOLVER_H
12#define EIGEN_ARPACKSELFADJOINTEIGENSOLVER_H
13
14#include "../../../../Eigen/Dense"
15
16// IWYU pragma: private
17#include "./InternalHeaderCheck.h"
18
19namespace Eigen {
20
21namespace internal {
22template <typename Scalar, typename RealScalar>
23struct arpack_wrapper;
24template <typename MatrixSolver, typename MatrixType, typename Scalar, bool BisSPD>
25struct OP;
26} // namespace internal
27
28template <typename MatrixType, typename MatrixSolver = SimplicialLLT<MatrixType>, bool BisSPD = false>
29class ArpackGeneralizedSelfAdjointEigenSolver {
30 public:
32 typedef typename MatrixType::Scalar Scalar;
33 typedef typename MatrixType::Index Index;
34
41 typedef typename NumTraits<Scalar>::Real RealScalar;
42
48 typedef typename internal::plain_col_type<MatrixType, RealScalar>::type RealVectorType;
49
56 ArpackGeneralizedSelfAdjointEigenSolver()
57 : m_eivec(),
58 m_eivalues(),
59 m_isInitialized(false),
60 m_eigenvectorsOk(false),
61 m_nbrConverged(0),
62 m_nbrIterations(0) {}
63
86 ArpackGeneralizedSelfAdjointEigenSolver(const MatrixType &A, const MatrixType &B, Index nbrEigenvalues,
87 std::string eigs_sigma = "LM", int options = ComputeEigenvectors,
88 RealScalar tol = 0.0)
89 : m_eivec(),
90 m_eivalues(),
91 m_isInitialized(false),
92 m_eigenvectorsOk(false),
93 m_nbrConverged(0),
94 m_nbrIterations(0) {
95 compute(A, B, nbrEigenvalues, eigs_sigma, options, tol);
96 }
97
119
120 ArpackGeneralizedSelfAdjointEigenSolver(const MatrixType &A, Index nbrEigenvalues, std::string eigs_sigma = "LM",
121 int options = ComputeEigenvectors, RealScalar tol = 0.0)
122 : m_eivec(),
123 m_eivalues(),
124 m_isInitialized(false),
125 m_eigenvectorsOk(false),
126 m_nbrConverged(0),
127 m_nbrIterations(0) {
128 compute(A, nbrEigenvalues, eigs_sigma, options, tol);
129 }
130
154 ArpackGeneralizedSelfAdjointEigenSolver &compute(const MatrixType &A, const MatrixType &B, Index nbrEigenvalues,
155 std::string eigs_sigma = "LM", int options = ComputeEigenvectors,
156 RealScalar tol = 0.0);
157
180 ArpackGeneralizedSelfAdjointEigenSolver &compute(const MatrixType &A, Index nbrEigenvalues,
181 std::string eigs_sigma = "LM", int options = ComputeEigenvectors,
182 RealScalar tol = 0.0);
183
203 const Matrix<Scalar, Dynamic, Dynamic> &eigenvectors() const {
204 eigen_assert(m_isInitialized && "ArpackGeneralizedSelfAdjointEigenSolver is not initialized.");
205 eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
206 return m_eivec;
207 }
208
224 const Matrix<Scalar, Dynamic, 1> &eigenvalues() const {
225 eigen_assert(m_isInitialized && "ArpackGeneralizedSelfAdjointEigenSolver is not initialized.");
226 return m_eivalues;
227 }
228
247 Matrix<Scalar, Dynamic, Dynamic> operatorSqrt() const {
248 eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
249 eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
250 return m_eivec * m_eivalues.cwiseSqrt().asDiagonal() * m_eivec.adjoint();
251 }
252
271 Matrix<Scalar, Dynamic, Dynamic> operatorInverseSqrt() const {
272 eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
273 eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
274 return m_eivec * m_eivalues.cwiseInverse().cwiseSqrt().asDiagonal() * m_eivec.adjoint();
275 }
276
281 ComputationInfo info() const {
282 eigen_assert(m_isInitialized && "ArpackGeneralizedSelfAdjointEigenSolver is not initialized.");
283 return m_info;
284 }
285
286 size_t getNbrConvergedEigenValues() const { return m_nbrConverged; }
287
288 size_t getNbrIterations() const { return m_nbrIterations; }
289
290 protected:
291 Matrix<Scalar, Dynamic, Dynamic> m_eivec;
292 Matrix<Scalar, Dynamic, 1> m_eivalues;
293 ComputationInfo m_info;
294 bool m_isInitialized;
295 bool m_eigenvectorsOk;
296
297 size_t m_nbrConverged;
298 size_t m_nbrIterations;
299};
300
301template <typename MatrixType, typename MatrixSolver, bool BisSPD>
302ArpackGeneralizedSelfAdjointEigenSolver<MatrixType, MatrixSolver, BisSPD> &
303ArpackGeneralizedSelfAdjointEigenSolver<MatrixType, MatrixSolver, BisSPD>::compute(const MatrixType &A,
304 Index nbrEigenvalues,
305 std::string eigs_sigma, int options,
306 RealScalar tol) {
307 MatrixType B(0, 0);
308 compute(A, B, nbrEigenvalues, eigs_sigma, options, tol);
309
310 return *this;
311}
312
313template <typename MatrixType, typename MatrixSolver, bool BisSPD>
314ArpackGeneralizedSelfAdjointEigenSolver<MatrixType, MatrixSolver, BisSPD> &
315ArpackGeneralizedSelfAdjointEigenSolver<MatrixType, MatrixSolver, BisSPD>::compute(const MatrixType &A,
316 const MatrixType &B,
317 Index nbrEigenvalues,
318 std::string eigs_sigma, int options,
319 RealScalar tol) {
320 eigen_assert(A.cols() == A.rows());
321 eigen_assert(B.cols() == B.rows());
322 eigen_assert(B.rows() == 0 || A.cols() == B.rows());
323 eigen_assert((options & ~(EigVecMask | GenEigMask)) == 0 && (options & EigVecMask) != EigVecMask &&
324 "invalid option parameter");
325
326 bool isBempty = (B.rows() == 0) || (B.cols() == 0);
327
328 // For clarity, all parameters match their ARPACK name
329 //
330 // Always 0 on the first call
331 //
332 int ido = 0;
333
334 int n = (int)A.cols();
335
336 // User options: "LA", "SA", "SM", "LM", "BE"
337 //
338 char whch[3] = "LM";
339
340 // Specifies the shift if iparam[6] = { 3, 4, 5 }, not used if iparam[6] = { 1, 2 }
341 //
342 RealScalar sigma = 0.0;
343
344 if (eigs_sigma.length() >= 2 && isalpha(eigs_sigma[0]) && isalpha(eigs_sigma[1])) {
345 eigs_sigma[0] = toupper(eigs_sigma[0]);
346 eigs_sigma[1] = toupper(eigs_sigma[1]);
347
348 // In the following special case we're going to invert the problem, since solving
349 // for larger magnitude is much much faster
350 // i.e., if 'SM' is specified, we're going to really use 'LM', the default
351 //
352 if (eigs_sigma.substr(0, 2) != "SM") {
353 whch[0] = eigs_sigma[0];
354 whch[1] = eigs_sigma[1];
355 }
356 } else {
357 eigen_assert(false && "Specifying clustered eigenvalues is not yet supported!");
358
359 // If it's not scalar values, then the user may be explicitly
360 // specifying the sigma value to cluster the evs around
361 //
362 sigma = atof(eigs_sigma.c_str());
363
364 // If atof fails, it returns 0.0, which is a fine default
365 //
366 }
367
368 // "I" means normal eigenvalue problem, "G" means generalized
369 //
370 char bmat[2] = "I";
371 if (eigs_sigma.substr(0, 2) == "SM" || !(isalpha(eigs_sigma[0]) && isalpha(eigs_sigma[1])) || (!isBempty && !BisSPD))
372 bmat[0] = 'G';
373
374 // Now we determine the mode to use
375 //
376 int mode = (bmat[0] == 'G') + 1;
377 if (eigs_sigma.substr(0, 2) == "SM" || !(isalpha(eigs_sigma[0]) && isalpha(eigs_sigma[1]))) {
378 // We're going to use shift-and-invert mode, and basically find
379 // the largest eigenvalues of the inverse operator
380 //
381 mode = 3;
382 }
383
384 // The user-specified number of eigenvalues/vectors to compute
385 //
386 int nev = (int)nbrEigenvalues;
387
388 // Allocate space for ARPACK to store the residual
389 //
390 Scalar *resid = new Scalar[n];
391
392 // Number of Lanczos vectors, must satisfy nev < ncv <= n
393 // Note that this indicates that nev != n, and we cannot compute
394 // all eigenvalues of a matrix
395 //
396 int ncv = std::min(std::max(2 * nev, 20), n);
397
398 // The working n x ncv matrix, also store the final eigenvectors (if computed)
399 //
400 Scalar *v = new Scalar[n * ncv];
401 int ldv = n;
402
403 // Working space
404 //
405 Scalar *workd = new Scalar[3 * n];
406 int lworkl = ncv * ncv + 8 * ncv; // Must be at least this length
407 Scalar *workl = new Scalar[lworkl];
408
409 int *iparam = new int[11];
410 iparam[0] = 1; // 1 means we let ARPACK perform the shifts, 0 means we'd have to do it
411 iparam[2] = std::max(300, numext::div_ceil(2 * n, std::max(ncv, 1)));
412 iparam[6] = mode; // The mode, 1 is standard ev problem, 2 for generalized ev, 3 for shift-and-invert
413
414 // Used during reverse communicate to notify where arrays start
415 //
416 int *ipntr = new int[11];
417
418 // Error codes are returned in here, initial value of 0 indicates a random initial
419 // residual vector is used, any other values means resid contains the initial residual
420 // vector, possibly from a previous run
421 //
422 int info = 0;
423
424 Scalar scale = 1.0;
425
426 MatrixSolver OP;
427 if (mode == 1 || mode == 2) {
428 if (!isBempty) OP.compute(B);
429 } else if (mode == 3) {
430 if (sigma == 0.0) {
431 OP.compute(A);
432 } else {
433 // Note: We will never enter here because sigma must be 0.0
434 //
435 if (isBempty) {
436 MatrixType AminusSigmaB(A);
437 for (Index i = 0; i < A.rows(); ++i) AminusSigmaB.coeffRef(i, i) -= sigma;
438
439 OP.compute(AminusSigmaB);
440 } else {
441 MatrixType AminusSigmaB = A - sigma * B;
442 OP.compute(AminusSigmaB);
443 }
444 }
445 }
446
447 if (!(mode == 1 && isBempty) && !(mode == 2 && isBempty) && OP.info() != Success) {
448 m_info = OP.info();
449 delete[] v;
450 delete[] iparam;
451 delete[] ipntr;
452 delete[] workd;
453 delete[] workl;
454 delete[] resid;
455 m_isInitialized = false;
456 return *this;
457 }
458
459 do {
460 internal::arpack_wrapper<Scalar, RealScalar>::saupd(&ido, bmat, &n, whch, &nev, &tol, resid, &ncv, v, &ldv, iparam,
461 ipntr, workd, workl, &lworkl, &info);
462
463 if (ido == -1 || ido == 1) {
464 Scalar *in = workd + ipntr[0] - 1;
465 Scalar *out = workd + ipntr[1] - 1;
466
467 if (ido == 1 && mode != 2) {
468 Scalar *out2 = workd + ipntr[2] - 1;
469 if (isBempty || mode == 1)
471 else
473
474 in = workd + ipntr[2] - 1;
475 }
476
477 if (mode == 1) {
478 if (isBempty) {
479 // OP = A
480 //
482 } else {
483 // OP = L^{-1}AL^{-T}
484 //
485 internal::OP<MatrixSolver, MatrixType, Scalar, BisSPD>::applyOP(OP, A, n, in, out);
486 }
487 } else if (mode == 2) {
489
490 // OP = B^{-1} A
491 //
493 } else if (mode == 3) {
494 // OP = (A-\sigmaB)B (\sigma could be 0, and B could be I)
495 // The B * in is already computed and stored at in if ido == 1
496 //
497 if (ido == 1 || isBempty)
499 else
501 }
502 } else if (ido == 2) {
503 Scalar *in = workd + ipntr[0] - 1;
504 Scalar *out = workd + ipntr[1] - 1;
505
506 if (isBempty || mode == 1)
508 else
510 }
511 } while (ido != 99);
512
513 if (info == 1)
514 m_info = NoConvergence;
515 else if (info == 3)
516 m_info = NumericalIssue;
517 else if (info < 0)
518 m_info = InvalidInput;
519 else if (info != 0)
520 eigen_assert(false && "Unknown ARPACK return value!");
521 else {
522 // Do we compute eigenvectors or not?
523 //
524 int rvec = (options & ComputeEigenvectors) == ComputeEigenvectors;
525
526 // "A" means "All", use "S" to choose specific eigenvalues (not yet supported in ARPACK)
527 //
528 char howmny[2] = "A";
529
530 // if howmny == "S", specifies the eigenvalues to compute (not implemented in ARPACK)
531 //
532 int *select = new int[ncv];
533
534 // Final eigenvalues
535 //
536 m_eivalues.resize(nev, 1);
537
538 internal::arpack_wrapper<Scalar, RealScalar>::seupd(&rvec, howmny, select, m_eivalues.data(), v, &ldv, &sigma, bmat,
539 &n, whch, &nev, &tol, resid, &ncv, v, &ldv, iparam, ipntr,
540 workd, workl, &lworkl, &info);
541
542 if (info == -14)
543 m_info = NoConvergence;
544 else if (info != 0)
545 m_info = InvalidInput;
546 else {
547 if (rvec) {
548 m_eivec.resize(A.rows(), nev);
549 for (int i = 0; i < nev; i++)
550 for (int j = 0; j < n; j++) m_eivec(j, i) = v[i * n + j] / scale;
551
552 if (mode == 1 && !isBempty && BisSPD)
553 internal::OP<MatrixSolver, MatrixType, Scalar, BisSPD>::project(OP, n, nev, m_eivec.data());
554
555 m_eigenvectorsOk = true;
556 }
557
558 m_nbrIterations = iparam[2];
559 m_nbrConverged = iparam[4];
560
561 m_info = Success;
562 }
563
564 delete[] select;
565 }
566
567 delete[] v;
568 delete[] iparam;
569 delete[] ipntr;
570 delete[] workd;
571 delete[] workl;
572 delete[] resid;
573
574 m_isInitialized = (m_info == Success);
575
576 return *this;
577}
578
579// Single precision
580//
581extern "C" void ssaupd_(int *ido, char *bmat, int *n, char *which, int *nev, float *tol, float *resid, int *ncv,
582 float *v, int *ldv, int *iparam, int *ipntr, float *workd, float *workl, int *lworkl,
583 int *info);
584
585extern "C" void sseupd_(int *rvec, char *All, int *select, float *d, float *z, int *ldz, float *sigma, char *bmat,
586 int *n, char *which, int *nev, float *tol, float *resid, int *ncv, float *v, int *ldv,
587 int *iparam, int *ipntr, float *workd, float *workl, int *lworkl, int *ierr);
588
589// Double precision
590//
591extern "C" void dsaupd_(int *ido, char *bmat, int *n, char *which, int *nev, double *tol, double *resid, int *ncv,
592 double *v, int *ldv, int *iparam, int *ipntr, double *workd, double *workl, int *lworkl,
593 int *info);
594
595extern "C" void dseupd_(int *rvec, char *All, int *select, double *d, double *z, int *ldz, double *sigma, char *bmat,
596 int *n, char *which, int *nev, double *tol, double *resid, int *ncv, double *v, int *ldv,
597 int *iparam, int *ipntr, double *workd, double *workl, int *lworkl, int *ierr);
598
599namespace internal {
600
601template <typename Scalar, typename RealScalar>
602struct arpack_wrapper {
603 static inline void saupd(int *ido, char *bmat, int *n, char *which, int *nev, RealScalar *tol, Scalar *resid,
604 int *ncv, Scalar *v, int *ldv, int *iparam, int *ipntr, Scalar *workd, Scalar *workl,
605 int *lworkl, int *info) {
606 EIGEN_STATIC_ASSERT(!NumTraits<Scalar>::IsComplex, NUMERIC_TYPE_MUST_BE_REAL)
607 }
608
609 static inline void seupd(int *rvec, char *All, int *select, Scalar *d, Scalar *z, int *ldz, RealScalar *sigma,
610 char *bmat, int *n, char *which, int *nev, RealScalar *tol, Scalar *resid, int *ncv,
611 Scalar *v, int *ldv, int *iparam, int *ipntr, Scalar *workd, Scalar *workl, int *lworkl,
612 int *ierr) {
613 EIGEN_STATIC_ASSERT(!NumTraits<Scalar>::IsComplex, NUMERIC_TYPE_MUST_BE_REAL)
614 }
615};
616
617template <>
618struct arpack_wrapper<float, float> {
619 static inline void saupd(int *ido, char *bmat, int *n, char *which, int *nev, float *tol, float *resid, int *ncv,
620 float *v, int *ldv, int *iparam, int *ipntr, float *workd, float *workl, int *lworkl,
621 int *info) {
622 ssaupd_(ido, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, ipntr, workd, workl, lworkl, info);
623 }
624
625 static inline void seupd(int *rvec, char *All, int *select, float *d, float *z, int *ldz, float *sigma, char *bmat,
626 int *n, char *which, int *nev, float *tol, float *resid, int *ncv, float *v, int *ldv,
627 int *iparam, int *ipntr, float *workd, float *workl, int *lworkl, int *ierr) {
628 sseupd_(rvec, All, select, d, z, ldz, sigma, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, ipntr, workd,
629 workl, lworkl, ierr);
630 }
631};
632
633template <>
634struct arpack_wrapper<double, double> {
635 static inline void saupd(int *ido, char *bmat, int *n, char *which, int *nev, double *tol, double *resid, int *ncv,
636 double *v, int *ldv, int *iparam, int *ipntr, double *workd, double *workl, int *lworkl,
637 int *info) {
638 dsaupd_(ido, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, ipntr, workd, workl, lworkl, info);
639 }
640
641 static inline void seupd(int *rvec, char *All, int *select, double *d, double *z, int *ldz, double *sigma, char *bmat,
642 int *n, char *which, int *nev, double *tol, double *resid, int *ncv, double *v, int *ldv,
643 int *iparam, int *ipntr, double *workd, double *workl, int *lworkl, int *ierr) {
644 dseupd_(rvec, All, select, d, v, ldv, sigma, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, ipntr, workd,
645 workl, lworkl, ierr);
646 }
647};
648
649template <typename MatrixSolver, typename MatrixType, typename Scalar, bool BisSPD>
650struct OP {
651 static inline void applyOP(MatrixSolver &OP, const MatrixType &A, int n, Scalar *in, Scalar *out);
652 static inline void project(MatrixSolver &OP, int n, int k, Scalar *vecs);
653};
654
655template <typename MatrixSolver, typename MatrixType, typename Scalar>
656struct OP<MatrixSolver, MatrixType, Scalar, true> {
657 static inline void applyOP(MatrixSolver &OP, const MatrixType &A, int n, Scalar *in, Scalar *out) {
658 // OP = L^{-1} A L^{-T} (B = LL^T)
659 //
660 // First solve L^T out = in
661 //
662 Matrix<Scalar, Dynamic, 1>::Map(out, n) = OP.matrixU().solve(Matrix<Scalar, Dynamic, 1>::Map(in, n));
663 Matrix<Scalar, Dynamic, 1>::Map(out, n) = OP.permutationPinv() * Matrix<Scalar, Dynamic, 1>::Map(out, n);
664
665 // Then compute out = A out
666 //
667 Matrix<Scalar, Dynamic, 1>::Map(out, n) = A * Matrix<Scalar, Dynamic, 1>::Map(out, n);
668
669 // Then solve L out = out
670 //
671 Matrix<Scalar, Dynamic, 1>::Map(out, n) = OP.permutationP() * Matrix<Scalar, Dynamic, 1>::Map(out, n);
672 Matrix<Scalar, Dynamic, 1>::Map(out, n) = OP.matrixL().solve(Matrix<Scalar, Dynamic, 1>::Map(out, n));
673 }
674
675 static inline void project(MatrixSolver &OP, int n, int k, Scalar *vecs) {
676 // Solve L^T out = in
677 //
678 Matrix<Scalar, Dynamic, Dynamic>::Map(vecs, n, k) =
679 OP.matrixU().solve(Matrix<Scalar, Dynamic, Dynamic>::Map(vecs, n, k));
680 Matrix<Scalar, Dynamic, Dynamic>::Map(vecs, n, k) =
681 OP.permutationPinv() * Matrix<Scalar, Dynamic, Dynamic>::Map(vecs, n, k);
682 }
683};
684
685template <typename MatrixSolver, typename MatrixType, typename Scalar>
686struct OP<MatrixSolver, MatrixType, Scalar, false> {
687 static inline void applyOP(MatrixSolver &OP, const MatrixType &A, int n, Scalar *in, Scalar *out) {
688 eigen_assert(false && "Should never be in here...");
689 }
690
691 static inline void project(MatrixSolver &OP, int n, int k, Scalar *vecs) {
692 eigen_assert(false && "Should never be in here...");
693 }
694};
695
696} // end namespace internal
697
698} // end namespace Eigen
699
700#endif // EIGEN_ARPACKSELFADJOINTEIGENSOLVER_H
ComputationInfo
NumericalIssue
ComputeEigenvectors
Namespace containing all symbols from the Eigen library.