Peano
Loading...
Searching...
No Matches
test_exagrype_ccz4_solver.py
Go to the documentation of this file.
1import os
2import re
3
4import pytest
5
6import peano4.api
8import exahype2.api
9import exagrype.api
10
11
12with open(
13 os.path.join(
14 os.path.dirname(__file__), "..", "..", "src", "exagrype", "ccz4", "Kernels.h"
15 )
16) as kernels_header:
17 KERNELS_HEADER = kernels_header.read()
18
19
21 solver = exagrype.api.FOCCZ4Solver("CCZ4")
22 assert solver.unknowns == 58
23 assert solver.unknowns == exagrype.api.FOCCZ4Solver.NUMBER_OF_CCZ4_ENTRIES
24 assert solver.number_of_auxiliary_variables == 0
25 assert solver.variable_names_per_entry()[16] == "lapse"
26 assert solver.variable_names_per_entry()[23] == "Kex"
27 assert solver.variable_names_per_entry()[24] == "phi"
28 # The last unknowns are the derivatives of phi: K0 is no unknown
29 assert solver.variable_names_per_entry()[55:] == ["P[0]", "P[1]", "P[2]"]
30
31
32def _call(solver, term):
33 """!
34 C++ which calls the kernel of term. The solver registers its
35 non-conservative product only when it is realised, so the call of
36 the kernel is taken from the hook which writes it.
37 """
38 if term == exahype2.api.NonconservativeProduct.NAME:
39 return solver._ncp_implementation()
40 return solver.get_pde_term(term, stateless=True).implementation
41
42
44 """!
45 The non-conservative product is missing until the solver is realised
46 (test_realisation_registers_the_ncp_which_fits_the_numerical_scheme)
47 """
48 solver = exagrype.api.FOCCZ4Solver("CCZ4")
49 names = {term.name for term in solver.pde_terms}
50 assert names == {
51 exahype2.api.VolumetricSource.NAME,
52 exahype2.api.MaxEigenvalue.NAME,
53 }
54 assert "::exagrype::ccz4::ncpFirstOrder(" in _call(
55 solver, exahype2.api.NonconservativeProduct.NAME
56 )
57 assert (
58 "::exagrype::ccz4::sourceFirstOrder("
59 in solver.get_pde_term("volumetricSource", stateless=True).implementation
60 )
61 assert (
62 "::exagrype::ccz4::maxEigenvalue("
63 in solver.get_pde_term("maxEigenvalue", stateless=True).implementation
64 )
65 # All terms are generated, so no user class is required
66 assert not solver.requires_user_class
67
68
70 solver = exagrype.api.FOCCZ4Solver("CCZ4")
71 assert "initPointWisely" not in {term.name for term in solver.pde_terms}
72
73
75 solver = exagrype.api.FOCCZ4Solver("CCZ4")
76 solver.add_pde_term(exagrype.api.initialvalues.gauge_wave())
77 assert "gaugeWave" in solver.get_pde_term("initPointWisely").implementation
78 solver.add_pde_term(exagrype.api.initialvalues.flat())
79 assert (
80 "::exagrype::initialvalues::flat("
81 in solver.get_pde_term("initPointWisely").implementation
82 )
83
84
87 "CCZ4", parameters={"CCZ4k1": 0.0, "CCZ4LapseType": 1}
88 )
89 assert solver.parameters["CCZ4k1"] == 0.0
90 assert solver.parameters["CCZ4LapseType"] == 1
91 assert (
92 solver.parameters["CCZ4GLMd"]
93 == exagrype.api.FOCCZ4Solver.DefaultParameters["CCZ4GLMd"]
94 )
95
96
98 with pytest.raises(KeyError):
99 exagrype.api.FOCCZ4Solver("CCZ4", parameters={"CCZ4kk1": 0.0})
100
101
102@pytest.mark.parametrize("key", ["CCZ4ds", "CCZ4xi", "CCZ4sk", "CCZ4bs", "CCZ4SO"])
104 assert key not in exagrype.api.FOCCZ4Solver.DefaultParameters
105 with pytest.raises(KeyError):
106 exagrype.api.FOCCZ4Solver("CCZ4", parameters={key: 1})
107
108
110 defaults = exagrype.api.FOCCZ4Solver.DefaultParameters
111 assert defaults["CCZ4b"] == 1
112 assert defaults["CCZ4s"] == 0
113 for key in exagrype.api.FOCCZ4Solver.Switches:
114 assert isinstance(defaults[key], int)
115
116 solver = exagrype.api.FOCCZ4Solver("CCZ4", parameters={"CCZ4b": 1, "CCZ4s": 1})
117 attributes = "\n".join(solver._abstract_solver_attributes)
118 assert "static constexpr int CCZ4b = 1;" in attributes
119 assert "static constexpr int CCZ4s = 1;" in attributes
120 assert "static constexpr double CCZ4f = 0.75;" in attributes
121
122
123@pytest.mark.parametrize("value", [1.0, 2, -1, True, "1"])
125 with pytest.raises(TypeError):
126 exagrype.api.FOCCZ4Solver("CCZ4", parameters={"CCZ4s": value})
127 with pytest.raises(TypeError):
128 exagrype.api.FOSOCCZ4Solver("SO", parameters={"CCZ4b": value})
129
130
131@pytest.mark.parametrize(
133)
134@pytest.mark.parametrize(
135 "term", ["nonconservativeProduct", "volumetricSource", "maxEigenvalue"]
136)
138 """!
139
140 The CCZ4 parameters of a kernel call match the kernel's declaration
141
142 The parameters are doubles and integers, i.e. the compiler does not
143 notice if a call passes them in the wrong order. The test reads the
144 name of the kernel from the generated call and the parameters from its
145 declaration in Kernels.h, i.e. it holds no names of its own
146 (tests/unit/adrs/0001-unit-tests-query-names-from-the-code.md).
147
148 """
149 solver = solver_class("CCZ4")
150 call = _call(solver, term)
151 kernel = re.search(r"::exagrype::ccz4::(\w+)\‍(", call).group(1)
152 declaration = re.search(rf"void {kernel}\‍((.*?)\‍);", KERNELS_HEADER, re.DOTALL)
153 declared_parameters = re.findall(r"\bCCZ4\w+", declaration.group(1))
154
155 assert declared_parameters
156 assert re.findall(r"\bCCZ4\w+", call) == declared_parameters
157 assert set(declared_parameters) <= set(solver_class.DefaultParameters)
158
159
161 solver = exagrype.api.FOCCZ4Solver("CCZ4")
162 Enforce = exagrype.api.FOCCZ4Solver.EnforceCCZ4Constraint
163 assert solver._enforce_ccz4_constraint == Enforce.No
164 solver.enforce_ccz4_constraint(Enforce.IntermediateSteps)
165 assert solver._enforce_ccz4_constraint == Enforce.IntermediateSteps
166 solver.enforce_ccz4_constraint(Enforce.No)
167 assert solver._enforce_ccz4_constraint == Enforce.No
168 with pytest.raises(TypeError):
169 solver.enforce_ccz4_constraint(True)
170
171
172Kernel = exahype2.api.rkfd4.CentralDifferencesWithRungeKutta.RightHandSideKernel
173
174
176 return exahype2.api.rkfd4.CentralDifferencesWithRungeKutta(solver, 9, rk_order=4)
177
178
179def _dissipation(solver):
180 return exagrype.api.FD4WithKODissipation(solver, 9, 4, kreiss_oliger_sigma=1.0)
181
182
183def _lopsided(solver, advected_quantities=None, advection_velocity=None):
184 """! FD4 with lopsided advection, by default of the quantities the solver asks for"""
185 return exahype2.api.rkfd4.CentralDifferencesWithRungeKutta(
186 solver,
187 9,
188 rk_order=4,
189 right_hand_side_kernel=Kernel.CentralDifferencesWithLopsidedAdvection,
190 advection_velocity=advection_velocity or type(solver).ADVECTION_VELOCITY,
191 advected_quantities=(
192 solver.advected_quantities()
193 if advected_quantities is None
194 else advected_quantities
195 ),
196 )
197
198
199def _finite_volumes(solver):
200 return exahype2.api.fv.RusanovWithExplicitEuler(solver, 9)
201
202
203@pytest.mark.parametrize(
204 "solver_class", [exagrype.api.FOCCZ4Solver, exagrype.api.FOSOCCZ4Solver]
205)
206@pytest.mark.parametrize(
207 "parameters", [{}, {"CCZ4s": 1, "CCZ4b": 1}, {"CCZ4s": 1, "CCZ4b": 0}]
208)
209@pytest.mark.parametrize(
210 "scheme_factory, advection",
211 [
212 (_central_differences, True),
213 (_dissipation, True),
214 (_lopsided, False),
215 (_finite_volumes, False),
216 ],
217)
218def test_ncp_adds_advection_iff_the_scheme_does_not(
219 solver_class, parameters, scheme_factory, advection
220):
221 """!
222
223 The non-conservative product adds the advection terms if and only if the
224 Finite Differences do not (src/exagrype/ccz4/adrs/0003-the-solver-picks-who-adds-the-advection.md).
225 The Finite Volumes add none, and neither does the non-conservative product.
226
227 """
228 solver = solver_class("CCZ4", parameters=parameters)
229 solver.numerical_scheme = scheme_factory(solver)
230 assert solver.ncp_adds_advection() == advection
231
232
233@pytest.mark.parametrize(
234 "solver_class", [exagrype.api.FOCCZ4Solver, exagrype.api.FOSOCCZ4Solver]
235)
236def test_ncp_adds_advection_rejects_lopsided_advection_of_other_quantities(
237 solver_class,
238):
239 """!
240
241 A scheme which advects other quantities than those the kernels leave
242 out would add some advection terms twice or miss some
243
244 """
245 frozen_shift = solver_class("CCZ4")
246 moving_shift = solver_class("CCZ4", parameters={"CCZ4s": 1, "CCZ4b": 1})
247 wrong_choices = [
248 dict(advected_quantities=frozen_shift.advected_quantities()[1:]),
249 dict(advected_quantities=moving_shift.advected_quantities()),
250 dict(advection_velocity="b"),
251 ]
252 for choice in wrong_choices:
253 solver = solver_class("CCZ4")
254 solver.numerical_scheme = _lopsided(solver, **choice)
255 with pytest.raises(ValueError):
256 solver.ncp_adds_advection()
257
258
259def test_ncp_adds_advection_rejects_unknown_schemes():
260 solver = exagrype.api.FOCCZ4Solver("CCZ4")
261 with pytest.raises(TypeError):
262 solver.ncp_adds_advection()
263
264
265def _constexpr_list(code, name):
266 return [
267 int(entry)
268 for entry in re.search(rf"constexpr int {name}\‍[\‍] = {{(.*?)}};", code)
269 .group(1)
270 .split(",")
271 ]
272
273
274@pytest.mark.parametrize(
275 "solver_class", [exagrype.api.FOCCZ4Solver, exagrype.api.FOSOCCZ4Solver]
276)
277@pytest.mark.parametrize(
278 "parameters",
279 [{}, {"CCZ4s": 1, "CCZ4b": 1}, {"CCZ4s": 1, "CCZ4b": 0}, {"CCZ4s": 0, "CCZ4b": 1}],
280)
281def test_central_advection_adds_what_the_lopsided_advection_would_add(
282 solver_class, parameters
283):
284 """!
285
286 The advection which the non-conservative product appends covers exactly
287 the quantities and the velocity which the lopsided advection of the
288 scheme gets, i.e. either way the same terms are added. Both read them
289 from advected_quantities() and ADVECTION_VELOCITY, the one
290 definition of the advection terms. The call passes the arguments of
291 exahype2::fd::addCentralAdvection() in the order of its declaration.
292
293 """
294 solver = solver_class("CCZ4", parameters=parameters)
295 scheme = _lopsided(solver)
296 code = solver._advection_implementation()
297
298 quantities = _constexpr_list(code, "quantities")
299 assert quantities == scheme.advected_quantities
300 assert _constexpr_list(code, "velocity") == scheme.advection_velocity
301 assert all(index < solver.unknowns for index in quantities)
302
303 call = re.search(r"::exahype2::fd::addCentralAdvection\‍((.*?)\‍);", code)
304 assert call.group(1).split(", ") == [
305 "Q",
306 "deltaQ",
307 "BTimesDeltaQ",
308 "normal",
309 "velocity",
310 "quantities",
311 str(len(quantities)),
312 ]
313 with open(
314 os.path.join(
315 os.path.dirname(__file__),
316 "..",
317 "..",
318 "src",
319 "exahype2",
320 "fd",
321 "CentralAdvection.h",
322 )
323 ) as header:
324 declaration = re.search(
325 r"void addCentralAdvection\‍((.*?)\‍);", header.read(), re.DOTALL
326 )
327 declared = [parameter.split()[-1] for parameter in declaration.group(1).split(",")]
328 assert declared == [
329 "Q",
330 "deltaQ",
331 "BTimesDeltaQ",
332 "normal",
333 "velocity",
334 "quantities",
335 "numberOfQuantities",
336 ]
337
338
339def _realise(solver, tmp_path):
340 """! Realise a first-order solver with gauge wave initial data on the unit cube"""
341 exahype2_project = exahype2.api.Project(
342 ["probe"], "probe", "probe", directory=str(tmp_path)
343 )
344 exahype2_project.set_global_simulation_parameters(
345 dimensions=3,
346 offset=[0.0, 0.0, 0.0],
347 size=[1.0, 1.0, 1.0],
348 min_end_time=1.0,
349 periodic_BC=[True, True, True],
350 )
351 peano_project = peano4.api.Project(["probe"], "probe", str(tmp_path))
352 graphs = [peano4.api.taskgraph.Graph() for _ in range(4)]
353 solver.generate_solver_realisation(exahype2_project, peano_project, *graphs)
354
355
356def _solver_with(scheme_factory):
357 solver = exagrype.api.FOCCZ4Solver("CCZ4", parameters={"CCZ4s": 1, "CCZ4b": 1})
358 solver.add_pde_term(exagrype.api.initialvalues.gauge_wave())
359 solver.numerical_scheme = scheme_factory(solver)
360 solver.grid_construction = exahype2.api.rkfd4.SetupSimulationOverRegularGrid(
361 solver, volume_size=1.0 / 27.0
362 )
363 return solver
364
365
366def _non_conservative_products(solver):
367 return [
368 term
369 for term in solver.pde_terms
370 if term.name == exahype2.api.NonconservativeProduct.NAME
371 ]
372
373
374@pytest.mark.parametrize(
375 "scheme_factory, advection",
376 [(_central_differences, True), (_lopsided, False)],
377)
378def test_realisation_registers_the_ncp_which_fits_the_numerical_scheme(
379 scheme_factory, advection, tmp_path
380):
381 """!
382
383 The solver is created before its numerical scheme, so it can pick the
384 non-conservative product only when it is realised. It registers a
385 single, stateless one
386
387 """
388 solver = _solver_with(scheme_factory)
389 assert not _non_conservative_products(solver)
390 _realise(solver, tmp_path)
391
392 (term,) = _non_conservative_products(solver)
393 assert term.stateless
394 assert "::exagrype::ccz4::ncpFirstOrder(" in term.implementation
395 assert ("::exahype2::fd::addCentralAdvection(" in term.implementation) == advection
396
397
398def test_realising_twice_replaces_the_ncp_of_the_first_realisation(tmp_path):
399 """! A project can be generated several times"""
400 solver = _solver_with(_central_differences)
401 _realise(solver, tmp_path / "first")
402 _realise(solver, tmp_path / "second")
403 (term,) = _non_conservative_products(solver)
404 assert term.implementation.count("::exahype2::fd::addCentralAdvection(") == 1
405
406
407@pytest.mark.parametrize("stateless", [True, False])
408def test_realisation_rejects_an_ncp_added_by_somebody_else(stateless, tmp_path):
409 """!
410
411 The solver would replace it silently, and it might add advection terms
412 the scheme adds as well, or miss them
413 (src/exagrype/ccz4/adrs/0003-the-solver-picks-who-adds-the-advection.md)
414
415 """
416 solver = _solver_with(_central_differences)
417 solver.add_pde_term(
418 exahype2.api.NonconservativeProduct(implementation="", stateless=stateless)
419 )
420 with pytest.raises(ValueError, match="add_pde_term"):
421 _realise(solver, tmp_path)
Fourth-order Finite Differences with Kreiss-Oliger dissipation.
Solver for the Einstein equations in the first-order CCZ4 formulation.
Solver for the Einstein equations in the first-/second-order reconstructed CCZ4 formulation.
Fourth-order central Finite Differences with explicit Runge-Kutta time stepping, realised over a bloc...
exahype2.api.InitPointWisely gauge_wave()
Gauge wave along the x-axis,.
exahype2.api.InitPointWisely flat()
Flat (Minkowski) spacetime,.
This file is part of the ExaGRyPE project.
Definition __init__.py:1
The task graph abstraction allows users to formalise their solver steps over small task graphs which ...
Definition __init__.py:1
test_kernel_calls_pass_the_parameters_of_the_kernel_signature(solver_class, term)
The CCZ4 parameters of a kernel call match the kernel's declaration.
_call(solver, term)
C++ which calls the kernel of term.
test_solver_registers_ccz4_pde_terms()
The non-conservative product is missing until the solver is realised (test_realisation_registers_the_...
_lopsided(solver, advected_quantities=None, advection_velocity=None)
FD4 with lopsided advection, by default of the quantities the solver asks for.