FEAT 3
Finite Element Analysis Toolbox
Loading...
Searching...
No Matches
gmres.hpp
1// FEAT3: Finite Element Analysis Toolbox, Version 3
2// Copyright (C) 2010 by Stefan Turek & the FEAT group
3// FEAT3 is released under the GNU General Public License version 3,
4// see the file 'copyright.txt' in the top level directory for details.
5
6#pragma once
7
8// includes, FEAT
9#include <kernel/solver/iterative.hpp>
10#include <kernel/solver/krylov_orthogonalizer.hpp>
11
12// includes, FEAT
13#include <vector>
14
15namespace FEAT
16{
17 namespace Solver
18 {
85 template<
86 typename Matrix_,
87 typename Filter_>
88 class GMRES :
89 public PreconditionedIterativeSolver<typename Matrix_::VectorTypeR>
90 {
91 public:
92 typedef Matrix_ MatrixType;
93 typedef Filter_ FilterType;
94 typedef typename MatrixType::VectorTypeR VectorType;
95 typedef typename MatrixType::DataType DataType;
96 typedef PreconditionedIterativeSolver<VectorType> BaseClass;
97
98 typedef SolverBase<VectorType> PrecondType;
99 typedef KrylovSubspaceOrthogonalizer<VectorType> OrthoType;
100
101 protected:
103 const MatrixType& _system_matrix;
105 const FilterType& _system_filter;
107 Index _krylov_dim;
109 DataType _inner_res_scale;
111 KrylovOrthogonalizerType _ortho_type = KrylovOrthogonalizerType::modified_gram_schmidt;
112 // /// krylov basis vector
113 // std::vector<VectorType> _vec_v;
114 std::unique_ptr<OrthoType> _subspace;
115 VectorType _vec_w;
117 std::vector<DataType> _c, _s, _q;
119 std::vector<std::vector<DataType>> _h;
120
121 public:
140 explicit GMRES(const MatrixType& matrix, const FilterType& filter, Index krylov_dim,
141 DataType inner_res_scale = DataType(0), std::shared_ptr<PrecondType> precond = nullptr) :
142 BaseClass("GMRES(" + stringify(krylov_dim) + ")", precond),
143 _system_matrix(matrix),
144 _system_filter(filter),
145 _krylov_dim(krylov_dim)
146 {
147 // we always need to compute defect norms
148 this->_force_def_norm_calc = true;
149
150 // set communicator by system matrix
151 this->_set_comm_by_matrix(matrix);
152 set_inner_res_scale(inner_res_scale);
153 }
154
155 explicit GMRES(const String& section_name, const PropertyMap* section,
156 const MatrixType& matrix, const FilterType& filter, std::shared_ptr<PrecondType> precond = nullptr) :
157 BaseClass("GMRES", section_name, section, precond),
158 _system_matrix(matrix),
159 _system_filter(filter),
160 _inner_res_scale(DataType(0))
161 {
162 // we always need to compute defect norms
163 this->_force_def_norm_calc = true;
164
165 // set communicator by system matrix
166 this->_set_comm_by_matrix(matrix);
167
168 // Set _inner_res_scale by parameter or use default value
169 auto inner_res_scale_p = section->query("inner_res_scale");
170 if(inner_res_scale_p.second && (!inner_res_scale_p.first.parse(this->_inner_res_scale) || (this->_inner_res_scale < DataType(0))))
171 throw ParseError(section_name + ".inner_res_scale", inner_res_scale_p.first, "a non-negative float");
172
173 // Check if we have set _krylov_vim
174 auto krylov_dim_p = section->query("krylov_dim");
175 if(!krylov_dim_p.second)
176 throw ParseError("GMRES config section is missing the mandatory krylov_dim!");
177
178 if(!krylov_dim_p.first.parse(this->_krylov_dim) || (this->_krylov_dim <= Index(0)))
179 throw ParseError(section_name + ".krylov_dim", krylov_dim_p.first, "a positive integer");
180
181 // Set the orthogonalization strategy by parameter or use the default (modified Gram-Schmidt)
182 auto ortho_p = section->query("orthogonalizer");
183 if(ortho_p.second)
184 {
185 if(ortho_p.first == "mgs")
186 this->_ortho_type = KrylovOrthogonalizerType::modified_gram_schmidt;
187 else if(ortho_p.first == "cgs")
188 this->_ortho_type = KrylovOrthogonalizerType::classical_gram_schmidt;
189 else if(ortho_p.first == "cgs2")
190 this->_ortho_type = KrylovOrthogonalizerType::cgs2;
191 else
192 throw ParseError(section_name + ".orthogonalizer", ortho_p.first, "one of: mgs, cgs, cgs2");
193 }
194
195 this->set_plot_name("GMRES("+stringify(_krylov_dim)+")");
196 }
197
201 virtual ~GMRES()
202 {
203 }
204
206 virtual String name() const override
207 {
208 return "GMRES";
209 }
210
217 virtual void force_defect_norm_calc(bool DOXY(force)) override
218 {
219 // force is already applied in constructor
220 }
221
222 virtual void init_symbolic() override
223 {
224 BaseClass::init_symbolic();
225
226 _c.reserve(_krylov_dim);
227 _s.reserve(_krylov_dim);
228 _q.reserve(_krylov_dim + 1);
229 _h.resize(_krylov_dim);
230
231 for(Index i(0); i < _krylov_dim; ++i)
232 {
233 _h.at(i).resize(i+1);
234 }
235
236 _vec_w = this->_system_matrix.create_vector_r();
237 _subspace = _create_orthogonalizer(_vec_w);
238 }
239
240 virtual void done_symbolic() override
241 {
242 _subspace.reset();
243 _vec_w.clear();
244 BaseClass::done_symbolic();
245 }
246
254 virtual void set_krylov_dim(Index krylov_dim)
255 {
256 XASSERT(krylov_dim > Index(0));
257 _krylov_dim = krylov_dim;
258 }
259
266 virtual void set_inner_res_scale(DataType inner_res_scale)
267 {
268 XASSERT(inner_res_scale >= DataType(0));
269 _inner_res_scale = inner_res_scale;
270 }
271
280 virtual void set_orthogonalizer(KrylovOrthogonalizerType ortho_type)
281 {
282 _ortho_type = ortho_type;
283 }
284
286 virtual Status apply(VectorType& vec_sol, const VectorType& vec_rhs) override
287 {
288 // save input rhs vector as initial defect
289 this->_subspace->at(0).copy(vec_rhs);
290
291 // clear solution vector
292 vec_sol.format();
293
294 // apply
295 this->_status = _apply_intern(vec_sol, vec_rhs);
296 this->plot_summary();
297 return this->_status;
298 }
299
301 virtual Status correct(VectorType& vec_sol, const VectorType& vec_rhs) override
302 {
303 // compute initial defect
304 this->_system_matrix.apply(this->_subspace->at(0), vec_sol, vec_rhs, -DataType(1));
305 this->_system_filter.filter_def(this->_subspace->at(0));
306
307 // apply
308 this->_status = _apply_intern(vec_sol, vec_rhs);
309 this->plot_summary();
310 return this->_status;
311 }
312
313 protected:
314 virtual Status _apply_intern(VectorType& vec_sol, const VectorType& vec_rhs)
315 {
316 IterationStats pre_iter(*this);
317 Statistics::add_solver_expression(std::make_shared<ExpressionStartSolve>(this->name()));
318 const MatrixType& matrix(this->_system_matrix);
319 const FilterType& filter(this->_system_filter);
320
321 // compute initial defect
322 Status status = this->_set_initial_defect(this->_subspace->at(0), vec_sol);
323
324 pre_iter.destroy();
325
326 const Index krylov_dim = this->_subspace->get_krylov_dim();
327
328 // outer GMRES loop
329 while(status == Status::progress)
330 {
331 IterationStats stat(*this);
332
333 _q.clear();
334 _s.clear();
335 _c.clear();
336 _q.push_back(this->_def_cur);
337
338 // normalize v[0]
339 this->_subspace->at(0).scale(this->_subspace->at(0), DataType(1) / _q.back());
340
341 // inner GMRES loop
342 Index i(0);
343 while(i < krylov_dim)
344 {
345 // apply preconditioner
346 if(!this->_apply_precond(this->_vec_w, this->_subspace->at(i), filter))
347 {
348 stat.destroy();
349 Statistics::add_solver_expression(std::make_shared<ExpressionEndSolve>(this->name(), Status::aborted, this->get_num_iter()));
350 return Status::aborted;
351 }
352 //filter.filter_cor(this->_vec_z.at(i));
353
354 // v[i+1] := A*w
355 matrix.apply(this->_subspace->at(i+1), this->_vec_w);
356 filter.filter_def(this->_subspace->at(i+1));
357
358 // orthogonalize v_{i+1}
359 DataType alpha = this->_subspace->orthogonalize(this->_h.at(i).data(), i+1);
360
361 // and now normalize
362 this->_subspace->at(i+1).scale(this->_subspace->at(i+1), DataType(1) / alpha);
363
364 // apply Givens rotations
365 for(Index k(0); k < i; ++k)
366 {
367 DataType t(this->_h.at(i).at(k));
368 this->_h.at(i).at(k ) = this->_c.at(k) * t + this->_s.at(k) * this->_h.at(i).at(k+1);
369 this->_h.at(i).at(k+1) = this->_s.at(k) * t - this->_c.at(k) * this->_h.at(i).at(k+1);
370 }
371
372 // compute beta
373 DataType beta = Math::sqrt(Math::sqr(this->_h.at(i).at(i)) + Math::sqr(alpha));
374
375 // compute next plane rotation
376 _s.push_back(alpha / beta);
377 _c.push_back(this->_h.at(i).at(i) / beta);
378
379 this->_h.at(i).at(i) = beta;
380 this->_q.push_back(this->_s.back() * this->_q.at(i));
381 this->_q.at(i) *= this->_c.back();
382
383 // push our new defect
384 if(++i < this->_krylov_dim)
385 {
386 // get the absolute defect
387 DataType def_cur = Math::abs(this->_q.back());
388
389 // did we diverge?
390 if((def_cur > this->_div_abs) || (def_cur > (this->_div_rel * this->_def_init)))
391 break;
392
393 // minimum number of iterations performed?
394 if(!(this->_num_iter < this->_min_iter))
395 {
396 // did we converge?
397 if((def_cur <= _inner_res_scale * this->_tol_abs) &&
398 ((def_cur <= _inner_res_scale * (this->_tol_rel * this->_def_init)) || (def_cur <= _inner_res_scale * this->_tol_abs_low) ))
399 break;
400
401 // maximum number of iterations performed?
402 if(this->_num_iter >= this->_max_iter)
403 break;
404 }
405
406 // set our pseudo defect
407 // increase iteration count
408 ++this->_num_iter;
409
410 // compute new defect
411 this->_def_cur = def_cur;
412
413 // plot?
414 if(this->_plot_iter())
415 {
416 String msg = this->_plot_name
417 + "* " + stringify(this->_num_iter).pad_front(this->_iter_digits)
418 + " : " + stringify_fp_sci(this->_def_cur);
419 this->_print_line(msg);
420 }
421 }
422 }
423
424 if(this->_plot_iter())
425 {
426 /* DEBUG */
427 String msg = this->_plot_name
428 + "* " + stringify(this->_num_iter).pad_front(this->_iter_digits)
429 + " : " + stringify_fp_sci(Math::abs(this->_q.back()))
430 + " <= " + stringify_fp_sci(this->_inner_res_scale * this->_tol_abs)
431 + " && " + stringify_fp_sci(this->_inner_res_scale * this->_tol_rel);
432 this->_print_line(msg);
433 }
434
435 Index n = Math::min(i, krylov_dim);
436
437 // solve H*q = q
438 for(Index k(n); k > 0;)
439 {
440 --k;
441 this->_q.at(k) /= this->_h.at(k).at(k);
442 for(Index j(k); j > 0;)
443 {
444 --j;
445 this->_q.at(j) -= this->_h.at(k).at(j) * this->_q.at(k);
446 }
447 }
448
449 // update solution
450 this->_vec_w.format();
451
452 // dispatch vector correction to subspace (fused kernel possible)
453 this->_subspace->correct_vector(this->_vec_w, this->_q.data(), n, DataType(1));
454
455 // re-use v[0] for preconditioned correction
456 if(!this->_apply_precond(this->_subspace->at(0), this->_vec_w, filter))
457 {
458 stat.destroy();
459 Statistics::add_solver_expression(std::make_shared<ExpressionEndSolve>(this->name(), Status::aborted, this->get_num_iter()));
460 return Status::aborted;
461 }
462 vec_sol.axpy(this->_subspace->at(0));
463
464 // compute "real" residual
465 matrix.apply(this->_subspace->at(0), vec_sol, vec_rhs, -DataType(1));
466 filter.filter_def(this->_subspace->at(0));
467
468 // set the current defect
469 status = this->_set_new_defect(this->_subspace->at(0), vec_sol);
470
471 }
472
473 // finished
474 Statistics::add_solver_expression(std::make_shared<ExpressionEndSolve>(this->name(), status, this->get_num_iter()));
475 return status;
476 }
477
478 std::unique_ptr<OrthoType> _create_orthogonalizer(const VectorType& vec_w)
479 {
480 switch(_ortho_type)
481 {
482 case KrylovOrthogonalizerType::classical_gram_schmidt:
483 return std::make_unique<ClassicGramSchmidtOrthogonalizer<VectorType>>(vec_w, this->_krylov_dim);
484 case KrylovOrthogonalizerType::cgs2:
485 return std::make_unique<CGS2Orthogonalizer<VectorType>>(vec_w, this->_krylov_dim);
486 case KrylovOrthogonalizerType::modified_gram_schmidt:
487 default:
488 return std::make_unique<ModifiedGramSchmidtOrthogonalizer<VectorType>>(vec_w, this->_krylov_dim);
489 }
490 }
491 }; // class GMRES<...>
492
515 template<typename Matrix_, typename Filter_>
516 inline std::shared_ptr<GMRES<Matrix_, Filter_>> new_gmres(
517 const Matrix_& matrix, const Filter_& filter, Index krylov_dim,
518 typename Matrix_::DataType inner_res_scale = typename Matrix_::DataType(0),
519 std::shared_ptr<SolverBase<typename Matrix_::VectorTypeL>> precond = nullptr)
520 {
521 return std::make_shared<GMRES<Matrix_, Filter_>>(matrix, filter, krylov_dim, inner_res_scale, precond);
522 }
523
545 template<typename Matrix_, typename Filter_>
546 inline std::shared_ptr<GMRES<Matrix_, Filter_>> new_gmres(
547 const String& section_name, const PropertyMap* section,
548 const Matrix_& matrix, const Filter_& filter,
549 std::shared_ptr<SolverBase<typename Matrix_::VectorTypeL>> precond = nullptr)
550 {
551 return std::make_shared<GMRES<Matrix_, Filter_>>(section_name, section, matrix, filter, precond);
552 }
553 } // namespace Solver
554} // namespace FEAT
#define XASSERT(expr)
Assertion macro definition.
Definition: assertion.hpp:262
String pad_front(size_type len, char c=' ') const
Pads the front of the string up to a desired length.
Definition: string.hpp:393
Status
Solver status return codes enumeration.
Definition: base.hpp:47
KrylovOrthogonalizerType
Enumeration of the available Krylov subspace orthogonalization strategies.
FEAT namespace.
Definition: adjactor.hpp:12
String stringify(const T_ &item)
Converts an item into a String.
Definition: string.hpp:993
String stringify_fp_sci(DataType_ value, int precision=0, int width=0, bool sign=false)
Prints a floating point value to a string in scientific notation.
Definition: string.hpp:1137
std::uint64_t Index
Index data type.