ryujin 2.1.1 revision ee5cbcbf2346c1299c942d0e1f13b46449973c18
Loading...
Searching...
No Matches
parabolic_module.template.h
Go to the documentation of this file.
1//
2// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3// Copyright (C) 2023 - 2026 by the ryujin authors
4//
5
6#pragma once
7
8#include "parabolic_module.h"
9
10#include <computing_timer.h>
11#include <loop.h>
12#include <simd.h>
13
14#include <deal.II/lac/linear_operator.h>
15#include <deal.II/lac/precondition.h>
16#include <deal.II/lac/solver_cg.h>
17#include <deal.II/matrix_free/fe_evaluation.h>
18#include <deal.II/multigrid/mg_coarse.h>
19#include <deal.II/multigrid/mg_matrix.h>
20#include <deal.II/multigrid/mg_transfer.templates.h>
21#include <deal.II/multigrid/mg_transfer_matrix_free.h>
22#include <deal.II/multigrid/multigrid.h>
23
24#include <atomic>
25
26namespace ryujin
27{
28 namespace NavierStokes
29 {
30 using namespace dealii;
31
32 template <int dim, typename Number>
34 const MPIEnsemble &mpi_ensemble,
35 const OfflineData<dim, Number> &offline_data,
36 const HyperbolicSystem &hyperbolic_system,
37 const ParabolicSystem &parabolic_system,
38 const InitialValues<Description, dim, Number> &initial_values,
39 const std::string &subsection /*= "ParabolicModule"*/)
40 : ParameterAcceptor(subsection)
41 , mpi_ensemble_(mpi_ensemble)
42 , hyperbolic_system_(&hyperbolic_system)
43 , parabolic_system_(&parabolic_system)
44 , offline_data_(&offline_data)
45 , initial_values_(&initial_values)
46 , id_violation_strategy_(IDViolationStrategy::warn)
47 , cycle_(0)
48 , n_restarts_(0)
49 , n_corrections_(0)
50 , n_warnings_(0)
51 , n_iterations_velocity_(0.)
52 , n_iterations_internal_energy_(0.)
53 {
54 use_gmg_velocity_ = false;
55 add_parameter("multigrid velocity",
56 use_gmg_velocity_,
57 "Use geometric multigrid for velocity component");
58
59 gmg_max_iter_vel_ = 12;
60 add_parameter("multigrid velocity - max iter",
61 gmg_max_iter_vel_,
62 "Maximal number of CG iterations with GMG smoother");
63
64 gmg_smoother_range_vel_ = 8.;
65 add_parameter("multigrid velocity - chebyshev range",
66 gmg_smoother_range_vel_,
67 "Chebyshev smoother: eigenvalue range parameter");
68
69 gmg_smoother_max_eig_vel_ = 2.0;
70 add_parameter("multigrid velocity - chebyshev max eig",
71 gmg_smoother_max_eig_vel_,
72 "Chebyshev smoother: maximal eigenvalue");
73
74 use_gmg_internal_energy_ = false;
75 add_parameter("multigrid energy",
76 use_gmg_internal_energy_,
77 "Use geometric multigrid for internal energy component");
78
79 gmg_max_iter_en_ = 15;
80 add_parameter("multigrid energy - max iter",
81 gmg_max_iter_en_,
82 "Maximal number of CG iterations with GMG smoother");
83
84 gmg_smoother_range_en_ = 15.;
85 add_parameter("multigrid energy - chebyshev range",
86 gmg_smoother_range_en_,
87 "Chebyshev smoother: eigenvalue range parameter");
88
89 gmg_smoother_max_eig_en_ = 2.0;
90 add_parameter("multigrid energy - chebyshev max eig",
91 gmg_smoother_max_eig_en_,
92 "Chebyshev smoother: maximal eigenvalue");
93
94 gmg_smoother_degree_ = 3;
95 add_parameter("multigrid - chebyshev degree",
96 gmg_smoother_degree_,
97 "Chebyshev smoother: degree");
98
99 gmg_smoother_n_cg_iter_ = 10;
100 add_parameter(
101 "multigrid - chebyshev cg iter",
102 gmg_smoother_n_cg_iter_,
103 "Chebyshev smoother: number of CG iterations to approximate "
104 "eigenvalue");
105
106 gmg_min_level_ = 0;
107 add_parameter(
108 "multigrid - min level",
109 gmg_min_level_,
110 "Minimal mesh level to be visited in the geometric multigrid "
111 "cycle where the coarse grid solver (Chebyshev) is called");
112
113 tolerance_ = Number(1.0e-12);
114 add_parameter("tolerance", tolerance_, "Tolerance for linear solvers");
115
116 tolerance_linfty_norm_ = false;
117 add_parameter("tolerance linfty norm",
118 tolerance_linfty_norm_,
119 "Use the l_infty norm instead of the l_2 norm for the "
120 "stopping criterion");
121 }
122
123
124 template <int dim, typename Number>
126 {
127#ifdef DEBUG_OUTPUT
128 std::cout << "ParabolicModule<dim, Number>::prepare()" << std::endl;
129#endif
130 /*
131 * The cycle_ variabe is only used for gmg reinitialization, simply
132 * reset it to zero on prepare().
133 */
134 cycle_ = 0;
135
136 const auto &discretization = offline_data_->discretization();
137 AssertThrow(discretization.ansatz() == Ansatz::cg_q1,
138 dealii::ExcMessage("The Navier-Stokes module currently only "
139 "supports cG Q1 finite elements."));
140
141 AssertThrow(!offline_data_->dof_handler().has_hp_capabilities(),
142 dealii::ExcMessage(
143 "The Navier-Stokes module currently does not support "
144 "DoFHandlers set up with hp capabilities."));
145
146 /* Initialize vectors: */
147
148 typename MatrixFree<dim, Number>::AdditionalData additional_data;
149 additional_data.tasks_parallel_scheme =
150 MatrixFree<dim, Number>::AdditionalData::none;
151
152 matrix_free_.reinit(discretization.mapping(),
153 offline_data_->dof_handler(),
154 offline_data_->affine_constraints(),
155 discretization.quadrature_1d(),
156 additional_data);
157
158 const auto &scalar_partitioner =
159 matrix_free_.get_dof_info(0).vector_partitioner;
160
161 velocity_.reinit(dim);
162 velocity_rhs_.reinit(dim);
163 for (unsigned int i = 0; i < dim; ++i) {
164 velocity_.block(i).reinit(scalar_partitioner);
165 velocity_rhs_.block(i).reinit(scalar_partitioner);
166 }
167
168 internal_energy_.reinit(scalar_partitioner);
169 internal_energy_rhs_.reinit(scalar_partitioner);
170
171 density_.reinit(scalar_partitioner);
172
173 /* Initialize multigrid: */
174
175 if (!use_gmg_velocity_ && !use_gmg_internal_energy_)
176 return;
177
178 const unsigned int n_levels =
179 offline_data_->dof_handler().get_triangulation().n_global_levels();
180 const unsigned int min_level = std::min(gmg_min_level_, n_levels - 1);
181 MGLevelObject<IndexSet> relevant_sets(0, n_levels - 1);
182 for (unsigned int level = 0; level < n_levels; ++level)
183 relevant_sets[level] =
184 dealii::DoFTools::extract_locally_relevant_level_dofs(
185 offline_data_->dof_handler(), level);
186 mg_constrained_dofs_.initialize(offline_data_->dof_handler(),
187 relevant_sets);
188 std::set<types::boundary_id> boundary_ids;
189 boundary_ids.insert(Boundary::dirichlet);
190 boundary_ids.insert(Boundary::no_slip);
191 mg_constrained_dofs_.make_zero_boundary_constraints(
192 offline_data_->dof_handler(), boundary_ids);
193
194 typename MatrixFree<dim, float>::AdditionalData additional_data_level;
195 additional_data_level.tasks_parallel_scheme =
196 MatrixFree<dim, float>::AdditionalData::none;
197
198 level_matrix_free_.resize(min_level, n_levels - 1);
199 level_density_.resize(min_level, n_levels - 1);
200 for (unsigned int level = min_level; level < n_levels; ++level) {
201 additional_data_level.mg_level = level;
202 AffineConstraints<double> constraints(relevant_sets[level],
203 relevant_sets[level]);
204 // constraints.add_lines(mg_constrained_dofs_.get_boundary_indices(level));
205 // constraints.merge(mg_constrained_dofs_.get_level_constraints(level));
206 constraints.close();
207 level_matrix_free_[level].reinit(discretization.mapping(),
208 offline_data_->dof_handler(),
209 constraints,
210 discretization.quadrature_1d(),
211 additional_data_level);
212 level_matrix_free_[level].initialize_dof_vector(level_density_[level]);
213 }
214
215 mg_transfer_velocity_.build(offline_data_->dof_handler(),
216 mg_constrained_dofs_,
217 level_matrix_free_);
218 mg_transfer_energy_.build(offline_data_->dof_handler(),
219 level_matrix_free_);
220 }
221
222
223 template <int dim, typename Number>
225 StateVector & /*state_vector*/, Number /*t*/) const
226 {
227 /*
228 * There is no parabolic part of the state vector for Navier-Stokes,
229 * so we do nothing.
230 */
231 }
232
233
234 template <int dim, typename Number>
235 template <int stages>
237 const StateVector &old_state_vector,
238 const Number old_t,
239 std::array<std::reference_wrapper<const StateVector>,
240 stages> /*stage_state_vectors*/,
241 const std::array<Number, stages> /*stage_weights*/,
242 StateVector &new_state_vector,
243 Number tau) const
244 {
245 /* Backward Euler step to half time step, and extrapolate: */
246
247 step(old_state_vector,
248 old_t,
249 new_state_vector,
250 tau,
251 /*crank_nicolson_extrapolation = */ false);
252 }
253
254
255 template <int dim, typename Number>
257 const StateVector &old_state_vector,
258 const Number old_t,
259 StateVector &new_state_vector,
260 Number tau) const
261 {
262 try {
263 step(old_state_vector,
264 old_t,
265 new_state_vector,
266 tau / Number(2.),
267 /*crank_nicolson_extrapolation = */ true);
268
269 } catch (Correction) {
270
271 /*
272 * Under very rare circumstances we might fail to perform a Crank
273 * Nicolson step because the extrapolation step produced
274 * inadmissible states. We could correct the update now by
275 * performing a limiting step (either convex limiting, or flux
276 * corrected transport)... but *meh*, just perform a backward Euler
277 * step:
278 */
279 step(old_state_vector,
280 old_t,
281 new_state_vector,
282 tau,
283 /*crank_nicolson_extrapolation = */ false);
284 }
285 }
286
287
288 template <int dim, typename Number>
290 std::ostream &output) const
291 {
292 output << " [ " << std::setprecision(2) << std::fixed
293 << n_iterations_velocity_
294 << (use_gmg_velocity_ ? " GMG vel -- " : " CG vel -- ")
295 << n_iterations_internal_energy_
296 << (use_gmg_internal_energy_ ? " GMG int ]" : " CG int ]")
297 << std::endl;
298 }
299
300
301 template <int dim, typename Number>
303 const StateVector &old_state_vector,
304 const Number t,
305 StateVector &new_state_vector,
306 Number tau,
307 const bool crank_nicolson_extrapolation) const
308 {
309#ifdef DEBUG_OUTPUT
310 std::cout << "ParabolicModule<dim, Number>::step()" << std::endl;
311#endif
312 constexpr ScalarNumber eps = std::numeric_limits<ScalarNumber>::epsilon();
313
314 const auto old_U_view = std::get<0>(old_state_vector).view();
315 const auto new_U_view = std::get<0>(new_state_vector).view();
316
317 const auto lumped_mass_matrix_view =
318 offline_data_->lumped_mass_matrix().view();
319 const auto &affine_constraints = offline_data_->affine_constraints();
320
321 /* Index ranges for the iteration over the sparsity pattern : */
322
323 const unsigned int n_owned = offline_data_->n_locally_owned();
324
325 const auto sparsity_simd_view =
326 offline_data_->sparsity_pattern_simd().view();
327
328 DiagonalMatrix<dim, Number> diagonal_matrix;
329
330#ifdef DEBUG_OUTPUT
331 std::cout << " perform time-step with tau = " << tau << std::endl;
332 if (crank_nicolson_extrapolation)
333 std::cout << " and extrapolate to t + 2 * tau" << std::endl;
334#endif
335
336 /*
337 * Update MG matrices all 4 time steps; this is a balance because more
338 * refreshes will render the approximation better, at some additional
339 * cost.
340 */
341 const bool reinitialize_gmg = (cycle_++ % 4 == 0);
342
343 /*
344 * A boolean indicating that a restart is required.
345 *
346 * In our current implementation we set this boolean to true if the
347 * backward Euler step produces an internal energy update that
348 * violates the minimum principle, i.e., the minimum of the new
349 * internal energy is smaller than the minimum of the old internal
350 * energy.
351 *
352 * Depending on the chosen "id_violation_strategy" we either signal a
353 * restart by throwing a "Restart" object, or we simply increase the
354 * number of warnings.
355 */
356 std::atomic<bool> restart_needed = false;
357
358 /*
359 * A boolean indicating that we have to correct the high-order Crank
360 * Nicolson update. Note that this is a truly exceptional case
361 * indicating that the high-order update produced an inadmissible
362 * state, *boo*.
363 *
364 * Our current limiting strategy is to simply fall back to perform a
365 * single backward Euler step...
366 */
367 std::atomic<bool> correction_needed = false;
368
369 /*
370 * Step 1:
371 *
372 * Build right hand side for the velocity update.
373 * Also initialize solution vectors for internal energy and velocity
374 * update.
375 */
376 {
377 ComputingTimer::Scope scope("time step [P] 1 - update velocities");
378
379 const auto body = [&](auto sentinel, unsigned int i) {
380 using T = decltype(sentinel);
381
382 const auto view = hyperbolic_system_->template view<dim, T>();
383
384 const auto U_i = old_U_view.template read_tensor<T>(i);
385 const auto rho_i = view.density(U_i);
386 const auto M_i = view.momentum(U_i);
387 const auto rho_e_i = view.internal_energy(U_i);
388 const auto m_i = lumped_mass_matrix_view.template read_entry<T>(i);
389
390 write_entry<T>(density_, rho_i, i);
391 /* (5.4a) */
392 for (unsigned int d = 0; d < dim; ++d) {
393 write_entry<T>(velocity_.block(d), M_i[d] / rho_i, i);
394 write_entry<T>(velocity_rhs_.block(d), m_i * (M_i[d]), i);
395 }
396 write_entry<T>(internal_energy_, rho_e_i / rho_i, i);
397 };
398
399 cpu_simd_loop<Number>(
400 "time_step_parabolic_1", body, 0, n_owned, n_owned);
401
402 /*
403 * Set up "strongly enforced" boundary conditions that are not stored
404 * in the AffineConstraints map. In this case we enforce boundary
405 * values by imposing them strongly in the iteration by setting the
406 * initial vector and the right hand side to the right value:
407 */
408
409 const auto &boundary_map = offline_data_->boundary_map();
410
411 for (auto entry : boundary_map) {
412 // [i, normal, normal_mass, boundary_mass, id, position] = entry
413 const auto i = std::get<0>(entry);
414 if (i >= n_owned)
415 continue;
416
417 const auto normal = std::get<1>(entry);
418 const auto id = std::get<4>(entry);
419 const auto position = std::get<5>(entry);
420
421 if (id == Boundary::slip) {
422 /* Remove normal component of velocity: */
423 Tensor<1, dim, Number> V_i;
424 Tensor<1, dim, Number> RHS_i;
425 for (unsigned int d = 0; d < dim; ++d) {
426 V_i[d] = velocity_.block(d).local_element(i);
427 RHS_i[d] = velocity_rhs_.block(d).local_element(i);
428 }
429 V_i -= 1. * (V_i * normal) * normal;
430 RHS_i -= 1. * (RHS_i * normal) * normal;
431 for (unsigned int d = 0; d < dim; ++d) {
432 velocity_.block(d).local_element(i) = V_i[d];
433 velocity_rhs_.block(d).local_element(i) = RHS_i[d];
434 }
435
436 } else if (id == Boundary::no_slip) {
437
438 /* Set velocity to zero: */
439 for (unsigned int d = 0; d < dim; ++d) {
440 velocity_.block(d).local_element(i) = Number(0.);
441 velocity_rhs_.block(d).local_element(i) = Number(0.);
442 }
443
444 } else if (id == Boundary::dirichlet) {
445
446 /* Prescribe velocity: */
447 const auto U_i = initial_values_->initial_state(position, t + tau);
448 const auto view = hyperbolic_system_->template view<dim, Number>();
449 const auto rho_i = view.density(U_i);
450 const auto V_i = view.momentum(U_i) / rho_i;
451 const auto e_i = view.internal_energy(U_i) / rho_i;
452
453 for (unsigned int d = 0; d < dim; ++d) {
454 velocity_.block(d).local_element(i) = V_i[d];
455 velocity_rhs_.block(d).local_element(i) = V_i[d];
456 }
457
458 internal_energy_.local_element(i) = e_i;
459 }
460 }
461
462 /*
463 * Zero out constrained degrees of freedom due to hanging nodes and
464 * periodic boundary conditions. These boundary conditions are
465 * enforced by modifying the stencil - consequently we have to
466 * remove constrained dofs from the linear system.
467 */
468
469 affine_constraints.set_zero(density_);
470 affine_constraints.set_zero(internal_energy_);
471 for (unsigned int d = 0; d < dim; ++d) {
472 affine_constraints.set_zero(velocity_.block(d));
473 affine_constraints.set_zero(velocity_rhs_.block(d));
474 }
475
476 /* Prepare preconditioner: */
477
478 diagonal_matrix.reinit(
479 lumped_mass_matrix_view, density_, affine_constraints);
480
481 if (use_gmg_velocity_ && reinitialize_gmg) {
482 MGLevelObject<typename PreconditionChebyshev<
483 VelocityMatrix<dim, float, Number>,
484 LinearAlgebra::distributed::BlockVector<float>,
485 DiagonalMatrix<dim, float>>::AdditionalData>
486 smoother_data(level_matrix_free_.min_level(),
487 level_matrix_free_.max_level());
488
489 level_velocity_matrices_.resize(level_matrix_free_.min_level(),
490 level_matrix_free_.max_level());
491 mg_transfer_velocity_.interpolate_to_mg(
492 offline_data_->dof_handler(), level_density_, density_);
493
494 for (unsigned int level = level_matrix_free_.min_level();
495 level <= level_matrix_free_.max_level();
496 ++level) {
497 level_velocity_matrices_[level].initialize(
498 *parabolic_system_,
499 *offline_data_,
500 level_matrix_free_[level],
501 level_density_[level],
502 tau,
503 level);
504 level_velocity_matrices_[level].compute_diagonal(
505 smoother_data[level].preconditioner);
506 if (level == level_matrix_free_.min_level()) {
507 smoother_data[level].degree = numbers::invalid_unsigned_int;
508 smoother_data[level].eig_cg_n_iterations = 500;
509 smoother_data[level].smoothing_range = 1e-3;
510 } else {
511 smoother_data[level].degree = gmg_smoother_degree_;
512 smoother_data[level].eig_cg_n_iterations =
513 gmg_smoother_n_cg_iter_;
514 smoother_data[level].smoothing_range = gmg_smoother_range_vel_;
515 if (gmg_smoother_n_cg_iter_ == 0)
516 smoother_data[level].max_eigenvalue = gmg_smoother_max_eig_vel_;
517 }
518 }
519 mg_smoother_velocity_.initialize(level_velocity_matrices_,
520 smoother_data);
521 }
522 }
523
524 Number e_min_old;
525
526 {
527 ComputingTimer::Scope scope(
528 "time step [X] _ - synchronization barriers");
529
530 /* Compute the global minimum of the internal energy: */
531
532 // .begin() and .end() denote the locally owned index range:
533 e_min_old =
534 *std::min_element(internal_energy_.begin(), internal_energy_.end());
535
536 e_min_old = Utilities::MPI::min(e_min_old,
537 mpi_ensemble_.ensemble_communicator());
538
539 // FIXME: create a meaningful relaxation based on global mesh size min.
540 constexpr Number eps = std::numeric_limits<Number>::epsilon();
541 e_min_old *= (1. - 1000. * eps);
542 }
543
544 /*
545 * Step 1: Solve velocity update:
546 */
547 {
548 ComputingTimer::Scope scope("time step [P] 1 - update velocities");
549
550 VelocityMatrix<dim, Number, Number> velocity_operator;
551 velocity_operator.initialize(
552 *parabolic_system_, *offline_data_, matrix_free_, density_, tau);
553
554 const auto tolerance_velocity =
555 (tolerance_linfty_norm_ ? velocity_rhs_.linfty_norm()
556 : velocity_rhs_.l2_norm()) *
557 tolerance_;
558
559 /*
560 * Multigrid might lack robustness for some cases, so in case it takes
561 * too many iterations we better switch to the more robust plain
562 * conjugate gradient method.
563 */
564 try {
565 if (!use_gmg_velocity_)
566 throw SolverControl::NoConvergence(0, 0.);
567
568 using bvt_float = LinearAlgebra::distributed::BlockVector<float>;
569
570 MGCoarseGridApplySmoother<bvt_float> mg_coarse;
571 mg_coarse.initialize(mg_smoother_velocity_);
572
573 mg::Matrix<bvt_float> mg_matrix(level_velocity_matrices_);
574
575 Multigrid<bvt_float> mg(mg_matrix,
576 mg_coarse,
577 mg_transfer_velocity_,
578 mg_smoother_velocity_,
579 mg_smoother_velocity_,
580 level_velocity_matrices_.min_level(),
581 level_velocity_matrices_.max_level());
582
583 const auto &dof_handler = offline_data_->dof_handler();
584 PreconditionMG<dim, bvt_float, MGTransferVelocity<dim, float>>
585 preconditioner(dof_handler, mg, mg_transfer_velocity_);
586
587 SolverControl solver_control(gmg_max_iter_vel_, tolerance_velocity);
588 SolverCG<BlockHostVector> solver(solver_control);
589 solver.solve(
590 velocity_operator, velocity_, velocity_rhs_, preconditioner);
591
592 /* update exponential moving average */
593 n_iterations_velocity_ =
594 0.9 * n_iterations_velocity_ + 0.1 * solver_control.last_step();
595
596 } catch (SolverControl::NoConvergence &) {
597
598 SolverControl solver_control(1000, tolerance_velocity);
599 SolverCG<BlockHostVector> solver(solver_control);
600 solver.solve(
601 velocity_operator, velocity_, velocity_rhs_, diagonal_matrix);
602
603 /* update exponential moving average, counting also GMG iterations */
604 n_iterations_velocity_ *= 0.9;
605 n_iterations_velocity_ +=
606 0.1 * (use_gmg_velocity_ ? gmg_max_iter_vel_ : 0) +
607 0.1 * solver_control.last_step();
608 }
609 }
610
611 /*
612 * Step 2: Build internal energy right hand side:
613 */
614 {
615 ComputingTimer::Scope scope("time step [P] 2 - update internal energy");
616
617 /* Compute m_i K_i^{n+1/2}: (5.5) */
618 matrix_free_.template cell_loop<ScalarHostVector, BlockHostVector>(
619 [this](const auto &data,
620 auto &dst,
621 const auto &src,
622 const auto cell_range) {
623 FEEvaluation<dim, order_fe, order_quad, dim, Number> velocity(
624 data);
625 FEEvaluation<dim, order_fe, order_quad, 1, Number> energy(data);
626
627 const auto mu = parabolic_system_->mu();
628 const auto lambda = parabolic_system_->lambda();
629
630 for (unsigned int cell = cell_range.first;
631 cell < cell_range.second;
632 ++cell) {
633 velocity.reinit(cell);
634 energy.reinit(cell);
635 velocity.gather_evaluate(src, EvaluationFlags::gradients);
636
637 for (unsigned int q = 0; q < velocity.n_q_points; ++q) {
638 if constexpr (dim == 1) {
639 /* Workaround: no symmetric gradient for dim == 1: */
640 const auto gradient = velocity.get_gradient(q);
641 auto S = (4. / 3. * mu + lambda) * gradient;
642 energy.submit_value(gradient * S, q);
643
644 } else {
645
646 const auto symmetric_gradient =
647 velocity.get_symmetric_gradient(q);
648 const auto divergence = trace(symmetric_gradient);
649 auto S = 2. * mu * symmetric_gradient;
650 for (unsigned int d = 0; d < dim; ++d)
651 S[d][d] += (lambda - 2. / 3. * mu) * divergence;
652 energy.submit_value(symmetric_gradient * S, q);
653 }
654 }
655 energy.integrate_scatter(EvaluationFlags::values, dst);
656 }
657 },
658 internal_energy_rhs_,
659 velocity_,
660 /* zero destination */ true);
661
662 const auto lumped_mass_matrix_view =
663 offline_data_->lumped_mass_matrix().view();
664
665 const auto body = [&](auto sentinel, unsigned int i) {
666 using T = decltype(sentinel);
667
668 const auto view = hyperbolic_system_->template view<dim, T>();
669
670 const auto rhs_i = read_entry<T>(internal_energy_rhs_, i);
671 const auto m_i = lumped_mass_matrix_view.template read_entry<T>(i);
672 const auto rho_i = read_entry<T>(density_, i);
673 const auto e_i = read_entry<T>(internal_energy_, i);
674
675 const auto U_i = old_U_view.template read_tensor<T>(i);
676 const auto V_i = view.momentum(U_i) / rho_i;
677
678 dealii::Tensor<1, dim, T> V_i_new;
679 for (unsigned int d = 0; d < dim; ++d) {
680 V_i_new[d] = read_entry<T>(velocity_.block(d), i);
681 }
682
683 /*
684 * For backward Euler we have to add this algebraic correction
685 * to ensure conservation of total energy.
686 */
687 const auto correction =
688 crank_nicolson_extrapolation
689 ? T(0.)
690 : Number(0.5) * (V_i - V_i_new).norm_square();
691
692 /* rhs_i contains already m_i K_i^{n+1/2} */
693 const auto result = m_i * rho_i * (e_i + correction) + tau * rhs_i;
694 write_entry<T>(internal_energy_rhs_, result, i);
695 };
696
697 cpu_simd_loop<Number>(
698 "time_step_parabolic_2", body, 0, n_owned, n_owned);
699
700 /*
701 * Set up "strongly enforced" boundary conditions that are not stored
702 * in the AffineConstraints map: We enforce Neumann conditions (i.e.,
703 * insulating boundary conditions) everywhere except for Dirichlet
704 * boundaries where we have to enforce prescribed conditions:
705 */
706
707 const auto &boundary_map = offline_data_->boundary_map();
708
709 for (auto entry : boundary_map) {
710 // [i, normal, normal_mass, boundary_mass, id, position] = entry
711 const auto i = std::get<0>(entry);
712 if (i >= n_owned)
713 continue;
714
715 const auto id = std::get<4>(entry);
716 const auto position = std::get<5>(entry);
717
718 if (id == Boundary::dirichlet) {
719 /* Prescribe internal energy: */
720 const auto U_i = initial_values_->initial_state(position, t + tau);
721 const auto view = hyperbolic_system_->template view<dim, Number>();
722 const auto rho_i = view.density(U_i);
723 const auto e_i = view.internal_energy(U_i) / rho_i;
724 internal_energy_rhs_.local_element(i) = e_i;
725 }
726 }
727
728 /*
729 * Zero out constrained degrees of freedom due to hanging nodes and
730 * periodic boundary conditions. These boundary conditions are
731 * enforced by modifying the stencil - consequently we have to
732 * remove constrained dofs from the linear system.
733 */
734 affine_constraints.set_zero(internal_energy_);
735 affine_constraints.set_zero(internal_energy_rhs_);
736
737 /*
738 * Update MG matrices all 4 time steps; this is a balance because more
739 * refreshes will render the approximation better, at some additional
740 * cost.
741 */
742 if (use_gmg_internal_energy_ && reinitialize_gmg) {
743 MGLevelObject<typename PreconditionChebyshev<
744 EnergyMatrix<dim, float, Number>,
745 LinearAlgebra::distributed::Vector<float>>::AdditionalData>
746 smoother_data(level_matrix_free_.min_level(),
747 level_matrix_free_.max_level());
748
749 level_energy_matrices_.resize(level_matrix_free_.min_level(),
750 level_matrix_free_.max_level());
751
752 for (unsigned int level = level_matrix_free_.min_level();
753 level <= level_matrix_free_.max_level();
754 ++level) {
755 level_energy_matrices_[level].initialize(
756 *offline_data_,
757 level_matrix_free_[level],
758 level_density_[level],
759 tau * parabolic_system_->cv_inverse_kappa(),
760 level);
761 level_energy_matrices_[level].compute_diagonal(
762 smoother_data[level].preconditioner);
763 if (level == level_matrix_free_.min_level()) {
764 smoother_data[level].degree = numbers::invalid_unsigned_int;
765 smoother_data[level].eig_cg_n_iterations = 500;
766 smoother_data[level].smoothing_range = 1e-3;
767 } else {
768 smoother_data[level].degree = gmg_smoother_degree_;
769 smoother_data[level].eig_cg_n_iterations =
770 gmg_smoother_n_cg_iter_;
771 smoother_data[level].smoothing_range = gmg_smoother_range_en_;
772 if (gmg_smoother_n_cg_iter_ == 0)
773 smoother_data[level].max_eigenvalue = gmg_smoother_max_eig_en_;
774 }
775 }
776 mg_smoother_energy_.initialize(level_energy_matrices_, smoother_data);
777 }
778 }
779
780 /*
781 * Step 2: Solve internal energy update:
782 */
783 {
784 ComputingTimer::Scope scope("time step [P] 2 - update internal energy");
785
786 EnergyMatrix<dim, Number, Number> energy_operator;
787 const auto &kappa = parabolic_system_->cv_inverse_kappa();
788 energy_operator.initialize(
789 *offline_data_, matrix_free_, density_, tau * kappa);
790
791 const auto tolerance_internal_energy =
792 (tolerance_linfty_norm_ ? internal_energy_rhs_.linfty_norm()
793 : internal_energy_rhs_.l2_norm()) *
794 tolerance_;
795
796 try {
797 if (!use_gmg_internal_energy_)
798 throw SolverControl::NoConvergence(0, 0.);
799
800 using vt_float = LinearAlgebra::distributed::Vector<float>;
801 MGCoarseGridApplySmoother<vt_float> mg_coarse;
802 mg_coarse.initialize(mg_smoother_energy_);
803 mg::Matrix<vt_float> mg_matrix(level_energy_matrices_);
804
805 Multigrid<vt_float> mg(mg_matrix,
806 mg_coarse,
807 mg_transfer_energy_,
808 mg_smoother_energy_,
809 mg_smoother_energy_,
810 level_energy_matrices_.min_level(),
811 level_energy_matrices_.max_level());
812
813 const auto &dof_handler = offline_data_->dof_handler();
814 PreconditionMG<dim, vt_float, MGTransferEnergy<dim, float>>
815 preconditioner(dof_handler, mg, mg_transfer_energy_);
816
817 SolverControl solver_control(gmg_max_iter_en_,
818 tolerance_internal_energy);
819 SolverCG<ScalarHostVector> solver(solver_control);
820 solver.solve(energy_operator,
821 internal_energy_,
822 internal_energy_rhs_,
823 preconditioner);
824
825 /* update exponential moving average */
826 n_iterations_internal_energy_ = 0.9 * n_iterations_internal_energy_ +
827 0.1 * solver_control.last_step();
828
829 } catch (SolverControl::NoConvergence &) {
830
831 SolverControl solver_control(1000, tolerance_internal_energy);
832 SolverCG<ScalarHostVector> solver(solver_control);
833 solver.solve(energy_operator,
834 internal_energy_,
835 internal_energy_rhs_,
836 diagonal_matrix);
837
838 /* update exponential moving average, counting also GMG iterations */
839 n_iterations_internal_energy_ *= 0.9;
840 n_iterations_internal_energy_ +=
841 0.1 * (use_gmg_internal_energy_ ? gmg_max_iter_en_ : 0) +
842 0.1 * solver_control.last_step();
843 }
844 }
845
846 /*
847 * Step 3: Copy vectors and check for local minimum principle on
848 * internal energy:
849 *
850 * FIXME: Memory access is suboptimal...
851 */
852 {
853 ComputingTimer::Scope scope("time step [P] 3 - write back vectors");
854
855 const auto body = [&](auto sentinel, unsigned int i) {
856 using T = decltype(sentinel);
857
858 const auto view = hyperbolic_system_->template view<dim, T>();
859
860 /* Skip constrained degrees of freedom: */
861 const unsigned int row_length = sparsity_simd_view.row_length(i);
862 if (row_length == 1)
863 return;
864
865 auto U_i = old_U_view.template read_tensor<T>(i);
866 const auto rho_i = view.density(U_i);
867
868 Tensor<1, dim, T> m_i_new;
869 for (unsigned int d = 0; d < dim; ++d) {
870 m_i_new[d] = rho_i * read_entry<T>(velocity_.block(d), i);
871 }
872
873 auto rho_e_i_new = rho_i * read_entry<T>(internal_energy_, i);
874
875 /*
876 * Check that the backward Euler step itself (which is our "low
877 * order" update) satisfies bounds. If not, signal a restart.
878 */
879
880 if (!(T(0.) == std::max(T(0.), rho_i * e_min_old - rho_e_i_new))) {
881#ifdef DEBUG_OUTPUT
882 std::cout << std::fixed << std::setprecision(16);
883 const auto e_i_new = rho_e_i_new / rho_i;
884 std::cout << "Bounds violation: internal energy (critical)!\n"
885 << "\t\te_min_old: " << e_min_old << "\n"
886 << "\t\te_min_old (delta): "
887 << negative_part(e_i_new - e_min_old) << "\n"
888 << "\t\te_min_new: " << e_i_new << "\n"
889 << std::endl;
890#endif
891 restart_needed = true;
892 }
893
894 if (crank_nicolson_extrapolation) {
895 m_i_new = Number(2.0) * m_i_new - view.momentum(U_i);
896 rho_e_i_new = Number(2.0) * rho_e_i_new - view.internal_energy(U_i);
897
898 /*
899 * If we do perform an extrapolation step for Crank Nicolson
900 * we have to check whether we maintain admissibility
901 */
902
903 if (!(T(0.) ==
904 std::max(T(0.), eps * rho_i * e_min_old - rho_e_i_new))) {
905#ifdef DEBUG_OUTPUT
906 std::cout << std::fixed << std::setprecision(16);
907 const auto e_i_new = rho_e_i_new / rho_i;
908
909 std::cout << "Bounds violation: high-order internal energy!"
910 << "\t\te_min_new: " << e_i_new << "\n"
911 << "\t\t-- correction required --" << std::endl;
912#endif
913 correction_needed = true;
914 }
915 }
916
917 const auto E_i_new = rho_e_i_new + 0.5 * m_i_new * m_i_new / rho_i;
918
919 for (unsigned int d = 0; d < dim; ++d)
920 U_i[1 + d] = m_i_new[d];
921 U_i[1 + dim] = E_i_new;
922
923 new_U_view.template write_tensor<T>(U_i, i);
924 };
925
926 cpu_simd_loop<Number>(
927 "time_step_parabolic_3", body, 0, n_owned, n_owned);
928
929 new_U_view.update_ghost_values();
930 }
931
932 {
933 ComputingTimer::Scope scope(
934 "time step [X] _ - synchronization barriers");
935
936 /*
937 * Synchronize whether we have to restart or correct the time step.
938 * Even though the restart/correction condition itself only affects
939 * the local ensemble we nevertheless need to synchronize the
940 * boolean in case we perform synchronized global time steps.
941 * (Otherwise different ensembles might end up with a different
942 * time step.)
943 */
944
945 restart_needed.store(Utilities::MPI::logical_or(
946 restart_needed.load(),
947 mpi_ensemble_.synchronization_communicator()));
948
949 correction_needed.store(Utilities::MPI::logical_or(
950 correction_needed.load(),
951 mpi_ensemble_.synchronization_communicator()));
952 }
953
954 if (correction_needed) {
955 /* If we can do a restart try that first: */
956 if (id_violation_strategy_ == IDViolationStrategy::raise_exception) {
957 n_restarts_++;
958 /* Half step size is a good heuristic: */
959 throw Restart{Number(0.5) * tau};
960 } else {
961 n_corrections_++;
962 throw Correction();
963 }
964 }
965
966 if (restart_needed) {
967 switch (id_violation_strategy_) {
969 n_warnings_++;
970 break;
972 n_restarts_++;
973 /* Half step size is a good heuristic: */
974 throw Restart{Number(0.5) * tau};
975 }
976 }
977 }
978
979 } // namespace NavierStokes
980} /* namespace ryujin */
void reinit(const Vector &lumped_mass_matrix, const vector_type &density, const dealii::AffineConstraints< Number > &affine_constraints)
typename View::StateVector StateVector
DEAL_II_HOST_DEVICE_ALWAYS_INLINE Number negative_part(const Number number)
Definition simd.h:161