Peano
Loading...
Searching...
No Matches
test_auxiliary_variables.py
Go to the documentation of this file.
1"""Unit tests for sets of auxiliary variables (@ref exahype2.api.AuxiliaryVariables)."""
2
3import types
4
5import peano4.api
7import pytest
8
9import unittest.mock
10
11import exahype2.api
12
13
14def _solver(name="Probe"):
15 solver = exahype2.api.Solver(name, {"h": 1, "hu": 2})
16 solver.add_pde_term(exahype2.api.Flux(implementation="F[0] = 1.0;", stateless=True))
17 solver.add_pde_term(
18 exahype2.api.NonconservativeProduct(implementation="", stateless=True)
19 )
20 solver.add_pde_term(exahype2.api.MaxEigenvalue(implementation="", stateless=False))
21 solver.add_pde_term(exahype2.api.InitPointWisely(implementation=""))
22 return solver
23
24
26 return (
27 exahype2.api.AuxiliaryVariables("Bathymetry", {"b": 1}),
28 exahype2.api.AuxiliaryVariables("Distortion", {"jacobian": 4, "shift": 1}),
29 )
30
31
34 "Distortion", {"jacobian": 4, "shift": 1}
35 )
36 assert distortion.size == 5
37 assert distortion.variable_positions == {"jacobian": 0, "shift": 4}
38 assert distortion.argument_name == "distortion"
39 assert distortion.delta_argument_name == "deltaDistortion"
40 assert "static constexpr int shift = 4;" in distortion.variables_declaration()
41
42
43@pytest.mark.parametrize("name", ["bathymetry", "1B", "B a"])
45 with pytest.raises(ValueError):
47
48
50 solver = _solver()
51 bathymetry, distortion = _two_sets()
52 solver.add_auxiliary_variables(bathymetry)
53 solver.add_auxiliary_variables(distortion)
54 assert solver.auxiliary_variables == [bathymetry, distortion]
55 assert solver.number_of_auxiliary_variables == 6
56 # Behind the three unknowns
57 assert solver.auxiliary_variable_offset(bathymetry) == 3
58 assert solver.auxiliary_variable_offset(distortion) == 4
59
60
62 solver = _solver()
63 bathymetry, _ = _two_sets()
64 solver.add_auxiliary_variables(bathymetry)
65 with pytest.raises(ValueError):
66 solver.add_auxiliary_variables(bathymetry)
67 with pytest.raises(ValueError):
68 solver.add_auxiliary_variables(
69 exahype2.api.AuxiliaryVariables("Bathymetry", {"c": 1})
70 )
71
72
74 first, second = _solver("First"), _solver("Second")
75 bathymetry, _ = _two_sets()
76 first.add_auxiliary_variables(bathymetry)
77 second.add_auxiliary_variables(bathymetry)
78 assert bathymetry.owner is first
79
80
82 solver = _solver()
83 flux = solver.get_pde_term("flux", True)
84 assert solver.signature_of(flux) == flux.SIGNATURE
85
86
88 solver = _solver()
89 for auxiliary in _two_sets():
90 solver.add_auxiliary_variables(auxiliary)
91 flux = solver.signature_of(solver.get_pde_term("flux", True))
92 assert flux.startswith(
93 "const double* __restrict__ Q, const double* __restrict__ bathymetry, "
94 "const double* __restrict__ distortion, const tarch::la::Vector<Dimensions, double>& x"
95 )
96 ncp = solver.signature_of(solver.get_pde_term("nonconservativeProduct", True))
97 assert (
98 "const double* __restrict__ Q, const double* __restrict__ bathymetry, "
99 "const double* __restrict__ distortion, "
100 "const double* __restrict__ deltaQ, const double* __restrict__ deltaBathymetry, "
101 "const double* __restrict__ deltaDistortion, " in ncp
102 )
103
104
106 owner, other = _solver("Owner"), _solver("Other")
107 bathymetry, _ = _two_sets()
108 owner.add_auxiliary_variables(bathymetry)
109 other.add_auxiliary_variables(bathymetry)
110 assert (
111 "double* __restrict__ Q, double* __restrict__ bathymetry"
112 in owner.signature_of(owner.get_pde_term("initPointWisely"))
113 )
114 assert (
115 "double* __restrict__ Q, const double* __restrict__ bathymetry"
116 in other.signature_of(other.get_pde_term("initPointWisely"))
117 )
118
119
121 solver = _solver()
122 for auxiliary in _two_sets():
123 solver.add_auxiliary_variables(auxiliary)
124 declaration = (
125 solver.get_pde_term("flux", True).generator_for(solver).generate_declaration()
126 )
127 # The extended term and the adapter which the kernels call
128 assert declaration.count("static GPUCallableMethod void flux(") == 2
129 definition = (
130 solver.get_pde_term("flux", True)
131 .generator_for(solver)
132 .generate_out_of_class_definitions("probe::AbstractProbe")
133 )
134 assert "flux(Q, Q + 3, Q + 4, x, normal, F, Offloadable::Yes);" in definition
135 ncp = (
136 solver.get_pde_term("nonconservativeProduct", True)
137 .generator_for(solver)
138 .generate_out_of_class_definitions("probe::AbstractProbe")
139 )
140 assert "deltaQ, deltaQ + 3, deltaQ + 4" in ncp
141
142
144 solver = _solver()
145 for auxiliary in _two_sets():
146 solver.add_auxiliary_variables(auxiliary)
147 from exahype2.api.AuxiliaryVariables import forwarding_arguments
148
149 assert forwarding_arguments(
150 solver.get_pde_term("maxEigenvalue").SIGNATURE, solver
151 ) == [
152 "Q",
153 "Q + 3",
154 "Q + 4",
155 "x",
156 "normal",
157 "lambdaMax",
158 ]
159
160
161def _graphs(solvers, tmp_path):
162 exahype2_project = types.SimpleNamespace(periodic_BC=[True] * 3, _dimensions=3)
163 peano_project = peano4.api.Project(["probe"], "probe", str(tmp_path))
165 time_step = peano4.api.taskgraph.Graph()
166 for solver in solvers:
167 solver.grid_construction = exahype2.api.fv.SetupSimulationOverRegularGrid(
168 solver, 0.1
169 )
170 solver.grid_construction.construct_output(
171 exahype2_project, peano_project, setup
172 )
173 solver.numerical_scheme.construct_output(
174 exahype2_project, peano_project, time_step
175 )
176 return peano_project, setup, time_step
177
178
179def _fv_solver(name):
180 solver = _solver(name)
181 solver.numerical_scheme = exahype2.api.fv.RusanovWithExplicitEuler(solver, 6)
182 return solver
183
184
186 first, second = _fv_solver("First"), _fv_solver("Second")
187 bathymetry, _ = _two_sets()
188 first.add_auxiliary_variables(bathymetry)
189 second.add_auxiliary_variables(bathymetry)
190 peano_project, setup, time_step = _graphs([first, second], tmp_path)
191 cells = [cell.name for cell in peano_project.datamodel.cell_data]
192 assert cells.count("BathymetryAuxiliaryVariables") == 1
193 # The unknowns do not hold auxiliary variables
194 assert first._patch.no_of_unknowns == 3
195 # The halos are temporary, i.e. each solver has its own
196 assert "BathymetryAuxiliaryVariablesWithHaloOfFirst" in cells
197 assert "BathymetryAuxiliaryVariablesWithHaloOfSecond" in cells
198 # The second solver initialises after the owner
199 tasks = {task.name: task for task in setup.tasks}
200 assert (
201 tasks["First Initial condition"]
202 in tasks["Second Initial condition"].dependencies
203 )
204
205
207 first, second = _fv_solver("First"), _fv_solver("Second")
208 bathymetry, _ = _two_sets()
209 first.add_auxiliary_variables(bathymetry)
210 second.add_auxiliary_variables(bathymetry)
211 with pytest.raises(ValueError, match="before"):
212 _graphs([second, first], tmp_path)
213
214
216 solver = _fv_solver("Probe")
217 for auxiliary in _two_sets():
218 solver.add_auxiliary_variables(auxiliary)
219 peano_project, setup, time_step = _graphs([solver], tmp_path)
220 cells = [cell.name for cell in peano_project.datamodel.cell_data]
221 assert "BathymetryAuxiliaryVariables" in cells
222 assert "DistortionAuxiliaryVariables" in cells
223
224
226 solver = _solver()
227 solver.add_auxiliary_variables(_two_sets()[0])
229 solver, 6
230 )
231 with pytest.raises(NotImplementedError):
232 solver.numerical_scheme.construct_output(
233 types.SimpleNamespace(periodic_BC=[True] * 3, _dimensions=3),
234 peano4.api.Project(["probe"], "probe", str(tmp_path)),
236 )
237
238
240 solver = _solver()
241 for auxiliary in _two_sets():
242 solver.add_auxiliary_variables(auxiliary)
243 solver.numerical_scheme = exahype2.api.fv.RusanovWithExplicitEuler(solver, 6)
244 solver._auxiliary_variable_halos = {
245 "Bathymetry": types.SimpleNamespace(name="BathymetryHalo"),
246 "Distortion": types.SimpleNamespace(name="DistortionHalo"),
247 }
248 solver.compute_kernel_call = "kernel();"
250 solver, "true"
251 ).get_body_of_operation(
252 peano4.api.solversteps.ActionSet.OPERATION_TOUCH_CELL_FIRST_TIME
253 )
254 # Stride of the kernels: three unknowns plus six auxiliary variables
255 assert "int inputStride = 9 *" in body
256 assert body.index("std::vector<double> kernelIn") < body.index("CopyCellDataGPU")
257 assert "fineGridCellBathymetryHalo.value[volume*1 + k]" in body
258 assert "fineGridCellDistortionHalo.value[volume*5 + k]" in body
259 assert body.index("copyBackAndDestroy") < body.rindex("kernelOut[volume*9 + k]")
260
261
263 solver = _solver()
264 solver.add_auxiliary_variables(_two_sets()[0])
266 solver, patch_size=6, rk_order=2, time_step_size=0.1
267 )
268 exahype2_project = types.SimpleNamespace(periodic_BC=[True] * 3, _dimensions=3)
269 peano_project = peano4.api.Project(["probe"], "probe", str(tmp_path))
270 time_step = peano4.api.taskgraph.Graph()
271 solver.numerical_scheme.construct_output(exahype2_project, peano_project, time_step)
272 tasks = {task.name: task for task in time_step.tasks}
273 # The unknowns and each set of auxiliary variables are reconstructed by tasks
274 # of their own, which run in parallel
275 reconstruction = tasks["Probe_Reconstruct stage 0"]
276 auxiliary = tasks["Probe_Reconstruct auxiliary variables Bathymetry stage 0"]
277 # The reconstruction of the unknowns interpolates the faces itself
278 assert [type(a).__name__ for a in reconstruction.action_sets] == [
279 "InterpolateHangingFaces",
280 "ReconstructPatchWithHalo",
281 ]
282 assert [type(a).__name__ for a in auxiliary.action_sets] == [
283 "InterpolateHangingFaces",
284 "ReconstructPatchWithHalo",
285 ]
286 assert reconstruction not in auxiliary.dependencies
287 assert auxiliary not in tasks["Probe_Reconstruct stage 0"].dependencies
288 update = tasks["Probe_Evaluate Runge-Kutta right hand side stage 0"]
289 body = update.action_sets[0].get_body_of_operation(
290 peano4.api.solversteps.ActionSet.OPERATION_TOUCH_CELL_FIRST_TIME
291 )
292 assert "std::vector<double> kernelIn" in body
293 # The kernels see the unknowns plus the auxiliary variables
294 assert (
295 "Probe_rightHandSideWithFD4<\n 6,\n 2,\n 3,\n 1\n>"
296 in solver.compute_kernel_call
297 )
298
299
301 auxiliary = exahype2.api.AuxiliaryVariables("Bathymetry", {"b": 1})
302 assert auxiliary.mode == exahype2.api.AuxiliaryVariables.Mode.STATIONARY_ON_FACES
303 assert auxiliary.data_name == "BathymetryAuxiliaryVariables"
304
305
308 "Derivatives",
309 {"d": 2},
310 mode=exahype2.api.AuxiliaryVariables.Mode.CHANGING_ON_FACES,
311 data_name="DerivativeVariables",
312 )
313 auxiliary.create_data_structures(9, 3, unittest.mock.MagicMock())
314 assert auxiliary.patch.name == "DerivativeVariables"
315 assert (
316 auxiliary.patch_overlap_current_time_step.name
317 == "DerivativeVariablesCurrentTimeStep"
318 )
319 assert auxiliary.patch_overlap_update.name == "DerivativeVariablesUpdate"
320
321
322def _fd4_time_step(tmp_path, mode, rk_order=3):
323 solver = _solver()
324 auxiliary = exahype2.api.AuxiliaryVariables("Bathymetry", {"b": 1}, mode=mode)
325 solver.add_auxiliary_variables(auxiliary)
327 solver, patch_size=6, rk_order=rk_order, time_step_size=0.1
328 )
329 exahype2_project = types.SimpleNamespace(periodic_BC=[True] * 3, _dimensions=3)
330 peano_project = peano4.api.Project(["probe"], "probe", str(tmp_path))
331 time_step = peano4.api.taskgraph.Graph()
332 solver.numerical_scheme.construct_output(exahype2_project, peano_project, time_step)
333 return solver, auxiliary, {task.name: task for task in time_step.tasks}
334
335
336def _reconstruction_name(auxiliary, stage):
337 name = exahype2.api.AuxiliaryVariables.RECONSTRUCTION_TASK_NAME.format(
338 auxiliary.name
339 )
340 return f"Probe_{name} stage {stage}"
341
342
344 Mode = exahype2.api.AuxiliaryVariables.Mode
345 solver, auxiliary, tasks = _fd4_time_step(tmp_path, Mode.CHANGING_ON_FACES)
346 Access = peano4.api.taskgraph.Task.DataAccess
347 halo = solver._auxiliary_variable_halos[auxiliary.name]
348 for stage in range(3):
349 assert _reconstruction_name(auxiliary, stage) in tasks
350 rhs = tasks[f"Probe_Evaluate Runge-Kutta right hand side stage {stage}"]
351 assert rhs.cell_data_access[halo] == Access.READ_AND_DISCARD
352
353
355 tmp_path,
356):
357 Mode = exahype2.api.AuxiliaryVariables.Mode
358 solver, auxiliary, tasks = _fd4_time_step(
359 tmp_path, Mode.STATIONARY_THROUGHOUT_TIME_STEPS_ON_FACES
360 )
361 Access = peano4.api.taskgraph.Task.DataAccess
362 halo = solver._auxiliary_variable_halos[auxiliary.name]
363 assert _reconstruction_name(auxiliary, 0) in tasks
364 assert _reconstruction_name(auxiliary, 1) not in tasks
365 assert _reconstruction_name(auxiliary, 2) not in tasks
366 assert (
367 tasks[_reconstruction_name(auxiliary, 0)].cell_data_access[halo]
368 == Access.WRITE
369 )
370 # The halo survives all stages but the last, which discards it
371 for stage, expected in [
372 (0, Access.READ_AND_WRITE),
373 (1, Access.READ_AND_WRITE),
374 (2, Access.READ_AND_DISCARD),
375 ]:
376 rhs = tasks[f"Probe_Evaluate Runge-Kutta right hand side stage {stage}"]
377 assert rhs.cell_data_access[halo] == expected
378 # The unknowns are still reconstructed in every stage
379 for stage in range(3):
380 assert f"Probe_Reconstruct stage {stage}" in tasks
381
382
384 Mode = exahype2.api.AuxiliaryVariables.Mode
385 solver, auxiliary, tasks = _fd4_time_step(
386 tmp_path, Mode.STATIONARY_THROUGHOUT_TIME_STEPS_ON_FACES, rk_order=1
387 )
388 Access = peano4.api.taskgraph.Task.DataAccess
389 halo = solver._auxiliary_variable_halos[auxiliary.name]
390 rhs = tasks["Probe_Evaluate Runge-Kutta right hand side stage 0"]
391 assert rhs.cell_data_access[halo] == Access.READ_AND_DISCARD
A set of auxiliary variables of a solver.
The conservative flux F(Q) of a hyperbolic PDE.
Definition Flux.py:8
Point-wise initial condition: given the physical position of a single degree of freedom,...
The maximum absolute eigenvalue of the flux Jacobian in a given direction, i.e.
The non-conservative product B(Q) applied to a jump deltaQ in a given direction, i....
Abstract base class for all ExaHyPE 2 solvers.
Definition Solver.py:17
Finite Volumes with a Rusanov Riemann solver and explicit Euler time stepping, realised over a block-...
Finite Volumes with a Rusanov Riemann solver and optimistic explicit Euler time stepping,...
Setup phase counterpart to RusanovWithExplicitEuler: sets the initial condition for a Finite Volume s...
Update a Finite Volume patch (solver._patch) from its halo-augmented reconstruction (solver....
Fourth-order central Finite Differences with explicit Runge-Kutta time stepping, realised over a bloc...
Represents a Peano 4 project.
Definition Project.py:26
Holds a sequence of Task instances.
Definition Graph.py:9
The task graph abstraction allows users to formalise their solver steps over small task graphs which ...
Definition __init__.py:1
test_fd4_reconstructs_the_halos_of_auxiliary_variables(tmp_path)
_fd4_time_step(tmp_path, mode, rk_order=3)
test_fd4_with_one_stage_discards_the_held_halo_right_away(tmp_path)
test_fd4_reconstructs_changing_halos_in_every_stage(tmp_path)
test_abstract_solver_declares_structs_and_kernel_adapters(tmp_path)
test_fd4_reconstructs_halos_that_are_stationary_through_the_time_step_once(tmp_path)
test_optimistic_scheme_rejects_auxiliary_variables(tmp_path)