dune-fem 2.12-git
Loading...
Searching...
No Matches
petscinverseoperators.hh
Go to the documentation of this file.
1#ifndef DUNE_FEM_PETSCINVERSEOPERATORS_HH
2#define DUNE_FEM_PETSCINVERSEOPERATORS_HH
3
4#include <limits>
5
7
12
13
14#if HAVE_PETSC
20
21namespace Dune
22{
23
24 namespace Fem
25 {
26
27 //=====================================================================
28 // Implementation for PETSc matrix based Krylov solvers
29 //=====================================================================
30
35 // PETScSolver
36 // --------------
37 template< class DF, class Op = Dune::Fem::Operator< DF, DF > >
38 class PetscInverseOperator;
39
40 template <class DF, class Op >
41 struct PetscInverseOperatorTraits
42 {
43 private:
44 typedef typename DF :: DiscreteFunctionSpaceType SpaceType ;
45 public:
46 typedef DF DiscreteFunctionType;
47 typedef Op OperatorType;
48 typedef OperatorType PreconditionerType;
49 typedef PetscDiscreteFunction< SpaceType > SolverDiscreteFunctionType;
50 typedef PetscLinearOperator< DF, DF > AssembledOperatorType;
51 typedef PetscInverseOperator< DF, Op > InverseOperatorType;
52 typedef PetscSolverParameter SolverParameterType;
53 };
54
55
57 template< class DF, class Op >
58 class PetscInverseOperator
59 : public InverseOperatorInterface< PetscInverseOperatorTraits< DF, Op > >,
60 public PetscInverseOperatorAvailable
61 {
62 protected:
63 // monitor function for PETSc solvers
64 static PetscErrorCode
65 monitor (KSP ksp, PetscInt it, PetscReal rnorm, void *mctx)
66 {
67 if( Parameter :: verbose ( Parameter::solverStatistics ) )
68 {
69 std::cout << "PETSc::KSP: it = "
70 << std::setw(3) << std::left << it
71 << " res = " << rnorm << std::endl;
72 }
73 return PetscErrorCode(0);
74 }
75
76 // destroy solver context
77 struct KSPDeleter
78 {
79 void operator() ( KSP* p ) const
80 {
81 if( !p )
82 return;
83
84 ::Dune::Petsc::KSPDestroy( p );
85 delete p;
86 }
87 };
88
89 typedef PetscInverseOperatorTraits< DF, Op > Traits;
90 typedef InverseOperatorInterface< Traits > BaseType;
91 friend class InverseOperatorInterface< Traits >;
92
93 using PetscInverseOperatorAvailable::PetscSolver;
94
95 public:
96 using PetscInverseOperatorAvailable::supportedSolverMethods;
97 using PetscInverseOperatorAvailable::supportedPreconditionMethods;
98 using PetscInverseOperatorAvailable::extraPreconditionMethods;
99
103 static const bool preconditioningAvailable = false;
104
105 typedef typename BaseType :: SolverDiscreteFunctionType PetscDiscreteFunctionType;
106 typedef typename BaseType :: SolverDiscreteFunctionSpaceType SolverDiscreteFunctionSpaceType;
107 typedef typename BaseType :: OperatorType OperatorType;
108 typedef typename BaseType :: PreconditionerType PreconditionerType;
109
110 PetscInverseOperator ( const PetscSolverParameter &parameter = PetscSolverParameter(Parameter::container()) )
111 : BaseType( parameter )
112 {}
113
114 PetscInverseOperator ( const OperatorType &op, const PetscSolverParameter &parameter = PetscSolverParameter(Parameter::container()) )
115 : BaseType( parameter )
116 {
117 bind( op );
118 }
119
120 void bind ( const OperatorType &op )
121 {
122 BaseType :: bind( op );
123 initialize( *parameter_ );
124 }
125
126 void bind ( const OperatorType &op, const PreconditionerType& p )
127 {
128 DUNE_THROW(NotImplemented,"PetscInverseOperator::bind: preconditioners cannot be set from outside!");
129 }
130
131 void unbind ()
132 {
133 BaseType :: unbind();
134 ksp_.reset();
135 }
136
137 void printTexInfo(std::ostream& out) const
138 {
139 out << "Solver: " << solverName_ << " eps = " << parameter_->tolerance() ;
140 out << "\\\\ \n";
141 }
142
143 protected:
144 template <class Reader>
145 bool parseAndSetOptions(const Reader& reader, const std::string& optionsKey) const
146 {
147 if( reader.exists(optionsKey) )
148 {
149 std::string opts = reader.template getValue< std::string > (optionsKey);
150
152
153 std::string key;
155 std::string nextKey;
156 bool readKey = true;
157
158 while (! options.eof() )
159 {
160 if( readKey )
161 options >> key;
162 else
163 {
164 key = nextKey;
165 readKey = true;
166 }
167
168 if( key.length() == 0 )
169 break;
170
171 options >> value;
172 // if a key was instead simply store for next iteration
173 if ( value.length() > 0 && value[0] == '-')
174 {
175 // store key for next iteration
176 nextKey = value;
177 value = ""; // empty value
178 readKey = false;
179 }
180
181 // add key,value to global options data base
182 ::Dune::Petsc::PetscOptionsSetValue( key, value);
183 }
184 return true;
185 }
186 else
187 {
188 std::cout << "WARNING: 'kspoptions' selected but no options delivered with '" << optionsKey << "'!" << std::endl;
189 return false;
190 }
191 }
192
193
194 void initialize ( const PetscSolverParameter& parameter )
195 {
196 if( !assembledOperator_ )
197 DUNE_THROW(NotImplemented,"Petsc solver with matrix free implementations not yet supported!");
198
199 // Create linear solver context
200 ksp_.reset( new KSP() );
201 const auto& comm = assembledOperator_->domainSpace().gridPart().comm();
202 const int backend = assembledOperator_->backend();
203
204 ::Dune::Petsc::KSPCreate( comm, &ksp() );
205
206 // attach Matrix to linear solver context
207 Mat& A = assembledOperator_->exportMatrix();
208#if PETSC_VERSION_MAJOR <= 3 && PETSC_VERSION_MINOR < 5
209 ::Dune::Petsc::KSPSetOperators( ksp(), A, A, SAME_PRECONDITIONER);
210#else
211 ::Dune::Petsc::KSPSetOperators( ksp(), A, A );
212#endif
213
214 // allow for non-zero initial guess
215 ::Dune::Petsc::KSPSetInitialGuessNonzero( ksp(), PETSC_TRUE );
216
217 // set prescribed tolerances
218 PetscInt maxits = parameter_->maxIterations();
219 PetscReal tolerance = parameter_->tolerance();
220 PetscReal omega = parameter_->relaxation();
221 if (parameter_->errorMeasure() == 0)
222 ::Dune::Petsc::KSPSetTolerances(ksp(), 1e-50, tolerance, PETSC_DEFAULT, maxits);
223 else
224 ::Dune::Petsc::KSPSetTolerances(ksp(), tolerance, 1e-50, PETSC_DEFAULT, maxits);
225
226 // if special petsc solver parameter exists use that one, otherwise
227 // use solverMethod from SolverParameter
228 const auto& reader = parameter.parameter();
229 PetscSolver kspType = PetscSolver::gmres;
230 if( reader.exists("petsc.kspsolver.method") )
231 {
232 // see PETSc docu for more types
233 const std::string kspNames[] = { "default", "cg", "bicgstab", "gmres", "minres", "gradient", "loop", "superlu", "bicg", "preonly" };
234 kspType = static_cast< PetscSolver >( reader.getEnum("petsc.kspsolver.method", kspNames, int(PetscSolver::gmres) ) );
235 std::cout << "WARNING: using deprecated parameter 'petsc.kpsolver.method' use "
236 << parameter.keyPrefix() << "method instead\n";
237 }
238 else
239 kspType = static_cast< PetscSolver >(
240 parameter.solverMethod (
241 supportedSolverMethods(), { "kspoptions" } )
242 );
243
244 if (kspType > PetscSolver::kspoptions)
245 solverName_ = SolverParameter::solverMethodTable( static_cast< int >( kspType ) );
246 else
247 solverName_ = "kspoptions";
248
249 // select linear solver
250 switch( kspType )
251 {
252 case PetscSolver::cg:
253 ::Dune::Petsc::KSPSetType( ksp(), KSPCG );
254 break;
255 case PetscSolver::bicgstab:
256 ::Dune::Petsc::KSPSetType( ksp(), KSPBCGS );
257 break;
258 case PetscSolver::gmres:
259 {
260 ::Dune::Petsc::KSPSetType( ksp(), KSPGMRES );
261 PetscInt restart = 10;
262 if( reader.exists("petsc.gmresrestart") )
263 {
264 restart = reader.getValue<int>("petsc.gmresrestart", restart );
265 std::cout << "WARNING: using deprecated parameter 'petsc.gmresrestart' use "
266 << parameter.keyPrefix() << "gmres.restart instead\n";
267 }
268 else
269 restart = parameter.gmresRestart() ;
270
271 ::Dune::Petsc::KSPGMRESSetRestart( ksp(), restart );
272 break;
273 }
274 case PetscSolver::minres:
275 ::Dune::Petsc::KSPSetType( ksp(), KSPMINRES );
276 break;
277 case PetscSolver::bicg:
278 ::Dune::Petsc::KSPSetType( ksp(), KSPBICG );
279 break;
280 case PetscSolver::preonly:
281 ::Dune::Petsc::KSPSetType( ksp(), KSPPREONLY );
282 break;
283 case PetscSolver::kspoptions:
284 {
285 const std::string key = parameter.keyPrefix() + "kspoptions";
286 const bool foundOptions = parseAndSetOptions( reader, key );
287
288 // setup solver context from database/cmdline options
289 ::Dune::Petsc::KSPSetFromOptions( ksp() );
290 ::Dune::Petsc::KSPSetUp( ksp() );
291 if( foundOptions )
292 {
293 // clear global options data base
294 ::Dune::Petsc::PetscOptionsClear();
295 }
296
297 break;
298 }
299 default:
300 DUNE_THROW(InvalidStateException,"PetscInverseOperator: invalid solver choosen." );
301 }
302 if ( parameter_->knollTrick() )
303 {
304 ::Dune::Petsc::KSPSetInitialGuessKnoll( ksp(), PETSC_TRUE );
305 }
306
308 // preconditioning
310
311 int pcType = SolverParameter::none;
312 if( reader.exists("petsc.preconditioning.method") )
313 {
314 const std::string pcNames[] = { "default", "none", "asm", "sor", "jacobi", "ilu", "icc", "superlu", "hypre", "ml", "lu" };
315 pcType = reader.getEnum("petsc.preconditioning.method", pcNames, 0 );
316 std::cout << "WARNING: using deprecated parameter 'petsc.preconditioning.method' use "
317 << parameter.keyPrefix() << ".preconditioning.method instead\n";
318 if (pcType >= 8)
319 pcType = 7-pcType; // hypre=-1, ml=-2, lu=-3
320 }
321 else
322 {
323 pcType = parameter.preconditionMethod(
324 supportedPreconditionMethods(),
325 extraPreconditionMethods() );
326 }
327
328 // setup preconditioning context
329 PC pc;
330 ::Dune::Petsc::KSPGetPC( ksp(), &pc );
331
332 switch( pcType )
333 {
334 case 0:
335 // don't setup the pc context twice
336 if ( kspType != PetscSolver::kspoptions )
337 {
338 const std::string key = parameter.keyPrefix() + "kspoptions";
339 const bool foundOptions = parseAndSetOptions( reader, key );
340
341 // setup pc context from database/cmdline options
342 ::Dune::Petsc::PCSetFromOptions( pc );
343 ::Dune::Petsc::PCSetUp( pc );
344 if( foundOptions )
345 {
346 // clear global options data base
347 ::Dune::Petsc::PetscOptionsClear();
348 }
349 }
350 break;
351 case SolverParameter::none:
352 ::Dune::Petsc::PCSetType( pc, PCNONE );
353 break;
354 case SolverParameter::oas:
355 {
356 ::Dune::Petsc::PCSetType( pc, PCASM );
357 ::Dune::Petsc::PCSetUp( pc );
358 break;
359 }
360 case SolverParameter::gauss_seidel:
361 ::Dune::Petsc::PCSetType( pc, PCSOR );
362 ::Dune::Petsc::PCSORSetOmega( pc, 1.0 );
363 break;
364 case SolverParameter::sor:
365 ::Dune::Petsc::PCSetType( pc, PCSOR );
366 if( (backend == Dune::Petsc::Backend::block) and (std::abs( omega - 1.0 ) > 1e-14) )
367 {
368 DUNE_THROW(InvalidStateException,"PETSc::SOR with backend `block` can only handle relaxation=1.0!");
369 }
370 // this fails with a PETSc Error if omega is not 1.0 for block matrices
371 // src/mat/impls/baij/seq/baij.c:232
372 ::Dune::Petsc::PCSORSetOmega( pc, omega );
373 break;
374 case SolverParameter::ssor:
375 ::Dune::Petsc::PCSetType( pc, PCSOR );
376 // set symmetric version
377 ::Dune::Petsc::PCSORSetSymmetric( pc, SOR_LOCAL_SYMMETRIC_SWEEP );
378 if( (backend == Dune::Petsc::Backend::block) and (std::abs( omega - 1.0 ) > 1e-14) )
379 {
380 DUNE_THROW(InvalidStateException,"PETSc::SOR with backend `block` can only handle relaxation=1.0!");
381 }
382 // this fails with a PETSc Error if omega is not 1.0 for block matrices
383 // src/mat/impls/baij/seq/baij.c:232
384 ::Dune::Petsc::PCSORSetOmega( pc, omega );
385 break;
386 case SolverParameter::jacobi:
387 ::Dune::Petsc::PCSetType( pc, PCJACOBI );
388 break;
389 case -1: // PetscPrec::hypre:
390 {
391#ifdef PETSC_HAVE_HYPRE
392 // set with parameter ...petsc.preconditioning.hypre.method
393 int hypreType = parameter.hypreMethod();
394 std::string hypre;
395 if ( hypreType == PetscSolverParameter::boomeramg )
396 hypre = "boomeramg";
397 else if ( hypreType == PetscSolverParameter::parasails )
398 hypre = "parasails";
399 else if ( hypreType == PetscSolverParameter::pilut )
400 hypre = "pilut";
401 else
402 DUNE_THROW( InvalidStateException, "PetscInverseOperator: invalid hypre preconditioner choosen." );
403
404 ::Dune::Petsc::PCSetType( pc, PCHYPRE );
405 ::Dune::Petsc::PCHYPRESetType( pc, hypre.c_str() );
406 ::Dune::Petsc::PCSetUp( pc );
407#else // PETSC_HAVE_HYPRE
408 DUNE_THROW( InvalidStateException, "PetscInverseOperator: petsc not build with hypre support." );
409#endif // PETSC_HAVE_HYPRE
410 break;
411 }
412 case -2: // PetscPrec::ml:
413#ifdef PETSC_HAVE_ML
414 ::Dune::Petsc::PCSetType( pc, PCML );
415#else // PETSC_HAVE_ML
416 DUNE_THROW( InvalidStateException, "PetscInverseOperator: petsc not build with ml support." );
417#endif // PETSC_HAVE_ML
418 break;
419 case SolverParameter::ilu:
420 {
421 if ( MPIManager::size() > 1 )
422 DUNE_THROW( InvalidStateException, "PetscInverseOperator: ilu preconditioner does not work in parallel." );
423
424 // get fill-in level
425 PetscInt pcLevel;
426 if( reader.exists("petsc.preconditioning.levels") )
427 {
428 pcLevel = reader.getValue<int>("petsc.preconditioning.levels", 0 );
429 std::cout << "WARNING: using deprecated parameter 'petsc.preconditioning.levels' use "
430 << parameter.keyPrefix() << "preconditioning.level instead\n";
431 }
432 else
433 pcLevel = parameter.preconditionerLevel() ;
434
435 ::Dune::Petsc::PCSetType( pc, PCILU );
436 ::Dune::Petsc::PCFactorSetLevels( pc, pcLevel );
437 break;
438 }
439 ::Dune::Petsc::PCSetType( pc, PCML );
440 break;
441 case SolverParameter::icc:
442 {
443#ifdef PETSC_HAVE_ICC
444 if ( MPIManager::size() > 1 )
445 DUNE_THROW( InvalidStateException, "PetscInverseOperator: icc preconditioner does not worl in parallel." );
446
447 // get fill-in level
448 PetscInt pcLevel;
449 if( reader.exists("petsc.preconditioning.levels") )
450 {
451 pcLevel = reader.getValue<int>("petsc.preconditioning.levels", 0 );
452 std::cout << "WARNING: using deprecated parameter 'petsc.preconditioning.levels' use "
453 << parameter.keyPrefix() << "preconditioning.level instead\n";
454 }
455 else
456 pcLevel = parameter.preconditionerLevel() ;
457
458
459 ::Dune::Petsc::PCSetType( pc, PCICC );
460 ::Dune::Petsc::PCFactorSetLevels( pc, pcLevel );
461#else // PETSC_HAVE_ICC
462 DUNE_THROW( InvalidStateException, "PetscInverseOperator: petsc not build with icc support." );
463#endif // PETSC_HAVE_ICC
464 break;
465 }
466 case -3: // PetscPrec::lu:
467 case SolverParameter::superlu:
468 {
469 enum class Factorization { petsc = 0, superlu = 1, mumps = 2 };
470 Factorization factorType = Factorization::superlu;
471 if (pcType != SolverParameter::superlu)
472 factorType = static_cast<Factorization>(parameter.superluMethod());
473
474 ::Dune::Petsc::PCSetType( pc, PCLU );
475
476 if ( factorType == Factorization::petsc )
477 ::Dune::Petsc::PCFactorSetMatSolverPackage( pc, MATSOLVERPETSC );
478 else if ( factorType == Factorization::superlu )
479 ::Dune::Petsc::PCFactorSetMatSolverPackage( pc, MATSOLVERSUPERLU_DIST );
480 else if ( factorType == Factorization::mumps )
481 ::Dune::Petsc::PCFactorSetMatSolverPackage( pc, MATSOLVERMUMPS );
482 else
483 DUNE_THROW( InvalidStateException, "PetscInverseOperator: invalid factorization package chosen." );
484
485 ::Dune::Petsc::PCSetUp( pc );
486 break;
487 }
488 case -4: // PetscPrec::pcgamg:
489 // requires MATRIX_AIJ, i.e. not blocking of entries
490 if( assembledOperator_->backend() == Dune::Petsc::Backend::block )
491 {
492 DUNE_THROW(NotImplemented,"PetscInverseOperator: 'pcgamg' requires 'aij' matrix. Set 'petsc.backend' to 'scalar'!");
493 }
494 ::Dune::Petsc::PCSetType( pc, PCGAMG );
495 break;
496
497 default:
498 DUNE_THROW( InvalidStateException, "PetscInverseOperator: invalid preconditioner chosen." );
499 }
500
501 // set monitor in verbose mode for all cores
502 // (and then check Parameter::verbose locally inside monitor)
503 if( parameter.verbose() && Parameter::verbose( Parameter::solverStatistics ) )
504 {
505 // only print information about solver type and pc type in extended mode
506 if( Parameter::verbose( Parameter::extendedStatistics ) )
507 ::Dune::Petsc::KSPView( comm, ksp() );
508
509 ::Dune::Petsc::KSPMonitorSet( ksp(), &monitor, PETSC_NULLPTR, PETSC_NULLPTR);
510 }
511 }
512
513 int apply( const PetscDiscreteFunctionType& arg, PetscDiscreteFunctionType& dest ) const
514 {
515 // need to have a 'distributed' destination vector for continuous spaces
516 if( dest.space().continuous() )
517 dest.dofVector().clearGhost();
518
519 // call PETSc solvers
520 ::Dune::Petsc::KSPSolve( *ksp_, *arg.petscVec() , *dest.petscVec() );
521
522 // a continuous solution is 'distributed' so need a communication here
523 if( dest.space().continuous() )
524 {
525 dest.communicate();
526 }
527
528 // get number of iterations
529 PetscInt its ;
530 ::Dune::Petsc::KSPGetIterationNumber( *ksp_, &its );
531 KSPConvergedReason reason;
532 ::Dune::Petsc::KSPGetConvergedReason( *ksp_, &reason );
533
534 bool converged = int(reason) >= 0 ;
535
536 if( parameter_->verbose() && Parameter::verbose( 1 ) )
537 {
538 // list of reasons:
539 // https://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/KSP/KSPConvergedReason.html
540 if( converged )
541 std::cout << "Converged reason: ";
542 else
543 std::cout << "**Diverged** reason: ";
544 std::cout << reason << " linear iterations: " << its << std::endl;
545 }
546
547 return (converged) ? its : -its;
548 }
549
550 protected:
552 void allocateMemory( const SolverDiscreteFunctionSpaceType& uSpace,
553 const SolverDiscreteFunctionSpaceType& wSpace ) const
554 {
555 typedef PetscDiscreteFunctionType SolverDiscreteFunctionType;
556 if( ! this->rhs_ )
557 {
558 // create temporary df with backend of assembled operator
559 this->rhs_.reset( new SolverDiscreteFunctionType( "InvOp::rhs", uSpace, assembledOperator_->backend() ) );
560 }
561
562 if( ! this->x_ )
563 {
564 // create temporary df with backend of assembled operator
565 this->x_.reset( new SolverDiscreteFunctionType( "InvOp::x", wSpace, assembledOperator_->backend() ) );
566 }
567 }
568
569 KSP & ksp () { assert( ksp_ ); return *ksp_; }
570
571 using BaseType :: assembledOperator_;
572 using BaseType :: parameter_;
573 using BaseType :: iterations_;
574
575 std::unique_ptr< KSP, KSPDeleter > ksp_; // PETSc Krylov Space solver context
576
577 std::string solverName_;
578 };
579
581
582 } // namespace Fem
583
584} // namespace Dune
585
586#endif // #if HAVE_PETSC
587
588#endif // #ifndef DUNE_FEM_PETSCINVERSEOPERATORS_HH
Dune::ParameterTree options
static Type apply(T &t)
virtual void operator()()=0
#define DUNE_THROW(E,...)
const Communication & comm() const
Dune::Fem::Double abs(const Dune::Fem::Double &a)
Definition double.hh:942
T bind(T... args)
T c_str(T... args)
T endl(T... args)
T left(T... args)
T setw(T... args)