Debian Codegraph @

include/deal.II/trilinos/nox.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 2022 - 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_trilinos_nox
16 #define dealii_trilinos_nox
17
18 #include <deal.II/base/config.h>
19
20 #ifdef DEAL_II_TRILINOS_WITH_NOX
21
22 # include <deal.II/base/exceptions.h>
23
24 # include <deal.II/lac/solver_control.h>
25
26 # include <Teuchos_ParameterList.hpp>
27
28 # include <exception>
29 # include <functional>
30
31 DEAL_II_NAMESPACE_OPEN
32
33 namespace TrilinosWrappers
34 {
35 // Indicate that NOXSolver has not converged.
36 DeclException0(ExcNOXNoConvergence);
37
38
39 /**
40 * Wrapper around the nonlinear solver from the NOX
41 * package (https://docs.trilinos.org/dev/packages/nox/doc/html/index.html),
42 * targeting deal.II data structures.
43 *
44 * The following code shows the steps how to use this class:
45 * @code
46 * // set configuration
47 * TrilinosWrappers::NOXSolver<VectorType>::AdditionalData additional_data;
48 *
49 * // Define ParameterList object for more options
50 * // These specifications are the default but we include them for
51 * // clarification
52 * const Teuchos::RCP<Teuchos::ParameterList> parameters =
53 * Teuchos::rcp(new Teuchos::ParameterList);
54 *
55 * // Specify nonlinear solver type
56 * parameters->set("Nonlinear Solver","Line Search Based");
57 *
58 * // Specify method of line search
59 * parameters->sublist("Line Search").set("Method","Full Step");
60 *
61 * // Specify direction
62 * parameters->sublist("Direction").set("Method","Newton")
63 *
64 * // create nonlinear solver
65 * TrilinosWrappers::NOXSolver<VectorType> solver(additional_data,parameters);
66 *
67 * // Set user functions to compute residual, to set up the Jacobian, and to
68 * // apply the inverse of the Jacobian.
69 * // Note that there are more functions that can be set.
70 * solver.residual = [](const auto &u, auto &F) {...};
71 * solver.setup_jacobian = [](const auto &u) {...};
72 * solver.solve_with_jacobian =
73 * [](const auto &u, auto &F, const auto) {...};
74 *
75 * // solver nonlinear system with solution containing the initial guess and
76 * // the final solution
77 * solver.solve(solution);
78 * @endcode
79 *
80 * The functions used in NOX are nearly identical to the functions in
81 * SUNDIALS::KINSOL with a few exceptions (for example,
82 * SUNDIALS::KINSOL requires a reinit() function where NOX does
83 * not). So check the SUNDIALS::KINSOL documentation for more precise details
84 * on how these functions are implemented.
85 */
86 template <typename VectorType>
87 class NOXSolver
88 {
89 public:
90 /**
91 * Struct that helps to configure NOXSolver. More advanced
92 * parameters are passed to the constructor NOXSolver
93 * directly via a Teuchos::ParameterList.
94 */
95 struct AdditionalData
96 {
97 public:
98 /**
99 * Constructor.
100 */
101 AdditionalData(const unsigned int max_iter = 10,
102 const double abs_tol = 1.e-20,
103 const double rel_tol = 1.e-5,
104 const unsigned int threshold_nonlinear_iterations = 1,
105 const unsigned int threshold_n_linear_iterations = 0,
106 const bool reuse_solver = false);
107
108 /**
109 * Max number of nonlinear iterations.
110 */
111 unsigned int max_iter;
112
113 /**
114 * Absolute l2 tolerance of the residual to be reached.
115 *
116 * @note Solver terminates successfully if either the absolute or
117 * the relative tolerance has been reached.
118 */
119 double abs_tol;
120
121 /**
122 * Relative l2 tolerance of the residual to be reached.
123 *
124 * @note Solver terminates successfully if either the absolute or
125 * the relative tolerance has been reached.
126 */
127 double rel_tol;
128
129 /**
130 * Number of nonlinear iterations after which the preconditioner
131 * should be updated.
132 */
133 unsigned int threshold_nonlinear_iterations;
134
135 /**
136 * A number that indicates how many iterations a linear solver
137 * should at most perform before the preconditioner should
138 * be updated. The use of this variable is predicated on the
139 * idea that one can keep using a preconditioner built earlier
140 * as long as it is a good preconditioner for the matrix currently
141 * in use -- where "good" is defined as leading to a number of
142 * iterations to solve linear systems less than the threshold
143 * given by the current variable.
144 *
145 * This variable is only used if the
146 * NOXSolver::solve_with_jacobian_and_track_n_linear_iterations
147 * function object has been given a target (i.e., it is not empty).
148 */
149 unsigned int threshold_n_linear_iterations;
150
151 /**
152 * Reuse nonlinear solver the next time solve() is called. In particular,
153 * this parameter allows to reuse the preconditioner from the last
154 * solution step, enabling preconditioner lagging over multiple nonlinear
155 * solutions.
156 */
157 bool reuse_solver;
158 };
159
160 /**
161 * Constructor, with class parameters set by the AdditionalData object.
162 *
163 * @param additional_data NOX configuration data.
164 * @param parameters More specific NOX solver configuration.
165 *
166 * If @p parameters is not filled, a Newton solver with a full step is used.
167 * An overview of possible parameters is given at
168 * https://docs.trilinos.org/dev/packages/nox/doc/html/parameters.html.
169 */
170 NOXSolver(AdditionalData &additional_data,
171 const Teuchos::RCP<Teuchos::ParameterList> &parameters =
172 Teuchos::rcp(new Teuchos::ParameterList));
173
174 /**
175 * Destructor.
176 */
177 ~NOXSolver();
178
179 /**
180 * Clear the internal state.
181 */
182 void
183 clear();
184
185 /**
186 * Solve the nonlinear problem and return the number of nonlinear
187 * iterations executed.
188 */
189 unsigned int
190 solve(VectorType &solution);
191
192 /**
193 * A function object that users should supply and that is intended to
194 * compute the residual $F(u)$.
195 *
196 * @note This variable represents a
197 * @ref GlossUserProvidedCallBack "user provided callback".
198 * See there for a description of how to deal with errors and other
199 * requirements and conventions. NOX can not deal
200 * with "recoverable" errors for this callback, so if it
201 * throws an exception of type RecoverableUserCallbackError, then this
202 * exception is treated like any other exception.
203 */
204 std::function<void(const VectorType &u, VectorType &F)> residual;
205
206 /**
207 * A user function that sets up the Jacobian, based on the
208 * current solution @p current_u.
209 *
210 * @note This variable represents a
211 * @ref GlossUserProvidedCallBack "user provided callback".
212 * See there for a description of how to deal with errors and other
213 * requirements and conventions. NOX can not deal
214 * with "recoverable" errors for this callback, so if it
215 * throws an exception of type RecoverableUserCallbackError, then this
216 * exception is treated like any other exception.
217 */
218 std::function<void(const VectorType &current_u)> setup_jacobian;
219
220 /**
221 * A user function that sets up the preconditioner for inverting
222 * the Jacobian, based on the current solution @p current_u.
223 *
224 * @note This function is optional and is used when setup_jacobian is
225 * called and the preconditioner needs to be updated (see
226 * update_preconditioner_predicate and
227 * AdditionalData::threshold_nonlinear_iterations).
228 *
229 * @note This variable represents a
230 * @ref GlossUserProvidedCallBack "user provided callback".
231 * See there for a description of how to deal with errors and other
232 * requirements and conventions. NOX can not deal
233 * with "recoverable" errors for this callback, so if it
234 * throws an exception of type RecoverableUserCallbackError, then this
235 * exception is treated like any other exception.
236 */
237 std::function<void(const VectorType &current_u)> setup_preconditioner;
238
239 /**
240 * A user function that applies the Jacobian $\nabla_u F(u)$ to
241 * @p x and writes the result in @p y. The Jacobian to be used
242 * (i.e., more precisely: the linearization point $u$ above) is
243 * the one computed when the `setup_jacobian` function was last called.
244 *
245 * @note This function is optional and is used in the case of certain
246 * configurations. For instance, this function is required if the
247 * polynomial line search (`NOX::LineSearch::Polynomial`) is
248 * chosen, whereas for the full step case (`NOX::LineSearch::FullStep`)
249 * it won't be called.
250 *
251 * @note This variable represents a
252 * @ref GlossUserProvidedCallBack "user provided callback".
253 * See there for a description of how to deal with errors and other
254 * requirements and conventions. NOX can not deal
255 * with "recoverable" errors for this callback, so if it
256 * throws an exception of type RecoverableUserCallbackError, then this
257 * exception is treated like any other exception.
258 */
259 std::function<void(const VectorType &x, VectorType &y)> apply_jacobian;
260
261 /**
262 * A user function that applies the inverse of the Jacobian
263 * $[\nabla_u F(u)]^{-1}$ to
264 * @p y and writes the result in @p x. The parameter @p tolerance
265 * specifies the error reduction if an iterative solver is used
266 * in applying the inverse matrix. The Jacobian to be used
267 * (i.e., more precisely: the linearization point $u$ above) is
268 * the one computed when the `setup_jacobian` function was last called.
269 *
270 * @note This function is optional and is used in the case of certain
271 * configurations.
272 *
273 * @note This variable represents a
274 * @ref GlossUserProvidedCallBack "user provided callback".
275 * See there for a description of how to deal with errors and other
276 * requirements and conventions. NOX can deal with "recoverable"
277 * errors for this callback, if the NOX parameter
278 * "Newton/Rescue Bad Newton Solve" is set to @p true (which is, in
279 * fact, its default value). If this parameters is set to @p true,
280 * then exceptions of type RecoverableUserCallbackError are eaten for
281 * this callback and NOX can safely proceed with a recovery step.
282 * Exceptions of other types are still treated as "irrecoverable".
283 */
284 std::function<
285 void(const VectorType &y, VectorType &x, const double tolerance)>
286 solve_with_jacobian;
287
288 /**
289 * A user function that applies the inverse of the Jacobian
290 * $[\nabla_u F(u)]^{-1}$ to
291 * @p y, writes the result in @p x and returns the number of
292 * linear iterations the linear solver needed.
293 * The parameter @p tolerance species the error reduction if an
294 * iterative solver is used. The Jacobian to be used
295 * (i.e., more precisely: the linearization point $u$ above) is
296 * the one computed when the `setup_jacobian` function was last called.
297 *
298 * @note This function is used if `solve_with_jacobian` is not
299 * provided. Its return value is compared again
300 * AdditionalFlags::threshold_n_linear_iterations; if it is
301 * larger, the preconditioner will be built before the next
302 * linear system is solved. The use of this approach is predicated on the
303 * idea that one can keep using a preconditioner built earlier
304 * as long as it is a good preconditioner for the matrix currently
305 * in use -- where "good" is defined as leading to a number of
306 * iterations to solve linear systems less than the threshold
307 * given by the current variable.
308 *
309 * @note This variable represents a
310 * @ref GlossUserProvidedCallBack "user provided callback".
311 * See there for a description of how to deal with errors and other
312 * requirements and conventions. NOX can deal with "recoverable"
313 * errors for this callback, if the NOX parameter
314 * "Newton/Rescue Bad Newton Solve" is set to @p true (which is, in
315 * fact, its default value). If this parameters is set to @p true,
316 * then exceptions of type RecoverableUserCallbackError are eaten for
317 * this callback and NOX can safely proceed with a recovery step.
318 * Exceptions of other types are still treated as "irrecoverable".
319 */
320 std::function<
321 int(const VectorType &y, VectorType &x, const double tolerance)>
322 solve_with_jacobian_and_track_n_linear_iterations;
323
324 /**
325 * A user function that allows to check convergence in addition to
326 * ones checking the l2-norm and the number of iterations (see
327 * AdditionalData). It is run after each nonlinear iteration.
328 *
329 * The input are the current iteration number @p i, the l2-norm
330 * @p norm_f of the residual vector, the current solution @p current_u,
331 * and the current residual vector @p f.
332 *
333 * @note This function is optional.
334 *
335 * @note This variable represents a
336 * @ref GlossUserProvidedCallBack "user provided callback".
337 * See there for a description of how to deal with errors and other
338 * requirements and conventions. NOX can not deal
339 * with "recoverable" errors for this callback, so if it
340 * throws an exception of type RecoverableUserCallbackError, then this
341 * exception is treated like any other exception.
342 */
343 std::function<SolverControl::State(const unsigned int i,
344 const double norm_f,
345 const VectorType &current_u,
346 const VectorType &f)>
347 check_iteration_status;
348
349 /**
350 * A user function that, in addition to
351 * AdditionalData::threshold_nonlinear_iterations,
352 * allows to force to update the preconditioner. A reason
353 * for wanting to update the preconditioner is when the expected number
354 * of linear iterations is exceeded.
355 *
356 * @note This function is optional. If no function is attached, this
357 * means implicitly a return value of `false`.
358 *
359 * @note This variable represents a
360 * @ref GlossUserProvidedCallBack "user provided callback".
361 * See there for a description of how to deal with errors and other
362 * requirements and conventions. NOX can not deal
363 * with "recoverable" errors for this callback, so if it
364 * throws an exception of type RecoverableUserCallbackError, then this
365 * exception is treated like any other exception.
366 */
367 std::function<bool()> update_preconditioner_predicate;
368
369 private:
370 /**
371 * Additional data with basic settings.
372 */
373 AdditionalData additional_data;
374
375 /**
376 * Additional data with advanced settings. An overview of
377 * possible parameters is given at
378 * https://docs.trilinos.org/dev/packages/nox/doc/html/parameters.html.
379 */
380 const Teuchos::RCP<Teuchos::ParameterList> parameters;
381
382 /**
383 * A counter for the number of (accumulated) residual evaluations.
384 */
385 unsigned int n_residual_evaluations;
386
387 /**
388 * A counter for the number of (accumulated) Jacobi applications.
389 */
390 unsigned int n_jacobian_applications;
391
392 /**
393 * A counter for the number of (accumulated) nonlinear iterations.
394 */
395 unsigned int n_nonlinear_iterations;
396
397 /**
398 * The number of linear iterations of the last Jacobian solve.
399 */
400 unsigned int n_last_linear_iterations;
401
402 /**
403 * A pointer to any exception that may have been thrown in user-defined
404 * call-backs and that we have to deal after the KINSOL function we call
405 * has returned.
406 */
407 mutable std::exception_ptr pending_exception;
408 };
409 } // namespace TrilinosWrappers
410
411 DEAL_II_NAMESPACE_CLOSE
412
413 #else
414
415 // Make sure the scripts that create the C++20 module input files have
416 // something to latch on if the preprocessor #ifdef above would
417 // otherwise lead to an empty content of the file.
418 DEAL_II_NAMESPACE_OPEN
419 DEAL_II_NAMESPACE_CLOSE
420
421 #endif
422
423 #endif