Peano
Loading...
Searching...
No Matches
RusanovWithExplicitEuler.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 os
4import re
5
6import peano4.api
10import toolbox.loadbalancing.api.actionsets
11import exahype2.api
12from exahype2.api import Target, OutputLanguage, MemoryLayout
13from collections import OrderedDict
14
15# This solver is using the rewritten version
16import exahype2.api.dslhype2 as dslhype
17
18from ..Solver import Solver
19from ..AuxiliaryVariables import (
20 register_auxiliary_variables,
21 add_reconstruction_tasks_of_auxiliary_variables,
22 use_halos_of_auxiliary_variables,
23 forwarding_arguments,
24)
25from ..blockstructured.BoundaryConditions import get_access_to_persistent_face_data
26from ..blockstructured.create_dynamic_mesh_refinement_action_set import (
27 create_dynamic_mesh_refinement_action_set,
28)
29from .actionsets import ApplyDirichletBoundaryConditions
30from .actionsets import ProjectPatchOntoFaces
31from .actionsets import RollOverUpdatedFaceWithSommerfeldBoundaryConditions
32from .actionsets import UpdateCell
33from .actionsets import UpdateCellGPU
34from .actionsets import ComputeGlobalCFLCondition
35from .actionsets import ComputeMaxEigenvalue
36from .actionsets import ReduceMaxEigenvalue
37from .MaxEigenvalueReduction import add_max_eigenvalue_reduction
38
39from ..VolumetricSource import VolumetricSource
40from ..Flux import Flux
41from ..NonconservativeProduct import NonconservativeProduct
42from ..MaxEigenvalue import MaxEigenvalue
43
54
55
56
57def timeStepWithRusanov2D(patchData: "::exahype2::CellData<double, double>&") -> "void":
58 N = Integer("patchData.numberOfCells")
59 t = DataBlock([[0, N]], "patchData.t", "double")
60 dt = DataBlock([[0, N]], "patchData.dt", "double")
61 h = DataBlock([[0, N]], "patchData.cellSize", "tarch::la::Vector<2, double>")
62 x = DataBlock([[0, N]], "patchData.cellCentre", "tarch::la::Vector<2, double>")
63
64 input = DataBlock([[0, NumberOfUnknowns + NumberOfAuxiliaryVariables], [-H, NV + H], [-H, NV + H], [0, N]], "patchData.QIn")
65 output = DataBlock([[0, NumberOfUnknowns + NumberOfAuxiliaryVariables], [0, NV], [0, NV], [0, N]], "patchData.QOut")
66 output = input[:, 0:NV, 0:NV]
67
68 if volumetricSource:
69 source = DataBlock([[0, NumberOfUnknowns], [0, NV], [0, NV], [0, N]], eval("volumetricSource", input[:, 0:NV, 0:NV], x, t))
70 output[0:NumberOfUnknowns, :, :] = output[0:NumberOfUnknowns, :, :] + dt * source
71
72 # The Rusanov flux at a face needs the eigenvalues of both adjacent
73 # volumes, i.e. the patch volumes plus the one halo layer across each
74 # face along the normal. We never evaluate the remaining halo (edges,
75 # corners), which holds no valid data.
76 maxEigenvaluesX = DataBlock([[0, 1], [-1, NV + 1], [0, NV], [0, N]], eval("maxEigenvalue", input[:, -1:NV+1, 0:NV], x, 0))
77 maxEigenvaluesY = DataBlock([[0, 1], [0, NV], [-1, NV + 1], [0, N]], eval("maxEigenvalue", input[:, 0:NV, -1:NV+1], x, 1))
78
79 lambdaLeft = max(maxEigenvaluesX[0:1, -1:NV-1, 0:NV], maxEigenvaluesX[0:1, 0:NV, 0:NV])
80 lambdaRight = max(maxEigenvaluesX[0:1, 0:NV, 0:NV], maxEigenvaluesX[0:1, 1:NV + 1, 0:NV])
81 lambdaBottom = max(maxEigenvaluesY[0:1, 0:NV, -1:NV-1], maxEigenvaluesY[0:1, 0:NV, 0:NV])
82 lambdaTop = max(maxEigenvaluesY[0:1, 0:NV, 0:NV], maxEigenvaluesY[0:1, 0:NV, 1:NV + 1])
83
84 fluxLeft = -1.0 * lambdaLeft * (input[0:NumberOfUnknowns, 0:NV, 0:NV] - input[0:NumberOfUnknowns, -1:NV-1, 0:NV])
85 fluxRight = -1.0 * lambdaRight * (input[0:NumberOfUnknowns, 1:NV+1, 0:NV] - input[0:NumberOfUnknowns, 0:NV, 0:NV])
86 output[0:NumberOfUnknowns, :, :] = output[0:NumberOfUnknowns, :, :] + dt / h(0) * (fluxLeft - fluxRight) * NV * 0.5
87
88 fluxBottom = -1.0 * lambdaBottom * (input[0:NumberOfUnknowns, 0:NV, 0:NV] - input[0:NumberOfUnknowns, 0:NV, -1:NV-1])
89 fluxTop = -1.0 * lambdaTop * (input[0:NumberOfUnknowns, 0:NV, 1:NV+1] - input[0:NumberOfUnknowns, 0:NV, 0:NV])
90 output[0:NumberOfUnknowns, :, :] = output[0:NumberOfUnknowns, :, :] + dt / h(1) * (fluxBottom - fluxTop) * NV * 0.5
91
92 if flux:
93 flux_x = DataBlock([[0, NumberOfUnknowns], [-H, NV + H], [0, NV], [0, N]], eval("flux", input[:, -1:NV+1, 0:NV], x, 0))
94 flux_y = DataBlock([[0, NumberOfUnknowns], [0, NV], [-H, NV + H], [0, N]], eval("flux", input[:, 0:NV, -1:NV+1], x, 1))
95
96 output[0:NumberOfUnknowns, :, :] = output[0:NumberOfUnknowns, :, :] + 0.5 * NV * dt / h(0) * (flux_x[:, -1:NV-1, 0:NV] - flux_x[:, 1:NV+1, 0:NV])
97 output[0:NumberOfUnknowns, :, :] = output[0:NumberOfUnknowns, :, :] + 0.5 * NV * dt / h(1) * (flux_y[:, 0:NV, -1:NV-1] - flux_y[:, 0:NV, 1:NV+1])
98
99 if nonconservativeProduct:
100 average_x = 0.5 * (input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, -1:NV, 0:NV] + input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV + 1, 0:NV])
101 delta_x = input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV + H, 0:NV] - input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, -H:NV, 0:NV]
102 nonconservative_x = DataBlock([[0, NumberOfUnknowns], [0, NV + H], [0, NV], [0, N]], eval("nonconservativeProduct", average_x, delta_x, x, h, t, dt, 0))
103 output[0:NumberOfUnknowns, :, :] = output[0:NumberOfUnknowns, :, :] + 0.5 * NV * dt / h(0) * (-nonconservative_x[:, 0:NV, 0:NV] - nonconservative_x[:, 1:NV+1, 0:NV])
104
105 average_y = 0.5 * (input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, -1:NV] + input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, 0:NV + 1])
106 delta_y = input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, 0:NV + H] - input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, -H:NV]
107 nonconservative_y = DataBlock([[0, NumberOfUnknowns], [0, NV], [0, NV + H], [0, N]], eval("nonconservativeProduct", average_y, delta_y, x, h, t, dt, 1))
108 output[0:NumberOfUnknowns, :, :] = output[0:NumberOfUnknowns, :, :] + 0.5 * NV * dt / h(1) * (-nonconservative_y[:, 0:NV, 0:NV] - nonconservative_y[:, 0:NV, 1:NV+1])
109
110
111
112def timeStepWithRusanov3D(patchData: "::exahype2::CellData<double, double>&") -> "void":
113 N = Integer("patchData.numberOfCells")
114 t = DataBlock([[0, N]], "patchData.t", "double")
115 dt = DataBlock([[0, N]], "patchData.dt", "double")
116 h = DataBlock([[0, N]], "patchData.cellSize", "tarch::la::Vector<3, double>")
117 x = DataBlock([[0, N]], "patchData.cellCentre", "tarch::la::Vector<3, double>")
118
119 input = DataBlock([[0, NumberOfUnknowns + NumberOfAuxiliaryVariables], [-H, NV + H], [-H, NV + H], [-H, NV + H], [0, N]], "patchData.QIn")
120 output = DataBlock([[0, NumberOfUnknowns + NumberOfAuxiliaryVariables], [0, NV], [0, NV], [0, NV], [0, N]], "patchData.QOut")
121 output = input[:, 0:NV, 0:NV, 0:NV]
122
123 if volumetricSource:
124 source = DataBlock([[0, NumberOfUnknowns], [0, NV], [0, NV], [0, NV], [0, N]], eval("volumetricSource", input[:, 0:NV, 0:NV, 0:NV], x, t))
125 output[0:NumberOfUnknowns, :, :, :] = output[0:NumberOfUnknowns, :, :, :] + dt * source
126
127 # As in 2d: patch volumes plus the one halo layer across each face along
128 # the normal only, never the edges and corners of the halo
129 maxEigenvaluesX = DataBlock([[0, 1], [-1, NV + 1], [0, NV], [0, NV], [0, N]], eval("maxEigenvalue", input[:, -1:NV+1, 0:NV, 0:NV], x, 0))
130 maxEigenvaluesY = DataBlock([[0, 1], [0, NV], [-1, NV + 1], [0, NV], [0, N]], eval("maxEigenvalue", input[:, 0:NV, -1:NV+1, 0:NV], x, 1))
131 maxEigenvaluesZ = DataBlock([[0, 1], [0, NV], [0, NV], [-1, NV + 1], [0, N]], eval("maxEigenvalue", input[:, 0:NV, 0:NV, -1:NV+1], x, 2))
132
133 lambdaLeft = max(maxEigenvaluesX[0:1, -1:NV-1, 0:NV, 0:NV], maxEigenvaluesX[0:1, 0:NV, 0:NV, 0:NV])
134 lambdaRight = max(maxEigenvaluesX[0:1, 0:NV, 0:NV, 0:NV], maxEigenvaluesX[0:1, 1:NV + 1, 0:NV, 0:NV])
135 lambdaBottom = max(maxEigenvaluesY[0:1, 0:NV, -1:NV-1, 0:NV], maxEigenvaluesY[0:1, 0:NV, 0:NV, 0:NV])
136 lambdaTop = max(maxEigenvaluesY[0:1, 0:NV, 0:NV, 0:NV], maxEigenvaluesY[0:1, 0:NV, 1:NV + 1, 0:NV])
137 lambdaNear = max(maxEigenvaluesZ[0:1, 0:NV, 0:NV, -1:NV-1], maxEigenvaluesZ[0:1, 0:NV, 0:NV, 0:NV])
138 lambdaFar = max(maxEigenvaluesZ[0:1, 0:NV, 0:NV, 0:NV], maxEigenvaluesZ[0:1, 0:NV, 0:NV, 1:NV + 1])
139
140 fluxLeft = -1.0 * lambdaLeft * (input[0:NumberOfUnknowns, 0:NV, 0:NV, 0:NV] - input[0:NumberOfUnknowns, -1:NV-1, 0:NV, 0:NV])
141 fluxRight = -1.0 * lambdaRight * (input[0:NumberOfUnknowns, 1:NV+1, 0:NV, 0:NV] - input[0:NumberOfUnknowns, 0:NV, 0:NV, 0:NV])
142 output[0:NumberOfUnknowns, :, :, :] = output[0:NumberOfUnknowns, :, :, :] + dt / h(0) * (fluxLeft - fluxRight) * NV * 0.5
143
144 fluxBottom = -1.0 * lambdaBottom * (input[0:NumberOfUnknowns, 0:NV, 0:NV, 0:NV] - input[0:NumberOfUnknowns, 0:NV, -1:NV-1, 0:NV])
145 fluxTop = -1.0 * lambdaTop * (input[0:NumberOfUnknowns, 0:NV, 1:NV+1, 0:NV] - input[0:NumberOfUnknowns, 0:NV, 0:NV, 0:NV])
146 output[0:NumberOfUnknowns, :, :, :] = output[0:NumberOfUnknowns, :, :, :] + dt / h(1) * (fluxBottom - fluxTop) * NV * 0.5
147
148 fluxNear = -1.0 * lambdaNear * (input[0:NumberOfUnknowns, 0:NV, 0:NV, 0:NV] - input[0:NumberOfUnknowns, 0:NV, 0:NV, -1:NV-1])
149 fluxFar = -1.0 * lambdaFar * (input[0:NumberOfUnknowns, 0:NV, 0:NV, 1:NV+1] - input[0:NumberOfUnknowns, 0:NV, 0:NV, 0:NV])
150 output[0:NumberOfUnknowns, :, :, :] = output[0:NumberOfUnknowns, :, :, :] + dt / h(2) * (fluxNear - fluxFar) * NV * 0.5
151
152 if flux:
153 flux_x = DataBlock([[0, NumberOfUnknowns], [-H, NV + H], [0, NV], [0, NV], [0, N]], eval("flux", input[:, -1:NV+1, 0:NV, 0:NV], x, 0))
154 flux_y = DataBlock([[0, NumberOfUnknowns], [0, NV], [-H, NV + H], [0, NV], [0, N]], eval("flux", input[:, 0:NV, -1:NV+1, 0:NV], x, 1))
155 flux_z = DataBlock([[0, NumberOfUnknowns], [0, NV], [0, NV], [-H, NV + H], [0, N]], eval("flux", input[:, 0:NV, 0:NV, -1:NV+1], x, 2))
156 output[0:NumberOfUnknowns, :, :, :] = output[0:NumberOfUnknowns, :, :, :] + 0.5 * NV * dt / h(0) * (flux_x[:, -1:NV-1, 0:NV, 0:NV] - flux_x[:, 1:NV+1, 0:NV, 0:NV])
157 output[0:NumberOfUnknowns, :, :, :] = output[0:NumberOfUnknowns, :, :, :] + 0.5 * NV * dt / h(1) * (flux_y[:, 0:NV, -1:NV-1, 0:NV] - flux_y[:, 0:NV, 1:NV+1, 0:NV])
158 output[0:NumberOfUnknowns, :, :, :] = output[0:NumberOfUnknowns, :, :, :] + 0.5 * NV * dt / h(2) * (flux_z[:, 0:NV, 0:NV, -1:NV-1] - flux_z[:, 0:NV, 0:NV, 1:NV+1])
159
160 if nonconservativeProduct:
161 average_x = 0.5 * (input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, -1:NV, 0:NV, 0:NV] + input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV + 1, 0:NV, 0:NV])
162 delta_x = input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV + H, 0:NV, 0:NV] - input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, -H:NV, 0:NV, 0:NV]
163 nonconservative_x = DataBlock([[0, NumberOfUnknowns], [0, NV + H], [0, NV], [0, NV], [0, N]], eval("nonconservativeProduct", average_x, delta_x, x, h, t, dt, 0))
164 output[0:NumberOfUnknowns, :, :, :] = output[0:NumberOfUnknowns, :, :, :] + 0.5 * NV * dt / h(0) * (-nonconservative_x[:, 0:NV, 0:NV, 0:NV] - nonconservative_x[:, 1:NV+1, 0:NV, 0:NV])
165
166 average_y = 0.5 * (input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, -1:NV, 0:NV] + input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, 0:NV + 1, 0:NV])
167 delta_y = input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, 0:NV + H, 0:NV] - input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, -H:NV, 0:NV]
168 nonconservative_y = DataBlock([[0, NumberOfUnknowns], [0, NV], [0, NV + H], [0, NV], [0, N]], eval("nonconservativeProduct", average_y, delta_y, x, h, t, dt, 1))
169 output[0:NumberOfUnknowns, :, :, :] = output[0:NumberOfUnknowns, :, :, :] + 0.5 * NV * dt / h(1) * (-nonconservative_y[:, 0:NV, 0:NV, 0:NV] - nonconservative_y[:, 0:NV, 1:NV+1, 0:NV])
170
171 average_z = 0.5 * (input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, 0:NV, -1:NV] + input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, 0:NV, 0:NV + 1])
172 delta_z = input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, 0:NV, 0:NV + H] - input[0:NumberOfUnknowns + NumberOfAuxiliaryVariables, 0:NV, 0:NV, -H:NV]
173 nonconservative_z = DataBlock([[0, NumberOfUnknowns], [0, NV], [0, NV], [0, NV + H], [0, N]], eval("nonconservativeProduct", average_z, delta_z, x, h, t, dt, 2))
174 output[0:NumberOfUnknowns, :, :, :] = output[0:NumberOfUnknowns, :, :, :] + 0.5 * NV * dt / h(2) * (-nonconservative_z[:, 0:NV, 0:NV, 0:NV] - nonconservative_z[:, 0:NV, 0:NV, 1:NV+1])
175
176
177
178def maxEigenvalueOverPatch2D(patchData: "::exahype2::CellData<double, double>&") -> "void":
179 N = Integer("patchData.numberOfCells")
180 x = DataBlock([[0, N]], "patchData.cellCentre", "tarch::la::Vector<2, double>")
181 maxEigenvalues = DataBlock([[0, N]], "patchData.maxEigenvalue", "double")
182 input = DataBlock([[0, NumberOfUnknowns + NumberOfAuxiliaryVariables], [0, NV], [0, NV], [0, N]], "patchData.QIn")
183
184 if maxEigenvalue:
185 maxEigenvaluesX = DataBlock([[0, 1], [0, NV], [0, NV], [0, N]], eval("maxEigenvalue", input, x, 0))
186 maxEigenvaluesY = DataBlock([[0, 1], [0, NV], [0, NV], [0, N]], eval("maxEigenvalue", input, x, 1))
187 maxEigenvaluesPerVolume = max(maxEigenvaluesX, maxEigenvaluesY)
188 maxEigenvalues = max(maxEigenvaluesPerVolume)
189
190
191
192def maxEigenvalueOverPatch3D(patchData: "::exahype2::CellData<double, double>&") -> "void":
193 N = Integer("patchData.numberOfCells")
194 x = DataBlock([[0, N]], "patchData.cellCentre", "tarch::la::Vector<3, double>")
195 maxEigenvalues = DataBlock([[0, N]], "patchData.maxEigenvalue", "double")
196 input = DataBlock([[0, NumberOfUnknowns + NumberOfAuxiliaryVariables], [0, NV], [0, NV], [0, NV], [0, N]], "patchData.QIn")
197
198 if maxEigenvalue:
199 maxEigenvaluesX = DataBlock([[0, 1], [0, NV], [0, NV], [0, NV], [0, N]], eval("maxEigenvalue", input, x, 0))
200 maxEigenvaluesY = DataBlock([[0, 1], [0, NV], [0, NV], [0, NV], [0, N]], eval("maxEigenvalue", input, x, 1))
201 maxEigenvaluesZ = DataBlock([[0, 1], [0, NV], [0, NV], [0, NV], [0, N]], eval("maxEigenvalue", input, x, 2))
202 maxEigenvaluesXY = max(maxEigenvaluesX, maxEigenvaluesY)
203 maxEigenvaluesPerVolume = max(maxEigenvaluesXY, maxEigenvaluesZ)
204 maxEigenvalues = max(maxEigenvaluesPerVolume)
205
206
208 """!
209
210 Finite Volumes with a Rusanov Riemann solver and explicit Euler time
211 stepping, realised over a block-structured mesh.
212
213 """
214
216 self,
217 solver: Solver,
218 patch_size: int,
219 overlap: int = 1,
220 cfl_constant: float = 0.9,
221 interpolation: "toolbox.blockstructured.api.InterpolateHangingFaces.Scheme" = toolbox.blockstructured.api.InterpolateHangingFaces.Scheme.Linear,
222 restriction: "toolbox.blockstructured.api.RestrictHangingFaces.Scheme" = toolbox.blockstructured.api.RestrictHangingFaces.Scheme.Averaging,
223 min_volume_size: float = None,
224 max_volume_size: float = None,
225 ):
226 """!
227
228 The constructor memorises the attributes. However, it does not do this
229 within this class, but it adds the important properties straight to the
230 solver, so anybody else working against this solver knows about the
231 properties introduced by the numerical scheme.
232
233 @see @ref __create_data_structures()
234
235 patch_size: int
236 Number of Finite Volumes per axis within one patch (i.e. within
237 one mesh cell).
238
239 overlap: int
240 Number of Finite Volumes the halo layer reconstructed around a
241 patch - from the neighbouring patches' faces - is wide.
242
243 cfl_constant: float
244 Safety factor the admissible time step size (@see
245 exahype2.api.fv.actionsets.ComputeGlobalCFLCondition,
246 which this is passed straight through to) is scaled down by,
247 relative to the theoretical CFL=1 stability limit
248 h / (Dimensions * lambda_max). 0.9 is a
249 conservative default for an explicit-Euler Finite Volume scheme;
250 this codebase has no prior precedent value to match (grep for
251 "cfl" outside this class finds only exaparty's unrelated SPH
252 solvers, which default to 0.1).
253
254 interpolation: toolbox.blockstructured.api.InterpolateHangingFaces.Scheme
255 How the scheme initialises the halo of a fine patch next to a
256 coarser patch on an adaptive mesh. Whenever the time step
257 reconstructs the halo of a fine cell, it interpolates the data of
258 the adjacent coarse face onto the fine cell's hanging face
259 (toolbox.blockstructured.api.InterpolateHangingFaces). The
260 default is linear interpolation.
261
262 restriction: toolbox.blockstructured.api.RestrictHangingFaces.Scheme
263 How the scheme hands the data of fine patches over to an adjacent
264 coarser patch. Whenever the fine cells project their data onto
265 their faces, the scheme restricts the data of the hanging faces
266 onto the coarse face (toolbox.blockstructured.api.RestrictHangingFaces).
267 The default is averaging.
268
269 min_volume_size: float
270 The time step asks for a refinement of a cell only if its volumes
271 are at least of this size (@ref exahype2.api.blockstructured.DynamicMeshRefinement).
272 None (the default) does not bound the refinement.
273
274 max_volume_size: float
275 The time step asks for an erase, i.e. coarsening, of a cell only
276 if the volumes of the coarser cell would be strictly smaller than
277 this size. None (the default) does not bound the coarsening.
278
279 On a regular mesh, there are no hanging faces, and the two schemes
280 are never used. The fluxes along a face between a coarse and a fine
281 patch are not corrected, i.e. the scheme is not exactly conservative
282 on adaptive meshes.
283
284 """
285 super().__init__(solver)
286 assert (
287 min_volume_size is None
288 or max_volume_size is None
289 or min_volume_size <= max_volume_size
290 ), f"min_volume_size={min_volume_size} has to be smaller than or equal to max_volume_size={max_volume_size}"
291 self.min_volume_size = min_volume_size
292 self.max_volume_size = max_volume_size
293 self.interpolation = interpolation
294 self.restriction = restriction
295 # patch_size and halo_size must be set for proper solver generation
296 self.patch_size = patch_size
297 self.halo_size = overlap
298 self.overlap = overlap
299 # Set in construct_output(): the generated kernels live in the project
300 # namespace, as their names are solver-specific
303 self.cfl_constant = cfl_constant
304 self._generator = RusanovWithExplicitEulerGenerator(solver, [(Target.Serial, False, OutputLanguage.CPP, MemoryLayout.AoS_AllNested)])
306
307 @property
308 def kernel_function_name(self) -> str:
309 """!
310 Name of the generated time step kernel. It carries the solver name,
311 as do the kernels/<SolverName>_rusanov*.h files holding it, so two
312 solvers' kernels do not clash.
313 """
314 return self._solver.name + "_timeStepWithRusanov"
315
316 @property
318 """!
319 Name of the generated kernel which determines the maximum eigenvalue
320 over a patch. It is a kernel of its own, i.e. the time step kernel
321 does not return any eigenvalue (@ref exahype2.api.fv.actionsets.ComputeMaxEigenvalue).
322 """
323 return self._solver.name + "_maxEigenvalueOverPatch"
324
326 """!
327
328 Create the mesh data structures (a Finite Volume patch per cell,
329 plus the face-based overlap patches used to reconstruct its halo)
330 this numerical scheme requires.
331
332 Ported from the legacy exahype2.solvers.fv.FV.create_data_structures():
333 one @ref peano4.api.datamodel.Patch of patch_size^d Finite Volumes
334 per mesh cell (_patch), plus a halo-augmented copy of it
335 (_patch_with_halo, (patch_size+2*overlap)^d, @see
336 toolbox.blockstructured.api.ReconstructPatchWithHalo) and two overlap
337 patches of width 2*overlap attached to the mesh faces:
338
339 - _patch_overlap_current_time_step: the persistent halo data
340 toolbox.blockstructured.api.ReconstructPatchWithHalo reads from to
341 rebuild _patch_with_halo (@see construct_output(), which hands it
342 _patch/_patch_overlap_current_time_step/_patch_with_halo directly
343 rather than the whole solver).
344 - _patch_overlap_update: the projection of the just-updated _patch
345 accumulated by the current sweep (@see
346 exahype2.api.fv.actionsets.ProjectPatchOntoFaces), rolled over
347 into _patch_overlap_current_time_step by
348 exahype2.api.fv.actionsets.RollOverUpdatedFace once the update is
349 complete.
350 - _max_eigenvalue: one double per cell, named after the solver
351 followed by MaxEigenvalue (e.g. EulerFVSmoothMaxEigenvalue),
352 which holds the maximum eigenvalue of
353 the patch after its last update
354 (@see exahype2.api.fv.actionsets.ComputeMaxEigenvalue).
355 exahype2.api.fv.actionsets.ReduceMaxEigenvalue reduces these
356 values into the solver, and
357 exahype2.api.fv.actionsets.ComputeGlobalCFLCondition derives the
358 next time step size from the outcome. It is modelled via DaStGen2
359 as an array of cardinality one. The array is a
360 peano4.api.dastgen2.Peano4SmartPointerDoubleArray, i.e. the value
361 resides on the heap.
362
363 All five are assigned onto self._solver (the shared
364 exahype2.api.Solver instance both this numerical scheme and its
365 surrounding solver's Solver.GridConstruction/Solver.Plotter
366 counterparts hold a reference to as self._solver), not onto self,
367 since the remaining FV action sets that need them - @see
368 exahype2.api.fv.actionsets.ApplyDirichletBoundaryConditions,
369 exahype2.api.fv.actionsets.UpdateCell,
370 exahype2.api.fv.actionsets.ComputeGlobalCFLCondition - are handed that
371 shared solver and look the patches up as solver._patch /
372 solver._patch_overlap_*.
373
374 Storage is hardwired to smart pointers (peano4.api.datamodel's
375 PatchToDoubleArrayWithSmartPointer), matching the legacy default
376 (Storage.SmartPointers for both cell and face data) - the legacy
377 Storage enum's other two backends (CallStack, Heap) are not
378 exposed here.
379
380 Two pieces of the legacy method are deliberately not ported yet:
381 - The cell/face label creation
382 (exahype2.grid.create_cell_label()/create_face_label()) - that
383 module has not been ported to the new API.
384 - The load/store/compute guards
385 (FV._provide_cell_data_to_compute_kernels_default_guard() and
386 friends) - they are keyed off the legacy SolverState state
387 machine, which the task-graph architecture has no equivalent of:
388 a task only ever runs within its own phase's task graph in the
389 first place, so "are we still constructing the grid" does not
390 need to be re-checked at runtime the same way.
391
392 """
393 total_unknowns = self._solver.unknowns
394 identifier = self._solver._unknown_identifier()
395
397 (self.patch_size, self.patch_size, self.patch_size),
398 total_unknowns,
399 identifier,
400 )
401 self._solver._patch_with_halo = peano4.api.datamodel.Patch(
402 (self.patch_size+2*self.overlap, self.patch_size+2*self.overlap, self.patch_size+2*self.overlap),
403 total_unknowns,
404 identifier + "WithHalo",
405 )
406 self._solver._patch_overlap_current_time_step = peano4.api.datamodel.Patch(
407 (2 * self.overlap, self.patch_size, self.patch_size),
408 total_unknowns,
409 identifier + "CurrentTimeStep",
410 )
411 self._solver._patch_overlap_update = peano4.api.datamodel.Patch(
412 (2 * self.overlap, self.patch_size, self.patch_size),
413 total_unknowns,
414 identifier + "Update",
415 )
416 self._solver._max_eigenvalue = peano4.api.datamodel.DaStGen2(self._solver.name + "MaxEigenvalue")
417 self._solver._max_eigenvalue.data.add_attribute(
419 )
420 add_max_eigenvalue_reduction(self._solver)
421
422
423 def __add_data_to_repository(self, peano_project):
424 """!
425
426 Consult @ref page_exahype_programmers_guide_new_solver for some information
427 how this routine fits to the typical workflow when we introduce a new
428 solver.
429
430 """
431 peano4.api.Logger().log("""
432Patch data
433----------
434{}
435Patch overlap data
436------------------
437{}
438{}""".format( str(self._solver._patch), str(self._solver._patch_overlap_current_time_step), str(self._solver._patch_overlap_update) ) )
439
440 peano_project.datamodel.add_cell(self._solver._patch)
441 peano_project.datamodel.add_cell(self._solver._patch_with_halo)
442 peano_project.datamodel.add_face(self._solver._patch_overlap_current_time_step)
443 peano_project.datamodel.add_face(self._solver._patch_overlap_update)
444 peano_project.datamodel.add_cell(self._solver._max_eigenvalue)
445 register_auxiliary_variables(self._solver, peano_project, self.patch_size, self.overlap)
446
447 # The task graph compiler only uses, loads and stores data where the
448 # solver's grid selector holds, too (@see peano4.api.datamodel.DoF).
449 for patch in (
450 self._solver._patch,
451 self._solver._patch_with_halo,
452 self._solver._patch_overlap_current_time_step,
453 self._solver._patch_overlap_update,
454 self._solver._max_eigenvalue,
455 ):
456 patch.grid_selector = self._solver.grid_selector
457
459 self._solver._patch, "double"
460 )
462 self._solver._patch_with_halo, "double"
463 )
464 self._solver._patch_overlap_current_time_step.generator = peano4.api.datamodel.PatchToDoubleArrayWithSmartPointer(
465 self._solver._patch_overlap_current_time_step, "double"
466 )
467 self._solver._patch_overlap_update.generator = peano4.api.datamodel.PatchToDoubleArrayWithSmartPointer(
468 self._solver._patch_overlap_update, "double"
469 )
470
471 self._solver._patch_overlap_current_time_step.generator.merge_method_definition = (
472 toolbox.blockstructured.api.get_face_merge_implementation(
473 self._solver._patch_overlap_current_time_step
474 )
475 )
476 self._solver._patch_overlap_current_time_step.generator.includes += """
477#include "peano4/utils/Loop.h"
478"""
479
480 # Only faces selected by the solver's grid selector hold valid data,
481 # so only those are exchanged.
482 self._solver._patch_overlap_current_time_step.generator.send_condition = self._solver.grid_selector.createFaceGuard()
483 self._solver._patch_overlap_current_time_step.generator.receive_and_merge_condition = self._solver.grid_selector.createFaceGuard()
484
485 self._solver._patch_overlap_update.generator.send_condition = "false"
486 self._solver._patch_overlap_update.generator.receive_and_merge_condition = "false"
487
488 def create_default_mesh_adaptation(self) -> Solver.MeshAdaptation:
489 """!
490
491 The Finite Volume schemes adapt the mesh and balance the load
492 through exahype2.api.fv.AdaptMeshAndBalanceLoad by default
493
494 """
495 from .AdaptMeshAndBalanceLoad import AdaptMeshAndBalanceLoad
496
498
500 exahype2_project,
501 peano_project,
502 time_step,
503 add_global_tasks=True):
504 """!
505
506 """
507 peano4.api.Logger().log("Create time stepping task graph for Finite Volume scheme over block-structured meshes with Rusanov flux")
508
509 self.__add_data_to_repository(peano_project)
510 self.kernel_namespace = peano_project.namespace
511 self._generator.construct_output(exahype2_project, peano_project, time_step, add_global_tasks)
512
513 def create_restriction_of_hanging_faces(self) -> "toolbox.blockstructured.api.RestrictHangingFaces":
514 """!
515
516 Action set which restricts the projected fine data from the hanging
517 faces onto the coarse faces
518
519 Every task which projects the solution onto the faces has to host
520 this action set, so the faces between coarse and fine patches hold
521 consistent data afterwards. Besides the time step, this is the
522 projection at the end of the setup
523 (@ref exahype2.api.fv.SetupSimulationOverRegularGrid). The task has
524 to write all of _patch_overlap_update, as averaging clears it first.
525
526 """
527 return toolbox.blockstructured.api.RestrictHangingFaces(
528 self._solver._patch_overlap_update,
529 scheme=self.restriction,
530 clear_guard=self._solver.grid_selector.createFaceGuard(),
531 additional_includes=self._solver._get_default_includes() + self._solver.user_solver_includes,
532 )
533
534
536 def construct_output(self, exahype2_project, peano_project, time_step, add_global_tasks=True):
537 # The kernels are stateless only if all PDE terms they call are. Otherwise
538 # they have to call the (virtual) member functions of the solver instance.
539 terms = [term for term in self._solver.pde_terms if term.NAME in ["flux", "nonconservativeProduct", "volumetricSource", "maxEigenvalue"]]
540 if terms and not all(term.stateless for term in terms):
541 self._configurations = [(target, False, language, layout) for (target, _, language, layout) in self._configurations]
542 # Construct the call first, as it validates the PDE terms' variants
543 # Although we may generate multiple definitions for the purpose of benchmarking, we
544 # only need one kernel call
545 self._solver.compute_kernel_call = self.__construct_kernel_calls()[0]
546 # The eigenvalue kernel always runs on the host
547 self._solver.numerical_scheme.max_eigenvalue_kernel_call = self.__construct_kernel_call(
548 Target.Serial,
549 self._configurations[0][1],
550 self._configurations[0][2],
551 MemoryLayout.AoS_AllNested,
552 function_name=self._solver.numerical_scheme.max_eigenvalue_kernel_function_name,
553 )
554
555 self.__create_time_step_functions(exahype2_project, peano_project)
556
557 reconstruction_task = peano4.api.taskgraph.Task(name=f"{self._solver.name}_Reconstruct", entity=peano4.api.taskgraph.Task.GridEntity.CELL)
558 update_cell_task = peano4.api.taskgraph.Task(name=f"{self._solver.name}_Update cell", entity=peano4.api.taskgraph.Task.GridEntity.CELL)
559 project_on_faces_task = peano4.api.taskgraph.Task(name=f"{self._solver.name}_Project on faces", entity=peano4.api.taskgraph.Task.GridEntity.CELL)
560 compute_eigenvalue_task = peano4.api.taskgraph.Task(name=f"{self._solver.name}_Compute max eigenvalue", entity=peano4.api.taskgraph.Task.GridEntity.CELL)
561 reduce_eigenvalue_task = peano4.api.taskgraph.Task(name=f"{self._solver.name}_Reduce max eigenvalue", entity=peano4.api.taskgraph.Task.GridEntity.CELL)
562 compute_cfl_condition_task = peano4.api.taskgraph.Task(name=f"{self._solver.name}_Compute global CFL condition", entity=peano4.api.taskgraph.Task.GridEntity.GLOBAL_END_OF_STEP, may_spawn_background_tasks=False)
563
564 time_step.add_task(reconstruction_task)
565 time_step.add_task(update_cell_task)
566 time_step.add_task(compute_eigenvalue_task)
567 time_step.add_task(reduce_eigenvalue_task)
568 time_step.add_task(project_on_faces_task)
569 time_step.add_task(compute_cfl_condition_task)
570
571
572 reconstruction_task.use_cell(self._solver._patch, peano4.api.taskgraph.Task.DataAccess.READ_AND_WRITE)
573 reconstruction_task.use_cell(self._solver._patch_with_halo, peano4.api.taskgraph.Task.DataAccess.WRITE)
574
576 reconstruction_task.use_face(
577 self._solver._patch_overlap_current_time_step,
578 get_access_to_persistent_face_data(self._solver, exahype2_project, peano4.api.taskgraph.Task.DataAccess.READ_AND_DISCARD),
579 )
580
583 reconstruction_task.add_action_set(
584 toolbox.blockstructured.api.InterpolateHangingFaces(
585 self._solver._patch_overlap_current_time_step,
586 scheme=self._solver.numerical_scheme.interpolation,
587 additional_includes=self._solver._get_default_includes() + self._solver.user_solver_includes,
588 )
589 )
590 reconstruction_task.add_action_set(
591 toolbox.blockstructured.api.ReconstructPatchWithHalo(
592 patch=self._solver._patch,
593 patch_overlap=self._solver._patch_overlap_current_time_step,
594 reconstructed_patch=self._solver._patch_with_halo,
595 guard=self._solver.grid_selector.createCellGuard(),
596 add_assertions_to_halo_exchange=False,
597 additional_includes=self._solver._get_default_includes() + self._solver.user_solver_includes,
598 )
599 )
600
603 ApplyDirichletBoundaryConditions.add_task_to_time_step(self._solver, exahype2_project, time_step, reconstruction_task)
604
605
606 auxiliary_reconstruction_tasks = add_reconstruction_tasks_of_auxiliary_variables(
607 self._solver, time_step, self._solver.numerical_scheme.interpolation
608 )
609
610
611 update_cell_task.add_dependency(reconstruction_task)
612 for task in auxiliary_reconstruction_tasks:
613 update_cell_task.add_dependency(task)
614 use_halos_of_auxiliary_variables(update_cell_task, self._solver)
615 update_cell_task.use_cell(self._solver._patch_with_halo, peano4.api.taskgraph.Task.DataAccess.READ_AND_DISCARD)
616 update_cell_task.use_cell(self._solver._patch, peano4.api.taskgraph.Task.DataAccess.WRITE)
617 if self._configurations[0][0] == Target.Accelerator:
618 update_cell_task.add_action_set(
619 UpdateCellGPU(
620 self._solver,
621 guard=self._solver.grid_selector.createCellGuard(),
622 )
623 )
624 else:
625 update_cell_task.add_action_set(
627 self._solver,
628 guard=self._solver.grid_selector.createCellGuard(),
629 )
630 )
631 update_cell_task.tags.add(Solver.SolutionUpdateTaskTag)
632
633
640 compute_eigenvalue_task.add_dependency(update_cell_task)
641 compute_eigenvalue_task.use_cell(self._solver._patch, peano4.api.taskgraph.Task.DataAccess.READ_AND_WRITE)
642 compute_eigenvalue_task.use_cell(self._solver._max_eigenvalue, peano4.api.taskgraph.Task.DataAccess.WRITE)
643 for auxiliary in self._solver.auxiliary_variables:
644 compute_eigenvalue_task.use_cell(auxiliary.patch, peano4.api.taskgraph.Task.DataAccess.READ_AND_WRITE)
645 compute_eigenvalue_task.add_action_set(
646 ComputeMaxEigenvalue(
647 self._solver,
648 guard=self._solver.grid_selector.createCellGuard(),
649 )
650 )
651 reduce_eigenvalue_task.add_dependency(compute_eigenvalue_task)
652 reduce_eigenvalue_task.use_cell(self._solver._max_eigenvalue, peano4.api.taskgraph.Task.DataAccess.READ_AND_DISCARD)
653 reduce_eigenvalue_task.add_action_set(
654 ReduceMaxEigenvalue(
655 self._solver,
656 guard=self._solver.grid_selector.createCellGuard(),
657 )
658 )
659
660
662 compute_cfl_condition_task.add_dependency(reduce_eigenvalue_task)
663 compute_cfl_condition_task.add_action_set(
664 ComputeGlobalCFLCondition(
665 self._solver,
666 self._solver.numerical_scheme.cfl_constant,
667 self._solver.numerical_scheme.patch_size,
668 )
669 )
670
671
672 project_on_faces_task.add_dependency(update_cell_task)
673 project_on_faces_task.use_cell(self._solver._patch, peano4.api.taskgraph.Task.DataAccess.READ_AND_WRITE)
674 project_on_faces_task.use_face(self._solver._patch_overlap_update, peano4.api.taskgraph.Task.DataAccess.TEMPORARY)
675 project_on_faces_task.use_face(
676 self._solver._patch_overlap_current_time_step,
677 get_access_to_persistent_face_data(self._solver, exahype2_project, peano4.api.taskgraph.Task.DataAccess.WRITE),
678 )
679 project_on_faces_task.add_action_set(
680 ProjectPatchOntoFaces(
681 self._solver._patch,
682 self._solver._patch_overlap_update,
683 guard=self._solver.grid_selector.createCellGuard(),
684 includes=self._solver._get_default_includes() + self._solver.user_solver_includes,
685 )
686 )
687
695 project_on_faces_task.add_action_set(self._solver.numerical_scheme.create_restriction_of_hanging_faces())
696
704 project_on_faces_task.add_action_set(
705 RollOverUpdatedFaceWithSommerfeldBoundaryConditions.create_roll_over(
706 self._solver,
707 exahype2_project,
708 guard=self._solver.grid_selector.createFaceGuard(),
709 includes=self._solver._get_default_includes() + self._solver.user_solver_includes,
710 time_step_size=f"repositories::{self._solver.get_name_of_global_instance()}.getMinTimeStepSize()",
711 )
712 )
713
717 compute_cfl_condition_task.add_dependency(project_on_faces_task)
718
719 # The load balancing is switched off throughout the time step, and
720 # switched on again only at its very end, so it may then decide on
721 # splits. Peano carries these splits out in the subsequent mesh sweep.
722 if add_global_tasks:
723 self._solver.numerical_scheme.wrap_task_graph_in_load_balancing_and_amr_tasks(time_step)
724
725 if peano4.api.Logger().is_visualisation:
726 time_step.visualise(title="Time stepping task graph for {}".format(self._solver.name))
727 if peano4.api.Logger().is_text:
728 time_step.log_as_text(title="Time stepping task graph for {}".format(self._solver.name))
729
730 def __create_time_step_functions(self, exahype2_project, peano4_project):
731 """!
732
733 Calling this function is delayed until all PDE term information is provided.
734 In this way we can avoid generating code that will not be used. The following
735 information is required to translate a Python function using dslhype:
736 - template_parameters: the variables that are used within the Python function
737 to represent external information
738 - functor_parameters: the PDE terms that can be used by the solver
739 - function: the Python function itself
740
741 TODO: Currently the MLIR types are passed manually here, this should ideally
742 be inferred
743
744 """
745
746 #template_parameters = [
747 # dslhype.SyntaxTree.Argument("NV", dslhype.SyntaxTree.TInteger()),
748 # dslhype.SyntaxTree.Argument("H", dslhype.SyntaxTree.TInteger()),
749 # dslhype.SyntaxTree.Argument("NumberOfUnknowns", dslhype.SyntaxTree.TInteger()),
750 # dslhype.SyntaxTree.Argument("NumberOfAuxiliaryVariables", dslhype.SyntaxTree.TInteger())
751 #]
752 #
753 #functor_parameters = [
754 # dslhype.SyntaxTree.Argument("flux", dslhype.SyntaxTree.TCustom("const ::exahype2::fv::rusanov::FluxFunctor&"), "(!llvm.ptr, !llvm.ptr, !llvm.ptr, f64, f64, i32, !llvm.ptr) -> ()"),
755 # dslhype.SyntaxTree.Argument("nonconservativeProduct", dslhype.SyntaxTree.TCustom("const ::exahype2::fv::rusanov::NonconservativeProductFunctor&"), "(!llvm.ptr, !llvm.ptr, !llvm.ptr, !llvm.ptr, f64, f64, i32, !llvm.ptr) -> ()"),
756 # dslhype.SyntaxTree.Argument("volumetricSource", dslhype.SyntaxTree.TCustom("const ::exahype2::fv::rusanov::VolumetricSourceFunctor&"), "(!llvm.ptr, !llvm.ptr, f64, !llvm.ptr) -> ()"),
757 # dslhype.SyntaxTree.Argument("maxEigenvalue", dslhype.SyntaxTree.TCustom("const ::exahype2::fv::rusanov::MaxEigenvalueFunctor&"), "(!llvm.ptr, !llvm.ptr, !llvm.ptr, f64, f64, i32, !llvm.ptr) -> ()")
758 #]
759 dimensions = exahype2_project._dimensions
760 if dimensions == 2:
761 time_step_dsl_function = timeStepWithRusanov2D
762 else:
763 time_step_dsl_function = timeStepWithRusanov3D
764
765 output_directory = peano4_project.directory
766 temporary_output_directory = peano4_project.temporary_directory
767
768 required_includes = f"""
769#include "Abstract{self._solver.name}.h"
770#include "repositories/SolverRepository.h"
771#include "exahype2/Solver.h"
772#include "exahype2/CellData.h"
773#include "exahype2/VolumeIndex.h"
774#include "exahype2/fv/PatchUtils.h"
775#include "exahype2/fv/rusanov/Functors.h"
776#include "peano4/utils/Loop.h"
777#include "tarch/timing/Measurement.h"
778#include "tarch/timing/Watch.h"
779"""
780 stateless_kernel_generated=False
781 non_stateless_kernel_generated=False
782 mlir_kernel_generated=False
783 for (_, stateless, language, _) in self._configurations:
784 if stateless:
785 stateless_kernel_generated = True
786 else:
787 non_stateless_kernel_generated = True
788 if language == OutputLanguage.MLIR:
789 mlir_kernel_generated = True
790
791 temporary_kernels_directory = os.path.join(temporary_output_directory, "kernels")
792 kernels_directory = os.path.join(output_directory, "kernels")
793 os.makedirs(temporary_kernels_directory, exist_ok=True)
794 #file_name =
795 #for file_name in [f"{self._solver.name}_rusanov2d.h", f"{self._solver.name}_rusanov3d.h"]:
796 file = open(os.path.join(temporary_kernels_directory, f"{self._solver.name}_rusanov{dimensions}d.h"), "w")
797 file.write(f"""#pragma once
798{required_includes}\n""")
799 file.close()
800
801 if stateless_kernel_generated:
802 #for file_name in [f"{self._solver.name}_rusanov2d.cpph", f"{self._solver.name}_rusanov3d.cpph"]:
803 file = open(os.path.join(temporary_kernels_directory, f"{self._solver.name}_rusanov{dimensions}d.cpph"), "w")
804 file.write(f"""#include "{self._solver.name}_rusanov{dimensions}d.h"\n""")
805 file.close()
806
807 if non_stateless_kernel_generated or mlir_kernel_generated:
808 #for file_name in [f"{self._solver.name}_rusanov2d.cpp", f"{self._solver.name}_rusanov3d.cpp"]:
809 file = open(os.path.join(temporary_kernels_directory, f"{self._solver.name}_rusanov{dimensions}d.cpp"), "w")
810 file.write(f"""#include "{self._solver.name}_rusanov{dimensions}d.h"\n""")
811 file.close()
812
813 external_variables = {
814 dslhype.Argument(dslhype.Name("NV"), dslhype.TInteger()): self._solver.numerical_scheme.patch_size,
815 dslhype.Argument(dslhype.Name("H"), dslhype.TInteger()): self._solver.numerical_scheme.overlap,
816 dslhype.Argument(dslhype.Name("NumberOfUnknowns"), dslhype.TInteger()): self._solver.unknowns,
817 dslhype.Argument(dslhype.Name("NumberOfAuxiliaryVariables"), dslhype.TInteger()): self._solver.number_of_auxiliary_variables
818 }
819
820 function_map = {
821 dslhype.Name("volumetricSource"): dslhype.TFunction("const ::exahype2::fv::rusanov::VolumetricSourceFunctor&", OrderedDict({
822 dslhype.Name("Q"): dslhype.TArray(dslhype.TFloat(), 1),
823 dslhype.Name("x"): dslhype.TVector(dslhype.TFloat(), dimensions),
825 dslhype.Name("F"): dslhype.TArray(dslhype.TFloat(), 1)})),
826 dslhype.Name("flux"): dslhype.TFunction("const ::exahype2::fv::rusanov::FluxFunctor&", OrderedDict({
827 dslhype.Name("Q"): dslhype.TArray(dslhype.TFloat(), 1),
828 dslhype.Name("x"): dslhype.TVector(dslhype.TFloat(), dimensions),
829 dslhype.Name("normal"): dslhype.TInteger(),
830 dslhype.Name("F"): dslhype.TArray(dslhype.TFloat(), 1)})),
831 dslhype.Name("nonconservativeProduct"): dslhype.TFunction("const ::exahype2::fv::rusanov::NonconservativeProductFunctor&", OrderedDict({
832 dslhype.Name("Q"): dslhype.TArray(dslhype.TFloat(), 1),
833 dslhype.Name("deltaQ"): dslhype.TArray(dslhype.TFloat(), 1),
834 dslhype.Name("x"): dslhype.TVector(dslhype.TFloat(), dimensions),
835 dslhype.Name("h"): dslhype.TVector(dslhype.TFloat(), dimensions),
838 dslhype.Name("normal"): dslhype.TInteger(),
839 dslhype.Name("BTimesDeltaQ"): dslhype.TArray(dslhype.TFloat(), 1)})),
840 dslhype.Name("maxEigenvalue"): dslhype.TFunction("const ::exahype2::fv::rusanov::MaxEigenvalueFunctor&", OrderedDict({
841 dslhype.Name("Q"): dslhype.TArray(dslhype.TFloat(), 1),
842 dslhype.Name("x"): dslhype.TVector(dslhype.TFloat(), dimensions),
843 dslhype.Name("normal"): dslhype.TInteger(),
844 dslhype.Name("E"): dslhype.TArray(dslhype.TFloat(), 1)}))
845 }
846
847 if mlir_kernel_generated and stateless_kernel_generated:
848 dslhype.generate_mlir_function_call_bridges(
849 solver=self._solver,
850 function_map=function_map,
851 pde_terms=self._solver.pde_terms,
852 stateless=True,
853 output_file_name=f"{self._solver.name}_rusanov{dimensions}d",
854 output_directory=temporary_output_directory,)
855
856 if mlir_kernel_generated and non_stateless_kernel_generated:
857 dslhype.generate_mlir_function_call_bridges(
858 solver=self._solver,
859 function_map=function_map,
860 pde_terms=self._solver.pde_terms,
861 stateless=False,
862 output_file_name=f"{self._solver.name}_rusanov{dimensions}d",
863 output_directory=temporary_output_directory,)
864
865 for (target, stateless, language, memory_layout) in self._configurations:
866 dslhype.translate_dslhype_function(
867 solver=self._solver,
868 function = time_step_dsl_function,
869 dimensions=dimensions,
870 function_map=function_map,
871 external_variables=external_variables,
872 pde_terms=self._solver.pde_terms,
873 output_file_name=f"{self._solver.name}_rusanov{dimensions}d",
874 target=target,
875 stateless=stateless,
876 memory_layout=memory_layout,
877 function_name=self._solver.numerical_scheme.kernel_function_name,
878 output_language=language,
879 output_directory=temporary_output_directory,
880 )
881 # The maximum eigenvalue is a kernel of its own, which always runs on the host
882 for stateless in sorted({stateless for (_, stateless, _, _) in self._configurations}):
883 dslhype.translate_dslhype_function(
884 solver=self._solver,
885 function = maxEigenvalueOverPatch2D if dimensions == 2 else maxEigenvalueOverPatch3D,
886 dimensions=dimensions,
887 function_map=function_map,
888 external_variables=external_variables,
889 pde_terms=self._solver.pde_terms,
890 output_file_name=f"{self._solver.name}_rusanov{dimensions}d",
891 target=Target.Serial,
892 stateless=stateless,
893 function_name=self._solver.numerical_scheme.max_eigenvalue_kernel_function_name,
894 output_language=OutputLanguage.CPP,
895 output_directory=temporary_output_directory,
896 )
897
898 #for file_prefix in [f"{self._solver.name}_rusanov2d"]:#, f"{self._solver.name}_rusanov3d"]:
899 if stateless_kernel_generated:
900 file = open(os.path.join(temporary_kernels_directory, f"{self._solver.name}_rusanov{dimensions}d.h"), "a")
901 file.write(f"""#include "{self._solver.name}_rusanov{dimensions}d.cpph" """)
902 file.close()
903
904 peano4_project.output.makefile.add_h_file(os.path.join(kernels_directory, f"{self._solver.name}_rusanov{dimensions}d.h"))
905 if stateless_kernel_generated:
906 peano4_project.output.makefile.add_h_file(os.path.join(kernels_directory, f"{self._solver.name}_rusanov{dimensions}d.cpph"))
907 if non_stateless_kernel_generated or mlir_kernel_generated:
908 peano4_project.output.makefile.add_cpp_file(os.path.join(kernels_directory, f"{self._solver.name}_rusanov{dimensions}d.cpp"), generated=True)
909
910 for (_, stateless, language, memory_layout) in self._configurations:
911 if language == OutputLanguage.MLIR:
912 peano4_project.output.makefile.add_mlir_file(os.path.join(kernels_directory, f"{self._solver.name}_rusanov{dimensions}d_{memory_layout.name.lower()}.mlir"), "mlir-opt --pass-pipeline=\"builtin.module(canonicalize,cse,loop-invariant-code-motion,canonicalize,cse,loop-invariant-code-motion,cse,canonicalize,expand-strided-metadata,fold-memref-alias-ops,lower-affine,finalize-memref-to-llvm,loop-invariant-code-motion,canonicalize,cse,finalize-memref-to-llvm,convert-scf-to-cf,convert-openmp-to-llvm,convert-math-to-llvm,convert-func-to-llvm,reconcile-unrealized-casts,canonicalize,cse)\"")
913
914 file = open(os.path.join(temporary_output_directory, "kernels", f"{self._solver.name}_rusanov.h"), "w")
915 file.write(f"""#include "{self._solver.name}_rusanov{dimensions}d.h" """)
916 file.close()
917
919 kernel_calls = []
920 for (target, stateless, language, memory_layout) in self._configurations:
921 kernel_calls.append(self.__construct_kernel_call(target, stateless, language, memory_layout))
922 return kernel_calls
923
924 def __construct_kernel_call(self, target: Target, stateless: bool, language: OutputLanguage, memory_layout: MemoryLayout, function_name: str = None):
925 """!
926
927 This function constructs the calls to the compute kernels based on the
928 application PDE terms and the version chosen.
929
930 @param function_name: str
931 Unqualified name of the kernel. Defaults to the time step kernel.
932
933 """
934 if function_name is None:
935 function_name = self._solver.numerical_scheme.kernel_function_name
936 # Same order as the functor parameters of the generated kernels (@see function_map)
937 available_terms = ["volumetricSource", "flux", "nonconservativeProduct", "maxEigenvalue"]
938
939 if stateless:
940 # Stateless kernels require stateless functions, which are defined in the abstract solver
941 return f"""::{"::".join(self._solver.numerical_scheme.kernel_namespace + dslhype.generate_namespace(language, target, memory_layout))}::{function_name}Stateless<
942 Abstract{self._solver.name}
943 >(
944 {"0," if target==Target.Accelerator else ""}
945 {"gpuPatchData" if target==Target.Accelerator else "patchData"}
946 );"""
947 else:
948 # Variants per term the kernel takes: {name: {stateless: PDETerm}}
949 variants = {}
950 for application_term in self._solver.pde_terms:
951 if application_term.NAME in available_terms:
952 variants.setdefault(application_term.NAME, {})[application_term.stateless] = application_term
953
954 terms_with_both_variants = [name for name in variants if len(variants[name]) == 2]
955 terms_without_stateless_variant = [name for name in variants if True not in variants[name]]
956 if terms_with_both_variants and terms_without_stateless_variant:
957 raise Exception(
958 f"Solver {self._solver.name}: the PDE terms {terms_with_both_variants} are "
959 f"registered both with and without state. In this case, the generated code "
960 f"asks cellCanUseStatelessPDETerms() per cell before it invokes the kernel: "
961 f"if it returns true, the kernel is called with the stateless variants of all "
962 f"PDE terms, otherwise with the variants with state. However, the PDE terms "
963 f"{terms_without_stateless_variant} have no stateless variant, so a kernel "
964 f"call would mix stateless and stateful routines. Either add stateless "
965 f"variants of {terms_without_stateless_variant}, or register "
966 f"{terms_with_both_variants} only once."
967 )
968
969 def kernel_call(stateless: bool) -> str:
970 pde_term_calls = []
971 for term in available_terms:
972 if term not in variants:
973 continue
974 # A term registered only once is used in either case
975 application_term = variants[term].get(stateless, next(iter(variants[term].values())))
976 # Commas inside template brackets, e.g. Vector<Dimensions, double>,
977 # do not separate parameters
978 arguments = forwarding_arguments(application_term.SIGNATURE, self._solver)
979 # Stateless terms are static and take a dummy tag (@see PDETerm)
980 if application_term.stateless:
981 arguments.append("::exahype2::Solver::Offloadable::Yes")
982 pde_term_calls.append(f"""
983 [&](
984 {application_term.SIGNATURE}
985 )->void {{
986 repositories::{self._solver.get_name_of_global_instance()}.{application_term.name}({", ".join(arguments)});
987 }}""")
988 return f"""::{"::".join(self._solver.numerical_scheme.kernel_namespace + dslhype.generate_namespace(language, target, memory_layout))}::{function_name}(
989 patchData,
990{",\n".join(pde_term_calls)}
991);"""
992
993 if not terms_with_both_variants:
994 return kernel_call(stateless=False)
995 return f"""if (repositories::{self._solver.get_name_of_global_instance()}.cellCanUseStatelessPDETerms(
996 patchData.cellCentre[0],
997 patchData.cellSize[0],
998 patchData.t[0],
999 patchData.dt[0]
1000)) {{
1001{kernel_call(stateless=True)}
1002}} else {{
1003{kernel_call(stateless=False)}
1004}}"""
Specify which versions of a numerical scheme should be generated here.
Definition Solver.py:218
The concrete discretisation (Finite Volumes, ADER-DG, ...) realised by a Solver.
Definition Solver.py:60
Default mesh adaptation of the Finite Volume schemes.
__create_time_step_functions(self, exahype2_project, peano4_project)
Calling this function is delayed until all PDE term information is provided.
construct_output(self, exahype2_project, peano_project, time_step, add_global_tasks=True)
__construct_kernel_call(self, Target target, bool stateless, OutputLanguage language, MemoryLayout memory_layout, str function_name=None)
This function constructs the calls to the compute kernels based on the application PDE terms and the ...
Finite Volumes with a Rusanov Riemann solver and explicit Euler time stepping, realised over a block-...
__create_data_structures(self)
Create the mesh data structures (a Finite Volume patch per cell, plus the face-based overlap patches ...
__init__(self, Solver solver, int patch_size, int overlap=1, float cfl_constant=0.9, "toolbox.blockstructured.api.InterpolateHangingFaces.Scheme" interpolation=toolbox.blockstructured.api.InterpolateHangingFaces.Scheme.Linear, "toolbox.blockstructured.api.RestrictHangingFaces.Scheme" restriction=toolbox.blockstructured.api.RestrictHangingFaces.Scheme.Averaging, float min_volume_size=None, float max_volume_size=None)
The constructor memorises the attributes.
Solver.MeshAdaptation create_default_mesh_adaptation(self)
The Finite Volume schemes adapt the mesh and balance the load through exahype2.api....
"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.
str kernel_function_name(self)
Name of the generated time step kernel.
__add_data_to_repository(self, peano_project)
Consult page_exahype_programmers_guide_new_solver for some information how this routine fits to the t...
construct_output(self, exahype2_project, peano_project, time_step, add_global_tasks=True)
Has to be implemented by subclass.
str max_eigenvalue_kernel_function_name(self)
Name of the generated kernel which determines the maximum eigenvalue over a patch.
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
"void" timeStepWithRusanov3D("::exahype2::CellData<double, double>&" patchData)
Explicit Euler time step with a Rusanov flux over a 3d patch.
"void" maxEigenvalueOverPatch2D("::exahype2::CellData<double, double>&" patchData)
Maximum eigenvalue over a 2d patch without halo (patchData.QIn) into patchData.maxEigenvalue.
"void" timeStepWithRusanov2D("::exahype2::CellData<double, double>&" patchData)
DSLHyPE time step kernels.
"void" maxEigenvalueOverPatch3D("::exahype2::CellData<double, double>&" patchData)
Maximum eigenvalue over a 3d patch without halo (patchData.QIn) into patchData.maxEigenvalue.