Debian Codegraph @

include/deal.II/lac/solver_control.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 1998 - 2025 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_solver_control_h
16 #define dealii_solver_control_h
17
18
19 #include <deal.II/base/config.h>
20
21 #include <deal.II/base/enable_observer_pointer.h>
22 #include <deal.II/base/exceptions.h>
23
24 #include <vector>
25
26 DEAL_II_NAMESPACE_OPEN
27
28 #ifndef DOXYGEN
29 class ParameterHandler;
30 #endif
31
32 /**
33 * @addtogroup Solvers
34 * @{
35 */
36
37 /**
38 * Control class to determine convergence of iterative solvers.
39 *
40 * Used by iterative methods to determine whether the iteration should be
41 * continued. To this end, the virtual function <tt>check()</tt> is called in
42 * each iteration with the current iteration step and the value indicating
43 * convergence (usually the residual).
44 *
45 * After the iteration has terminated, the functions last_value() and
46 * last_step() can be used to obtain information about the final state of the
47 * iteration.
48 *
49 * check() can be replaced in derived classes to allow for more sophisticated
50 * tests.
51 *
52 *
53 * <h3>State</h3> The return states of the check function are of type #State,
54 * which is an enum local to this class. It indicates the state the solver is
55 * in.
56 *
57 * The possible values of State are
58 * <ul>
59 * <li> <tt>iterate = 0</tt>: continue the iteration.
60 * <li> @p success: the goal is reached, the iterative method can terminate
61 * successfully.
62 * <li> @p failure: the iterative method should stop because convergence could
63 * not be achieved or at least was not achieved within the given maximal
64 * number of iterations.
65 * </ul>
66 */
67 class SolverControl : public EnableObserverPointer
68 {
69 public:
70 /**
71 * Enum denoting the different states a solver can be in. See the general
72 * documentation of this class for more information.
73 */
74 enum State
75 {
76 /// Continue iteration
77 iterate = 0,
78 /// Stop iteration, goal reached
79 success,
80 /// Stop iteration, goal not reached
81 failure
82 };
83
84
85
86 /**
87 * Class to be thrown upon failing convergence of an iterative solver, when
88 * either the number of iterations exceeds the limit or the residual fails
89 * to reach the desired limit, e.g. in the case of a break-down.
90 *
91 * The residual in the last iteration, as well as the iteration number of
92 * the last step are stored in this object and can be recovered upon
93 * catching an exception of this class.
94 */
95 class NoConvergence : public dealii::ExceptionBase
96 {
97 public:
98 NoConvergence(const unsigned int last_step, const double last_residual)
99 : last_step(last_step)
100 , last_residual(last_residual)
101 {}
102
103 virtual ~NoConvergence() noexcept override = default;
104
105 virtual void
106 print_info(std::ostream &out) const override
107 {
108 out
109 << "Iterative method reported convergence failure in step " << last_step
110 << ". The residual in the last step was " << last_residual << ".\n\n"
111 << "This error message can indicate that you have simply not allowed "
112 << "a sufficiently large number of iterations for your iterative solver "
113 << "to converge. This often happens when you increase the size of your "
114 << "problem. In such cases, the last residual will likely still be very "
115 << "small, and you can make the error go away by increasing the allowed "
116 << "number of iterations when setting up the SolverControl object that "
117 << "determines the maximal number of iterations you allow."
118 << "\n\n"
119 << "The other situation where this error may occur is when your matrix "
120 << "is not invertible (e.g., your matrix has a null-space), or if you "
121 << "try to apply the wrong solver to a matrix (e.g., using CG for a "
122 << "matrix that is not symmetric or not positive definite). In these "
123 << "cases, the residual in the last iteration is likely going to be large."
124 << std::endl;
125 }
126
127 /**
128 * Iteration number of the last step.
129 */
130 const unsigned int last_step;
131
132 /**
133 * Residual in the last step.
134 */
135 const double last_residual;
136 };
137
138
139
140 /**
141 * Constructor. The parameters @p n and @p tol are the maximum number of
142 * iteration steps before failure and the tolerance to determine success of
143 * the iteration.
144 *
145 * @p log_history specifies whether the history (i.e. the value to be
146 * checked and the number of the iteration step) shall be printed to @p
147 * deallog stream. Default is: do not print. Similarly, @p log_result
148 * specifies the whether the final result is logged to @p deallog. Default
149 * is: do not print.
150 */
151 explicit SolverControl(const unsigned int n = 100,
152 const double tol = 1.e-10,
153 const bool log_history = false,
154 const bool log_result = false);
155
156 /**
157 * Virtual destructor is needed as there are virtual functions in this
158 * class.
159 */
160 virtual ~SolverControl() override = default;
161
162 /**
163 * Interface to parameter file.
164 */
165 static void
166 declare_parameters(ParameterHandler &param);
167
168 /**
169 * Read parameters from file.
170 */
171 void
172 parse_parameters(ParameterHandler &param);
173
174 /**
175 * Decide about success or failure of an iteration. This function gets the
176 * current iteration step to determine, whether the allowed number of steps
177 * has been exceeded and returns @p failure in this case. If @p check_value
178 * is below the prescribed tolerance, it returns @p success. In all other
179 * cases @p iterate is returned to suggest continuation of the iterative
180 * procedure.
181 *
182 * The iteration is also aborted if the residual becomes a denormalized
183 * value (@p NaN).
184 *
185 * <tt>check()</tt> additionally preserves @p step and @p check_value. These
186 * values are accessible by <tt>last_value()</tt> and <tt>last_step()</tt>.
187 *
188 * Derived classes may overload this function, e.g. to log the convergence
189 * indicators (@p check_value) or to do other computations.
190 */
191 virtual State
192 check(const unsigned int step, const double check_value);
193
194 /**
195 * Return the result of the last check operation.
196 */
197 State
198 last_check() const;
199
200 /**
201 * Return the initial convergence criterion.
202 */
203 double
204 initial_value() const;
205
206 /**
207 * Return the convergence value of last iteration step for which @p check
208 * was called by the solver.
209 */
210 double
211 last_value() const;
212
213 /**
214 * Number of last iteration step.
215 */
216 unsigned int
217 last_step() const;
218
219 /**
220 * Maximum number of steps.
221 */
222 unsigned int
223 max_steps() const;
224
225 /**
226 * Change maximum number of steps.
227 */
228 unsigned int
229 set_max_steps(const unsigned int);
230
231 /**
232 * Enables the failure check. Solving is stopped with @p ReturnState @p
233 * failure if <tt>residual>failure_residual</tt> with
234 * <tt>failure_residual := rel_failure_residual*first_residual</tt>.
235 */
236 void
237 set_failure_criterion(const double rel_failure_residual);
238
239 /**
240 * Disables failure check and resets @p relative_failure_residual and @p
241 * failure_residual to zero.
242 */
243 void
244 clear_failure_criterion();
245
246 /**
247 * Tolerance.
248 */
249 double
250 tolerance() const;
251
252 /**
253 * Change tolerance.
254 */
255 double
256 set_tolerance(const double);
257
258 /**
259 * Enables writing residuals of each step into a vector for later analysis.
260 */
261 void
262 enable_history_data();
263
264 /**
265 * Provide read access to the collected residual data.
266 */
267 const std::vector<double> &
268 get_history_data() const;
269
270 /**
271 * Average error reduction over all steps.
272 *
273 * Requires enable_history_data()
274 */
275 double
276 average_reduction() const;
277 /**
278 * Error reduction of the last step; for stationary iterations, this
279 * approximates the norm of the iteration matrix.
280 *
281 * Requires enable_history_data()
282 */
283 double
284 final_reduction() const;
285
286 /**
287 * Error reduction of any iteration step.
288 *
289 * Requires enable_history_data()
290 */
291 double
292 step_reduction(unsigned int step) const;
293
294 /**
295 * Log each iteration step. Use @p log_frequency for skipping steps.
296 */
297 void
298 log_history(const bool);
299
300 /**
301 * Return the @p log_history flag.
302 */
303 bool
304 log_history() const;
305
306 /**
307 * Set logging frequency.
308 */
309 unsigned int
310 log_frequency(unsigned int);
311
312 /**
313 * Log start and end step.
314 */
315 void
316 log_result(const bool);
317
318 /**
319 * Return the @p log_result flag.
320 */
321 bool
322 log_result() const;
323
324 /**
325 * This exception is thrown if a function operating on the vector of history
326 * data of a SolverControl object is called, but storage of history data was
327 * not enabled by enable_history_data().
328 */
329 DeclException0(ExcHistoryDataRequired);
330
331 protected:
332 /**
333 * Maximum number of steps.
334 */
335 unsigned int maxsteps;
336
337 /**
338 * Prescribed tolerance to be achieved.
339 */
340 double tol;
341
342 /**
343 * Result of last check operation.
344 */
345 State lcheck;
346
347 /**
348 * Initial value.
349 */
350 double initial_val;
351
352 /**
353 * Last value of the convergence criterion.
354 */
355 double lvalue;
356
357 /**
358 * Last step.
359 */
360 unsigned int lstep;
361
362 /**
363 * Is set to @p true by @p set_failure_criterion and enables failure
364 * checking.
365 */
366 bool check_failure;
367
368 /**
369 * Stores the @p rel_failure_residual set by @p set_failure_criterion
370 */
371 double relative_failure_residual;
372
373 /**
374 * @p failure_residual equals the first residual multiplied by @p
375 * relative_crit set by @p set_failure_criterion (see there).
376 *
377 * Until the first residual is known it is 0.
378 */
379 double failure_residual;
380
381 /**
382 * Log convergence history to @p deallog.
383 */
384 bool m_log_history;
385
386 /**
387 * Log only every nth step.
388 */
389 unsigned int m_log_frequency;
390
391 /**
392 * Log iteration result to @p deallog. If true, after finishing the
393 * iteration, a statement about failure or success together with @p lstep
394 * and @p lvalue are logged.
395 */
396 bool m_log_result;
397
398 /**
399 * Control over the storage of history data. Set by enable_history_data().
400 */
401 bool history_data_enabled;
402
403 /**
404 * Vector storing the result after each iteration step for later statistical
405 * analysis.
406 *
407 * Use of this vector is enabled by enable_history_data().
408 */
409 std::vector<double> history_data;
410 };
411
412
413 /**
414 * Specialization of @p SolverControl which returns @p success if either the
415 * specified tolerance is achieved or if the initial residual (or whatever
416 * criterion was chosen by the solver class) is reduced by a given factor.
417 * This is useful in cases where you don't want to solve exactly, but rather
418 * want to gain two digits or if the maximal number of iterations is achieved.
419 * For example: The maximal number of iterations is 20, the reduction factor
420 * is 1% and the tolerance is 0.1%. The initial residual is 2.5. The process
421 * will break if 20 iteration are completed or the new residual is less then
422 * 2.5*1% or if it is less then 0.1%.
423 */
424 class ReductionControl : public SolverControl
425 {
426 public:
427 /**
428 * Constructor. Provide the reduction factor in addition to arguments that
429 * have the same meaning as those of the constructor of the SolverControl
430 * constructor.
431 */
432 explicit ReductionControl(const unsigned int maxiter = 100,
433 const double tolerance = 1.e-10,
434 const double reduce = 1.e-2,
435 const bool log_history = false,
436 const bool log_result = false);
437
438 /**
439 * Initialize with a SolverControl object. The result will emulate
440 * SolverControl by setting @p reduce to zero.
441 */
442 explicit ReductionControl(const SolverControl &c);
443
444 /**
445 * Assign a SolverControl object to ReductionControl. The result of the
446 * assignment will emulate SolverControl by setting @p reduce to zero.
447 */
448 ReductionControl &
449 operator=(const SolverControl &c);
450
451 /**
452 * Virtual destructor is needed as there are virtual functions in this
453 * class.
454 */
455 virtual ~ReductionControl() override = default;
456
457 /**
458 * Interface to parameter file.
459 */
460 static void
461 declare_parameters(ParameterHandler &param);
462
463 /**
464 * Read parameters from file.
465 */
466 void
467 parse_parameters(ParameterHandler &param);
468
469 /**
470 * Decide about success or failure of an iteration. This function calls the
471 * one in the base class, but sets the tolerance to <tt>reduction * initial
472 * value</tt> upon the first iteration.
473 */
474 virtual State
475 check(const unsigned int step, const double check_value) override;
476
477 /**
478 * Reduction factor.
479 */
480 double
481 reduction() const;
482
483 /**
484 * Change reduction factor.
485 */
486 double
487 set_reduction(const double);
488
489 protected:
490 /**
491 * Desired reduction factor.
492 */
493 double reduce;
494
495 /**
496 * Reduced tolerance. Stop iterations if either this value is achieved or if
497 * the base class indicates success.
498 */
499 double reduced_tol;
500 };
501
502 /**
503 * Specialization of @p SolverControl which returns @p success if a given
504 * number of iteration was performed, irrespective of the actual residual.
505 * This is useful in cases where you don't want to solve exactly, but rather
506 * want to perform a fixed number of iterations, e.g. in an inner solver. The
507 * arguments given to this class are exactly the same as for the SolverControl
508 * class and the solver terminates similarly when one of the given tolerance
509 * or the maximum iteration count were reached. The only difference to
510 * SolverControl is that the solver returns success in the latter case.
511 */
512 class IterationNumberControl : public SolverControl
513 {
514 public:
515 /**
516 * Constructor. Provide exactly the same arguments as the constructor of
517 * the SolverControl class.
518 */
519 explicit IterationNumberControl(const unsigned int maxiter = 100,
520 const double tolerance = 1e-12,
521 const bool log_history = false,
522 const bool log_result = false);
523
524 /**
525 * Initialize with a SolverControl object. The result will emulate
526 * SolverControl by setting the reduction target to zero.
527 */
528 explicit IterationNumberControl(const SolverControl &c);
529
530 /**
531 * Assign a SolverControl object to ReductionControl. The result of the
532 * assignment will emulate SolverControl by setting the reduction target to
533 * zero.
534 */
535 IterationNumberControl &
536 operator=(const SolverControl &c);
537
538 /**
539 * Virtual destructor is needed as there are virtual functions in this
540 * class.
541 */
542 virtual ~IterationNumberControl() override = default;
543
544 /**
545 * Decide about success or failure of an iteration. This function bases
546 * success solely on the fact if a given number of iterations was reached or
547 * the check value reached exactly zero.
548 */
549 virtual State
550 check(const unsigned int step, const double check_value) override;
551 };
552
553
554 /**
555 * Specialization of @p SolverControl which returns SolverControl::State::success if
556 * and only if a certain positive number of consecutive iterations satisfy the
557 * specified tolerance. This is useful in cases when solving nonlinear problems
558 * using inexact Hessian.
559 *
560 * For example: The requested number of consecutively converged iterations is 2,
561 * the tolerance is 0.2. The ConsecutiveControl will return
562 * SolverControl::State::success only at the last step in the sequence 0.5,
563 * 0.0005, 1.0, 0.05, 0.01.
564 */
565 class ConsecutiveControl : public SolverControl
566 {
567 public:
568 /**
569 * Constructor. @p n_consecutive_iterations is the number of
570 * consecutive iterations which should satisfy the prescribed tolerance for
571 * convergence. Other arguments have the same meaning as those of the
572 * constructor of the SolverControl.
573 */
574 explicit ConsecutiveControl(const unsigned int maxiter = 100,
575 const double tolerance = 1.e-10,
576 const unsigned int n_consecutive_iterations = 2,
577 const bool log_history = false,
578 const bool log_result = false);
579
580 /**
581 * Initialize with a SolverControl object. The result will emulate
582 * SolverControl by setting @p n_consecutive_iterations to one.
583 */
584 explicit ConsecutiveControl(const SolverControl &c);
585
586 /**
587 * Assign a SolverControl object to ConsecutiveControl. The result of the
588 * assignment will emulate SolverControl by setting @p n_consecutive_iterations
589 * to one.
590 */
591 ConsecutiveControl &
592 operator=(const SolverControl &c);
593
594 /**
595 * Virtual destructor is needed as there are virtual functions in this
596 * class.
597 */
598 virtual ~ConsecutiveControl() override = default;
599
600 /**
601 * Decide about success or failure of an iteration, see the class description
602 * above.
603 */
604 virtual State
605 check(const unsigned int step, const double check_value) override;
606
607 protected:
608 /**
609 * The number of consecutive iterations which should satisfy the prescribed
610 * tolerance for convergence.
611 */
612 unsigned int n_consecutive_iterations;
613
614 /**
615 * Counter for the number of consecutively converged iterations.
616 */
617 unsigned int n_converged_iterations;
618 };
619
620 /** @} */
621 //---------------------------------------------------------------------------
622
623 #ifndef DOXYGEN
624
625 inline unsigned int
626 SolverControl::max_steps() const
627 {
628 return maxsteps;
629 }
630
631
632
633 inline unsigned int
634 SolverControl::set_max_steps(const unsigned int newval)
635 {
636 unsigned int old = maxsteps;
637 maxsteps = newval;
638 return old;
639 }
640
641
642
643 inline void
644 SolverControl::set_failure_criterion(const double rel_failure_residual)
645 {
646 relative_failure_residual = rel_failure_residual;
647 check_failure = true;
648 }
649
650
651
652 inline void
653 SolverControl::clear_failure_criterion()
654 {
655 relative_failure_residual = 0;
656 failure_residual = 0;
657 check_failure = false;
658 }
659
660
661
662 inline double
663 SolverControl::tolerance() const
664 {
665 return tol;
666 }
667
668
669
670 inline double
671 SolverControl::set_tolerance(const double t)
672 {
673 double old = tol;
674 tol = t;
675 return old;
676 }
677
678
679 inline void
680 SolverControl::log_history(const bool newval)
681 {
682 m_log_history = newval;
683 }
684
685
686
687 inline bool
688 SolverControl::log_history() const
689 {
690 return m_log_history;
691 }
692
693
694 inline void
695 SolverControl::log_result(const bool newval)
696 {
697 m_log_result = newval;
698 }
699
700
701 inline bool
702 SolverControl::log_result() const
703 {
704 return m_log_result;
705 }
706
707
708 inline double
709 ReductionControl::reduction() const
710 {
711 return reduce;
712 }
713
714
715 inline double
716 ReductionControl::set_reduction(const double t)
717 {
718 double old = reduce;
719 reduce = t;
720 return old;
721 }
722
723 #endif // DOXYGEN
724
725 DEAL_II_NAMESPACE_CLOSE
726
727 #endif