Debian Codegraph @

include/deal.II/lac/petsc_snes.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 2023 - 2024 by the deal.II authors
5 //
6 // This file is part of the deal.II library.
7 //
8 // Part of the source code is dual licensed under Apache-2.0 WITH
9 // LLVM-exception OR LGPL-2.1-or-later. Detailed license information
10 // governing the source code and code contributions can be found in
11 // LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II.
12 //
13 // ------------------------------------------------------------------------
14
15 #ifndef dealii_petsc_snes_h
16 #define dealii_petsc_snes_h
17
18 #include <deal.II/base/config.h>
19
20 #ifdef DEAL_II_WITH_PETSC
21 # include <deal.II/base/mpi.h>
22 # include <deal.II/base/observer_pointer.h>
23 # include <deal.II/base/parameter_handler.h>
24
25 # include <deal.II/lac/petsc_matrix_base.h>
26 # include <deal.II/lac/petsc_precondition.h>
27 # include <deal.II/lac/petsc_vector_base.h>
28
29 # include <petscsnes.h>
30
31 # include <exception>
32
33 # if defined(DEAL_II_HAVE_CXX20)
34 # include <concepts>
35 # endif
36
37
38 DEAL_II_NAMESPACE_OPEN
39
40 namespace PETScWrappers
41 {
42 /**
43 * Additional parameters that can be passed to the NonlinearSolver class.
44 */
45 class NonlinearSolverData
46 {
47 public:
48 /**
49 * Type that holds real-valued numbers.
50 *
51 * Used to represent norms.
52 */
53 using real_type = PetscReal;
54
55 /**
56 * Initialization parameters for NonlinearSolverData.
57 *
58 * Running parameters:
59 *
60 * @param options_prefix The string indicating the options prefix for command line customization.
61 * @param snes_type The string indicating the PETSc SNES solver type.
62 * @param snes_linesearch_type The string indicating the PETSc linesearch type.
63 * @param absolute_tolerance Absolute error tolerance.
64 * @param relative_tolerance Relative error tolerance.
65 * @param step_tolerance Step tolerance.
66 * @param maximum_non_linear_iterations Maximum number of iterations allowed.
67 * @param max_n_function_evaluations Maximum number of function evaluations allowed.
68 *
69 * @note All parameters values specified here can be overridden by
70 * command line choices.
71 *
72 * @ingroup PETScWrappers
73 */
74 NonlinearSolverData(
75 // Running parameters
76 const std::string &options_prefix = "",
77 const std::string &snes_type = "",
78 const std::string &snes_linesearch_type = "",
79 const real_type absolute_tolerance = 0,
80 const real_type relative_tolerance = 0,
81 const real_type step_tolerance = 0,
82 const int maximum_non_linear_iterations = -1,
83 const int max_n_function_evaluations = -1)
84 : options_prefix(options_prefix)
85 , snes_type(snes_type)
86 , snes_linesearch_type(snes_linesearch_type)
87 , absolute_tolerance(absolute_tolerance)
88 , relative_tolerance(relative_tolerance)
89 , step_tolerance(step_tolerance)
90 , maximum_non_linear_iterations(maximum_non_linear_iterations)
91 , max_n_function_evaluations(max_n_function_evaluations)
92 {}
93
94 /**
95 * Import parameter values.
96 */
97 void
98 add_parameters(ParameterHandler &prm);
99
100 /**
101 * Options database prefix.
102 */
103 std::string options_prefix;
104
105 /**
106 * PETSc nonlinear solver type. Valid options include "newtonls"
107 * (Newton with line search), "newtontr" (Newton with Trust
108 * Region), "nrichardson" (Picard), and many more. See
109 * https://petsc.org/release/manualpages/SNES/SNESType/ for more
110 * information.
111 */
112 std::string snes_type;
113
114 /**
115 * Linesearch type. Valid options include "bt" (backtracking) and
116 * "basic" (no line search). See
117 * https://petsc.org/release/manualpages/SNES/SNESLineSearchType/
118 * for more information.
119 */
120 std::string snes_linesearch_type;
121
122 /**
123 * Absolute error tolerance for function evaluation.
124 *
125 * @note Non-positive values indicate to use PETSc's default.
126 */
127 real_type absolute_tolerance;
128
129 /**
130 * Relative error tolerance for function evaluation.
131 *
132 * @note Non-positive values indicate to use PETSc's default.
133 */
134 real_type relative_tolerance;
135
136 /**
137 * Step tolerance for solution update.
138 *
139 * @note Non-positive values indicate to use PETSc's default.
140 */
141 real_type step_tolerance;
142
143 /**
144 * Maximum number of nonlinear iterations allowed.
145 *
146 * @note Negative values indicate to use PETSc's default.
147 */
148 int maximum_non_linear_iterations;
149
150 /**
151 * Maximum number of function evaluations allowed.
152 *
153 * @note Negative values indicate to use PETSc's default.
154 */
155 int max_n_function_evaluations;
156 };
157
158 /**
159 * Interface to PETSc SNES solver for nonlinear equations.
160 * The SNES solver is described in the
161 * [PETSc manual](https://petsc.org/release/manual/snes/).
162 *
163 * This class solves the nonlinear system of algebraic
164 * equations $F(x) = 0$.
165 *
166 * The interface to PETSc is realized by means of std::function callbacks
167 * like in the TrilinosWrappers::NOXSolver and SUNDIALS::KINSOL classes.
168 *
169 * NonlinearSolver supports any vector and matrix type having constructors and
170 * methods:
171 *
172 * @code
173 * class VectorType : public EnableObserverPointer
174 * ...
175 * explicit VectorType(Vec);
176 * ...
177 * Vec & petsc_vector();
178 * ...
179 * @endcode
180 *
181 * @code
182 * class MatrixType : public EnableObserverPointer
183 * ...
184 * explicit MatrixType(Mat);
185 * ...
186 * Mat & petsc_matrix();
187 * ...
188 * @endcode
189 *
190 * In particular, the supported types are the ones that can *wrap*
191 * PETSc's native vector and matrix classes, that are able to modify
192 * them in place, and that can return PETSc native types when requested.
193 *
194 * To use the solvers the user needs to provide the implementation of $F$ via
195 * the NonlinearSolver::residual callback.
196 *
197 * The default linearization procedure of a solver instantiated with
198 * this class consists in using Jacobian-Free-Newton-Krylov; the action of
199 * tangent matrices inside a linear solver process are approximated via
200 * matrix-free finite-differencing of the nonlinear residual equations.
201 * For details, consult the [PETSc
202 * manual](https://petsc.org/release/manual/snes/#sec-nlmatrixfree).
203 *
204 * Users can also provide the implementations of the Jacobian. This can be
205 * accomplished in two ways:
206 * - PETSc style using NonlinearSolver::jacobian
207 * - deal.II style using NonlinearSolver::setup_jacobian and
208 * NonlinearSolver::solve_with_jacobian.
209 * The preconditioning matrix can be specified using
210 * NonlinearSolver::set_matrix(). In case both approaches are implemented, the
211 * deal.II style will be used.
212 *
213 * NonlinearSolver::set_matrices() must be used in case the user wants to
214 * provide the iteration matrix of the tangent system in the deal.II style
215 * approach, thus replacing the matrix-free linearization.
216 *
217 * The correctness of the constructed Jacobians passed using
218 * NonlinearSolver::set_matrix() can be checked using
219 * @code
220 * ./myApp -snes_test_jacobian
221 * @endcode
222 * See NonlinearSolver::set_matrix() and NonlinearSolver::set_matrices() for
223 * additional details.
224 *
225 * The deal.II style approach still allows command line customization, like
226 * for example,
227 * @code
228 * ./myApp -snes_type newtontr -ksp_type cg
229 * @endcode
230 * in case the user wants to change the default nonlinear solver to
231 * a trust region solver and iterate on the matrix-free tangent system with
232 * CG, still using NonlinearSolver::solve_with_jacobian as a preconditioner.
233 *
234 * The PETSc style approach has instead the advantage that only the matrix
235 * assembly procedure has to be implemented, thus allowing quicker
236 * implementations and faster turnaround for experimenting with linear solver
237 * preconditioning configurations via command line customizations, like for
238 * example,
239 * @code
240 * ./myApp -ksp_type cg -pc_type gamg
241 * @endcode
242 *
243 * In case the nonlinear equations are derived from energy minimization
244 * arguments, it may be beneficial to perform linesearch or test trust-region
245 * model reductions using the energy functional. In such cases, users can
246 * set an optional NonlinearSolver::energy callback.
247 *
248 * @dealiiConceptRequires{(concepts::is_dealii_petsc_vector_type<VectorType>
249 * || std::constructible_from<VectorType,Vec>) &&
250 * (concepts::is_dealii_petsc_matrix_type<PMatrixType> ||
251 * std::constructible_from<PMatrixType,Mat>) &&
252 * (concepts::is_dealii_petsc_matrix_type<AMatrixType> ||
253 * std::constructible_from<AMatrixType, Mat>)}
254 *
255 * @ingroup PETScWrappers
256 */
257 template <typename VectorType = PETScWrappers::VectorBase,
258 typename PMatrixType = PETScWrappers::MatrixBase,
259 typename AMatrixType = PMatrixType>
260 DEAL_II_CXX20_REQUIRES(
261 (concepts::is_dealii_petsc_vector_type<VectorType> ||
262 std::constructible_from<
263 VectorType,
264 Vec>)&&(concepts::is_dealii_petsc_matrix_type<PMatrixType> ||
265 std::constructible_from<
266 PMatrixType,
267 Mat>)&&(concepts::is_dealii_petsc_matrix_type<AMatrixType> ||
268 std::constructible_from<AMatrixType, Mat>))
269 class NonlinearSolver
270 {
271 public:
272 /**
273 * Type that holds real-valued numbers.
274 *
275 * Used to represent norms.
276 */
277 using real_type = PetscReal;
278
279 /**
280 * Constructor.
281 */
282 NonlinearSolver(const NonlinearSolverData &data = NonlinearSolverData(),
283 const MPI_Comm mpi_comm = PETSC_COMM_WORLD);
284
285 /**
286 * Destructor.
287 */
288 ~NonlinearSolver();
289
290 /**
291 * Conversion operator to gain access to the underlying PETSc type. If you
292 * do this, you cut this class off some information it may need, so this
293 * conversion operator should only be used if you know what you do.
294 */
295 operator SNES() const;
296
297 /**
298 * Return the PETSc SNES object.
299 */
300 SNES
301 petsc_snes();
302
303 /**
304 * Return the underlying MPI communicator.
305 */
306 MPI_Comm
307 get_mpi_communicator() const;
308
309 /**
310 * Reset the solver, it does not change the customization.
311 */
312 void
313 reinit();
314
315 /**
316 * Reset solver.
317 * Change customization according to @p data.
318 */
319 void
320 reinit(const NonlinearSolverData &data);
321
322 /**
323 * Set the preconditioning matrix only.
324 *
325 * When used with NonlinearSolver::setup_jacobian and
326 * NonlinearSolver::solve_with_jacobian, PETSc will approximate the
327 * linear system matrix-vector product using an internal matrix-free
328 * representation.
329 *
330 * When used with NonlinearSolver::jacobian PETSc will use the same matrix
331 * for both preconditioning and matrix-vector products.
332 */
333 void
334 set_matrix(PMatrixType &P);
335
336 /**
337 * Set both the linear system matrix and the preconditioning matrix
338 * that PETSc will use (can be the same matrix). In this case, the
339 * Jacobian-Free-Newton-Krylov approach will not be used.
340 */
341 void
342 set_matrices(AMatrixType &A, PMatrixType &P);
343
344 /**
345 * Solve the nonlinear system of equations $F(x) = 0$.
346 *
347 * This function returns the number of iterations.
348 * The vector @p x must contain the initial guess.
349 * Upon returning, the @p x vector contains the solution.
350 */
351 unsigned int
352 solve(VectorType &x);
353
354 /**
355 * Solve the nonlinear system of equations $F(x) = 0$.
356 *
357 * This function returns the number of iterations.
358 * The vector @p x must contain the initial guess.
359 * Upon returning, the @p x vector contains the solution.
360 *
361 * Here we also set the matrix to precondition the tangent system.
362 */
363 unsigned int
364 solve(VectorType &x, PMatrixType &P);
365
366 /**
367 * Solve the nonlinear system of equations $F(x) = 0$.
368 *
369 * This function returns the number of iterations.
370 * The vector @p x must contain the initial guess.
371 * Upon returning, the @p x vector contains the solution.
372 *
373 * Here we also set the matrices to describe and precondition
374 * the tangent system.
375 */
376 unsigned int
377 solve(VectorType &x, AMatrixType &A, PMatrixType &P);
378
379 /**
380 * Callback for the computation of the nonlinear residual $F(x)$.
381 *
382 * @note This variable represents a
383 * @ref GlossUserProvidedCallBack "user provided callback".
384 * See there for a description of how to deal with errors and other
385 * requirements and conventions.
386 */
387 std::function<void(const VectorType &x, VectorType &res)> residual;
388
389 /**
390 * Callback for the computation of the Jacobian
391 * $\dfrac{\partial F}{\partial x}$.
392 *
393 * @note This variable represents a
394 * @ref GlossUserProvidedCallBack "user provided callback".
395 * See there for a description of how to deal with errors and other
396 * requirements and conventions.
397 */
398 std::function<void(const VectorType &x, AMatrixType &A, PMatrixType &P)>
399 jacobian;
400
401 /**
402 * Callback for monitoring the solution process.
403 *
404 * This function is called by NonlinearSolver at the beginning
405 * of each step. Input arguments are the current step number
406 * and the current value for $||F(x)||$.
407 *
408 * @note This variable represents a
409 * @ref GlossUserProvidedCallBack "user provided callback".
410 * See there for a description of how to deal with errors and other
411 * requirements and conventions.
412 */
413 std::function<void(const VectorType &x,
414 const unsigned int step_number,
415 const real_type f_norm)>
416 monitor;
417
418 /**
419 * Callback for the set up of the Jacobian system.
420 *
421 * This callback gives full control to users to set up the tangent
422 * operator $\dfrac{\partial F}{\partial x}$.
423 *
424 * Solvers must be provided via NonlinearSolver::solve_with_jacobian.
425 *
426 * @note This variable represents a
427 * @ref GlossUserProvidedCallBack "user provided callback".
428 * See there for a description of how to deal with errors and other
429 * requirements and conventions.
430 */
431 std::function<void(const VectorType &x)> setup_jacobian;
432
433 /**
434 * Callback for the solution of the tangent system set up with
435 * NonlinearSolver::setup_jacobian.
436 *
437 * This is used as a preconditioner inside the Krylov process.
438 *
439 * @note This variable represents a
440 * @ref GlossUserProvidedCallBack "user provided callback".
441 * See there for a description of how to deal with errors and other
442 * requirements and conventions.
443 */
444 std::function<void(const VectorType &src, VectorType &dst)>
445 solve_with_jacobian;
446
447 /**
448 * Callback for the computation of the energy function.
449 *
450 * This is usually not needed, since by default SNES assumes that the
451 * objective function to be minimized is $\frac{1}{2} || F(x) ||^2 $.
452 *
453 * However, if the nonlinear equations are derived from energy arguments, it
454 * may be useful to use this callback to perform linesearch or to test for
455 * the reduction in a trust region step.
456 *
457 * The value of the energy function must be returned in @p energy_value.
458 *
459 * @note This variable represents a
460 * @ref GlossUserProvidedCallBack "user provided callback".
461 * See there for a description of how to deal with errors and other
462 * requirements and conventions.
463 */
464 std::function<void(const VectorType &x, real_type &energy_value)> energy;
465
466 private:
467 /**
468 * The PETSc SNES object.
469 */
470 SNES snes;
471
472 /**
473 * Pointers to the internal PETSc matrix objects.
474 */
475 ObserverPointer<AMatrixType, NonlinearSolver> A;
476 ObserverPointer<PMatrixType, NonlinearSolver> P;
477
478 /**
479 * This flag is used to support versions of PETSc older than 3.13.
480 */
481 bool need_dummy_assemble;
482
483 /**
484 * A pointer to any exception that may have been thrown in user-defined
485 * call-backs and that we have to deal after the KINSOL function we call
486 * has returned.
487 */
488 mutable std::exception_ptr pending_exception;
489 };
490
491 } // namespace PETScWrappers
492
493 DEAL_II_NAMESPACE_CLOSE
494
495 #else
496
497 // Make sure the scripts that create the C++20 module input files have
498 // something to latch on if the preprocessor #ifdef above would
499 // otherwise lead to an empty content of the file.
500 DEAL_II_NAMESPACE_OPEN
501 DEAL_II_NAMESPACE_CLOSE
502
503 #endif // DEAL_II_WITH_PETSC
504
505 #endif