Debian Codegraph @

include/deal.II/sundials/arkode.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 2017 - 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
16 #ifndef dealii_sundials_arkode_h
17 #define dealii_sundials_arkode_h
18
19 #include <deal.II/base/config.h>
20
21
22 #ifdef DEAL_II_WITH_SUNDIALS
23
24 # include <deal.II/base/conditional_ostream.h>
25 # include <deal.II/base/exceptions.h>
26 # include <deal.II/base/mpi_stub.h>
27 # include <deal.II/base/parameter_handler.h>
28
29 # ifdef DEAL_II_WITH_PETSC
30 # include <deal.II/lac/petsc_block_vector.h>
31 # include <deal.II/lac/petsc_vector.h>
32 # endif
33 # include <deal.II/lac/vector.h>
34 # include <deal.II/lac/vector_memory.h>
35
36 # include <arkode/arkode.h>
37 # include <nvector/nvector_serial.h>
38 # ifdef DEAL_II_WITH_MPI
39 # include <nvector/nvector_parallel.h>
40 # endif
41 # include <deal.II/base/discrete_time.h>
42
43 # include <deal.II/sundials/n_vector.h>
44 # include <deal.II/sundials/sundials_types.h>
45 # include <deal.II/sundials/sunlinsol_wrapper.h>
46
47 # include <boost/signals2.hpp>
48
49 # include <sundials/sundials_linearsolver.h>
50 # include <sundials/sundials_math.h>
51
52 # include <exception>
53 # include <memory>
54
55
56 DEAL_II_NAMESPACE_OPEN
57
58
59 /**
60 * A namespace for dealing with ODE solvers through the SUNDIALS package.
61 */
62 namespace SUNDIALS
63 {
64 /**
65 * Interface to SUNDIALS additive Runge-Kutta methods (ARKode).
66 *
67 * The class ARKode is a wrapper to SUNDIALS variable-step, embedded,
68 * additive Runge-Kutta solver which is a general purpose solver for systems
69 * of ordinary differential equations characterized by the presence of both
70 * fast and slow dynamics.
71 *
72 * Fast dynamics are treated implicitly, and slow dynamics are treated
73 * explicitly, using nested families of implicit and explicit Runge-Kutta
74 * solvers.
75 *
76 * Citing directly from ARKode documentation:
77 *
78 * ARKode solves ODE initial value problems (IVPs) in $R^N$. These problems
79 * should be posed in explicit form as
80 *
81 * \f[
82 * M\dot y = f_E(t, y) + f_I (t, y), \qquad y(t_0) = y_0.
83 * \f]
84 *
85 * Here, $t$ is the independent variable (e.g. time), and the dependent
86 * variables are given by $y \in R^N$, and we use notation $\dot y$ to denote
87 * $dy/dt$. $M$ is a user-supplied nonsingular operator from $R^N \to R^N$.
88 * This operator may depend on $t$ but not on $y$.
89 *
90 * For standard systems of ordinary differential equations and for problems
91 * arising from the spatial semi-discretization of partial differential
92 * equations using finite difference or finite volume methods, $M$ is
93 * typically the identity matrix, $I$. For PDEs using a finite-element
94 * spatial semi-discretization $M$ is typically a well-conditioned mass
95 * matrix.
96 *
97 * The two right-hand side functions may be described as:
98 *
99 * - $f_E(t, y)$: contains the "slow" time scale components of the system.
100 * This will be integrated using explicit methods.
101 * - $f_I(t, y)$: contains the "fast" time scale components of the system.
102 * This will be integrated using implicit methods.
103 *
104 * ARKode may be used to solve stiff, nonstiff and multi-rate problems.
105 * Roughly speaking, stiffness is characterized by the presence of at least
106 * one rapidly damped mode, whose time constant is small compared to the time
107 * scale of the solution itself. In the implicit/explicit (ImEx) splitting
108 * above, these stiff components should be included in the right-hand side
109 * function $f_I (t, y)$.
110 *
111 * For multi-rate problems, a user should provide both of the functions $f_E$
112 * and $f_I$ that define the IVP system.
113 *
114 * For nonstiff problems, only $f_E$ should be provided, and $f_I$ is assumed
115 * to be zero, i.e. the system reduces to the non-split IVP:
116 *
117 * \f[
118 * M\dot y = f_E(t, y), \qquad y(t_0) = y_0.
119 * \f]
120 *
121 * In this scenario, the ARK methods reduce to classical explicit Runge-Kutta
122 * methods (ERK). For these classes of methods, ARKode allows orders of
123 * accuracy $q = \{2, 3, 4, 5, 6, 8\}$, with embeddings of orders $p = \{1,
124 * 2, 3, 4, 5, 7\}$. These default to the Heun-Euler-2-1-2,
125 * Bogacki-Shampine-4-2-3, Zonneveld-5-3-4, Cash-Karp-6-4-5, Verner-8-5-6 and
126 * Fehlberg-13-7-8 methods, respectively.
127 *
128 * Finally, for stiff (linear or nonlinear) problems the user may provide only
129 * $f_I$, implying that $f_E = 0$, so that the system reduces to the non-split
130 * IVP
131 *
132 * \f[
133 * M\dot y = f_I(t, y), \qquad y(t_0) = y_0.
134 * \f]
135 *
136 * Similarly to ERK methods, in this scenario the ARK methods reduce to
137 * classical diagonally-implicit Runge-Kutta methods (DIRK). For these
138 * classes of methods, ARKode allows orders of accuracy $q = \{2, 3, 4, 5\}$,
139 * with embeddings of orders $p = \{1, 2, 3, 4\}$. These default to the
140 * SDIRK-2-1-2, ARK-4-2-3 (implicit), SDIRK-5-3-4 and ARK-8-4-5 (implicit)
141 * methods, respectively.
142 *
143 * For both DIRK and ARK methods, an implicit system of the form
144 * \f[
145 * G(z_i) \dealcoloneq M z_i - h_n A^I_{i,i} f_I (t^I_{n,i}, z_i) - a_i = 0
146 * \f]
147 * must be solved for each stage $z_i , i = 1, \ldots, s$, where
148 * we have the data
149 * \f[
150 * a_i \dealcoloneq
151 * M y_{n-1} + h_n \sum_{j=1}^{i-1} [ A^E_{i,j} f_E(t^E_{n,j}, z_j)
152 * + A^I_{i,j} f_I (t^I_{n,j}, z_j)]
153 * \f]
154 * for the ARK methods, or
155 * \f[
156 * a_i \dealcoloneq
157 * M y_{n-1} + h_n \sum_{j=1}^{i-1} A^I_{i,j} f_I (t^I_{n,j}, z_j)
158 * \f]
159 * for the DIRK methods. Here $A^I_{i,j}$ and $A^E_{i,j}$ are the Butcher's
160 * tables for the chosen solver.
161 *
162 * If $f_I(t,y)$ depends nonlinearly on $y$ then the systems above correspond
163 * to a nonlinear system of equations; if $f_I (t, y)$ depends linearly on
164 * $y$ then this is a linear system of equations. By specifying the flag
165 * `implicit_function_is_linear`, ARKode takes some shortcuts that allow a
166 * faster solution process.
167 *
168 * For systems of either type, ARKode allows a choice of solution strategy.
169 * The default solver choice is a variant of Newton's method,
170 * \f[
171 * z_i^{m+1} = z_i^m +\delta^{m+1},
172 * \f]
173 * where $m$ is the Newton step index, and the Newton update $\delta^{m+1}$
174 * requires the solution of the linear Newton system
175 * \f[
176 * N(z_i^m) \delta^{m+1} = -G(z_i^m),
177 * \f]
178 * where
179 * \f[
180 * N \dealcoloneq M - \gamma J, \quad J
181 * \dealcoloneq \frac{\partial f_I}{\partial y},
182 * \qquad \gamma\dealcoloneq h_n A^I_{i,i}.
183 * \f]
184 *
185 * As an alternate to Newton's method, ARKode may solve for each stage $z_i ,i
186 * = 1, \ldots , s$ using an Anderson-accelerated fixed point iteration
187 * \f[
188 * z_i^{m+1} = g(z_i^{m}), m=0,1,\ldots.
189 * \f]
190 *
191 * Unlike with Newton's method, this option does not require the solution of
192 * a linear system at each iteration, instead opting for solution of a
193 * low-dimensional least-squares solution to construct the nonlinear update.
194 *
195 * Finally, if the user specifies `implicit_function_is_linear`, i.e.,
196 * $f_I(t, y)$ depends linearly on $y$, and if the Newton-based nonlinear
197 * solver is chosen, then the system will be solved using only a single
198 * Newton iteration. Notice that in order for the Newton solver to be used,
199 * then jacobian_times_vector() should be supplied. If it is not supplied then
200 * only the fixed-point iteration will be supported, and the
201 * `implicit_function_is_linear` setting is ignored.
202 *
203 * The optimal solver (Newton vs fixed-point) is highly problem-dependent.
204 * Since fixed-point solvers do not require the solution of any linear
205 * systems, each iteration may be significantly less costly than their Newton
206 * counterparts. However, this can come at the cost of slower convergence (or
207 * even divergence) in comparison with Newton-like methods. These fixed-point
208 * solvers do allow for user specification of the Anderson-accelerated
209 * subspace size, $m_k$. While the required amount of solver memory grows
210 * proportionately to $m_k N$, larger values of $m_k$ may result in faster
211 * convergence.
212 *
213 * This improvement may be significant even for "small" values, e.g. $1 \leq
214 * m_k \leq 5$, and convergence may not improve (or even deteriorate) for
215 * larger values of $m_k$. While ARKode uses a Newton-based iteration as its
216 * default solver due to its increased robustness on very stiff problems, it
217 * is highly recommended that users also consider the fixed-point solver for
218 * their cases when attempting a new problem.
219 *
220 * For either the Newton or fixed-point solvers, it is well-known that both
221 * the efficiency and robustness of the algorithm intimately depends on the
222 * choice of a good initial guess. In ARKode, the initial guess for either
223 * nonlinear solution method is a predicted value $z_i(0)$ that is computed
224 * explicitly from the previously-computed data (e.g. $y_{n-2}, y_{n-1}$, and
225 * $z_j$ where $j < i$). Additional information on the specific predictor
226 * algorithms implemented in ARKode is provided in ARKode documentation.
227 *
228 * The user has to provide the implementation of at least one (or both) of the
229 * following `std::function`s:
230 * - implicit_function()
231 * - explicit_function()
232 *
233 * If the @ref GlossMassMatrix "mass matrix" is different from the identity, the user should supply
234 * - mass_times_vector() and, optionally,
235 * - mass_times_setup()
236 *
237 * If the use of a Newton method is desired, then the user should also supply
238 * jacobian_times_vector(). jacobian_times_setup() is optional.
239 *
240 * @note Although SUNDIALS can provide a difference quotient approximation
241 * of the Jacobian, this is currently not supported through this wrapper.
242 *
243 * A SUNDIALS default solver (SPGMR) is used to solve the linear systems. To
244 * use a custom linear solver for the mass matrix and/or Jacobian, set:
245 * - solve_mass() and/or
246 * - solve_linearized_system()
247 *
248 * To use a custom preconditioner with either a default or custom linear
249 * solver, set:
250 * - jacobian_preconditioner_solve() and/or mass_preconditioner_solve()
251 * and, optionally,
252 * - jacobian_preconditioner_setup() and/or mass_preconditioner_setup()
253 *
254 * Also the following functions could be rewritten. By default
255 * they do nothing, or are not required.
256 * - solver_should_restart()
257 * - get_local_tolerances()
258 *
259 * To produce output at fixed steps, set the function
260 * - output_step()
261 *
262 * Any other custom settings of the ARKODE object can be specified in
263 * - custom_setup()
264 *
265 * To provide a simple example, consider the harmonic oscillator problem:
266 * \f[
267 * \begin{split}
268 * u'' & = -k^2 u \\
269 * u (0) & = 0 \\
270 * u'(0) & = k
271 * \end{split}
272 * \f]
273 *
274 * We write it in terms of a first order ode:
275 *\f[
276 * \begin{matrix}
277 * y_0' & = y_1 \\
278 * y_1' & = - k^2 y_0
279 * \end{matrix}
280 * \f]
281 *
282 * That is $y' = A y$
283 * where
284 * \f[
285 * A \dealcoloneq
286 * \begin{pmatrix}
287 * 0 & 1 \\
288 * -k^2 &0
289 * \end{pmatrix}
290 * \f]
291 * and $y(0)=(0, k)^T$.
292 *
293 * The exact solution is $y_0(t) = \sin(k t)$, $y_1(t) = y_0'(t) = k \cos(k
294 *t)$, $y_1'(t) = -k^2 \sin(k t)$.
295 *
296 * A minimal implementation, using only explicit RK methods, is given by the
297 * following code snippet:
298 *
299 * @code
300 * using VectorType = Vector<double>;
301 *
302 * SUNDIALS::ARKode<VectorType> ode;
303 *
304 * const double k = 1.0;
305 *
306 * ode.explicit_function = [k] (const double / * time * /,
307 * const VectorType &y,
308 * VectorType &ydot)
309 * {
310 * ydot[0] = y[1];
311 * ydot[1] = -k*k*y[0];
312 * };
313 *
314 * Vector<double> y(2);
315 * y[1] = k;
316 *
317 * ode.solve_ode(y);
318 * @endcode
319 *
320 * In practice, you would of course at least want to set the end time up
321 * to which the time integrator should run. In the example code shown here,
322 * it is taken from the default value defined by ARKode::AdditionalData.
323 */
324 template <typename VectorType = Vector<double>>
325 class ARKode
326 {
327 public:
328 /**
329 * Additional parameters that can be passed to the ARKode class.
330 */
331 class AdditionalData
332 {
333 public:
334 /**
335 * Initialization parameters for ARKode.
336 *
337 * Global parameters:
338 *
339 * @param initial_time Initial time
340 * @param final_time Final time
341 * @param initial_step_size Initial step size
342 * @param output_period Desired time interval between each output
343 *
344 * Running parameters:
345 *
346 * @param minimum_step_size Minimum step size
347 * @param maximum_order Maximum ARK order
348 * @param maximum_non_linear_iterations Maximum number of nonlinear
349 * iterations
350 * @param implicit_function_is_linear Specifies that the implicit portion
351 * of the problem is linear
352 * @param implicit_function_is_time_independent Specifies that the
353 * implicit portion of the problem is linear and time independent
354 * @param mass_is_time_independent Specifies that the mass pre-factor is
355 * independent of time
356 * @param anderson_acceleration_subspace The number of vectors to use for
357 * Anderson acceleration within the packaged SUNDIALS solver.
358 *
359 * Error parameters:
360 *
361 * @param absolute_tolerance Absolute error tolerance
362 * @param relative_tolerance Relative error tolerance
363 */
364 AdditionalData(
365 // Initial parameters
366 const double initial_time = 0.0,
367 const double final_time = 1.0,
368 const double initial_step_size = 1e-2,
369 const double output_period = 1e-1,
370 // Running parameters
371 const double minimum_step_size = 1e-6,
372 const unsigned int maximum_order = 5,
373 const unsigned int maximum_non_linear_iterations = 10,
374 const bool implicit_function_is_linear = false,
375 const bool implicit_function_is_time_independent = false,
376 const bool mass_is_time_independent = false,
377 const int anderson_acceleration_subspace = 3,
378 // Error parameters
379 const double absolute_tolerance = 1e-6,
380 const double relative_tolerance = 1e-5);
381
382 /**
383 * Add all AdditionalData() parameters to the given ParameterHandler
384 * object. When the parameters are parsed from a file, the internal
385 * parameters are automatically updated.
386 *
387 * The options you pass at construction time are set as default values in
388 * the ParameterHandler object `prm`. You can later modify them by parsing
389 * a parameter file using `prm`. The values of the parameter will be
390 * updated whenever the content of `prm` is updated.
391 *
392 * Make sure that this class lives longer than `prm`. Undefined behavior
393 * will occur if you destroy this class, and then parse a parameter file
394 * using `prm`.
395 */
396 void
397 add_parameters(ParameterHandler &prm);
398
399 /**
400 * Initial time for the DAE.
401 */
402 double initial_time;
403
404 /**
405 * Final time.
406 */
407 double final_time;
408
409 /**
410 * Initial step size.
411 */
412 double initial_step_size;
413
414 /**
415 * Minimum step size.
416 */
417 double minimum_step_size;
418
419 /**
420 * Absolute error tolerance for adaptive time stepping.
421 */
422 double absolute_tolerance;
423
424 /**
425 * Relative error tolerance for adaptive time stepping.
426 */
427 double relative_tolerance;
428
429 /**
430 * Maximum order of ARK.
431 */
432 unsigned int maximum_order;
433
434 /**
435 * Desired time period between each output. The actual output time period
436 * may be adjusted by Arkode.
437 */
438 double output_period;
439
440 /**
441 * Maximum number of iterations for Newton or fixed point method during
442 * time advancement.
443 */
444 unsigned int maximum_non_linear_iterations;
445
446 /**
447 * Specify whether the implicit portion of the problem is linear.
448 */
449 bool implicit_function_is_linear;
450
451 /**
452 * Specify whether the implicit portion of the problem is linear and time
453 * independent.
454 */
455 bool implicit_function_is_time_independent;
456
457 /**
458 * Specify whether the mass pre-factor is time independent. Has no effect
459 * if no mass is specified.
460 */
461 bool mass_is_time_independent;
462
463 /**
464 * Number of subspace vectors to use for Anderson acceleration. Only
465 * meaningful if the packaged SUNDIALS fixed-point solver is used.
466 */
467 int anderson_acceleration_subspace;
468 };
469
470 /**
471 * Constructor, with class parameters set by the AdditionalData object.
472 *
473 * @param data ARKode configuration data
474 *
475 * @note With SUNDIALS 6 and later this constructor sets up logging
476 * objects to only work on the present processor (i.e., results are only
477 * communicated over MPI_COMM_SELF).
478 */
479 ARKode(const AdditionalData &data = AdditionalData());
480
481 /**
482 * Constructor.
483 *
484 * @param data ARKode configuration data
485 * @param mpi_comm MPI Communicator over which logging operations are
486 * computed. Only used in SUNDIALS 6 and newer.
487 */
488 ARKode(const AdditionalData &data, const MPI_Comm mpi_comm);
489
490 /**
491 * Destructor.
492 */
493 ~ARKode();
494
495 /**
496 * Integrate the initial value problem. This function returns the final
497 * number of computed steps.
498 *
499 * @param solution On input, this vector contains the initial condition. On
500 * output, it contains the solution at the final time.
501 */
502 unsigned int
503 solve_ode(VectorType &solution);
504
505 /**
506 * Integrate the initial value problem. Compared to the function above, this
507 * function allows to specify an @p intermediate_time for the next solution.
508 * Repeated calls of this function must use monotonously increasing values
509 * for @p intermediate_time. The last solution state is saved internally
510 * along with the @p intermediate_time and will be reused as initial
511 * condition for the next call.
512 *
513 * Users may find this function useful when integrating ARKode into an outer
514 * time loop of their own, especially when output_step() is too restrictive.
515 *
516 * @note @p intermediate_time may be larger than AdditionalData::final_time,
517 * which is ignored by this function.
518 *
519 * @param solution The final solution. If the solver restarts, either
520 * because it is the first ever solve or the flag @p reset_solver is
521 * set, the vector is also used as initial condition.
522 * @param intermediate_time The time for the incremental solution step. Must
523 * be greater than the last time that was used in a previous call to this
524 * function.
525 * @param reset_solver Optional flag to recreate all internal objects which
526 * may be desirable for spatial adaptivity methods. If set to `true`,
527 * reset() is called before solving the ODE, which sets @p solution as
528 * initial condition. This will *not* reset the stored time from previous
529 * calls to this function.
530 */
531 unsigned int
532 solve_ode_incrementally(VectorType &solution,
533 const double intermediate_time,
534 const bool reset_solver = false);
535
536 /**
537 * Clear internal memory and start with clean objects. This function is
538 * called when the simulation starts and when the user returns true to a
539 * call to solver_should_restart().
540 *
541 * By default solver_should_restart() returns false. If the user needs to
542 * implement, for example, local adaptivity in space, he or she may assign
543 * a different function to solver_should_restart() that performs all mesh
544 * changes, transfers the solution to the new mesh, and returns true.
545 *
546 * @param t The new starting time
547 * @param h The new starting time step
548 * @param y The new initial solution
549 */
550 void
551 reset(const double t, const double h, const VectorType &y);
552
553 /**
554 * Provides user access to the internally used ARKODE memory.
555 *
556 * This functionality is intended for users who wish to query additional
557 * information directly from the ARKODE integrator, refer to the ARKODE
558 * manual for the various `ARKStepGet...` functions. The `ARKStepSet...`
559 * functions should not be called since this might lead to conflicts with
560 * various settings that are performed by this ARKode object.
561 *
562 * @note If custom settings of ARKODE functionality (that are not achievable
563 * via the interface of this class) are required, the function
564 * custom_setup() should be used.
565 *
566 * @return pointer to the ARKODE memory block that can be passed to SUNDIALS
567 * functions
568 */
569 void *
570 get_arkode_memory() const;
571
572 /**
573 * A function object that users may supply and that is intended to compute
574 * the explicit part of the IVP right hand side. Sets $explicit_f = f_E(t,
575 * y)$.
576 *
577 * At least one of explicit_function() or implicit_function() must be
578 * provided. According to which one is provided, explicit, implicit, or
579 * mixed RK methods are used.
580 *
581 * @note This variable represents a
582 * @ref GlossUserProvidedCallBack "user provided callback".
583 * See there for a description of how to deal with errors and other
584 * requirements and conventions. In particular, ARKode can deal
585 * with "recoverable" errors in some circumstances, so callbacks
586 * can throw exceptions of type RecoverableUserCallbackError.
587 */
588 std::function<
589 void(const double t, const VectorType &y, VectorType &explicit_f)>
590 explicit_function;
591
592 /**
593 * A function object that users may supply and that is intended to compute
594 * the implicit part of the IVP right hand side. Sets $implicit_f = f_I(t,
595 * y)$.
596 *
597 * At least one of explicit_function() or implicit_function() must be
598 * provided. According to which one is provided, explicit, implicit, or
599 * mixed RK methods are used.
600 *
601 * @note This variable represents a
602 * @ref GlossUserProvidedCallBack "user provided callback".
603 * See there for a description of how to deal with errors and other
604 * requirements and conventions. In particular, ARKode can deal
605 * with "recoverable" errors in some circumstances, so callbacks
606 * can throw exceptions of type RecoverableUserCallbackError.
607 */
608 std::function<void(const double t, const VectorType &y, VectorType &res)>
609 implicit_function;
610
611 /**
612 * A function object that users may supply and that is intended to compute
613 * the product of the @ref GlossMassMatrix "mass matrix" with a given vector `v`. This function
614 * will be called by ARKode (possibly several times) after
615 * mass_times_setup() has been called at least once. ARKode tries to do its
616 * best to call mass_times_setup() the minimum amount of times.
617 *
618 * A call to this function should store in `Mv` the result of $M$
619 * applied to `v`.
620 *
621 * @note This variable represents a
622 * @ref GlossUserProvidedCallBack "user provided callback".
623 * See there for a description of how to deal with errors and other
624 * requirements and conventions. In particular, ARKode can deal
625 * with "recoverable" errors in some circumstances, so callbacks
626 * can throw exceptions of type RecoverableUserCallbackError.
627 */
628 std::function<void(const double t, const VectorType &v, VectorType &Mv)>
629 mass_times_vector;
630
631 /**
632 * A function object that users may supply and that is intended to set up
633 * the @ref GlossMassMatrix "mass matrix". This function is called by ARKode any time a mass
634 * matrix update is required. The user should compute the mass matrix (or
635 * update all the variables that allow the application of the mass matrix).
636 * This function is guaranteed to be called by ARKode at least once, before
637 * any call to mass_times_vector().
638 *
639 * ARKode supports the case where the mass matrix may depend on time, but
640 * not the case where the mass matrix depends on the solution itself.
641 *
642 * If the user does not provide a mass_times_vector() function, then the
643 * identity is used. If the mass_times_setup() function is not provided,
644 * then mass_times_vector() should do all the work by itself.
645 *
646 * If the user uses a matrix-based computation of the mass matrix, then
647 * this is the right place where an assembly routine should be called to
648 * assemble the matrix. Subsequent calls (possibly more than one) to
649 * mass_times_vector() can assume that this function has been called at
650 * least once.
651 *
652 * @note No assumption is made by this interface on what the user
653 * should do in this function. ARKode only assumes that after a call to
654 * mass_times_setup() it is possible to call mass_times_vector().
655 *
656 * @param t The current evaluation time
657 *
658 * @note This variable represents a
659 * @ref GlossUserProvidedCallBack "user provided callback".
660 * See there for a description of how to deal with errors and other
661 * requirements and conventions. In particular, ARKode can deal
662 * with "recoverable" errors in some circumstances, so callbacks
663 * can throw exceptions of type RecoverableUserCallbackError.
664 */
665 std::function<void(const double t)> mass_times_setup;
666
667 /**
668 * A function object that users may supply and that is intended to compute
669 * the product of the Jacobian matrix with a given vector `v`. The Jacobian
670 * here refers to $J=\frac{\partial f_I}{\partial y}$, i.e., the Jacobian of
671 * the user-specified implicit_function.
672 *
673 * A call to this function should store in `Jv` the result of $J$
674 * applied to `v`.
675 *
676 * Arguments to the function are
677 *
678 * @param[in] v The vector to be multiplied by the Jacobian
679 * @param[out] Jv The vector to be filled with the product J*v
680 * @param[in] t The current time
681 * @param[in] y The current $y$ vector for the current ARKode internal
682 * step
683 * @param[in] fy The current value of the implicit right-hand side at y,
684 * $f_I (t_n, y)$.
685 *
686 * @note This variable represents a
687 * @ref GlossUserProvidedCallBack "user provided callback".
688 * See there for a description of how to deal with errors and other
689 * requirements and conventions. In particular, ARKode can deal
690 * with "recoverable" errors in some circumstances, so callbacks
691 * can throw exceptions of type RecoverableUserCallbackError.
692 */
693 std::function<void(const VectorType &v,
694 VectorType &Jv,
695 const double t,
696 const VectorType &y,
697 const VectorType &fy)>
698 jacobian_times_vector;
699
700 /**
701 * A function object that users may supply and that is intended to set up
702 * all data necessary for the application of jacobian_times_vector(). This
703 * function is called by ARKode any time a Jacobian update is required.
704 * The user should compute the Jacobian (or update all the variables that
705 * allow the application of Jacobian). This function is guaranteed to
706 * be called by ARKode at least once, before any call to
707 * jacobian_times_vector().
708 *
709 * If the jacobian_times_setup() function is not provided, then
710 * jacobian_times_vector() should do all the work by itself.
711 *
712 * If the user uses a matrix based computation of the Jacobian, then this is
713 * the right place where an assembly routine should be called to assemble
714 * the matrix. Subsequent calls (possibly more than one) to
715 * jacobian_times_vector() can assume that this function has been called at
716 * least once.
717 *
718 * @note No assumption is made by this interface on what the user
719 * should do in this function. ARKode only assumes that after a call to
720 * jacobian_times_setup() it is possible to call jacobian_times_vector().
721 *
722 * @param t The current time
723 * @param y The current ARKode internal solution vector $y$
724 * @param fy The implicit right-hand side function evaluated at the
725 * current time $t$ and state $y$, i.e., $f_I(y,t)$
726 *
727 * @note This variable represents a
728 * @ref GlossUserProvidedCallBack "user provided callback".
729 * See there for a description of how to deal with errors and other
730 * requirements and conventions. In particular, ARKode can deal
731 * with "recoverable" errors in some circumstances, so callbacks
732 * can throw exceptions of type RecoverableUserCallbackError.
733 */
734 std::function<
735 void(const double t, const VectorType &y, const VectorType &fy)>
736 jacobian_times_setup;
737
738 /**
739 * A LinearSolveFunction object that users may supply and that is intended
740 * to solve the linearized system $Ax=b$, where $A = M-\gamma J$ is the
741 * Jacobian of the nonlinear residual. The application of the @ref GlossMassMatrix "mass matrix"
742 * $M$ and Jacobian $J$ are known through the functions mass_times_vector()
743 * and jacobian_times_vector() and $\gamma$ is a factor provided by
744 * SUNDIALS. The matrix-vector product $Ax$ is encoded in the supplied
745 * SundialsOperator. If a preconditioner was set through
746 * jacobian_preconditioner_solve(), it is encoded in the
747 * SundialsPreconditioner. If no preconditioner was supplied this way, the
748 * preconditioner is the identity matrix, i.e., no preconditioner. The user
749 * is free to use a custom preconditioner in this function object that is
750 * not supplied through SUNDIALS.
751 *
752 * If you do not specify a solve_linearized_system() function, then a
753 * SUNDIALS packaged SPGMR solver with default settings is used.
754 *
755 * For more details on the function type refer to LinearSolveFunction.
756 *
757 * @note This variable represents a
758 * @ref GlossUserProvidedCallBack "user provided callback".
759 * See there for a description of how to deal with errors and other
760 * requirements and conventions. In particular, ARKode can deal
761 * with "recoverable" errors in some circumstances, so callbacks
762 * can throw exceptions of type RecoverableUserCallbackError.
763 */
764 LinearSolveFunction<VectorType> solve_linearized_system;
765
766 /**
767 * A LinearSolveFunction object that users may supply and that is intended
768 * to solve the mass system $Mx=b$. The matrix-vector product $Mx$ is
769 * encoded in the supplied SundialsOperator. If a preconditioner was set
770 * through mass_preconditioner_solve(), it is encoded in the
771 * SundialsPreconditioner. If no preconditioner was supplied this way, the
772 * preconditioner is the identity matrix, i.e., no preconditioner. The user
773 * is free to use a custom preconditioner in this function object that is
774 * not supplied through SUNDIALS.
775 *
776 * The user must specify this function if a non-identity mass matrix is used
777 * and applied in mass_times_vector().
778 *
779 * For more details on the function type refer to LinearSolveFunction.
780 *
781 * @note This variable represents a
782 * @ref GlossUserProvidedCallBack "user provided callback".
783 * See there for a description of how to deal with errors and other
784 * requirements and conventions. In particular, ARKode can deal
785 * with "recoverable" errors in some circumstances, so callbacks
786 * can throw exceptions of type RecoverableUserCallbackError.
787 */
788 LinearSolveFunction<VectorType> solve_mass;
789
790 /**
791 * A function object that users may supply to either pass a preconditioner
792 * to a SUNDIALS built-in solver or to apply a custom preconditioner within
793 * the user's own linear solve specified in solve_linearized_system().
794 *
795 * This function should compute the solution to the preconditioner equation
796 * $Pz=r$ and store it in @p z. In this equation $P$ should approximate the
797 * Jacobian $M-\gamma J$ of the nonlinear system.
798 *
799 * @param[in] t The current time
800 * @param[in] y The current $y$ vector for the current ARKode internal
801 * step
802 * @param[in] fy The current value of the implicit right-hand side at y,
803 * $f_I (t_n, y)$.
804 * @param[in] r The right-hand side of the preconditioner equation
805 * @param[out] z The solution of applying the preconditioner, i.e., solving
806 * $Pz=r$
807 * @param[in] gamma The value $\gamma$ in the preconditioner equation
808 * @param[in] tol The tolerance up to which the system should be solved
809 * @param[in] lr An input flag indicating whether the preconditioner solve
810 * is to use the left preconditioner (lr = 1) or the right preconditioner
811 * (lr = 2). Only relevant if used with a SUNDIALS packaged solver. If
812 * used with a custom solve_mass() function this will be set to zero.
813 *
814 * @note This variable represents a
815 * @ref GlossUserProvidedCallBack "user provided callback".
816 * See there for a description of how to deal with errors and other
817 * requirements and conventions. In particular, ARKode can deal
818 * with "recoverable" errors in some circumstances, so callbacks
819 * can throw exceptions of type RecoverableUserCallbackError.
820 */
821 std::function<void(const double t,
822 const VectorType &y,
823 const VectorType &fy,
824 const VectorType &r,
825 VectorType &z,
826 const double gamma,
827 const double tol,
828 const int lr)>
829 jacobian_preconditioner_solve;
830
831 /**
832 * A function object that users may supply to set up a preconditioner
833 * specified in jacobian_preconditioner_solve().
834 *
835 * This function should prepare the solution of the preconditioner equation
836 * $Pz=r$. In this equation $P$ should approximate the Jacobian $M-\gamma J$
837 * of the nonlinear system.
838 *
839 * If the jacobian_preconditioner_setup() function is not provided, then
840 * jacobian_preconditioner_solve() should do all the work by itself.
841 *
842 * @note No assumption is made by this interface on what the user
843 * should do in this function. ARKode only assumes that after a call to
844 * jacobian_preconditioner_setup() it is possible to call
845 * jacobian_preconditioner_solve().
846 *
847 * @param[in] t The current time
848 * @param[in] y The current $y$ vector for the current ARKode internal
849 * step
850 * @param[in] fy The current value of the implicit right-hand side at y,
851 * $f_I (t_n, y)$.
852 * @param[in] jok An input flag indicating whether the Jacobian-related
853 * data needs to be updated. The jok argument provides for the reuse of
854 * Jacobian data in the preconditioner solve function. When jok =
855 * SUNFALSE, the Jacobian-related data should be recomputed from scratch.
856 * When jok = SUNTRUE the Jacobian data, if saved from the previous call
857 * to this function, can be reused (with the current value of gamma). A
858 * call with jok = SUNTRUE can only occur after a call with jok =
859 * SUNFALSE.
860 * @param[out] jcur On output this should be set to SUNTRUE if Jacobian data
861 * was recomputed, or set to SUNFALSE if Jacobian data was not recomputed,
862 * but saved data was still reused.
863 * @param[in] gamma The value $\gamma$ in $M-\gamma J$. The preconditioner
864 * should approximate the inverse of this matrix.
865 *
866 * @note This variable represents a
867 * @ref GlossUserProvidedCallBack "user provided callback".
868 * See there for a description of how to deal with errors and other
869 * requirements and conventions. In particular, ARKode can deal
870 * with "recoverable" errors in some circumstances, so callbacks
871 * can throw exceptions of type RecoverableUserCallbackError.
872 */
873 std::function<void(const double t,
874 const VectorType &y,
875 const VectorType &fy,
876 const int jok,
877 int &jcur,
878 const double gamma)>
879 jacobian_preconditioner_setup;
880
881 /**
882 * A function object that users may supply to either pass a preconditioner
883 * to a SUNDIALS built-in solver or to apply a custom preconditioner within
884 * the user's own linear solve specified in solve_mass().
885 *
886 * This function should compute the solution to the preconditioner equation
887 * $Pz=r$ and store it in @p z. In this equation $P$ should approximate the
888 * @ref GlossMassMatrix "mass matrix" $M$.
889 *
890 * @param[in] t The current time
891 * @param[in] r The right-hand side of the preconditioner equation
892 * @param[out] z The solution of applying the preconditioner, i.e., solving
893 * $Pz=r$
894 * @param[in] gamma The value $\gamma$ in the preconditioner equation
895 * @param[in] tol The tolerance up to which the system should be solved
896 * @param[in] lr An input flag indicating whether the preconditioner solve
897 * is to use the left preconditioner (lr = 1) or the right preconditioner
898 * (lr = 2). Only relevant if used with a SUNDIALS packaged solver. If
899 * used with a custom solve_mass() function this will be set to zero.
900 *
901 * @note This variable represents a
902 * @ref GlossUserProvidedCallBack "user provided callback".
903 * See there for a description of how to deal with errors and other
904 * requirements and conventions. In particular, ARKode can deal
905 * with "recoverable" errors in some circumstances, so callbacks
906 * can throw exceptions of type RecoverableUserCallbackError.
907 */
908 std::function<void(const double t,
909 const VectorType &r,
910 VectorType &z,
911 const double tol,
912 const int lr)>
913 mass_preconditioner_solve;
914
915 /**
916 * A function object that users may supply to set up a preconditioner
917 * specified in mass_preconditioner_solve().
918 *
919 * This function should prepare the solution of the preconditioner equation
920 * $Pz=r$. In this equation $P$ should approximate the @ref GlossMassMatrix "mass matrix" $M$.
921 *
922 * If the mass_preconditioner_setup() function is not provided, then
923 * mass_preconditioner_solve() should do all the work by itself.
924 *
925 * @note No assumption is made by this interface on what the user
926 * should do in this function. ARKode only assumes that after a call to
927 * mass_preconditioner_setup() it is possible to call
928 * mass_preconditioner_solve().
929 *
930 * @param[in] t The current time
931 *
932 * @note This variable represents a
933 * @ref GlossUserProvidedCallBack "user provided callback".
934 * See there for a description of how to deal with errors and other
935 * requirements and conventions. In particular, ARKode can deal
936 * with "recoverable" errors in some circumstances, so callbacks
937 * can throw exceptions of type RecoverableUserCallbackError.
938 */
939 std::function<void(const double t)> mass_preconditioner_setup;
940
941 /**
942 * A function object that users may supply and that is intended to
943 * postprocess the solution. This function is called by ARKode at fixed
944 * time increments (every `output_period` time units), and it is passed a
945 * polynomial interpolation of the solution, computed using the current ARK
946 * order and the (internally stored) previously computed solution steps.
947 *
948 * @note It is well possible that internally ARKode computes a time
949 * step which is much larger than the `output_period` step, and therefore
950 * calls this function consecutively several times by simply performing
951 * all intermediate interpolations. There is no relationship between how
952 * many times this function is called and how many time steps have
953 * actually been computed.
954 */
955 std::function<void(const double t,
956 const VectorType &sol,
957 const unsigned int step_number)>
958 output_step;
959
960 /**
961 * A function object that users may supply and that is intended to evaluate
962 * whether the solver should be restarted (for example because the number of
963 * degrees of freedom has changed).
964 *
965 * This function is supposed to perform all operations that are necessary
966 * in `sol` to make sure that the resulting vectors are consistent, and of
967 * the correct final size.
968 *
969 * For example, one may decide that a local refinement is necessary at time
970 * t. This function should then return true, and change the dimension of
971 * `sol` to reflect the new dimension. Since ARKode does not know about the
972 * new dimension, an internal reset is necessary.
973 *
974 * The default implementation simply returns `false`, i.e., no restart is
975 * performed during the evolution.
976 */
977 std::function<bool(const double t, VectorType &sol)> solver_should_restart;
978
979 /**
980 * A function object that users may supply and that is intended to return a
981 * vector whose components are the weights used by ARKode to compute the
982 * vector norm. The implementation of this function is optional, and it is
983 * used only if implemented.
984 */
985 std::function<VectorType &()> get_local_tolerances;
986
987 /**
988 * A function object that users may supply and which is intended to perform
989 * custom settings on the supplied @p arkode_mem object. Refer to the
990 * SUNDIALS documentation for valid options.
991 *
992 * For instance, the following code attaches two files for diagnostic and
993 * error output of the internal ARKODE implementation:
994 *
995 * @code
996 * ode.custom_setup = [&](void *arkode_mem) {
997 * ARKStepSetErrFile(arkode_mem, errfile);
998 * ARKStepSetDiagnostics(arkode_mem, diagnostics_file);
999 * };
1000 * @endcode
1001 *
1002 * @note This function will be called at the end of all other set up right
1003 * before the actual time evolution is started or continued with
1004 * solve_ode(). This function is also called when the solver is restarted,
1005 * see solver_should_restart(). Consult the SUNDIALS manual to see which
1006 * options are still available at this point.
1007 *
1008 * @param arkode_mem pointer to the ARKODE memory block which can be used
1009 * for custom calls to `ARKStepSet...` methods.
1010 */
1011 std::function<void(void *arkode_mem)> custom_setup;
1012
1013 private:
1014 /**
1015 * Throw an exception when a function with the given name is not
1016 * implemented.
1017 */
1018 DeclException1(ExcFunctionNotProvided,
1019 std::string,
1020 << "Please provide an implementation for the function \""
1021 << arg1 << "\"");
1022
1023 /**
1024 * Internal routine to call ARKode repeatedly.
1025 */
1026 unsigned int
1027 do_evolve_time(VectorType &solution,
1028 dealii::DiscreteTime &time,
1029 const bool do_reset);
1030
1031 /**
1032 * Set up the (non)linear solver and preconditioners in the ARKODE memory
1033 * object based on the user-specified functions.
1034 * @param solution The solution vector which is used as a template to create
1035 * new vectors.
1036 */
1037 void
1038 setup_system_solver(const VectorType &solution);
1039
1040 /**
1041 * Set up the solver and preconditioner for a non-identity @ref GlossMassMatrix "mass matrix" in
1042 * the ARKODE memory object based on the user-specified functions.
1043 * @param solution The solution vector which is used as a template to create
1044 * new vectors.
1045 */
1046 void
1047 setup_mass_solver(const VectorType &solution);
1048
1049 /**
1050 * This function is executed at construction time to set the
1051 * std::function above to trigger an assert if they are not
1052 * implemented.
1053 */
1054 void
1055 set_functions_to_trigger_an_assert();
1056
1057 /**
1058 * ARKode configuration data.
1059 */
1060 AdditionalData data;
1061
1062 /**
1063 * ARKode memory object.
1064 */
1065 void *arkode_mem;
1066
1067 # if DEAL_II_SUNDIALS_VERSION_GTE(6, 0, 0)
1068 /**
1069 * A context object associated with the ARKode solver.
1070 */
1071 SUNContext arkode_ctx;
1072 # endif
1073
1074 /**
1075 * MPI communicator. Only used for SUNDIALS' logging routines - the actual
1076 * solve routines will use the communicator provided by the vector class.
1077 */
1078 MPI_Comm mpi_communicator;
1079
1080 /**
1081 * The final time in the last call to solve_ode().
1082 */
1083 double last_end_time;
1084
1085 std::unique_ptr<internal::LinearSolverWrapper<VectorType>> linear_solver;
1086 std::unique_ptr<internal::LinearSolverWrapper<VectorType>> mass_solver;
1087
1088 /**
1089 * A pointer to any exception that may have been thrown in user-defined
1090 * call-backs and that we have to deal after the KINSOL function we call
1091 * has returned.
1092 */
1093 mutable std::exception_ptr pending_exception;
1094
1095 # ifdef DEAL_II_WITH_PETSC
1096 # ifdef PETSC_USE_COMPLEX
1097 static_assert(!std::is_same_v<VectorType, PETScWrappers::MPI::Vector>,
1098 "Sundials does not support complex scalar types, "
1099 "but PETSc is configured to use a complex scalar type!");
1100
1101 static_assert(!std::is_same_v<VectorType, PETScWrappers::MPI::BlockVector>,
1102 "Sundials does not support complex scalar types, "
1103 "but PETSc is configured to use a complex scalar type!");
1104 # endif // PETSC_USE_COMPLEX
1105 # endif // DEAL_II_WITH_PETSC
1106 };
1107
1108
1109 /**
1110 * Handle ARKode exceptions.
1111 */
1112 DeclException1(ExcARKodeError,
1113 int,
1114 << "One of the SUNDIALS ARKode internal functions "
1115 << " returned a negative error code: " << arg1
1116 << ". Please consult SUNDIALS manual.");
1117
1118
1119 template <typename VectorType>
1120 ARKode<VectorType>::AdditionalData::AdditionalData(
1121 // Initial parameters
1122 const double initial_time,
1123 const double final_time,
1124 const double initial_step_size,
1125 const double output_period,
1126 // Running parameters
1127 const double minimum_step_size,
1128 const unsigned int maximum_order,
1129 const unsigned int maximum_non_linear_iterations,
1130 const bool implicit_function_is_linear,
1131 const bool implicit_function_is_time_independent,
1132 const bool mass_is_time_independent,
1133 const int anderson_acceleration_subspace,
1134 // Error parameters
1135 const double absolute_tolerance,
1136 const double relative_tolerance)
1137 : initial_time(initial_time)
1138 , final_time(final_time)
1139 , initial_step_size(initial_step_size)
1140 , minimum_step_size(minimum_step_size)
1141 , absolute_tolerance(absolute_tolerance)
1142 , relative_tolerance(relative_tolerance)
1143 , maximum_order(maximum_order)
1144 , output_period(output_period)
1145 , maximum_non_linear_iterations(maximum_non_linear_iterations)
1146 , implicit_function_is_linear(implicit_function_is_linear)
1147 , implicit_function_is_time_independent(
1148 implicit_function_is_time_independent)
1149 , mass_is_time_independent(mass_is_time_independent)
1150 , anderson_acceleration_subspace(anderson_acceleration_subspace)
1151 {}
1152
1153
1154
1155 template <typename VectorType>
1156 void
1157 ARKode<VectorType>::AdditionalData::add_parameters(ParameterHandler &prm)
1158 {
1159 prm.add_parameter("Initial time", initial_time);
1160 prm.add_parameter("Final time", final_time);
1161 prm.add_parameter("Time interval between each output", output_period);
1162 prm.enter_subsection("Running parameters");
1163 prm.add_parameter("Initial step size", initial_step_size);
1164 prm.add_parameter("Minimum step size", minimum_step_size);
1165 prm.add_parameter("Maximum order of ARK", maximum_order);
1166 prm.add_parameter("Maximum number of nonlinear iterations",
1167 maximum_non_linear_iterations);
1168 prm.add_parameter("Implicit function is linear",
1169 implicit_function_is_linear);
1170 prm.add_parameter("Implicit function is time independent",
1171 implicit_function_is_time_independent);
1172 prm.add_parameter("Mass is time independent", mass_is_time_independent);
1173 prm.add_parameter("Anderson-acceleration subspace",
1174 anderson_acceleration_subspace);
1175 prm.leave_subsection();
1176 prm.enter_subsection("Error control");
1177 prm.add_parameter("Absolute error tolerance", absolute_tolerance);
1178 prm.add_parameter("Relative error tolerance", relative_tolerance);
1179 prm.leave_subsection();
1180 }
1181
1182 } // namespace SUNDIALS
1183
1184 DEAL_II_NAMESPACE_CLOSE
1185
1186 #else
1187
1188 // Make sure the scripts that create the C++20 module input files have
1189 // something to latch on if the preprocessor #ifdef above would
1190 // otherwise lead to an empty content of the file.
1191 DEAL_II_NAMESPACE_OPEN
1192 DEAL_II_NAMESPACE_CLOSE
1193
1194 #endif
1195
1196
1197 #endif