Peano
Loading...
Searching...
No Matches
CentralDifferencesWithRungeKutta.py
Go to the documentation of this file.
1# This file is part of the ExaHyPE2 project. For conditions of distribution and
2# use, please see the copyright notice at www.peano-framework.org
3import enum
4import os
5import re
6
7import peano4.api
12import toolbox.loadbalancing.api.actionsets
13import exahype2.api.dslhype as dslhype
14
15from ..MaxEigenvalue import MaxEigenvalue
16from ..Solver import Solver
17from ..AuxiliaryVariables import (
18 register_auxiliary_variables,
19 add_reconstruction_tasks_of_auxiliary_variables,
20 use_halos_of_auxiliary_variables,
21 forwarding_arguments,
22)
23from ..rungekutta import ButcherTableau
24from ..rungekutta.LinearCombination import generate_linear_combination_kernel
25from ..rungekutta.LinearCombination import include_implementation_into_header
26from . import FD4Kernels
27from .Quantities import resolve_quantities
28from .actionsets import AddLopsidedAdvection
29from .actionsets import ApplyDirichletBoundaryConditions
30from ..blockstructured.BoundaryConditions import get_access_to_persistent_face_data
31from ..blockstructured.BoundaryConditions import get_boundary_conditions
32from ..blockstructured.SommerfeldBoundaryConditions import SommerfeldBoundaryConditions
33from ..blockstructured.create_dynamic_mesh_refinement_action_set import (
34 create_dynamic_mesh_refinement_action_set,
35)
36from .actionsets import ComputeLinearCombination
37from .actionsets import ComputeMaxEigenvalue
38from .actionsets import ComputeTimeStepSize
39from .actionsets import EvaluateRungeKuttaRightHandSide
40from .actionsets import ProjectPatchOntoFaces
41from .actionsets import ReduceMaxEigenvalue
42from .actionsets import RollOverUpdatedFaceWithSommerfeldBoundaryConditions
43
44
46 access: "peano4.api.taskgraph.Task.DataAccess", position: int, length: int
47) -> "peano4.api.taskgraph.Task.DataAccess":
48 """!
49
50 Qualifier of one task within a chain of tasks that share cell data
51
52 The original step used the data with the qualifier access. If we split it
53 into a chain of length tasks, the first task keeps the load part of access,
54 the last task keeps the store part, and all tasks in between both load and
55 store the data. The fused traversal merges the qualifiers back into access
56 (@ref peano4.api.taskgraph.compiler.FuseSteps), while a compiler that puts
57 the tasks into different traversals still hands the data on correctly.
58 Temporary data stay temporary: such data rely on the fusion anyway.
59
60 Do not use this for face data that several tasks of a chain access: A
61 writing task prevents the compiler from fusing them with the other tasks
62 that use the face data.
63
64 @param access: peano4.api.taskgraph.Task.DataAccess
65 Qualifier of the original, unsplit step.
66
67 @param position: int
68 Position of the task within the chain, starting with zero.
69
70 @param length: int
71 Number of tasks in the chain.
72
73 """
74 Access = peano4.api.taskgraph.Task.DataAccess
75 if access == Access.TEMPORARY:
76 return Access.TEMPORARY
77 load = access in (Access.READ_AND_DISCARD, Access.READ_AND_WRITE) or position > 0
78 store = access in (Access.WRITE, Access.READ_AND_WRITE) or position < length - 1
79 if load and store:
80 return Access.READ_AND_WRITE
81 if load:
82 return Access.READ_AND_DISCARD
83 if store:
84 return Access.WRITE
85 return Access.TEMPORARY
86
87
88def _readable_name(class_name: str) -> str:
89 """! Turn a class name such as AddLopsidedAdvection into the task name "Add lopsided advection" """
90 words = re.sub(r"(?<!^)(?=[A-Z])", " ", class_name).split()
91 return " ".join(words[:1] + [word.lower() for word in words[1:]])
92
93
95 """!
96
97 Fourth-order central Finite Differences with explicit Runge-Kutta time
98 stepping, realised over a block-structured mesh
99
100 Each mesh cell hosts a patch of patch_size^d grid cells. The unknowns
101 sit in the grid cells' centres. The scheme evaluates the right-hand side
102 of
103
104 @f$ \\partial _t Q = F(Q) @f$
105
106 through fourth-order central differences (@ref
107 exahype2.api.rkfd4.FD4Kernels), and integrates in time with the explicit
108 Runge-Kutta scheme from @ref exahype2.api.rungekutta.ButcherTableau. The
109 stencils reach two grid cells into the neighbouring patches, i.e. the
110 halo is HALO_SIZE=2 grid cells wide:
111
112 @image html central-differences-with-runge-kutta-stencil.png
113
114 The script central-differences-with-runge-kutta-illustrations.py next to
115 this file generates the illustrations of this page.
116
117 ## Usage
118
119 The scheme plugs into an exahype2.api.Solver like the Finite Volumes of
120 exahype2.api.fv, but with the grid construction and the plotter of
121 exahype2.api.rkfd4:
122
123 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
124 solver.numerical_scheme = exahype2.api.rkfd4.CentralDifferencesWithRungeKutta(solver, patch_size=9, rk_order=4)
125 solver.grid_construction = exahype2.api.rkfd4.SetupSimulationOverRegularGrid(solver, volume_size=0.01)
126 solver.plotter = exahype2.api.rkfd4.PlotAsVTKFile(solver, time_in_between_plots=0.1)
127 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
128
129 The solver can have a Flux, a NonconservativeProduct and a
130 VolumetricSource. It needs an InitPointWisely term, a MaxEigenvalue term
131 unless the time step size is fixed, and either a
132 DirichletBoundaryConditions or a SommerfeldBoundaryConditions term
133 unless all axes are periodic (@ref
134 exahype2.api.blockstructured.BoundaryConditions.get_boundary_conditions()). Sommerfeld
135 conditions also require a MaxEigenvalue term, and a Butcher tableau whose
136 stage time stamps do not decrease. @ref
137 benchmarks_exahype2_euler_smooth_setup demonstrates fourth-order
138 convergence for the Euler equations.
139
140 ## Extending the scheme
141
142 The scheme has no artificial dissipation. Subclasses can add further
143 terms to the right-hand side:
144
145 - _right_hand_side_action_sets() returns the action sets of the task
146 which evaluates the right-hand side of one stage. Subclasses can
147 append action sets which add their terms to the stage's estimate.
148 They run after the right-hand side kernel, within the same task.
149 - Subclasses which need wider stencils override HALO_SIZE.
150
151 @ref exagrype.api.FD4WithKODissipation adds the Kreiss-Oliger
152 dissipation this way.
153
154 ## Right-hand side kernels
155
156 The constructor's argument right_hand_side_kernel selects how the
157 scheme evaluates the right-hand side
158 (CentralDifferencesWithRungeKutta.RightHandSideKernel):
159
160 - CentralDifferences: all derivatives through fourth-order central
161 differences (@ref exahype2.api.rkfd4.FD4Kernels). This is the
162 default.
163 - CentralDifferencesWithLopsidedAdvection: the central differences
164 plus advection terms @f$ v_d \\partial _d Q_q @f$, which a separate
165 kernel discretises through lopsided (upwind-biased) fourth-order
166 stencils (@ref exahype2::fd::addLopsidedAdvection()). The kernel
167 runs after the central differences within each Runge-Kutta stage.
168 You specify the velocity v, which has to be part of Q, and the
169 advected quantities q. The PDE terms of the solver must not contain
170 these advection terms themselves. As the lopsided stencils reach
171 three grid cells into the neighbouring patches, the halo is three
172 grid cells wide.
173
174 ## Data flow
175
176 __create_data_structures() documents the data per mesh cell and
177 face. Per time step, the scheme runs through the Runge-Kutta stages
178 k=0,...,s-1. Stage k
179
180 1. reconstructs its input @f$ Y_k @f$ with a halo
181 (solver._patch_with_halo). The interior is solver._patch for the
182 first stage and solver._stage_input for all others, the halo is
183 taken from the faces (solver._patch_overlap_current_time_step);
184 2. evaluates the right-hand side @f$ K_k = F(Y_k) @f$ and stores it in
185 the stage's slot of solver._rhs_estimates;
186 3. computes the input of the next stage
187 @f$ Y_{k+1} = Q^n + \\Delta t \\sum _{j \\leq k} a_{k+1,j} K_j @f$
188 into solver._stage_input and projects it onto the faces, so the
189 neighbours can reconstruct their halo from it in the next stage.
190
191 The last stage computes
192 @f$ Q^{n+1} = Q^n + \\Delta t \\sum _k b_k K_k @f$ instead, i.e. it
193 overwrites solver._patch, and projects the new solution onto the faces,
194 where the first stage of the next time step picks it up.
195
196 As the reconstruction of a stage reads the face data the previous stage
197 has written, the task graph compiler maps each stage onto a mesh
198 traversal of its own (@ref peano4.api.taskgraph.compiler.FuseSteps).
199 For a second-order Runge-Kutta scheme with Dirichlet boundary
200 conditions, the time step's task graph reads:
201
202 @image html central-differences-with-runge-kutta-time-step-task-graph.png
203
204 The boundary values are evaluated at the time stamp of the respective
205 stage, i.e. at @f$ t^n + c_k \\Delta t @f$. Otherwise, the scheme would
206 drop to first order along the boundary.
207
208 ## Time step sizes
209
210 If you pass a time_step_size, the scheme uses this fixed time step size.
211 Otherwise, it derives the time step size from the maximum eigenvalue of
212 the solution after each time step through the CFL condition with
213 cfl_constant (@ref exahype2.api.rkfd4.actionsets.ComputeTimeStepSize).
214 This requires a MaxEigenvalue PDE term, with or without state.
215
216 """
217
218
219 HALO_SIZE = 2
220
221 @property
222 def halo_size(self) -> int:
223 """! Width of the halo. Alias of HALO_SIZE, as the generic parts of exahype2.api expect this name."""
224 return self.HALO_SIZE
225
226 class RightHandSideKernel(enum.Enum):
227 """!
228 The kernels which evaluate the right-hand side, @see the class documentation
229 """
230
231 CentralDifferences = 0
232 CentralDifferencesWithLopsidedAdvection = 1
233
235 self,
236 solver: Solver,
237 patch_size: int,
238 rk_order: int,
239 time_step_size: float = None,
240 cfl_constant: float = 0.5,
241 right_hand_side_kernel: "CentralDifferencesWithRungeKutta.RightHandSideKernel" = RightHandSideKernel.CentralDifferences,
242 advection_velocity=None,
243 advected_quantities=None,
244 min_volume_size: float = None,
245 max_volume_size: float = None,
246 interpolation: "toolbox.blockstructured.api.InterpolateHangingFaces.Scheme" = toolbox.blockstructured.api.InterpolateHangingFaces.Scheme.Linear,
247 restriction: "toolbox.blockstructured.api.RestrictHangingFaces.Scheme" = toolbox.blockstructured.api.RestrictHangingFaces.Scheme.Averaging,
248 ):
249 """!
250
251 The constructor memorises the attributes and creates the data
252 structures. It does not add the data to the solver's Peano 4
253 project yet, but it assigns them to the solver, so anybody else
254 working against this solver, such as the grid construction or the
255 plotter, finds them there.
256
257 @param solver: exahype2.api.Solver
258 The solver this numerical scheme realises.
259
260 @param patch_size: int
261 Number of grid cells per axis within one patch, i.e. within one
262 mesh cell. Has to be at least HALO_SIZE, as the projection onto
263 the faces takes the HALO_SIZE outermost layers of the patch.
264
265 @param rk_order: int
266 Order of the Runge-Kutta scheme, i.e. its number of stages. Has
267 to be between one and four, @ref
268 exahype2.api.rungekutta.ButcherTableau.
269
270 @param time_step_size: float or None
271 Fixed time step size. If None, the time step size is adaptive.
272
273 @param cfl_constant: float
274 CFL constant for adaptive time step sizes. It scales the time step
275 size h / (d lambda_max), with h the grid cell size, d the
276 dimension and lambda_max the maximum eigenvalue. Ignored if
277 time_step_size is set. Fourth-order central differences with the
278 classic fourth-order Runge-Kutta scheme are stable up to roughly
279 two for linear advection without dissipation, so 0.5 is a
280 conservative default.
281
282 @param right_hand_side_kernel: CentralDifferencesWithRungeKutta.RightHandSideKernel
283 The kernel which evaluates the right-hand side, @see the class
284 documentation.
285
286 @param advection_velocity: str or List[str or int] or None
287 Only for CentralDifferencesWithLopsidedAdvection: the entries of Q
288 which hold the advection velocity, one per dimension. Pass the name
289 of a variable with one entry per dimension (e.g. "shift" for
290 exagrype.api.FOCCZ4Solver), or a list of names or indices. The
291 velocity may be an auxiliary variable.
292
293 @param advected_quantities: List[str or int] or None
294 Only for CentralDifferencesWithLopsidedAdvection: the unknowns
295 which are advected, as names of variables or indices of entries,
296 @see exahype2.api.rkfd4.Quantities.resolve_quantities().
297
298 @param min_volume_size: float
299 The time step asks for a refinement of a cell only if its grid
300 cells are at least of this size (@ref exahype2.api.blockstructured.DynamicMeshRefinement).
301 None (the default) does not bound the refinement.
302
303 @param max_volume_size: float
304 The time step asks for an erase, i.e. coarsening, of a cell only
305 if the grid cells of the coarser cell would be strictly smaller
306 than this size. None (the default) does not bound the coarsening.
307
308 @param interpolation: toolbox.blockstructured.api.InterpolateHangingFaces.Scheme
309 How the scheme initialises the halo of a fine patch next to a
310 coarser patch on an adaptive mesh. Whenever a Runge-Kutta stage
311 reconstructs the halo of a fine cell, it interpolates the data of
312 the adjacent coarse face onto the fine cell's hanging face
313 (toolbox.blockstructured.api.InterpolateHangingFaces). The
314 default is linear interpolation.
315
316 @param restriction: toolbox.blockstructured.api.RestrictHangingFaces.Scheme
317 How the scheme hands the data of fine patches over to an adjacent
318 coarser patch. Whenever the fine cells project their data onto
319 their faces, the scheme restricts the data of the hanging faces
320 onto the coarse face (toolbox.blockstructured.api.RestrictHangingFaces).
321 The default is averaging.
322
323 On a regular mesh, there are no hanging faces, and the two schemes
324 are never used. At resolution transitions, the halo of a fine patch
325 is only as accurate as the interpolation, i.e. the scheme drops to
326 low order there.
327
328 """
329 super().__init__(solver)
330 self.interpolation = interpolation
331 self.restriction = restriction
332 if patch_size < self.HALO_SIZE:
333 raise ValueError(
334 f"Solver {solver.name}: patch_size has to be at least {self.HALO_SIZE}, "
335 f"as the stencils reach {self.HALO_SIZE} grid cells into "
336 f"the neighbouring patches, but got {patch_size}"
337 )
338 if time_step_size is not None and time_step_size <= 0.0:
339 raise ValueError(
340 f"Solver {solver.name}: time_step_size has to be positive, "
341 f"but got {time_step_size}"
342 )
343 if cfl_constant <= 0.0:
344 raise ValueError(
345 f"Solver {solver.name}: cfl_constant has to be positive, "
346 f"but got {cfl_constant}"
347 )
348 if not isinstance(
350 ):
351 raise TypeError(
352 f"Solver {solver.name}: right_hand_side_kernel has to be a "
353 f"CentralDifferencesWithRungeKutta.RightHandSideKernel, but got "
354 f"{right_hand_side_kernel!r}"
355 )
356 self.right_hand_side_kernel = right_hand_side_kernel
358 if right_hand_side_kernel == Kernel.CentralDifferencesWithLopsidedAdvection:
359 if advection_velocity is None or advected_quantities is None:
360 raise ValueError(
361 f"Solver {solver.name}: the kernel "
362 f"CentralDifferencesWithLopsidedAdvection needs an "
363 f"advection_velocity and advected_quantities"
364 )
365 if isinstance(advection_velocity, (str, int)):
366 advection_velocity = [advection_velocity]
367 self.advection_velocity = resolve_quantities(solver, advection_velocity)
368 self.advected_quantities = resolve_quantities(solver, advected_quantities)
369 # The lopsided stencils reach three grid cells into the neighbours
370 self.HALO_SIZE = max(self.HALO_SIZE, 3)
371 if patch_size < self.HALO_SIZE:
372 raise ValueError(
373 f"Solver {solver.name}: patch_size has to be at least "
374 f"{self.HALO_SIZE} for lopsided advection, but got {patch_size}"
375 )
376 else:
377 if advection_velocity is not None or advected_quantities is not None:
378 raise ValueError(
379 f"Solver {solver.name}: advection_velocity and "
380 f"advected_quantities are only used by the kernel "
381 f"CentralDifferencesWithLopsidedAdvection"
382 )
383 self.advection_velocity = None
384 self.advected_quantities = None
385 self.patch_size = patch_size
386 assert (
387 min_volume_size is None
388 or max_volume_size is None
389 or min_volume_size <= max_volume_size
390 ), f"min_volume_size={min_volume_size} has to be smaller than or equal to max_volume_size={max_volume_size}"
391 self.min_volume_size = min_volume_size
392 self.max_volume_size = max_volume_size
393 self.butcher_tableau = ButcherTableau(rk_order)
394 self.time_step_size = time_step_size
395 self.cfl_constant = cfl_constant
396 # Set in construct_output(): the generated kernels live in the project
397 # namespace
401
402 @property
403 def overlap(self) -> int:
404 """!
405 Width of the halo, i.e. number of grid cells each face holds per
406 adjacent patch. Always HALO_SIZE.
407 """
408 return self.HALO_SIZE
409
410 @property
411 def rk_order(self) -> int:
412 return self.butcher_tableau.order
413
414 @property
416 return self.time_step_size is None
417
418 @property
420 """!
421 Name of the generated right-hand side kernel. It carries the solver
422 name, as do the kernels/{SolverName}_fd4*.h files holding it, so
423 two solvers' kernels do not clash.
424 """
425 return self._solver.name + "_rightHandSideWithFD4"
426
427 @property
429 return self._solver.name + "_maxEigenvalueOverPatch"
430
431 def _right_hand_side_action_sets(self, stage, cell_guard):
432 """!
433
434 Action sets of the task which evaluates the right-hand side of one stage
435
436 The task reads solver._patch_with_halo, i.e. the stage's input with
437 its halo, and writes the stage's slot of solver._rhs_estimates. By
438 default, it holds one action set, which invokes the fourth-order
439 Finite Differences kernel. Subclasses can append action sets which
440 add further terms to the estimate. The action sets of one task run
441 one after the other, in the order of the list. For the kernel
442 CentralDifferencesWithLopsidedAdvection, the list holds the
443 lopsided advection as second action set.
444
445 @param stage: int
446 Number of the Runge-Kutta stage, starting with zero.
447
448 @param cell_guard: str
449 C++ boolean expression, evaluated per cell.
450
451 @return List[peano4.api.solversteps.ActionSet]
452
453 """
454 action_sets = [
455 EvaluateRungeKuttaRightHandSide(self._solver, stage, guard=cell_guard)
456 ]
457 if (
459 == CentralDifferencesWithRungeKutta.RightHandSideKernel.CentralDifferencesWithLopsidedAdvection
460 ):
461 action_sets.append(
462 AddLopsidedAdvection(
464 stage,
467 guard=cell_guard,
468 )
469 )
470 return action_sets
471
473 """!
474
475 Create the mesh data structures this numerical scheme requires
476
477 All of them are assigned to self._solver rather than self, so the
478 solver's grid construction and plotter, as well as the action sets,
479 find them there:
480
481 - _patch: the solution @f$ Q^n @f$, i.e. patch_size^d grid cells per
482 mesh cell, with the unknowns and the auxiliary variables per grid
483 cell.
484 - _stage_input: the input @f$ Y_k @f$ of the next Runge-Kutta stage,
485 with the same layout as _patch. It is written at the end of one
486 stage and read by the next one.
487 - _patch_with_halo: the input of the current Runge-Kutta stage
488 with its halo, i.e. (patch_size+2*HALO_SIZE)^d grid cells,
489 reconstructed from _patch or _stage_input and the faces (see
490 toolbox.blockstructured.api.ReconstructPatchWithHalo). It is
491 logically temporary.
492 - _rhs_estimates: the right-hand side estimates @f$ K_k @f$ of all
493 rk_order stages. They hold the unknowns only, as the auxiliary
494 variables do not evolve in time. The estimates of the stages are
495 stored one after the other, i.e. as rk_order patches of
496 patch_size^d grid cells each. This is why the first dimension is
497 rk_order*patch_size.
498 - _patch_overlap_current_time_step: the face data the halo is
499 reconstructed from, i.e. 2*HALO_SIZE layers along the face's
500 normal. The face data are exchanged between ranks.
501 - _patch_overlap_update: the projection of the patches onto the
502 faces which the current sweep accumulates (@ref
503 exahype2.api.rkfd4.actionsets.ProjectPatchOntoFaces). It is
504 rolled over into _patch_overlap_current_time_step once complete
505 (@ref exahype2.api.rkfd4.actionsets.RollOverUpdatedFace).
506 - _max_eigenvalue: only with adaptive time step sizes. One double
507 per cell, named after the solver followed by MaxEigenvalue. It
508 holds the maximum eigenvalue of the patch after the last time step.
509 It is modelled via DaStGen2 as array of cardinality one on the
510 heap (peano4.api.dastgen2.Peano4SmartPointerDoubleArray). A task of
511 its own reduces it into the generated abstract solver class
512 (reduceMaxEigenvalue()), and the global time step size computation
513 reads and resets the outcome (getAndResetMaxEigenvalue()). It
514 thus works on this global datum only, i.e. it is a task that acts
515 at the end of the time step
516 (@ref peano4.api.taskgraph.Task.Task.GridEntity).
517
518 All patches use smart pointers (@ref
519 peano4.api.datamodel.PatchToDoubleArrayWithSmartPointer), like the
520 Finite Volumes of exahype2.api.fv. The legacy
521 exahype2.solvers.rkfd.CellCenteredFiniteDifferences held a third
522 face overlap with the data of the previous time step. It is
523 required for AMR and local time stepping only, so we do not create
524 it.
525
526 """
527 total_unknowns = self._solver.unknowns
528 identifier = self._solver._unknown_identifier()
529 n = self.patch_size
530 h = self.HALO_SIZE
531
533 (n, n, n),
534 total_unknowns,
535 identifier,
536 )
537 self._solver._stage_input = peano4.api.datamodel.Patch(
538 (n, n, n),
539 total_unknowns,
540 identifier + "StageInput",
541 )
542 self._solver._patch_with_halo = peano4.api.datamodel.Patch(
543 (n + 2 * h, n + 2 * h, n + 2 * h),
544 total_unknowns,
545 identifier + "WithHalo",
546 )
547 self._solver._rhs_estimates = peano4.api.datamodel.Patch(
548 (self.rk_order * n, n, n),
549 self._solver.unknowns,
550 identifier + "RhsEstimates",
551 )
552 self._solver._patch_overlap_current_time_step = peano4.api.datamodel.Patch(
553 (2 * h, n, n),
554 total_unknowns,
555 identifier + "CurrentTimeStep",
556 )
557 self._solver._patch_overlap_update = peano4.api.datamodel.Patch(
558 (2 * h, n, n),
559 total_unknowns,
560 identifier + "Update",
561 )
563 self._solver._max_eigenvalue = peano4.api.datamodel.DaStGen2(
564 self._solver.name + "MaxEigenvalue"
565 )
566 self._solver._max_eigenvalue.data.add_attribute(
568 )
570 else:
571 self._solver._max_eigenvalue = None
572
574 """!
575
576 Let the generated abstract solver class host the maximum eigenvalue of a time step
577
578 The class collects the maximum over all patches and threads. This is
579 a reduction over the whole mesh, hence it belongs to the solver and
580 not to a cell. Reading and resetting it is one operation, as the
581 patches contribute in a different traversal than the one that
582 derives the time step size from it.
583
584 """
585 solver = self._solver
586 solver.add_user_solver_includes(
587 """
588#include "tarch/multicore/BooleanSemaphore.h"
589#include "tarch/multicore/Lock.h"
590"""
591 )
592 solver.add_abstract_solver_attribute("double _maxEigenvalueOfTimeStep{0.0};")
593 solver.add_abstract_solver_attribute(
594 "tarch::multicore::BooleanSemaphore _maxEigenvalueSemaphore;"
595 )
596 solver.add_abstract_solver_method(
597 "void reduceMaxEigenvalue(double eigenvalue);",
598 lambda qualified_class_name: "void "
599 + qualified_class_name
600 + "::reduceMaxEigenvalue(double eigenvalue) {\n"
601 + " tarch::multicore::Lock lock(_maxEigenvalueSemaphore);\n"
602 + " _maxEigenvalueOfTimeStep = std::max(_maxEigenvalueOfTimeStep, eigenvalue);\n"
603 + "}\n",
604 )
605 solver.add_abstract_solver_method(
606 "double getAndResetMaxEigenvalue();",
607 lambda qualified_class_name: "double "
608 + qualified_class_name
609 + "::getAndResetMaxEigenvalue() {\n"
610 + " tarch::multicore::Lock lock(_maxEigenvalueSemaphore);\n"
611 + " const double result = _maxEigenvalueOfTimeStep;\n"
612 + " _maxEigenvalueOfTimeStep = 0.0;\n"
613 + " return result;\n"
614 + "}\n",
615 )
616
617 def _patches(self):
618 """!
619 All patches of this numerical scheme, i.e. all data besides the
620 maximum eigenvalue.
621 """
622 return [
623 self._solver._patch,
624 self._solver._stage_input,
625 self._solver._patch_with_halo,
626 self._solver._rhs_estimates,
627 self._solver._patch_overlap_current_time_step,
628 self._solver._patch_overlap_update,
629 ]
630
631 def __add_data_to_repository(self, peano_project):
632 """!
633
634 Add the data from __create_data_structures() to the Peano 4 project
635 and configure their generators
636
637 Only _patch_overlap_current_time_step is exchanged between ranks,
638 and only on the faces the solver's grid selector holds for. The
639 task graph compiler uses, loads and stores data only where the
640 solver's grid selector holds, too (@ref peano4.api.datamodel.DoF).
641
642 """
643 peano4.api.Logger().log(
644 """
645Patch data
646----------
647{}
648Right-hand side estimates
649-------------------------
650{}
651Patch overlap data
652------------------
653{}
654{}""".format(
655 str(self._solver._patch),
656 str(self._solver._rhs_estimates),
657 str(self._solver._patch_overlap_current_time_step),
658 str(self._solver._patch_overlap_update),
659 )
660 )
661
662 peano_project.datamodel.add_cell(self._solver._patch)
663 peano_project.datamodel.add_cell(self._solver._stage_input)
664 peano_project.datamodel.add_cell(self._solver._patch_with_halo)
665 peano_project.datamodel.add_cell(self._solver._rhs_estimates)
666 peano_project.datamodel.add_face(self._solver._patch_overlap_current_time_step)
667 peano_project.datamodel.add_face(self._solver._patch_overlap_update)
668 register_auxiliary_variables(
669 self._solver, peano_project, self.patch_size, self.HALO_SIZE
670 )
671
672 data = self._patches()
674 peano_project.datamodel.add_cell(self._solver._max_eigenvalue)
675 data.append(self._solver._max_eigenvalue)
676 for entry in data:
677 entry.grid_selector = self._solver.grid_selector
678
679 for patch in self._patches():
681 patch, "double"
682 )
683
684 current_time_step = self._solver._patch_overlap_current_time_step
685 current_time_step.generator.merge_method_definition = (
686 toolbox.blockstructured.api.get_face_merge_implementation(current_time_step)
687 )
688 current_time_step.generator.includes += """
689#include "peano4/utils/Loop.h"
690"""
691 current_time_step.generator.send_condition = (
692 self._solver.grid_selector.createFaceGuard()
693 )
694 current_time_step.generator.receive_and_merge_condition = (
695 self._solver.grid_selector.createFaceGuard()
696 )
697
698 self._solver._patch_overlap_update.generator.send_condition = "false"
699 self._solver._patch_overlap_update.generator.receive_and_merge_condition = (
700 "false"
701 )
702
703 def __create_kernels(self, peano4_project):
704 """!
705
706 Translate the DSLHyPE kernels into C++
707
708 The kernels end up in the kernels/ subdirectory of output_directory:
709
710 - {SolverName}_fd4_2d.h/.cpph and {SolverName}_fd4_3d.h/.cpph hold
711 the right-hand side (@ref exahype2.api.rkfd4.FD4Kernels).
712 - {SolverName}_fd4_eigenvalue_2d.h/.cpph and
713 {SolverName}_fd4_eigenvalue_3d.h/.cpph hold the maximum
714 eigenvalue over a patch. They exist only with adaptive time step
715 sizes.
716 - {SolverName}_fd4.h includes the variants for the dimension the
717 code is compiled for.
718 - rungekutta_linear_combination.h/.cpph holds the linear combination
719 of the Runge-Kutta estimates (@ref
720 exahype2.api.rungekutta.LinearCombination).
721
722 Calling this function is delayed until all PDE term information is
723 provided, as the kernels contain only the PDE terms the solver has.
724
725 """
726 template_parameters = [
730 "NumberOfUnknowns", dslhype.SyntaxTree.TInteger()
731 ),
733 "NumberOfAuxiliaryVariables", dslhype.SyntaxTree.TInteger()
734 ),
735 ]
736 functor_parameters = [
738 "flux",
740 "const ::exahype2::fv::rusanov::FluxFunctor&"
741 ),
742 "(!llvm.ptr, !llvm.ptr, !llvm.ptr, f64, f64, i32, !llvm.ptr) -> ()",
743 ),
745 "nonconservativeProduct",
747 "const ::exahype2::fv::rusanov::NonconservativeProductFunctor&"
748 ),
749 "(!llvm.ptr, !llvm.ptr, !llvm.ptr, !llvm.ptr, f64, f64, i32, !llvm.ptr) -> ()",
750 ),
752 "volumetricSource",
754 "const ::exahype2::fv::rusanov::VolumetricSourceFunctor&"
755 ),
756 "(!llvm.ptr, !llvm.ptr, f64, !llvm.ptr) -> ()",
757 ),
759 "maxEigenvalue",
761 "const ::exahype2::fv::rusanov::MaxEigenvalueFunctor&"
762 ),
763 "(!llvm.ptr, !llvm.ptr, !llvm.ptr, f64, f64, i32, !llvm.ptr) -> ()",
764 ),
765 ]
766
767 kernels = [
768 (
769 FD4Kernels.rightHandSideWithFD42D,
770 "_fd4_2d",
772 ),
773 (
774 FD4Kernels.rightHandSideWithFD43D,
775 "_fd4_3d",
777 ),
778 ]
780 kernels += [
781 (
782 FD4Kernels.maxEigenvalueOverPatch2D,
783 "_fd4_eigenvalue_2d",
785 ),
786 (
787 FD4Kernels.maxEigenvalueOverPatch3D,
788 "_fd4_eigenvalue_3d",
790 ),
791 ]
792
793 output_directory = peano4_project.directory
794 temporary_output_directory = peano4_project.temporary_directory
795
796 for function, file_suffix, function_name in kernels:
797 dslhype.translate_dslhype_function(
798 function=function,
799 function_namespace=self.kernel_namespace,
800 template_parameters=template_parameters,
801 functor_parameters=functor_parameters,
802 pde_terms=self._solver.pde_terms,
803 output_file_name=self._solver.name + file_suffix,
804 target=dslhype.Target.Serial,
805 stateless=False,
806 function_name=function_name,
807 output_directory=temporary_output_directory,
808 )
809
810 for _, file_suffix, _ in kernels:
811 include_implementation_into_header(
812 os.path.join(temporary_output_directory, "kernels"),
813 f"{self._solver.name}{file_suffix}",
814 )
815
816 includes_2d = "\n".join(
817 f' #include "{self._solver.name}{file_suffix}.h"'
818 for _, file_suffix, _ in kernels
819 if file_suffix.endswith("2d")
820 )
821 includes_3d = "\n".join(
822 f' #include "{self._solver.name}{file_suffix}.h"'
823 for _, file_suffix, _ in kernels
824 if file_suffix.endswith("3d")
825 )
826 with open(
827 os.path.join(temporary_output_directory, "kernels", f"{self._solver.name}_fd4.h"), "w"
828 ) as file:
829 file.write(
830 f"""#pragma once
831#if Dimensions == 2
832{includes_2d}
833#else
834{includes_3d}
835#endif
836"""
837 )
838
839 generate_linear_combination_kernel(self.kernel_namespace, output_directory)
840
841 def __construct_kernel_call(self, function_name, additional_arguments):
842 """!
843
844 Construct the call of a generated kernel
845
846 The kernel takes a ::exahype2::CellData called patchData, the
847 additional arguments and one functor per PDE term the solver has,
848 in the order flux, nonconservativeProduct, volumetricSource,
849 maxEigenvalue (see __create_kernels()). Each functor forwards to
850 the solver instance.
851
852 If PDE terms are registered both with and without state, the
853 generated code asks cellCanUseStatelessPDETerms() before it invokes
854 the kernel, and hands over the stateless variants if it returns
855 true. This logic is a copy of the one of exahype2.api.fv, as rkfd4
856 does not depend on the Finite Volume package.
857
858 @param function_name: str
859 Unqualified name of the kernel.
860
861 @param additional_arguments: [str]
862 C++ expressions passed after patchData.
863
864 """
865 available_terms = [
866 "flux",
867 "nonconservativeProduct",
868 "volumetricSource",
869 "maxEigenvalue",
870 ]
871
872 # Variants per term the kernel takes: {name: {stateless: PDETerm}}
873 variants = {}
874 for application_term in self._solver.pde_terms:
875 if application_term.NAME in available_terms:
876 variants.setdefault(application_term.NAME, {})[
877 application_term.stateless
878 ] = application_term
879
880 terms_with_both_variants = [
881 name for name in variants if len(variants[name]) == 2
882 ]
883 terms_without_stateless_variant = [
884 name for name in variants if True not in variants[name]
885 ]
886 if terms_with_both_variants and terms_without_stateless_variant:
887 raise Exception(
888 f"Solver {self._solver.name}: the PDE terms {terms_with_both_variants} are "
889 f"registered both with and without state. In this case, the generated code "
890 f"asks cellCanUseStatelessPDETerms() per cell before it invokes the kernel: "
891 f"if it returns true, the kernel is called with the stateless variants of all "
892 f"PDE terms, otherwise with the variants with state. However, the PDE terms "
893 f"{terms_without_stateless_variant} have no stateless variant, so a kernel "
894 f"call would mix stateless and stateful routines. Either add stateless "
895 f"variants of {terms_without_stateless_variant}, or register "
896 f"{terms_with_both_variants} only once."
897 )
898
899 def kernel_call(stateless: bool) -> str:
900 arguments = ["patchData"] + list(additional_arguments)
901 for term in available_terms:
902 if term not in variants:
903 continue
904 # A term registered only once is used in either case
905 application_term = variants[term].get(
906 stateless, next(iter(variants[term].values()))
907 )
908 # Commas inside template brackets, e.g. Vector<Dimensions, double>,
909 # do not separate parameters
910 term_arguments = forwarding_arguments(
911 application_term.SIGNATURE, self._solver
912 )
913 # Stateless terms are static and take a dummy tag (@see PDETerm)
914 if application_term.stateless:
915 term_arguments.append("::exahype2::Solver::Offloadable::Yes")
916 arguments.append(
917 f"""
918 [&](
919 {application_term.SIGNATURE}
920 )->void {{
921 repositories::{self._solver.get_name_of_global_instance()}.{application_term.name}({", ".join(term_arguments)});
922 }}"""
923 )
924 return f"""::{"::".join(self.kernel_namespace)}::{function_name}<
925 {self.patch_size},
926 {self.HALO_SIZE},
927 {self._solver.unknowns},
928 {self._solver.number_of_auxiliary_variables}
929>(
930 {",".join(arguments)}
931);"""
932
933 if not terms_with_both_variants:
934 return kernel_call(stateless=False)
935 return f"""if (repositories::{self._solver.get_name_of_global_instance()}.cellCanUseStatelessPDETerms(
936 patchData.cellCentre[0],
937 patchData.cellSize[0],
938 patchData.t[0],
939 patchData.dt[0]
940)) {{
941{kernel_call(stateless=True)}
942}} else {{
943{kernel_call(stateless=False)}
944}}"""
945
946 def create_default_mesh_adaptation(self) -> Solver.MeshAdaptation:
947 """!
948
949 The finite differences adapt the mesh and balance the load through
950 exahype2.api.rkfd4.AdaptMeshAndBalanceLoad by default
951
952 """
953 from .AdaptMeshAndBalanceLoad import AdaptMeshAndBalanceLoad
954
956
958 self,
959 ) -> "toolbox.blockstructured.api.RestrictHangingFaces":
960 """!
961
962 Action set which restricts the projected fine data from the hanging
963 faces onto the coarse faces
964
965 Every task which projects the solution onto the faces has to host
966 this action set, so the faces between coarse and fine patches hold
967 consistent data afterwards. The task has to write all of
968 _patch_overlap_update, as averaging clears it first.
969
970 """
971 return toolbox.blockstructured.api.RestrictHangingFaces(
972 self._solver._patch_overlap_update,
973 scheme=self.restriction,
974 clear_guard=self._solver.grid_selector.createFaceGuard(),
975 additional_includes=self._solver._get_default_includes()
976 + self._solver.user_solver_includes,
977 )
978
980 self, exahype2_project, peano_project, time_step, add_global_tasks=True
981 ):
982 """!
983
984 Add the data to the Peano 4 project, generate the kernels and add
985 the tasks of one Runge-Kutta step to time_step
986
987 @param add_global_tasks: bool
988 If False, the scheme adds neither the task that switches the load
989 balancing off nor the last task that evaluates the adaptivity
990 criterion and switches the load balancing on again,
991 @see exahype2.api.Solver.Solver.NumericalScheme.construct_output().
992
993 Per stage k, the time step holds the following tasks (see the class
994 documentation for the data flow). Every task holds exactly one
995 action set, with the exception of the reconstruction of the
996 unknowns, which also holds the interpolation onto the hanging faces,
997 and the reconstruction of several sets of auxiliary variables. This is deliberate: the task graph compiler
998 runs the action sets of independent tasks in parallel only if each
999 task holds one action set (@ref peano4.api.taskgraph.compiler.FuseSteps).
1000 Where the scheme needs several action sets in a row, it hence creates
1001 a chain of tasks. If several solvers share a task graph, their chains
1002 overlap.
1003
1004 - {SolverName}_Disable load balancing: switches the load balancing
1005 off throughout the time step. Added last by
1006 wrap_task_graph_in_load_balancing_and_amr_tasks(), which makes all
1007 tasks without predecessor wait for it.
1008 - {SolverName}_Apply Dirichlet BCs stage k: sets the ghost grid
1009 cells along the domain boundary for Dirichlet boundary conditions.
1010 The task does not exist if all axes are periodic, or for Sommerfeld
1011 boundary conditions, which advance the ghost grid cells within the
1012 roll over of the projection onto the faces.
1013 - {SolverName}_Reconstruct stage k: interpolates the coarse face
1014 data onto the hanging faces and reconstructs the stage's input with
1015 its halo. Interpolation is no task of its own.
1016 - {SolverName}_Reconstruct auxiliary variables stage k: reconstructs
1017 the halos of the auxiliary variables. Exists only if the solver has
1018 auxiliary variables. Sets which are stationary throughout the time
1019 step (exahype2.api.AuxiliaryVariables.Mode.STATIONARY_THROUGHOUT_TIME_STEPS_ON_FACES)
1020 have this task in the first stage only: The right-hand-side tasks
1021 hold their halo as persistent cell data until the last stage
1022 discards it.
1023 - {SolverName}_Evaluate Runge-Kutta right hand side stage k. Where
1024 the right-hand side has further terms
1025 (_right_hand_side_action_sets()), each term adds a task behind it,
1026 e.g. {SolverName}_Add lopsided advection stage k.
1027 - {SolverName}_Prepare stage k+1, or {SolverName}_Complete time step
1028 after the last stage: computes the linear combination of the
1029 estimates. Prepare stage k+1 is tagged with
1030 exahype2.api.Solver.IntermediateSolutionUpdateTag, Complete time
1031 step with exahype2.api.Solver.SolutionUpdateTaskTag, i.e.
1032 postprocessing such as the enforcement of constraints can be
1033 inserted directly after them (see @ref
1034 page_exahype2_solver_manipulate_solver_steps).
1035 - {SolverName}_Compute max eigenvalue: determines the maximum
1036 eigenvalue of the new solution. Exists after the last stage for
1037 adaptive time stepping only.
1038 - {SolverName}_Project stage k+1 onto faces, or {SolverName}_Project
1039 solution onto faces after the last stage: projects the outcome of
1040 the linear combination onto the faces and restricts the hanging
1041 faces onto the coarse faces.
1042 - {SolverName}_Roll over stage k+1 faces, or {SolverName}_Roll over
1043 solution faces. The projection (with the restriction) and the roll over
1044 share the update patch, which is temporary, i.e. they rely on the
1045 task graph compiler to fuse them into one mesh traversal. Only
1046 the roll over writes the face data of the current time step, but
1047 the projection declares it, and the roll over declares it as
1048 temporary. If the roll over declared it, the projection would not conflict with the reconstruction, which reads
1049 the faces. The compiler would then fuse them into the traversal of
1050 the previous stage, and only the roll over would start a new
1051 traversal. The update patch does not survive such a split, and the
1052 roll over reads uninitialised data (observed as NaNs in the next
1053 stage's input). The fused traversal merges the qualifiers back into
1054 the one of the projection.
1055
1056 After the last stage, {SolverName}_Compute time step size determines
1057 the time step size of the next time step and advances the solver's
1058 time stamp. {SolverName}_Dynamic mesh refinement and load balancing finally evaluates the
1059 adaptivity criterion if the solver has one
1060 (@ref exahype2.api.blockstructured.create_dynamic_mesh_refinement_action_set.create_dynamic_mesh_refinement_action_set()),
1061 switches the load balancing on again and informs it that the time
1062 step has finished.
1063
1064 """
1065 peano4.api.Logger().log(
1066 "Create time stepping task graph for fourth-order Finite Differences "
1067 f"with Runge-Kutta of order {self.rk_order} over block-structured meshes"
1068 )
1069
1070 if self.advection_velocity is not None and len(self.advection_velocity) != len(
1071 exahype2_project.periodic_BC
1072 ):
1073 raise ValueError(
1074 f"Solver {self._solver.name}: the advection velocity has "
1075 f"{len(self.advection_velocity)} entries, but the domain has "
1076 f"{len(exahype2_project.periodic_BC)} dimensions"
1077 )
1078
1080 assert any(
1081 isinstance(term, MaxEigenvalue) for term in self._solver.pde_terms
1082 ), (
1083 f"Solver {self._solver.name} uses adaptive time step sizes, but has no "
1084 "MaxEigenvalue PDE term. Add one via "
1085 "solver.add_pde_term(exahype2.api.MaxEigenvalue(...)), or pass a "
1086 "time_step_size to CentralDifferencesWithRungeKutta."
1087 )
1088
1089 relative_time_step_sizes = self.butcher_tableau.relative_time_step_sizes()
1090 if isinstance(
1091 get_boundary_conditions(self._solver, exahype2_project),
1092 SommerfeldBoundaryConditions,
1093 ) and any(
1094 later < earlier
1095 for earlier, later in zip(
1096 relative_time_step_sizes, relative_time_step_sizes[1:]
1097 )
1098 ):
1099 raise ValueError(
1100 f"Solver {self._solver.name} uses Sommerfeld boundary conditions, but "
1101 f"the time stamps c={relative_time_step_sizes} of the stages of its "
1102 f"Runge-Kutta scheme of order {self.rk_order} decrease. The roll over "
1103 "advances the ghost grid cells from one stage to the next, so it "
1104 "requires non-decreasing time stamps "
1105 "(@ref exahype2::blockstructured::applySommerfeldBoundaryConditions())."
1106 )
1107
1108 self.__add_data_to_repository(peano_project)
1109
1110 self.kernel_namespace = peano_project.namespace
1111 # Construct the calls first, as they validate the PDE terms' variants
1112 self._solver.compute_kernel_call = self.__construct_kernel_call(
1114 )
1118 )
1119 self.__create_kernels(peano_project)
1120
1121 cell_guard = self._solver.grid_selector.createCellGuard()
1122 face_guard = self._solver.grid_selector.createFaceGuard()
1123 includes = (
1124 self._solver._get_default_includes() + self._solver.user_solver_includes
1125 )
1126 name = self._solver.name
1127 weight_matrix = self.butcher_tableau.weight_matrix()
1128 Access = peano4.api.taskgraph.Task.DataAccess
1129 Entity = peano4.api.taskgraph.Task.GridEntity
1130
1131 previous_stage_task = None
1132 for stage in range(self.rk_order):
1133 is_last_stage = stage == self.rk_order - 1
1134 stage_input = (
1135 self._solver._patch if stage == 0 else self._solver._stage_input
1136 )
1137
1138
1144 face_read = get_access_to_persistent_face_data(
1145 self._solver, exahype2_project, Access.READ_AND_DISCARD
1146 )
1147
1148
1149 reconstruction_task = peano4.api.taskgraph.Task(
1150 name=f"{name}_Reconstruct stage {stage}", entity=Entity.CELL
1151 )
1152 time_step.add_task(reconstruction_task)
1153 if previous_stage_task is not None:
1154 reconstruction_task.add_dependency(previous_stage_task)
1155
1159 reconstruction_task.use_cell(
1160 stage_input,
1161 Access.READ_AND_WRITE if stage == 0 else Access.READ_AND_DISCARD,
1162 )
1163 reconstruction_task.use_cell(self._solver._patch_with_halo, Access.WRITE)
1164 # Sommerfeld boundary conditions read the old face data within the
1165 # roll over, i.e. it has to survive the reconstruction
1166 reconstruction_task.use_face(
1167 self._solver._patch_overlap_current_time_step, face_read
1168 )
1169
1174 reconstruction_task.add_action_set(
1175 toolbox.blockstructured.api.InterpolateHangingFaces(
1176 self._solver._patch_overlap_current_time_step,
1177 scheme=self.interpolation,
1178 additional_includes=includes,
1179 )
1180 )
1181 reconstruction_task.add_action_set(
1182 toolbox.blockstructured.api.ReconstructPatchWithHalo(
1183 patch=stage_input,
1184 patch_overlap=self._solver._patch_overlap_current_time_step,
1185 reconstructed_patch=self._solver._patch_with_halo,
1186 guard=cell_guard,
1187 add_assertions_to_halo_exchange=False,
1188 additional_includes=includes,
1189 )
1190 )
1191
1195 boundary_task = ApplyDirichletBoundaryConditions.add_task_to_time_step(
1196 self._solver,
1197 exahype2_project,
1198 time_step,
1199 reconstruction_task,
1200 name_suffix=f" stage {stage}",
1201 relative_time_step_size=self.butcher_tableau.relative_time_step_sizes()[
1202 stage
1203 ],
1204 )
1205 if boundary_task is not None and previous_stage_task is not None:
1206 boundary_task.add_dependency(previous_stage_task)
1207
1208
1213 reconstruction_tasks = [reconstruction_task] + (
1214 add_reconstruction_tasks_of_auxiliary_variables(
1215 self._solver,
1216 time_step,
1217 self.interpolation,
1218 [previous_stage_task] if previous_stage_task is not None else [],
1219 name_suffix=f" stage {stage}",
1220 auxiliaries=[
1221 auxiliary
1222 for auxiliary in self._solver.auxiliary_variables
1223 if stage == 0 or not auxiliary.halo_is_held_through_stages
1224 ],
1225 )
1226 )
1227
1228
1231 right_hand_side_tasks = []
1232 for index, action_set in enumerate(
1233 self._right_hand_side_action_sets(stage, cell_guard)
1234 ):
1235 task_name = (
1236 "Evaluate Runge-Kutta right hand side"
1237 if index == 0
1238 else getattr(action_set, "TASK_NAME", None)
1239 or _readable_name(type(action_set).__name__)
1240 )
1242 name=f"{name}_{task_name} stage {stage}", entity=Entity.CELL
1243 )
1244 task.add_action_set(action_set)
1245 for dependency in (
1246 [right_hand_side_tasks[-1]]
1247 if right_hand_side_tasks
1248 else reconstruction_tasks
1249 ):
1250 task.add_dependency(dependency)
1251 time_step.add_task(task)
1252 right_hand_side_tasks.append(task)
1253 for position, task in enumerate(right_hand_side_tasks):
1254 length = len(right_hand_side_tasks)
1255 task.use_cell(
1256 self._solver._patch_with_halo,
1257 _access_within_chain(Access.READ_AND_DISCARD, position, length),
1258 )
1259
1265 task.use_cell(self._solver._rhs_estimates, Access.READ_AND_WRITE)
1266 use_halos_of_auxiliary_variables(
1267 task,
1268 self._solver,
1269 _access_within_chain(Access.READ_AND_DISCARD, position, length),
1270 # Halos that are held through the stages survive all but the last stage
1271 held_access=_access_within_chain(
1272 (
1273 Access.READ_AND_DISCARD
1274 if is_last_stage
1275 else Access.READ_AND_WRITE
1276 ),
1277 position,
1278 length,
1279 ),
1280 )
1281 right_hand_side_task = right_hand_side_tasks[-1]
1282
1283
1289 if is_last_stage:
1290 weights = self.butcher_tableau.final_estimate_weights()
1291 output = self._solver._patch
1292 combination_task = peano4.api.taskgraph.Task(
1293 name=f"{name}_Complete time step", entity=Entity.CELL
1294 )
1295 suffix = "solution"
1296 else:
1297 weights = weight_matrix[stage + 1]
1298 output = self._solver._stage_input
1299 combination_task = peano4.api.taskgraph.Task(
1300 name=f"{name}_Prepare stage {stage + 1}", entity=Entity.CELL
1301 )
1302 suffix = f"stage {stage + 1}"
1303 time_step.add_task(combination_task)
1304 combination_task.add_dependency(right_hand_side_task)
1305 combination_task.use_cell(self._solver._patch, Access.READ_AND_WRITE)
1306
1307 combination_task.use_cell(
1308 self._solver._rhs_estimates,
1309 Access.READ_AND_DISCARD if is_last_stage else Access.READ_AND_WRITE,
1310 )
1311 if not is_last_stage:
1312 combination_task.use_cell(self._solver._stage_input, Access.WRITE)
1313 combination_task.add_action_set(
1314 ComputeLinearCombination(
1315 self._solver, weights, output, guard=cell_guard
1316 )
1317 )
1318 combination_task.tags.add(
1319 Solver.SolutionUpdateTaskTag
1320 if is_last_stage
1321 else Solver.IntermediateSolutionUpdateTag
1322 )
1323
1324
1331 eigenvalue_task = None
1332 if is_last_stage and self.has_adaptive_time_step_size:
1333 eigenvalue_task = peano4.api.taskgraph.Task(
1334 name=f"{name}_Compute max eigenvalue", entity=Entity.CELL
1335 )
1336 eigenvalue_task.use_cell(output, Access.READ_AND_WRITE)
1337 eigenvalue_task.use_cell(self._solver._max_eigenvalue, Access.WRITE)
1338 for auxiliary in self._solver.auxiliary_variables:
1339 eigenvalue_task.use_cell(auxiliary.patch, Access.READ_AND_WRITE)
1340 eigenvalue_task.add_action_set(
1341 ComputeMaxEigenvalue(self._solver, guard=cell_guard)
1342 )
1343 eigenvalue_task.add_dependency(combination_task)
1344 time_step.add_task(eigenvalue_task)
1345 reduction_task = peano4.api.taskgraph.Task(
1346 name=f"{name}_Reduce max eigenvalue", entity=Entity.CELL
1347 )
1348 reduction_task.use_cell(
1349 self._solver._max_eigenvalue, Access.READ_AND_DISCARD
1350 )
1351 reduction_task.add_action_set(
1352 ReduceMaxEigenvalue(self._solver, guard=cell_guard)
1353 )
1354 reduction_task.add_dependency(eigenvalue_task)
1355 time_step.add_task(reduction_task)
1356
1357 projection_task = peano4.api.taskgraph.Task(
1358 name=f"{name}_Project {suffix} onto faces"
1359 if not is_last_stage
1360 else f"{name}_Project solution onto faces",
1361 entity=Entity.CELL,
1362 )
1363 projection_task.add_dependency(combination_task)
1364 projection_task.use_cell(output, Access.READ_AND_WRITE)
1365 projection_task.use_face(
1366 self._solver._patch_overlap_update, Access.TEMPORARY
1367 )
1368
1369 projection_task.use_face(
1370 self._solver._patch_overlap_current_time_step,
1371 get_access_to_persistent_face_data(
1372 self._solver, exahype2_project, Access.WRITE
1373 ),
1374 )
1375 projection_task.add_action_set(
1376 ProjectPatchOntoFaces(
1377 output,
1378 self._solver._patch_overlap_update,
1379 guard=cell_guard,
1380 includes=includes,
1381 )
1382 )
1383
1389 projection_task.add_action_set(self.create_restriction_of_hanging_faces())
1390 time_step.add_task(projection_task)
1391 if eigenvalue_task is not None:
1392 eigenvalue_task.add_dependency(projection_task)
1393
1394 # Sommerfeld boundary conditions advance the ghost grid cells
1395 # within the roll over, from the time stamp of this stage to the
1396 # one of the next stage (@ref exahype2.api.blockstructured.BoundaryConditions)
1397 next_relative_time_step_size = (
1398 1.0 if is_last_stage else relative_time_step_sizes[stage + 1]
1399 )
1400 roll_over_task = peano4.api.taskgraph.Task(
1401 name=f"{name}_Roll over {suffix} faces", entity=Entity.CELL
1402 )
1403 roll_over_task.use_face(
1404 self._solver._patch_overlap_update, Access.TEMPORARY
1405 )
1406 roll_over_task.use_face(
1407 self._solver._patch_overlap_current_time_step, Access.TEMPORARY
1408 )
1409 roll_over_task.add_action_set(
1410 RollOverUpdatedFaceWithSommerfeldBoundaryConditions.create_roll_over(
1411 self._solver,
1412 exahype2_project,
1413 guard=face_guard,
1414 includes=includes,
1415 time_step_size=(
1416 f"{next_relative_time_step_size - relative_time_step_sizes[stage]!r}"
1417 f" * repositories::{self._solver.get_name_of_global_instance()}.getMinTimeStepSize()"
1418 ),
1419 )
1420 )
1421 roll_over_task.add_dependency(projection_task)
1422 time_step.add_task(roll_over_task)
1423 previous_stage_task = roll_over_task
1424
1425
1427 time_step_size_task = peano4.api.taskgraph.Task(
1428 name=f"{name}_Compute time step size",
1429 entity=Entity.GLOBAL_END_OF_STEP,
1430 may_spawn_background_tasks=False,
1431 )
1432
1436 time_step_size_task.add_dependency(previous_stage_task)
1438 time_step_size_task.add_dependency(reduction_task)
1439 time_step_size_task.add_action_set(
1440 ComputeTimeStepSize(
1441 self._solver,
1442 self.patch_size,
1443 cfl_constant=self.cfl_constant
1445 else None,
1446 time_step_size=None
1448 else self.time_step_size,
1449 )
1450 )
1451 time_step.add_task(time_step_size_task)
1452
1453
1456 if add_global_tasks:
1458
1459 if peano4.api.Logger().is_visualisation:
1460 time_step.visualise(
1461 title="Time stepping task graph for {}".format(name)
1462 )
1463 if peano4.api.Logger().is_text:
1464 time_step.log_as_text(
1465 title="Time stepping task graph for {}".format(name)
1466 )
The concrete discretisation (Finite Volumes, ADER-DG, ...) realised by a Solver.
Definition Solver.py:60
wrap_task_graph_in_load_balancing_and_amr_tasks(self, time_step)
Embed the time step's task graph into the global load balancing and AMR tasks.
Definition Solver.py:108
Sommerfeld (radiative, outgoing) boundary conditions: waves leave the domain with little reflection,...
Default mesh adaptation of the fourth-order finite differences.
Fourth-order central Finite Differences with explicit Runge-Kutta time stepping, realised over a bloc...
__construct_kernel_call(self, function_name, additional_arguments)
Construct the call of a generated kernel.
"toolbox.blockstructured.api.RestrictHangingFaces" create_restriction_of_hanging_faces(self)
Action set which restricts the projected fine data from the hanging faces onto the coarse faces.
patch_size
The task must not run before the final roll over of the time step: Roll overs such as the Sommerfeld ...
__add_data_to_repository(self, peano_project)
Add the data from __create_data_structures() to the Peano 4 project and configure their generators.
Solver.MeshAdaptation create_default_mesh_adaptation(self)
The finite differences adapt the mesh and balance the load through exahype2.api.rkfd4....
__add_max_eigenvalue_reduction(self)
Let the generated abstract solver class host the maximum eigenvalue of a time step.
has_adaptive_time_step_size
The task must not run before the final roll over of the time step: Roll overs such as the Sommerfeld ...
construct_output(self, exahype2_project, peano_project, time_step, add_global_tasks=True)
Add the data to the Peano 4 project, generate the kernels and add the tasks of one Runge-Kutta step t...
__create_data_structures(self)
Create the mesh data structures this numerical scheme requires.
__init__(self, Solver solver, int patch_size, int rk_order, float time_step_size=None, float cfl_constant=0.5, "CentralDifferencesWithRungeKutta.RightHandSideKernel" right_hand_side_kernel=RightHandSideKernel.CentralDifferences, advection_velocity=None, advected_quantities=None, float min_volume_size=None, float max_volume_size=None, "toolbox.blockstructured.api.InterpolateHangingFaces.Scheme" interpolation=toolbox.blockstructured.api.InterpolateHangingFaces.Scheme.Linear, "toolbox.blockstructured.api.RestrictHangingFaces.Scheme" restriction=toolbox.blockstructured.api.RestrictHangingFaces.Scheme.Averaging)
The constructor memorises the attributes and creates the data structures.
_right_hand_side_action_sets(self, stage, cell_guard)
Action sets of the task which evaluates the right-hand side of one stage.
Singleton logger for the Peano 4 Python API.
Definition Logger.py:37
Specialisation of array using Peano's tarch with a smart pointer.
Default superclass for any data model in Peano which is stored within the grid.
Definition DaStGen2.py:189
Patch implementation of a degree of freedom.
Definition Patch.py:7
One task within a peano4.api.taskgraph.Graph.
Definition Task.py:8
"peano4.api.taskgraph.Task.DataAccess" _access_within_chain("peano4.api.taskgraph.Task.DataAccess" access, int position, int length)
Qualifier of one task within a chain of tasks that share cell data.
str _readable_name(str class_name)
Turn a class name such as AddLopsidedAdvection into the task name "Add lopsided advection".
The task graph abstraction allows users to formalise their solver steps over small task graphs which ...
Definition __init__.py:1