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