AMDiS 2.10
The Adaptive Multi-Dimensional Simulation Toolbox
LinearSolver.hpp
1#pragma once
2
3#include <petscpc.h>
4#include <petscksp.h>
5
6#include <amdis/Initfile.hpp>
7#include <amdis/linearalgebra/LinearSolverInterface.hpp>
8#include <amdis/linearalgebra/petsc/Interface.hpp>
9#include <amdis/linearalgebra/petsc/SolverConfig.hpp>
10
11
12namespace AMDiS
13{
15
39 template <class Matrix, class VectorX, class VectorY = VectorX>
40 class LinearSolver
41 : public LinearSolverInterface<Matrix,VectorX,VectorY>
42 {
43 using Vector = VectorX;
44
45 public:
47
55 LinearSolver(std::string const& /*name*/, std::string const& prefix)
56 : prefix_(prefix)
57 {
58 Parameters::get(prefix + "->info", info_);
59 }
60
62 {
63 finish();
64 }
65
67 void init(Matrix const& A) override
68 {
69 finish();
70 KSPCreate(A.comm(), &ksp_);
71
72 PETSc::KSPSetOperators(ksp_, A.matrix(), A.matrix());
73 initKSP(ksp_, prefix_);
74 initialized_ = true;
75 }
76
78 void finish() override
79 {
80 if (initialized_)
81 KSPDestroy(&ksp_);
82 initialized_ = false;
83 }
84
86 void apply(VectorX& x, VectorY const& b, Dune::InverseOperatorResult& stat) override
87 {
88 KSPSolve(ksp_, b.vector(), x.vector());
89
90 if (info_ > 0)
91 PETSc::KSPConvergedReasonView(ksp_, PETSC_VIEWER_STDOUT_WORLD);
92
93 KSPConvergedReason reason;
94 KSPGetConvergedReason(ksp_, &reason);
95
96 stat.converged = (reason > 0);
97 }
98
99 KSP ksp() { return ksp_; }
100
101 protected:
102 // initialize the KSP solver from the initfile
103 virtual void initKSP(KSP ksp, std::string prefix) const
104 {
105 PETSc::configKSP(ksp, prefix);
106
107 // show details of ksp object
108 if (info_ >= 10)
109 KSPView(ksp, PETSC_VIEWER_STDOUT_WORLD);
110 }
111
112 protected:
113 std::string prefix_;
114 int info_ = 0;
115
116 KSP ksp_;
117 bool initialized_ = false;
118 };
119
120} // end namespace AMDiS
static std::optional< T > get(std::string const &key)
Get parameter-values from parameter-tree.
Definition: Initfile.hpp:25
Implementation of LinearSolverInterface for EIGEN solvers.
Definition: LinearSolver.hpp:16
void init(Matrix const &A) override
Implements LinearSolverInterface::init()
Definition: LinearSolver.hpp:67
void finish() override
Implements LinearSolverInterface::finish()
Definition: LinearSolver.hpp:35
void apply(VectorX &x, VectorY const &b, Dune::InverseOperatorResult &stat) override
Implements LinearSolverInterface::apply()
Definition: LinearSolver.hpp:86
LinearSolver(std::string const &, std::string const &prefix)
Constructor.
Definition: LinearSolver.hpp:55