3from __future__
import annotations
7from typing
import Dict, List
17 A set of auxiliary variables of a solver
19 Auxiliary variables are quantities such as the sea floor, a mesh
20 distortion or a density which live in every Finite Volume (or Finite
21 Difference point) next to the unknowns, but which are not evolved by the
22 PDE. A solver can have an arbitrary number of such sets, each of them
23 vector-valued, e.g. ten bathymetry entries and another five entries
24 describing a mesh distortion. Each set is held by its own cell data
25 object, i.e. its own patch, rather than by the patch of the unknowns.
27 Create a set with a name and a dictionary which maps the names of the
28 parameters onto their multiplicities,
30 bathymetry = exahype2.api.AuxiliaryVariables("Bathymetry", {"b": 1})
32 and attach it to a solver via exahype2.api.Solver.add_auxiliary_variables().
33 The name is also the name of a struct within the generated abstract
34 solver, so you can write bathymetry[Bathymetry::b] in your C++ code.
36 ## Impact on the C++ signatures
38 Every PDE term of a solver with auxiliary variables receives, directly
39 behind each Q (and each deltaQ), one pointer per attached set. The
40 pointers come in the order in which the sets have been attached. The
41 pointer is named after the set (first letter in lower case), the pointers
42 behind deltaQ carry the prefix delta. For the set above and the flux, the
43 signature therefore reads
45 flux(const double* Q, const double* bathymetry, const Vector& x, int normal, double* F)
47 and the signature of the non-conservative product is
49 nonconservativeProduct(Q, bathymetry, deltaQ, deltaBathymetry, x, ...)
51 Solvers without auxiliary variables keep their original signatures.
53 ## Ownership and sharing
55 The first solver a set is attached to owns it. Only the owner's
56 initPointWisely() receives the set as writable argument and initialises
57 it. Further solvers can attach the same set object. They share the data,
58 i.e. they do not hold an additional copy, and initPointWisely() sees the
62 These quantities used to be called material parameters. "Material"
63 suggests that they are invariant, but they do not have to be: an
64 auxiliary variable is any quantity that lives next to the unknowns and
65 is not evolved by the PDE terms of the solver. It may well change over
66 time if some other mechanism updates it. The current implementation
67 writes the variables once during the setup, i.e. they are constant in
68 time, but this is a restriction of the implementation, not part of the
71 Besides periodic boundaries, the halo layer of the volumes at the
72 domain boundary is not available for auxiliary variables.
76 RECONSTRUCTION_TASK_NAME =
"Reconstruct auxiliary variables {}"
78 Name of the task that reconstructs the halo of a set, without solver prefix and
79 stage suffix. The argument is the name of the set.
85 Where the values of a set live and whether they change
87 Data on faces are always interpolated onto hanging faces before
88 anybody reads them (see
89 src/exahype2/api/adrs/0001-interpolation-and-restriction-ride-along-with-face-users.md).
91 - CELL_WISE: The values only sit in the cells, i.e. the faces hold no
92 overlap of the set. Reconstructing the halo of a cell, interpolating,
93 projecting and rolling over need face data, so the solver schemes
94 reject such sets for the time being.
95 - STATIONARY_ON_FACES: The values also sit on the faces, and they do
96 not change after the setup. The faces are interpolated, but nobody
97 projects new values onto them.
98 - CHANGING_ON_FACES: The values also sit on the faces, and some solver
99 updates them after the setup (such as
100 exagrype.api.FOSOReconstructionSolver). That solver projects the new
101 values onto the faces after each (intermediate) step, restricts them
102 on hanging faces and rolls the face data over.
103 - STATIONARY_THROUGHOUT_TIME_STEPS_ON_FACES: The values sit on the
104 faces and change between time steps (some task, such as the
105 preamble of a coupling, projects new values onto the faces and
106 restricts them at the begin of each time step), but not within a
107 time step. A scheme with several stages per time step (Runge-Kutta)
108 reconstructs the halo of such a set in the first stage only,
109 holds it persistently through the later stages, and discards it
110 in the last stage. The halo thus does not survive a time step. For
111 the other modes, the schemes reconstruct the halo in every stage.
115 STATIONARY_ON_FACES = 1
116 CHANGING_ON_FACES = 2
117 STATIONARY_THROUGHOUT_TIME_STEPS_ON_FACES = 3
122 variables: Dict[str, int],
123 mode:
"AuxiliaryVariables.Mode" = Mode.STATIONARY_ON_FACES,
124 data_name: str =
None,
129 Name of the set. Has to be a valid C++ identifier starting with a
130 capital letter. It feeds into the names of the data structures, the
131 name of the struct which hosts the positions of the variables
132 within the set, and - with a lower-case first letter - into the
133 name of the arguments in the PDE term signatures.
135 @param variables: dict
136 Maps the name of each parameter onto its multiplicity.
138 @param mode: AuxiliaryVariables.Mode
139 Whether the values also sit on the faces and whether they change
140 after the setup. Defaults to STATIONARY_ON_FACES. See
141 AuxiliaryVariables.Mode.
143 @param data_name: str
144 Name of the generated data (patch and face overlaps). Defaults to
145 the name of the set plus "AuxiliaryVariables".
147 if not re.fullmatch(
r"[A-Z][A-Za-z0-9_]*", name):
149 f
"The name of a set of auxiliary variables has to be a valid C++ identifier starting with a capital letter, but got {name!r}"
151 if not isinstance(variables, dict)
or not variables:
153 "variables has to be a non-empty dict which maps variable names onto multiplicities"
159 for variable_name, multiplicity
in self.
_variables.items():
162 f
"Auxiliary variable {variable_name} of {name} has multiplicity {multiplicity}"
165 offset += multiplicity
170 f
"mode has to be an AuxiliaryVariables.Mode, but got {mode!r}"
174 data_name
if data_name
is not None else name +
"AuxiliaryVariables"
190 def mode(self) -> "AuxiliaryVariables.Mode":
191 """! Whether the values sit on the faces, and whether they change after the setup"""
196 """! Name of the generated data"""
201 """! Total number of entries of the set, i.e. the sum of all multiplicities"""
210 """! Position of each named variable within the set"""
215 """! The solver which initialises the set, i.e. the first one it was attached to"""
220 """! Name of the argument of the PDE terms"""
227 Whether the halo has to be reconstructed in the first stage of a time step only
229 True for AuxiliaryVariables.Mode.STATIONARY_THROUGHOUT_TIME_STEPS_ON_FACES.
234 == AuxiliaryVariables.Mode.STATIONARY_THROUGHOUT_TIME_STEPS_ON_FACES
239 """! Name of the argument behind deltaQ"""
240 return "delta" + self.
_name
244 One name per entry of the set, qualified by the set's name. A
245 variable of multiplicity k yields k names with an index.
248 for variable_name, multiplicity
in self.
_variables.items():
249 if multiplicity == 1:
250 names.append(f
"{self._name}.{variable_name}")
253 f
"{self._name}.{variable_name}[{j}]" for j
in range(multiplicity)
258 """! C++ struct which hosts the positions of the variables within the set"""
259 constants =
"\n".join(
260 f
" static constexpr int {variable_name} = {position};"
261 for variable_name, position
in self.
_positions.items()
264 f
" /**\n * Positions of the variables of the auxiliary variables {self._name}\n */\n"
265 f
" struct {self._name} {{\n{constants}\n }};"
271 Create the cell and face data of the set
273 The routine is idempotent, as a set may be shared by several solvers:
274 the first call creates the data, any further call checks that the
275 numerical schemes of the solvers agree on the patch size and halo.
277 @param patch_size: int
278 Number of volumes per axis within a patch.
281 Width of the halo layer.
283 @param grid_selector: peano4.api.toolbox.GridSelector
284 Selects the mesh entities which hold data.
287 if self.
patch is not None:
290 f
"The auxiliary variables {self._name} are shared by solvers with different patch sizes or halos: "
291 f
"{self._patch_size}/{self._overlap} vs {patch_size}/{overlap}"
298 (patch_size, patch_size, patch_size), self.
_size, identifier
301 (2 * overlap, patch_size, patch_size),
303 identifier +
"CurrentTimeStep",
306 (2 * overlap, patch_size, patch_size), self.
_size, identifier +
"Update"
313 patch.grid_selector = grid_selector
318 toolbox.blockstructured.api.get_face_merge_implementation(
323#include "peano4/utils/Loop.h"
326 grid_selector.createFaceGuard()
329 grid_selector.createFaceGuard()
335 """! Register the data with the project (once, even if the set is shared)"""
339 peano_project.datamodel.add_cell(self.
patch)
344 return f
"{self._name}: {self._variables}"
348 """! Split a C++ parameter list at the commas that are not within template brackets"""
351 for parameter
in re.split(
r",(?![^<]*>)", signature)
359 Add the pointers to the auxiliary variables of a solver to a PDE term's
362 Each argument named Q is followed by one pointer per set, each argument
363 named deltaQ is followed by one pointer to the jump of each set. The
364 pointers are non-const iff Q is non-const (the initial condition) and the
367 @param signature: str
368 The signature without auxiliary variables
370 @param solver: exahype2.api.Solver
373 sets = solver.auxiliary_variables
378 result.append(parameter)
379 name = parameter.split()[-1]
381 writable =
not parameter.startswith(
"const")
382 for auxiliary
in sets:
383 qualifier =
"" if writable
and auxiliary.owner
is solver
else "const "
385 f
"{qualifier}double* __restrict__ {auxiliary.argument_name}"
387 elif name ==
"deltaQ":
388 for auxiliary
in sets:
390 f
"const double* __restrict__ {auxiliary.delta_argument_name}"
392 return ", ".join(result)
398 Arguments to call the version of a PDE term with auxiliary variables
399 from a caller that holds the original signature
401 The caller's Q (and deltaQ) points to a volume in a buffer which hosts
402 the unknowns followed by the entries of all auxiliary variables (the
403 layout the compute kernels work on). The auxiliary variables are slices
409 name = parameter.split()[-1]
410 arguments.append(name)
411 if name
in (
"Q",
"deltaQ"):
412 for auxiliary
in solver.auxiliary_variables:
414 f
"{name} + {solver.auxiliary_variable_offset(auxiliary)}"
422 Create and register the data of all auxiliary variables of a solver
424 The persistent data of a set (its patch and the face overlaps) exists only
425 once, even if several solvers share it. Each solver gets its own
426 temporary patch with halo per set (solver._auxiliary_variable_halos, a
427 dict from the name of the set to the patch), so concurrently running
428 solvers do not overwrite each other's halos.
431 solver._auxiliary_variable_halos = {}
432 for auxiliary
in solver.auxiliary_variables:
433 if auxiliary.mode == AuxiliaryVariables.Mode.CELL_WISE:
434 raise NotImplementedError(
435 f
"Solver {solver.name}: the auxiliary variables {auxiliary.name} are cell-wise, i.e. not on the faces. "
436 "The numerical schemes reconstruct the halos of auxiliary variables from the face data."
438 auxiliary.create_data_structures(patch_size, overlap, solver.grid_selector)
439 auxiliary.add_to_datamodel(peano_project)
442 patch_size + 2 * overlap,
443 patch_size + 2 * overlap,
444 patch_size + 2 * overlap,
447 auxiliary.data_name +
"WithHaloOf" + solver.name,
449 halo.grid_selector = solver.grid_selector
453 peano_project.datamodel.add_cell(halo)
454 solver._auxiliary_variable_halos[auxiliary.name] = halo
460 Make a reconstruction task of a solver fill the halos of the solver's
463 @param task: peano4.api.taskgraph.Task
464 The task which reconstructs the halos.
466 @param auxiliaries: List[AuxiliaryVariables]
467 The sets to reconstruct. Defaults to all sets of the solver.
470 Access = peano4.api.taskgraph.Task.DataAccess
471 if auxiliaries
is None:
472 auxiliaries = solver.auxiliary_variables
473 for auxiliary
in auxiliaries:
474 halo = solver._auxiliary_variable_halos[auxiliary.name]
475 task.use_cell(auxiliary.patch, Access.READ_AND_WRITE)
476 task.use_cell(halo, Access.WRITE)
477 task.use_face(auxiliary.patch_overlap_current_time_step, Access.READ_AND_WRITE)
479 toolbox.blockstructured.api.ReconstructPatchWithHalo(
480 patch=auxiliary.patch,
481 patch_overlap=auxiliary.patch_overlap_current_time_step,
482 reconstructed_patch=halo,
483 guard=solver.grid_selector.createCellGuard(),
484 add_assertions_to_halo_exchange=
False,
485 additional_includes=solver._get_default_includes()
486 + solver.user_solver_includes,
492 solver, time_step, interpolation, predecessors=(), name_suffix=
"", auxiliaries=
None
496 Add the tasks that interpolate and reconstruct the auxiliary variables
498 Each set of auxiliary variables gets a task of its own that interpolates
499 its coarse face data onto the hanging faces and reconstructs its halo
500 (register_auxiliary_variables() rejects cell-wise sets).
501 Interpolation is no task of its own, see
502 src/exahype2/api/adrs/0001-interpolation-and-restriction-ride-along-with-face-users.md.
503 All tasks depend on the predecessors only, i.e. the reconstructions of all
504 sets (and of the unknowns, which the caller creates) run in parallel.
506 @param solver: exahype2.api.Solver
507 The solver whose sets are reconstructed.
509 @param time_step: peano4.api.taskgraph.Graph
512 @param interpolation: toolbox.blockstructured.api.InterpolateHangingFaces.Scheme
513 Interpolation scheme.
515 @param predecessors: List[peano4.api.taskgraph.Task]
516 Tasks which the new tasks wait for.
518 @param name_suffix: str
519 Appended to the names of the tasks, e.g. " stage 1".
521 @param auxiliaries: List[AuxiliaryVariables]
522 The sets to reconstruct. Defaults to all sets of the solver. A scheme
523 with several stages passes only the sets whose halo has not been
524 held through the stages (AuxiliaryVariables.halo_is_held_through_stages).
526 @return List[peano4.api.taskgraph.Task]
527 The reconstruction tasks, one per set. The update of the cells has to
528 wait for all of them.
531 Entity = peano4.api.taskgraph.Task.GridEntity
534 solver.auxiliary_variables
if auxiliaries
is None else auxiliaries
537 name=f
"{solver.name}_{AuxiliaryVariables.RECONSTRUCTION_TASK_NAME.format(auxiliary.name)}{name_suffix}",
541 reconstruction.add_action_set(
542 toolbox.blockstructured.api.InterpolateHangingFaces(
543 auxiliary.patch_overlap_current_time_step,
544 scheme=interpolation,
545 additional_includes=solver._get_default_includes()
546 + solver.user_solver_includes,
550 for predecessor
in predecessors:
551 reconstruction.add_dependency(predecessor)
552 time_step.add_task(reconstruction)
553 reconstructions.append(reconstruction)
554 return reconstructions
560 Let a task (typically the update of the cells) read the halos of the auxiliary variables
562 @param access: peano4.api.taskgraph.Task.DataAccess
563 How the task uses the halos. Defaults to READ_AND_DISCARD. Pass another
564 qualifier if the halos have to survive the task, e.g. because a later
565 task of the same chain reads them, too.
567 @param held_access: peano4.api.taskgraph.Task.DataAccess
568 How the task uses the halos of the sets whose halo is held through
569 the stages of a time step
570 (AuxiliaryVariables.halo_is_held_through_stages). Defaults to access.
571 Schemes with several stages pass a qualifier that keeps the halo alive
572 unless the task belongs to the last stage.
576 access = peano4.api.taskgraph.Task.DataAccess.READ_AND_DISCARD
577 if held_access
is None:
579 for auxiliary
in solver.auxiliary_variables:
581 solver._auxiliary_variable_halos[auxiliary.name],
582 held_access
if auxiliary.halo_is_held_through_stages
else access,
587 """! C++ expression for the number of volumes of a patch with halo"""
588 edge = f
"({patch_size} + 2 * {halo})"
589 return f
"({edge} * {edge} * (Dimensions == 3 ? {edge} : 1))"
593 solver, buffer: str, unknowns: str, halo_size: int, parameters_of=
None
597 C++ code which assembles the input buffer of the compute kernels
599 The kernels work on one buffer that holds the unknowns of a volume
600 followed by the entries of all sets of auxiliary variables. The code
601 defines a std::vector<double> named buffer. It is empty if the solver has
602 no auxiliary variables.
605 C++ expression for the unknowns of the patch with halo.
607 @param parameters_of: function
608 Maps a set onto the C++ expression of its patch with halo. Defaults to
609 the halo patches of the solver.
612 if not solver.auxiliary_variables:
614 if parameters_of
is None:
616 lambda auxiliary: f
"fineGridCell{solver._auxiliary_variable_halos[auxiliary.name].name}.value"
619 stride = solver.unknowns + solver.number_of_auxiliary_variables
622 for (int k=0; k<{auxiliary.size}; k++) {{
623 {buffer}[volume*{stride} + {solver.auxiliary_variable_offset(auxiliary)} + k] = {parameters_of(auxiliary)}[volume*{auxiliary.size} + k];
625 for auxiliary
in solver.auxiliary_variables
628 const int {buffer}Volumes = {volumes};
629 std::vector<double> {buffer}( {buffer}Volumes * {stride}, 0.0 );
630 for (int volume=0; volume<{buffer}Volumes; volume++) {{
631 for (int k=0; k<{solver.unknowns}; k++) {{
632 {buffer}[volume*{stride} + k] = {unknowns}[volume*{solver.unknowns} + k];
639 """! C++ code which defines the output buffer (a std::vector<double>) of the compute kernels"""
640 if not solver.auxiliary_variables:
643 stride = solver.unknowns + solver.number_of_auxiliary_variables
645 const int {buffer}Volumes = {volumes};
646 std::vector<double> {buffer}( {buffer}Volumes * {stride}, 0.0 );
651 """! C++ code which copies the unknowns of the output buffer back into the patch"""
652 if not solver.auxiliary_variables:
654 stride = solver.unknowns + solver.number_of_auxiliary_variables
656 for (int volume=0; volume<{buffer}Volumes; volume++) {{
657 for (int k=0; k<{solver.unknowns}; k++) {{
658 {unknowns}[volume*{solver.unknowns} + k] = {buffer}[volume*{stride} + k];
666 initial_condition_task,
667 project_on_faces_task,
668 project_patch_onto_faces,
669 roll_over_updated_face,
673 Let the setup of a solver write its auxiliary variables
675 Auxiliary variables are written once, by their owner: the owner
676 initialises them in its initial condition task and projects them onto the
677 faces, so the halos can be reconstructed later on. A solver that merely
678 shares a set reads it after the owner has written it.
680 @param project_patch_onto_faces: class
681 The action set that projects a patch onto the faces
682 (exahype2.api.fv.actionsets.ProjectPatchOntoFaces).
684 @param roll_over_updated_face: class
685 The action set that rolls the projection over
686 (exahype2.api.fv.actionsets.RollOverUpdatedFace).
689 Access = peano4.api.taskgraph.Task.DataAccess
690 includes = solver._get_default_includes() + solver.user_solver_includes
691 for auxiliary
in solver.auxiliary_variables:
693 auxiliary.create_data_structures(
694 solver.numerical_scheme.patch_size,
695 solver.numerical_scheme.halo_size,
696 solver.grid_selector,
698 if auxiliary.owner
is solver:
699 initial_condition_task.use_cell(auxiliary.patch, Access.WRITE)
700 project_on_faces_task.use_cell(auxiliary.patch, Access.READ_AND_WRITE)
701 project_on_faces_task.use_face(
702 auxiliary.patch_overlap_update, Access.TEMPORARY
704 project_on_faces_task.use_face(
705 auxiliary.patch_overlap_current_time_step, Access.WRITE
707 project_on_faces_task.add_action_set(
708 project_patch_onto_faces(
710 auxiliary.patch_overlap_update,
711 guard=solver.grid_selector.createCellGuard(),
715 project_on_faces_task.add_action_set(
716 roll_over_updated_face(
717 auxiliary.patch_overlap_current_time_step,
718 auxiliary.patch_overlap_update,
719 guard=solver.grid_selector.createFaceGuard(),
723 auxiliary._setup_initial_condition_task = initial_condition_task
725 owners_task = getattr(auxiliary,
"_setup_initial_condition_task",
None)
726 if owners_task
is None:
728 f
"Solver {solver.name} shares the auxiliary variables {auxiliary.name} with "
729 f
"{auxiliary.owner.name}, but the setup of {auxiliary.owner.name} has not been created yet. "
730 f
"Add {auxiliary.owner.name} to the project before {solver.name}."
732 initial_condition_task.add_dependency(owners_task)
733 initial_condition_task.use_cell(auxiliary.patch, Access.READ_AND_DISCARD)
734 project_on_faces_task.use_cell(auxiliary.patch, Access.READ_AND_WRITE)
Where the values of a set live and whether they change.
A set of auxiliary variables of a solver.
peano4.api.datamodel.Patch patch_overlap_current_time_step
owner(self)
The solver which initialises the set, i.e.
__init__(self, str name, Dict[str, int] variables, "AuxiliaryVariables.Mode" mode=Mode.STATIONARY_ON_FACES, str data_name=None)
int size(self)
Total number of entries of the set, i.e.
Dict[str, int] variable_positions(self)
Position of each named variable within the set.
List[str] variable_names_per_entry(self)
One name per entry of the set, qualified by the set's name.
"AuxiliaryVariables.Mode" _mode
str data_name(self)
Name of the generated data.
Dict[str, int] variables(self)
peano4.api.datamodel.Patch patch
str variables_declaration(self)
C++ struct which hosts the positions of the variables within the set.
peano4.api.datamodel.Patch patch_overlap_update
bool halo_is_held_through_stages(self)
Whether the halo has to be reconstructed in the first stage of a time step only.
create_data_structures(self, int patch_size, int overlap, grid_selector)
Create the cell and face data of the set.
"AuxiliaryVariables.Mode" mode(self)
Whether the values sit on the faces, and whether they change after the setup.
Dict[str, int] _variables
str delta_argument_name(self)
Name of the argument behind deltaQ.
str argument_name(self)
Name of the argument of the PDE terms.
add_to_datamodel(self, peano_project)
Register the data with the project (once, even if the set is shared).
Realise patch via smart pointers.
Patch implementation of a degree of freedom.
One task within a peano4.api.taskgraph.Graph.
List[str] split_signature(str signature)
Split a C++ parameter list at the commas that are not within template brackets.
str volumes_expression(int patch_size, int halo)
C++ expression for the number of volumes of a patch with halo.
str code_to_assemble_kernel_input(solver, str buffer, str unknowns, int halo_size, parameters_of=None)
C++ code which assembles the input buffer of the compute kernels.
List[str] forwarding_arguments(str signature, solver)
Arguments to call the version of a PDE term with auxiliary variables from a caller that holds the ori...
use_halos_of_auxiliary_variables(task, solver, access=None, held_access=None)
Let a task (typically the update of the cells) read the halos of the auxiliary variables.
str extend_signature(str signature, solver)
Add the pointers to the auxiliary variables of a solver to a PDE term's signature.
add_reconstruction_of_auxiliary_variables(task, solver, auxiliaries=None)
Make a reconstruction task of a solver fill the halos of the solver's auxiliary variables.
str code_to_copy_back_kernel_output(solver, str buffer, str unknowns)
C++ code which copies the unknowns of the output buffer back into the patch.
str code_to_allocate_kernel_output(solver, str buffer)
C++ code which defines the output buffer (a std.vector<double>) of the compute kernels.
add_auxiliary_variables_to_setup(solver, initial_condition_task, project_on_faces_task, project_patch_onto_faces, roll_over_updated_face)
Let the setup of a solver write its auxiliary variables.
add_reconstruction_tasks_of_auxiliary_variables(solver, time_step, interpolation, predecessors=(), name_suffix="", auxiliaries=None)
Add the tasks that interpolate and reconstruct the auxiliary variables.
register_auxiliary_variables(solver, peano_project, int patch_size, int overlap)
Create and register the data of all auxiliary variables of a solver.
The task graph abstraction allows users to formalise their solver steps over small task graphs which ...