deal.II version GIT relicensing-7155-g69b6eb7651 2026-11-23 20:20:01+00:00
\(\newcommand{\dealvcentcolon}{\mathrel{\mathop{:}}}\) \(\newcommand{\dealcoloneq}{\dealvcentcolon\mathrel{\mkern-1.2mu}=}\) \(\newcommand{\jump}[1]{\left[\!\left[ #1 \right]\!\right]}\) \(\newcommand{\average}[1]{\left\{\!\left\{ #1 \right\}\!\right\}}\)
Loading...
Searching...
No Matches
ida.cc
Go to the documentation of this file.
1// -----------------------------------------------------------------------------
2//
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception OR LGPL-2.1-or-later
4// Copyright (C) 2017 - 2026 by the deal.II authors
5//
6// This file is part of the deal.II library.
7//
8// Detailed license information governing the source code and contributions
9// can be found in LICENSE.md and CONTRIBUTING.md at the top level directory.
10//
11// -----------------------------------------------------------------------------
12
13#include <deal.II/base/config.h>
14
16
18
19#ifdef DEAL_II_WITH_SUNDIALS
21
23
26# ifdef DEAL_II_WITH_TRILINOS
29# endif
30# ifdef DEAL_II_WITH_PETSC
33# endif
34
37
38# include <idas/idas.h>
39# if DEAL_II_SUNDIALS_VERSION_GTE(6, 0, 0)
40# include <sundials/sundials_context.h>
41# endif
42
43# include <iomanip>
44# include <iostream>
45
46
47#endif // DEAL_II_WITH_SUNDIALS
48
50
51#ifdef DEAL_II_WITH_SUNDIALS
52
53namespace SUNDIALS
54{
55 template <typename VectorType>
57 : IDA(data, MPI_COMM_SELF)
58 {}
59
60
61
62 template <typename VectorType>
64 : data(data)
65 , ida_mem(nullptr)
67 , ida_ctx(nullptr)
68# endif
69 , mpi_communicator(mpi_comm)
70 , pending_exception(nullptr)
71 {
73
74 // SUNDIALS will always duplicate communicators if we provide them. This
75 // can cause problems if SUNDIALS is configured with MPI and we pass along
76 // MPI_COMM_SELF in a serial application as MPI won't be
77 // initialized. Hence, work around that by just not providing a
78 // communicator in that case.
79# if DEAL_II_SUNDIALS_VERSION_GTE(7, 0, 0)
80 const int status =
81 SUNContext_Create(mpi_communicator == MPI_COMM_SELF ? SUN_COMM_NULL :
83 &ida_ctx);
84 (void)status;
85 AssertIDA(status);
86# elif DEAL_II_SUNDIALS_VERSION_GTE(6, 0, 0)
87 const int status =
88 SUNContext_Create(mpi_communicator == MPI_COMM_SELF ? nullptr :
90 &ida_ctx);
91 (void)status;
92 AssertIDA(status);
93# endif
94 }
95
96
97
98 template <typename VectorType>
100 {
101 IDAFree(&ida_mem);
102# if DEAL_II_SUNDIALS_VERSION_GTE(6, 0, 0)
103 const int status = SUNContext_Free(&ida_ctx);
104 (void)status;
105 AssertIDA(status);
106# endif
107
108 Assert(pending_exception == nullptr, ExcInternalError());
109 }
110
111
112
113 template <typename VectorType>
114 unsigned int
115 IDA<VectorType>::solve_dae(VectorType &solution, VectorType &solution_dot)
116 {
117 double t = data.initial_time;
118 double h = data.initial_step_size;
119 unsigned int step_number = 0;
120
121 int status;
122 (void)status;
123
124 reset(data.initial_time, data.initial_step_size, solution, solution_dot);
125
126 // The solution is stored in
127 // solution. Here we take only a
128 // view of it.
129
130 double next_time = data.initial_time;
131
132 output_step(0, solution, solution_dot, 0);
133
134 while (t < data.final_time)
135 {
136 next_time += data.output_period;
137
138 auto yy = internal::make_nvector_view(solution
139# if !DEAL_II_SUNDIALS_VERSION_LT(6, 0, 0)
140 ,
141 ida_ctx
142# endif
143 );
144 auto yp = internal::make_nvector_view(solution_dot
145# if !DEAL_II_SUNDIALS_VERSION_LT(6, 0, 0)
146 ,
147 ida_ctx
148# endif
149 );
150
151 // Execute time steps. If we ended up with a pending exception,
152 // see if it was recoverable; if it was, and if IDA recovered,
153 // just continue on. If IDA did not recover, rethrow the exception.
154 // Do the same if the exception was not recoverable.
155 status = IDASolve(ida_mem, next_time, &t, yy, yp, IDA_NORMAL);
156 if (pending_exception)
157 {
158 try
159 {
160 std::rethrow_exception(pending_exception);
161 }
162 catch (const RecoverableUserCallbackError &exc)
163 {
164 pending_exception = nullptr;
165 if (status == 0)
166 /* just eat the exception and continue */;
167 else
168 throw;
169 }
170 catch (...)
171 {
172 pending_exception = nullptr;
173 throw;
174 }
175 }
176 AssertIDA(status);
177
178 status = IDAGetLastStep(ida_mem, &h);
179 AssertIDA(status);
180
181 while (solver_should_restart(t, solution, solution_dot))
182 reset(t, h, solution, solution_dot);
183
184 ++step_number;
185
186 output_step(t, solution, solution_dot, step_number);
187 }
188 long int n_steps;
189 status = IDAGetNumSteps(ida_mem, &n_steps);
190 AssertIDA(status);
191 return n_steps;
192 }
193
194
195
196 template <typename VectorType>
197 void
198 IDA<VectorType>::reset(const double current_time,
199 const double current_time_step,
200 VectorType &solution,
201 VectorType &solution_dot)
202 {
203 bool first_step = (current_time == data.initial_time);
204
205 int status;
206 (void)status;
207
208# if DEAL_II_SUNDIALS_VERSION_GTE(7, 0, 0)
209 status = SUNContext_Free(&ida_ctx);
210 AssertIDA(status);
211
212 // Same comment applies as in class constructor:
213 status =
214 SUNContext_Create(mpi_communicator == MPI_COMM_SELF ? SUN_COMM_NULL :
215 mpi_communicator,
216 &ida_ctx);
217 AssertIDA(status);
218# elif DEAL_II_SUNDIALS_VERSION_GTE(6, 0, 0)
219 status = SUNContext_Free(&ida_ctx);
220 AssertIDA(status);
221
222 // Same comment applies as in class constructor:
223 status =
224 SUNContext_Create(mpi_communicator == MPI_COMM_SELF ? nullptr :
225 &mpi_communicator,
226 &ida_ctx);
227 AssertIDA(status);
228# endif
229
230 if (ida_mem)
231 {
232 IDAFree(&ida_mem);
233 // Initialization is version-dependent: do that in a moment
234 }
235
236# if DEAL_II_SUNDIALS_VERSION_LT(6, 0, 0)
237 ida_mem = IDACreate();
238# else
239 ida_mem = IDACreate(ida_ctx);
240# endif
241
242 auto yy = internal::make_nvector_view(solution
243# if !DEAL_II_SUNDIALS_VERSION_LT(6, 0, 0)
244 ,
245 ida_ctx
246# endif
247 );
248 auto yp = internal::make_nvector_view(solution_dot
249# if !DEAL_II_SUNDIALS_VERSION_LT(6, 0, 0)
250 ,
251 ida_ctx
252# endif
253 );
254
255 status = IDAInit(
256 ida_mem,
257 [](SUNDIALS::realtype tt,
258 N_Vector yy,
259 N_Vector yp,
260 N_Vector rr,
261 void *user_data) -> int {
262 IDA<VectorType> &solver = *static_cast<IDA<VectorType> *>(user_data);
263
264 auto *src_yy = internal::unwrap_nvector_const<VectorType>(yy);
265 auto *src_yp = internal::unwrap_nvector_const<VectorType>(yp);
266 auto *residual = internal::unwrap_nvector<VectorType>(rr);
267
269 solver.residual,
270 solver.pending_exception,
271 tt,
272 *src_yy,
273 *src_yp,
274 *residual);
275 },
276 current_time,
277 yy,
278 yp);
279 AssertIDA(status);
280 if (get_local_tolerances)
281 {
282 const auto abs_tols = internal::make_nvector_view(get_local_tolerances()
283# if !DEAL_II_SUNDIALS_VERSION_LT(6, 0, 0)
284 ,
285 ida_ctx
286# endif
287 );
288 status = IDASVtolerances(ida_mem, data.relative_tolerance, abs_tols);
289 AssertIDA(status);
290 }
291 else
292 {
293 status = IDASStolerances(ida_mem,
294 data.relative_tolerance,
295 data.absolute_tolerance);
296 AssertIDA(status);
297 }
298
299 status = IDASetInitStep(ida_mem, current_time_step);
300 AssertIDA(status);
301
302 status = IDASetUserData(ida_mem, this);
303 AssertIDA(status);
304
305 if (data.ic_type == AdditionalData::use_y_diff ||
306 data.reset_type == AdditionalData::use_y_diff ||
307 data.ignore_algebraic_terms_for_errors)
308 {
309 VectorType diff_comp_vector(solution);
310 diff_comp_vector = 0.0;
311 for (const auto &component : differential_components())
312 diff_comp_vector[component] = 1.0;
313 diff_comp_vector.compress(VectorOperation::insert);
314
315 const auto diff_id = internal::make_nvector_view(diff_comp_vector
316# if !DEAL_II_SUNDIALS_VERSION_LT(6, 0, 0)
317 ,
318 ida_ctx
319# endif
320 );
321 status = IDASetId(ida_mem, diff_id);
322 AssertIDA(status);
323 }
324
325 status = IDASetSuppressAlg(ida_mem, data.ignore_algebraic_terms_for_errors);
326 AssertIDA(status);
327
328 // status = IDASetMaxNumSteps(ida_mem, max_steps);
329 status = IDASetStopTime(ida_mem, data.final_time);
330 AssertIDA(status);
331
332 status = IDASetMaxNumSteps(ida_mem, data.maximum_number_of_steps);
333 AssertIDA(status);
334 status = IDASetMaxStep(ida_mem, data.maximum_step_size);
335 AssertIDA(status);
336# if DEAL_II_SUNDIALS_VERSION_GTE(6, 2, 0)
337 status = IDASetMinStep(ida_mem, data.minimum_step_size);
338 AssertIDA(status);
339# endif
340 status = IDASetMaxErrTestFails(ida_mem, data.maximum_error_test_failures);
341 AssertIDA(status);
342 status = IDASetMaxConvFails(ida_mem, data.maximum_convergence_failures);
343 AssertIDA(status);
344 status =
345 IDASetNonlinConvCoef(ida_mem, data.nonlinear_convergence_coefficient);
346 AssertIDA(status);
347
348 status = IDASetMaxNonlinIters(ida_mem, data.maximum_non_linear_iterations);
349 AssertIDA(status);
350
351 // Initialize solver
352 SUNMatrix J = nullptr;
353 SUNLinearSolver LS = nullptr;
354
355 // and attach it to the SUNLinSol object. The functions that will get
356 // called do not actually receive the IDAMEM object, just the LS
357 // object, so we have to store a pointer to the current
358 // object in the LS object
359# if DEAL_II_SUNDIALS_VERSION_LT(6, 0, 0)
360 LS = SUNLinSolNewEmpty();
361# else
362 LS = SUNLinSolNewEmpty(ida_ctx);
363# endif
364
365 LS->content = this;
366
367 LS->ops->gettype = [](SUNLinearSolver /*ignored*/) -> SUNLinearSolver_Type {
368 return SUNLINEARSOLVER_MATRIX_ITERATIVE;
369 };
370
371 LS->ops->free = [](SUNLinearSolver LS) -> int {
372 if (LS->content)
373 {
374 LS->content = nullptr;
375 }
376 if (LS->ops)
377 {
378 std::free(LS->ops);
379 LS->ops = nullptr;
380 }
381 std::free(LS);
382 LS = nullptr;
383 return 0;
384 };
385
386 AssertThrow(solve_with_jacobian,
387 ExcFunctionNotProvided("solve_with_jacobian"));
388 LS->ops->solve = [](SUNLinearSolver LS,
389 SUNMatrix /*ignored*/,
390 N_Vector x,
391 N_Vector b,
392 SUNDIALS::realtype tol) -> int {
393 IDA<VectorType> &solver = *static_cast<IDA<VectorType> *>(LS->content);
394
395 auto *src_b = internal::unwrap_nvector_const<VectorType>(b);
396 auto *dst_x = internal::unwrap_nvector<VectorType>(x);
398 solver.solve_with_jacobian,
399 solver.pending_exception,
400 *src_b,
401 *dst_x,
402 tol);
403 };
404
405 // When we set an iterative solver IDA requires that resid is provided. From
406 // SUNDIALS docs If an iterative method computes the preconditioned initial
407 // residual and returns with a successful solve without performing any
408 // iterations (i.e., either the initial guess or the preconditioner is
409 // sufficiently accurate), then this optional routine may be called by the
410 // SUNDIALS package. This routine should return the N_Vector containing the
411 // preconditioned initial residual vector.
412 LS->ops->resid = [](SUNLinearSolver /*ignored*/) -> N_Vector {
413 return nullptr;
414 };
415 // When we set an iterative solver IDA requires that last number of
416 // iteration is provided. Since we can't know what kind of solver the user
417 // has provided we set 1. This is clearly suboptimal.
418 LS->ops->numiters = [](SUNLinearSolver /*ignored*/) -> int { return 1; };
419 // Even though we don't use it, IDA still wants us to set some
420 // kind of matrix object for the nonlinear solver. This is because
421 // if we don't set it, it won't call the functions that set up
422 // the matrix object (i.e., the argument to the 'IDASetJacFn'
423 // function below).
424# if DEAL_II_SUNDIALS_VERSION_LT(6, 0, 0)
425 J = SUNMatNewEmpty();
426# else
427 J = SUNMatNewEmpty(ida_ctx);
428# endif
429 J->content = this;
430
431 J->ops->getid = [](SUNMatrix /*ignored*/) -> SUNMatrix_ID {
432 return SUNMATRIX_CUSTOM;
433 };
434
435 J->ops->destroy = [](SUNMatrix A) {
436 if (A->content)
437 {
438 A->content = nullptr;
439 }
440 if (A->ops)
441 {
442 std::free(A->ops);
443 A->ops = nullptr;
444 }
445 std::free(A);
446 A = nullptr;
447 };
448
449 // Now set the linear system and Jacobian objects in the solver:
450 status = IDASetLinearSolver(ida_mem, LS, J);
451 AssertIDA(status);
452
453 // IDASetLinearSolver initializes the linear solver options to their
454 // defaults, so apply the user settings only after attaching the solver.
455 status = IDASetLSNormFactor(ida_mem, data.ls_norm_factor);
456 AssertIDA(status);
457 status = IDASetEpsLin(ida_mem, data.linear_tolerance_factor);
458 AssertIDA(status);
459 status = IDASetIncrementFactor(ida_mem, data.increment_factor);
460 AssertIDA(status);
461 status = IDASetLinearSolutionScaling(ida_mem, data.linear_solution_scaling);
462 AssertIDA(status);
463# if DEAL_II_SUNDIALS_VERSION_GTE(6, 2, 0)
464 status = IDASetDeltaCjLSetup(ida_mem, data.delta_cj_lsetup);
465 AssertIDA(status);
466# endif
467 // Finally tell IDA about
468 // it as well. The manual says that this must happen *after*
469 // calling IDASetLinearSolver
470 status = IDASetJacFn(
471 ida_mem,
472 [](SUNDIALS::realtype tt,
474 N_Vector yy,
475 N_Vector yp,
476 N_Vector /* residual */,
477 SUNMatrix /* ignored */,
478 void *user_data,
479 N_Vector /* tmp1 */,
480 N_Vector /* tmp2 */,
481 N_Vector /* tmp3 */) -> int {
482 Assert(user_data != nullptr, ExcInternalError());
483 IDA<VectorType> &solver = *static_cast<IDA<VectorType> *>(user_data);
484
485 auto *src_yy = internal::unwrap_nvector_const<VectorType>(yy);
486 auto *src_yp = internal::unwrap_nvector_const<VectorType>(yp);
487
489 solver.setup_jacobian,
490 solver.pending_exception,
491 tt,
492 *src_yy,
493 *src_yp,
494 cj);
495 });
496 AssertIDA(status);
497 status = IDASetMaxOrd(ida_mem, data.maximum_order);
498 AssertIDA(status);
499
500 if (get_constraint_vector)
501 {
502 const auto constraints =
503 internal::make_nvector_view(get_constraint_vector()
504# if !DEAL_II_SUNDIALS_VERSION_LT(6, 0, 0)
505 ,
506 ida_ctx
507# endif
508 );
509 // IDA rejects a non-null all-zero vector. Treat it as no constraints.
510 if (N_VMaxNorm(constraints) > 0.0)
511 {
512 status = IDASetConstraints(ida_mem, constraints);
513 AssertIDA(status);
514 }
515 }
516
517# if DEAL_II_SUNDIALS_VERSION_GTE(6, 2, 0)
518 status =
519 IDASetEtaFixedStepBounds(ida_mem, data.eta_min_fixed, data.eta_max_fixed);
520 AssertIDA(status);
521 status = IDASetEtaMin(ida_mem, data.eta_min);
522 AssertIDA(status);
523 status = IDASetEtaMax(ida_mem, data.eta_max);
524 AssertIDA(status);
525 status = IDASetEtaLow(ida_mem, data.eta_low);
526 AssertIDA(status);
527 status = IDASetEtaMinErrFail(ida_mem, data.eta_min_err_fail);
528 AssertIDA(status);
529 status = IDASetEtaConvFail(ida_mem, data.eta_conv_fail);
530 AssertIDA(status);
531# endif
532
534 if (first_step)
535 type = data.ic_type;
536 else
537 type = data.reset_type;
538
539 status =
540 IDASetMaxNumItersIC(ida_mem, data.maximum_non_linear_iterations_ic);
541 AssertIDA(status);
542 status = IDASetNonlinConvCoefIC(ida_mem,
543 data.nonlinear_convergence_coefficient_ic);
544 AssertIDA(status);
545 status = IDASetMaxNumStepsIC(ida_mem, data.maximum_number_of_steps_ic);
546 AssertIDA(status);
547 status = IDASetMaxNumJacsIC(ida_mem, data.maximum_number_of_jacobians_ic);
548 AssertIDA(status);
549 status = IDASetMaxBacksIC(ida_mem, data.maximum_number_of_backtracks_ic);
550 AssertIDA(status);
551 status = IDASetLineSearchOffIC(ida_mem, !data.line_search_enabled_ic);
552 AssertIDA(status);
553 status = IDASetStepToleranceIC(ida_mem, data.step_tolerance_ic);
554 AssertIDA(status);
555# if DEAL_II_SUNDIALS_VERSION_GTE(7, 6, 0)
556 status =
557 IDASetMaxNumConstraintFails(ida_mem, data.maximum_constraint_failures);
558 AssertIDA(status);
559# endif
560
561 if (custom_setup)
562 custom_setup(ida_mem);
563
564 if (type == AdditionalData::use_y_dot)
565 {
566 // (re)initialization of the vectors
567 status =
568 IDACalcIC(ida_mem, IDA_Y_INIT, current_time + current_time_step);
569 AssertIDA(status);
570
571 status = IDAGetConsistentIC(ida_mem, yy, yp);
572 AssertIDA(status);
573 }
574 else if (type == AdditionalData::use_y_diff)
575 {
576 status =
577 IDACalcIC(ida_mem, IDA_YA_YDP_INIT, current_time + current_time_step);
578 AssertIDA(status);
579
580 status = IDAGetConsistentIC(ida_mem, yy, yp);
581 AssertIDA(status);
582 }
583 }
584
585 template <typename VectorType>
586 void
588 {
589 reinit_vector = [](VectorType &) {
590 AssertThrow(false, ExcFunctionNotProvided("reinit_vector"));
591 };
592
593 residual = [](const double,
594 const VectorType &,
595 const VectorType &,
596 VectorType &) -> int {
597 int ret = 0;
598 AssertThrow(false, ExcFunctionNotProvided("residual"));
599 return ret;
600 };
601
602
603 output_step = [](const double,
604 const VectorType &,
605 const VectorType &,
606 const unsigned int) { return; };
607
608 solver_should_restart =
609 [](const double, VectorType &, VectorType &) -> bool { return false; };
610
611 differential_components = [&]() -> IndexSet {
613 typename VectorMemory<VectorType>::Pointer v(mem);
614 reinit_vector(*v);
615 return v->locally_owned_elements();
616 };
617 }
618
619
620 template <typename VectorType>
621 void *
623 {
624 return ida_mem;
625 }
626
627
628
629 template class IDA<Vector<double>>;
630 template class IDA<BlockVector<double>>;
631
632# ifdef DEAL_II_WITH_MPI
633
634# ifdef DEAL_II_WITH_TRILINOS
637# endif // DEAL_II_WITH_TRILINOS
638
639# ifdef DEAL_II_WITH_PETSC
640# ifndef PETSC_USE_COMPLEX
641 template class IDA<PETScWrappers::MPI::Vector>;
643# endif // PETSC_USE_COMPLEX
644# endif // DEAL_II_WITH_PETSC
645
646# endif // DEAL_II_WITH_MPI
647
648} // namespace SUNDIALS
649
650
651#endif // DEAL_II_WITH_SUNDIALS
*const unsigned int n_steps
std::function< void(const VectorType &rhs, VectorType &dst, const double tolerance)> solve_with_jacobian
Definition ida.h:1326
unsigned int solve_dae(VectorType &solution, VectorType &solution_dot)
Definition ida.cc:115
MPI_Comm mpi_communicator
Definition ida.h:1472
std::function< void(const double t, const VectorType &y, const VectorType &y_dot, const double alpha)> setup_jacobian
Definition ida.h:1281
void set_functions_to_trigger_an_assert()
Definition ida.cc:587
void reset(const double t, const double h, VectorType &y, VectorType &yp)
Definition ida.cc:198
std::function< void(const double t, const VectorType &y, const VectorType &y_dot, VectorType &res)> residual
Definition ida.h:1245
void * get_ida_memory() const
Definition ida.cc:622
IDA(const AdditionalData &data=AdditionalData())
Definition ida.cc:56
SUNContext ida_ctx
Definition ida.h:1465
std::exception_ptr pending_exception
Definition ida.h:1484
#define DEAL_II_NAMESPACE_OPEN
Definition config.h:38
#define DEAL_II_SUNDIALS_VERSION_GTE(major, minor, patch)
Definition config.h:532
#define DEAL_II_SUNDIALS_VERSION_LT(major, minor, patch)
Definition config.h:539
#define DEAL_II_NAMESPACE_CLOSE
Definition config.h:39
#define AssertIDA(code)
static ::ExceptionBase & ExcFunctionNotProvided(std::string arg1)
#define Assert(cond, exc)
static ::ExceptionBase & ExcInternalError()
static ::ExceptionBase & RecoverableUserCallbackError()
#define AssertThrow(cond, exc)
std::vector< index_type > data
Definition mpi.cc:734
int call_and_possibly_capture_exception(const F &f, std::exception_ptr &eptr, Args &&...args)
Definition utilities.h:48
::sunrealtype realtype