version GIT relicensing-7278-g091132d5eb 2026-12-02 03:10:01+00:00
\(\newcommand{\dealvcentcolon}{\mathrel{\mathop{:}}}\) \(\newcommand{\dealcoloneq}{\dealvcentcolon\mathrel{\mkern-1.2mu}=}\) \(\newcommand{\jump}[1]{\left[\!\left[ #1 \right]\!\right]}\) \(\newcommand{\average}[1]{\left\{\!\left\{ #1 \right\}\!\right\}}\)
Loading...
Searching...
No Matches
petsc_solver.cc
Go to the documentation of this file.
1// -----------------------------------------------------------------------------
2//
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception OR LGPL-2.1-or-later
4// Copyright (C) 2004 - 2026 by the deal.II authors
5//
6// This file is part of the deal.II library.
7//
8// Detailed license information governing the source code and contributions
9// can be found in LICENSE.md and CONTRIBUTING.md at the top level directory.
10//
11// -----------------------------------------------------------------------------
12
13
15
17
18#ifdef DEAL_II_WITH_PETSC
19
25
26// Shorthand notation for PETSc error codes.
27# define AssertPETSc(code) \
28 do \
29 { \
30 PetscErrorCode ierr = (code); \
31 AssertThrow(ierr == 0, ExcPETScError(ierr)); \
32 } \
33 while (false)
34
35
36#endif // DEAL_II_WITH_PETSC
37
39
40#ifdef DEAL_II_WITH_PETSC
41
42namespace PETScWrappers
43{
45 : ksp(nullptr)
46 , solver_control(nullptr)
47 {}
48
49
51 : ksp(nullptr)
52 , solver_control(&cn)
53 {}
54
55
56
57 void
59 {}
60
61
62
64 {
65 AssertPETSc(KSPDestroy(&ksp));
66 }
67
68
69
70 KSP
72 {
73 return ksp;
74 }
75
76
77
78 SolverBase::
79 operator KSP() const
80 {
81 return ksp;
82 }
83
84
85
86 void
88 VectorBase &x,
89 const VectorBase &b,
90 const PreconditionBase &preconditioner)
91 {
92 // first create a solver object if this
93 // is necessary
94 if (ksp == nullptr)
95 {
96 initialize_ksp_with_comm(A.get_mpi_communicator());
97
98 // let derived classes set the solver
99 // type, and the preconditioning
100 // object set the type of
101 // preconditioner
103
104 AssertPETSc(KSPSetPC(ksp, preconditioner.get_pc()));
105
106 /*
107 * by default we set up the preconditioner only once.
108 * this can be overridden by command line.
109 */
110 AssertPETSc(KSPSetReusePreconditioner(ksp, PETSC_TRUE));
111 }
112
113 // setting the preconditioner overwrites the used matrices.
114 // hence, we need to set the matrices after the preconditioner.
115 Mat B;
116 AssertPETSc(KSPGetOperators(ksp, nullptr, &B));
117 AssertPETSc(KSPSetOperators(ksp, A, B));
118
119 // set the command line option prefix name
120 AssertPETSc(KSPSetOptionsPrefix(ksp, prefix_name.c_str()));
121
122 // set the command line options provided
123 // by the user to override the defaults
124 AssertPETSc(KSPSetFromOptions(ksp));
125
126 // then do the real work: set up solver
127 // internal data and solve the
128 // system.
129 AssertPETSc(KSPSetUp(ksp));
130
131 AssertPETSc(KSPSolve(ksp, b, x));
132
133 // in case of failure: throw
134 // exception
135 if (solver_control &&
136 solver_control->last_check() != SolverControl::success)
137 AssertThrow(false,
139 solver_control->last_value()));
140 // otherwise exit as normal
141 }
142
143
144 void
145 SolverBase::set_prefix(const std::string &prefix)
147 prefix_name = prefix;
148 }
149
150
151 void
153 {
154 AssertPETSc(KSPDestroy(&ksp));
155 }
156
157
160 {
164 "You need to create the solver with a SolverControl object if you want to call the function that returns it."));
165 return *solver_control;
166 }
167
168
169 PetscErrorCode
171 const PetscInt iteration,
172 const PetscReal residual_norm,
173 KSPConvergedReason *reason,
174 void *solver_control_x)
175 {
176 PetscFunctionBeginUser;
178 *reinterpret_cast<SolverControl *>(solver_control_x);
179
180 const SolverControl::State state =
181 solver_control.check(iteration, residual_norm);
182
183 switch (state)
184 {
185 case ::SolverControl::iterate:
186 *reason = KSP_CONVERGED_ITERATING;
187 break;
188
189 case ::SolverControl::success:
190 *reason = KSP_CONVERGED_RTOL;
191 break;
192
193 case ::SolverControl::failure:
194 if (solver_control.last_step() > solver_control.max_steps())
195 *reason = KSP_DIVERGED_ITS;
196 else
197 *reason = KSP_DIVERGED_DTOL;
198 break;
199
200 default:
202 }
203
204 PetscFunctionReturn(PETSC_SUCCESS);
205 }
206
207
208
209 void
211 {
212 // Create the PETSc KSP object
213 AssertPETSc(KSPCreate(comm, &ksp));
214
215 // then a convergence monitor
216 // function that simply
217 // checks with the solver_control
218 // object we have in this object for
219 // convergence
221 }
222
223
224
225 void
227 {
228 if (ksp && solver_control)
230 KSPSetConvergenceTest(ksp, &convergence_test, solver_control, nullptr));
231 }
232
233
234 void
236 {
238
239 // let derived classes set the solver
240 // type, and the preconditioning
241 // object set the type of
242 // preconditioner
244
245 // set the command line options provided
246 // by the user to override the defaults
247 AssertPETSc(KSPSetFromOptions(ksp));
248 }
249
250
251
252 /* ---------------------- SolverRichardson ------------------------ */
253
255 : omega(omega)
256 {}
257
258
259
265
266
267
268 void
270 {
271 AssertPETSc(KSPSetType(ksp, KSPRICHARDSON));
272
273 // set the damping factor from the data
274 AssertPETSc(KSPRichardsonSetScale(ksp, additional_data.omega));
275
276 // in the deal.II solvers, we always
277 // honor the initial guess in the
278 // solution vector. do so here as well:
279 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
280
281 // Hand over the absolute
282 // tolerance and the maximum
283 // iteration number to the PETSc
284 // convergence criterion. The
285 // custom deal.II SolverControl
286 // object is ignored by the PETSc
287 // Richardson method (when no
288 // PETSc monitoring is present),
289 // since in this case PETSc
290 // uses a faster version of
291 // the Richardson iteration,
292 // where no residual is
293 // available.
294 AssertPETSc(KSPSetTolerances(ksp,
295 PETSC_DEFAULT,
296 this->solver_control->tolerance(),
297 PETSC_DEFAULT,
298 this->solver_control->max_steps() + 1));
299 }
300
301
302 /* ---------------------- SolverChebychev ------------------------ */
303
305 const AdditionalData &data)
306 : SolverBase(cn)
307 , additional_data(data)
308 {}
309
310
311 void
313 {
314 AssertPETSc(KSPSetType(ksp, KSPCHEBYSHEV));
315
316 // in the deal.II solvers, we always
317 // honor the initial guess in the
318 // solution vector. do so here as well:
319 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
320 }
321
322
323 /* ---------------------- SolverCG ------------------------ */
324
326 : SolverBase(cn)
327 , additional_data(data)
328 {}
329
330
331 void
333 {
334 AssertPETSc(KSPSetType(ksp, KSPCG));
335
336 // in the deal.II solvers, we always
337 // honor the initial guess in the
338 // solution vector. do so here as well:
339 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
340
341 // Use the unpreconditioned residual norm for the convergence check, to
342 // match the behavior of deal.II's own SolverCG. Users can still override
343 // this via the -ksp_norm_type command-line option.
344 AssertPETSc(KSPSetNormType(ksp, KSP_NORM_UNPRECONDITIONED));
345 }
346
347
348 /* ---------------------- SolverBiCG ------------------------ */
349
351 : SolverBase(cn)
352 , additional_data(data)
353 {}
354
355
356
357 void
359 {
360 AssertPETSc(KSPSetType(ksp, KSPBICG));
361
362 // in the deal.II solvers, we always
363 // honor the initial guess in the
364 // solution vector. do so here as well:
365 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
366 }
367
368
369 /* ---------------------- SolverGMRES ------------------------ */
370
372 const unsigned int restart_parameter,
373 const bool right_preconditioning)
374 : restart_parameter(restart_parameter)
375 , right_preconditioning(right_preconditioning)
376 {}
377
378
379
384
385
386
387 void
389 {
390 AssertPETSc(KSPSetType(ksp, KSPGMRES));
391
392 AssertPETSc(KSPGMRESSetRestart(ksp, additional_data.restart_parameter));
393
394 // Set preconditioning side to right
396 {
397 AssertPETSc(KSPSetPCSide(ksp, PC_RIGHT));
398 }
399
400 // in the deal.II solvers, we always
401 // honor the initial guess in the
402 // solution vector. do so here as well:
403 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
404 }
405
406
407 /* ---------------------- SolverBicgstab ------------------------ */
408
410 : SolverBase(cn)
411 , additional_data(data)
412 {}
413
414
415 void
417 {
418 AssertPETSc(KSPSetType(ksp, KSPBCGS));
419
420 // in the deal.II solvers, we always
421 // honor the initial guess in the
422 // solution vector. do so here as well:
423 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
424 }
425
426
427 /* ---------------------- SolverCGS ------------------------ */
428
430 : SolverBase(cn)
431 , additional_data(data)
432 {}
433
434
435 void
437 {
438 AssertPETSc(KSPSetType(ksp, KSPCGS));
439
440 // in the deal.II solvers, we always
441 // honor the initial guess in the
442 // solution vector. do so here as well:
443 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
444 }
445
446
447 /* ---------------------- SolverTFQMR ------------------------ */
448
450 : SolverBase(cn)
451 , additional_data(data)
452 {}
453
454
455 void
457 {
458 AssertPETSc(KSPSetType(ksp, KSPTFQMR));
459
460 // in the deal.II solvers, we always
461 // honor the initial guess in the
462 // solution vector. do so here as well:
463 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
464 }
465
466
467 /* ---------------------- SolverTCQMR ------------------------ */
468
470 : SolverBase(cn)
471 , additional_data(data)
472 {}
473
474
475 void
477 {
478 AssertPETSc(KSPSetType(ksp, KSPTCQMR));
479
480 // in the deal.II solvers, we always
481 // honor the initial guess in the
482 // solution vector. do so here as well:
483 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
484 }
485
486
487 /* ---------------------- SolverCR ------------------------ */
488
490 : SolverBase(cn)
491 , additional_data(data)
492 {}
493
494
495 void
497 {
498 AssertPETSc(KSPSetType(ksp, KSPCR));
499
500 // in the deal.II solvers, we always
501 // honor the initial guess in the
502 // solution vector. do so here as well:
503 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
504 }
505
506
507 /* ---------------------- SolverLSQR ------------------------ */
508
510 : SolverBase(cn)
511 , additional_data(data)
512 {}
513
514
515
516 void
518 {
519 AssertPETSc(KSPSetType(ksp, KSPLSQR));
520
521 // in the deal.II solvers, we always
522 // honor the initial guess in the
523 // solution vector. do so here as well:
524 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
525
526 // The KSPLSQR implementation overwrites the user-defined
527 // convergence test at creation (i.e. KSPSetType) time.
528 // This is probably a bad design decision in PETSc.
529 // Anyway, here we make sure we use our own convergence
530 // test.
532 }
533
534
535 /* ---------------------- SolverPreOnly ------------------------ */
536
538 : SolverBase(cn)
539 , additional_data(data)
540 {}
541
542
543
544 void
546 {
547 AssertPETSc(KSPSetType(ksp, KSPPREONLY));
548
549 // The KSPPREONLY solver of
550 // PETSc never calls the convergence
551 // monitor, which leads to failure
552 // even when everything was ok.
553 // Therefore the SolverControl status
554 // is set to some nice values, which
555 // guarantee a nice result at the end
556 // of the solution process.
557 solver_control->check(1, 0.0);
558
559 // Using the PREONLY solver with
560 // a nonzero initial guess leads
561 // PETSc to produce some error messages.
562 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_FALSE));
563 }
564
565
566 /* ---------------------- SparseDirectMUMPS------------------------ */
567
569 const AdditionalData &data)
570 : SolverBase(cn)
571 , additional_data(data)
572 , symmetric_mode(false)
573 {}
574
575
576
577 void
579 {
580 /*
581 * KSPPREONLY implements a stub method that applies only the
582 * preconditioner. Its use is due to SparseDirectMUMPS being a direct
583 * (rather than iterative) solver
584 */
585 AssertPETSc(KSPSetType(ksp, KSPPREONLY));
586
587 /*
588 * The KSPPREONLY solver of PETSc never calls the convergence monitor,
589 * which leads to failure even when everything was ok. Therefore, the
590 * SolverControl status is set to some nice values, which guarantee a
591 * nice result at the end of the solution process.
592 */
593 solver_control->check(1, 0.0);
594
595 /*
596 * Using a PREONLY solver with a nonzero initial guess leads PETSc to
597 * produce some error messages.
598 */
599 AssertPETSc(KSPSetInitialGuessNonzero(ksp, PETSC_FALSE));
600 }
601
602 void
604 VectorBase &x,
605 const VectorBase &b)
606 {
607 initialize(A);
608 solve(x, b);
609 }
610
611
612
613 void
615 {
616# ifdef DEAL_II_PETSC_WITH_MUMPS
617 // Start afresh so a previous factorization cannot be reused for A.
618 reset();
619 initialize_ksp_with_comm(A.get_mpi_communicator());
620
621 /*
622 * setting the solver type
623 */
625
626 // Associate the matrix before configuring its factorization.
627 AssertPETSc(KSPSetOperators(ksp, A, A));
628
629 /*
630 * getting the associated preconditioner context
631 */
632 PC pc;
633 AssertPETSc(KSPGetPC(ksp, &pc));
634
635 /*
636 * build PETSc PC for particular PCLU or PCCHOLESKY preconditioner
637 * depending on whether the symmetric mode has been set
638 */
639 if (symmetric_mode)
640 AssertPETSc(PCSetType(pc, PCCHOLESKY));
641 else
642 AssertPETSc(PCSetType(pc, PCLU));
643
644 // Select MUMPS for the LU or Cholesky factorization.
645# if DEAL_II_PETSC_VERSION_LT(3, 9, 0)
646 AssertPETSc(PCFactorSetMatSolverPackage(pc, MATSOLVERMUMPS));
647# else
648 AssertPETSc(PCFactorSetMatSolverType(pc, MATSOLVERMUMPS));
649# endif
650
651 /*
652 * set up the package to call for the factorization
653 */
654# if DEAL_II_PETSC_VERSION_LT(3, 9, 0)
655 AssertPETSc(PCFactorSetUpMatSolverPackage(pc));
656# else
657 AssertPETSc(PCFactorSetUpMatSolverType(pc));
658# endif
659
660 /*
661 * get the factored matrix F from the preconditioner context.
662 */
663 Mat F;
664 AssertPETSc(PCFactorGetMatrix(pc, &F));
665
666 /*
667 * pass control parameters to MUMPS.
668 * Setting entry 7 of MUMPS ICNTL array to a value
669 * of 2. This sets use of Approximate Minimum Fill (AMF)
670 */
671 AssertPETSc(MatMumpsSetIcntl(F, 7, 2));
672
673 // The two-vector solve() overload reuses this factorization.
674 AssertPETSc(KSPSetReusePreconditioner(ksp, PETSC_TRUE));
675
676 /*
677 * set the command line option prefix name
678 */
679 AssertPETSc(KSPSetOptionsPrefix(ksp, prefix_name.c_str()));
680
681 /*
682 * set the command line options provided by the user to override
683 * the defaults
684 */
685 AssertPETSc(KSPSetFromOptions(ksp));
686
687 AssertPETSc(KSPSetUp(ksp));
688
689# else // DEAL_II_PETSC_WITH_MUMPS
690 Assert(
691 false,
693 "Your PETSc installation does not include a copy of "
694 "the MUMPS package necessary for this solver. You will need to configure "
695 "PETSc so that it includes MUMPS, recompile it, and then re-configure "
696 "and recompile deal.II as well."));
697 (void)A;
698# endif
699 }
700
701
702
703 void
705 {
706# ifdef DEAL_II_PETSC_WITH_MUMPS
707 Assert(ksp != nullptr, ExcNotInitialized());
708 AssertPETSc(KSPSolve(ksp, b, x));
709
710 /*
711 * in case of failure throw exception
712 */
713 if (solver_control &&
714 solver_control->last_check() != SolverControl::success)
715 {
716 AssertThrow(false,
718 solver_control->last_value()));
719 }
720# else
721 Assert(false, ExcMessage("This solver requires PETSc with MUMPS support."));
722 (void)x;
723 (void)b;
724# endif
725 }
726
727
728
729 void
730 SparseDirectMUMPS::set_symmetric_mode(const bool matrix_is_symmetric)
731 {
732 symmetric_mode = matrix_is_symmetric;
733 }
734
735} // namespace PETScWrappers
736
737
738#endif // DEAL_II_WITH_PETSC
SolverControl & control() const
ObserverPointer< SolverControl, SolverBase > solver_control
void initialize(const PreconditionBase &preconditioner)
void perhaps_set_convergence_test() const
static PetscErrorCode convergence_test(KSP ksp, const PetscInt iteration, const PetscReal residual_norm, KSPConvergedReason *reason, void *solver_control)
void set_prefix(const std::string &prefix)
void initialize_ksp_with_comm(const MPI_Comm comm)
void solve(const MatrixBase &A, VectorBase &x, const VectorBase &b, const PreconditionBase &preconditioner)
virtual void set_solver_type(KSP &ksp) const
SolverBiCG(SolverControl &cn, const AdditionalData &data=AdditionalData())
virtual void set_solver_type(KSP &ksp) const override
virtual void set_solver_type(KSP &ksp) const override
SolverBicgstab(SolverControl &cn, const AdditionalData &data=AdditionalData())
virtual void set_solver_type(KSP &ksp) const override
SolverCGS(SolverControl &cn, const AdditionalData &data=AdditionalData())
SolverCG(SolverControl &cn, const AdditionalData &data=AdditionalData())
virtual void set_solver_type(KSP &ksp) const override
virtual void set_solver_type(KSP &ksp) const override
SolverCR(SolverControl &cn, const AdditionalData &data=AdditionalData())
virtual void set_solver_type(KSP &ksp) const override
SolverChebychev(SolverControl &cn, const AdditionalData &data=AdditionalData())
const AdditionalData additional_data
virtual void set_solver_type(KSP &ksp) const override
SolverGMRES(SolverControl &cn, const AdditionalData &data=AdditionalData())
virtual void set_solver_type(KSP &ksp) const override
SolverLSQR(SolverControl &cn, const AdditionalData &data=AdditionalData())
SolverPreOnly(SolverControl &cn, const AdditionalData &data=AdditionalData())
virtual void set_solver_type(KSP &ksp) const override
virtual void set_solver_type(KSP &ksp) const override
const AdditionalData additional_data
SolverRichardson(SolverControl &cn, const AdditionalData &data=AdditionalData())
virtual void set_solver_type(KSP &ksp) const override
SolverTCQMR(SolverControl &cn, const AdditionalData &data=AdditionalData())
virtual void set_solver_type(KSP &ksp) const override
SolverTFQMR(SolverControl &cn, const AdditionalData &data=AdditionalData())
SparseDirectMUMPS(SolverControl &cn, const AdditionalData &data=AdditionalData())
virtual void set_solver_type(KSP &ksp) const override
void solve(VectorBase &x, const VectorBase &b)
void set_symmetric_mode(const bool matrix_is_symmetric)
void initialize(const MatrixBase &A)
virtual State check(const unsigned int step, const double check_value)
@ success
Stop iteration, goal reached.
#define DEAL_II_NAMESPACE_OPEN
Definition config.h:38
#define DEAL_II_NAMESPACE_CLOSE
Definition config.h:39
#define DEAL_II_NOT_IMPLEMENTED()
#define Assert(cond, exc)
static ::ExceptionBase & ExcNotInitialized()
static ::ExceptionBase & ExcMessage(std::string arg1)
#define AssertThrow(cond, exc)
std::vector< index_type > data
Definition mpi.cc:734
const MPI_Comm comm
Definition mpi.cc:912
#define AssertPETSc(code)
AdditionalData(const unsigned int restart_parameter=30, const bool right_preconditioning=false)