3First-order vs. second-order reconstructed CCZ4: gauge wave benchmark
5This is the gauge wave benchmark (@ref benchmarks_exagrype_gauge_wave) with the
6fourth-order Finite Differences (exahype2.api.rkfd4), but we instantiate two
7solvers in one setup: exagrype.api.FOCCZ4Solver, which evolves all 58 CCZ4
8unknowns, and exagrype.api.FOSOCCZ4Solver, which evolves 25 of them and obtains
9the 33 first derivatives from the exagrype.api.FOSOReconstructionSolver next to it
10(both are hosted by an exagrype.api.FOSOSolver). Both solvers
11use the same Runge-Kutta scheme, the same lopsided advection and no
12dissipation. The two do not yield identical results: The first-order solver
13evolves the derivatives as unknowns, whereas the second-order solver
14re-computes them from the 25 unknowns in each Runge-Kutta stage. The script
15builds and runs the code, and then quantifies the difference of the 25
16evolved unknowns of both solvers, and the deviation of both from the
17analytical solution of the gauge wave.
19Two exahype2.api.rkfd4 solvers cannot live in one project yet, as both
20generate the solver-independent kernel rungekutta_linear_combination into the
21same file (@ref page_exagrype_fo_so_project_plan). The script therefore
22builds and runs each solver on its own, in a directory of its own
23(run-FO and run-SO), and then compares the plot files.
25@todo This post-run comparison of plot files is a stop-gap. We have to return
26 to it and replace it by an on-the-fly check, i.e. a check within the
27 simulation that compares both solvers' data while the code runs.
29The gauge wave is a pure gauge perturbation of flat spacetime, i.e. an
30analytical solution of the Einstein equations that travels along the x-axis
31with speed one. It is periodic over the unit cube and hence a standard first
32test of any numerical relativity code. This script uses exagrype.api, i.e.
33the CCZ4 solvers of the new Python API. It requires a Peano build with
35 --enable-exahype --enable-blockstructured --enable-loadbalancing --enable-exagrype
37and is run from this directory via
41## Schemes, formulations and grid sizes
43The benchmark covers two numerical schemes:
45- RK4FD4: fourth-order Finite Differences with classic Runge-Kutta 4 and lopsided
46 advection (exahype2.api.rkfd4.CentralDifferencesWithRungeKutta). The
47 second-order solver reconstructs the derivatives with the fourth-order
48 stencil in each Runge-Kutta stage.
49- RK1FD4: the same spatial discretisation, but with first-order Runge-Kutta
50 (explicit Euler, rk_order=1), i.e. one stage per time step.
51- FV: Finite Volumes with a Rusanov flux and explicit Euler
52 (exahype2.api.fv.RusanovWithExplicitEuler). The second-order solver
53 reconstructs the derivatives with second-order central differences
54 once per time step. Neither advection nor dissipation are used, which is
55 fine as the shift of the gauge wave is zero.
57Each of the two comes in the formulations FO (exagrype.api.FOCCZ4Solver) and
58SO (exagrype.api.FOSOCCZ4Solver). The grid has cells x cells x cells grid
59points (patch size 9 and 3^k patches per axis, i.e. cells is 27, 81, ... (Peano refines to at least three patches per axis)). The grid size is
60compiled into the executable, so each combination is built in a directory of
61its own (run-scheme-formulation-cells).
63 python3 fo_vs_so.py # same as --mode=run-and-compare
64 python3 fo_vs_so.py --mode=build # generate and compile all combinations
65 python3 fo_vs_so.py --mode=run # generate, compile and run all combinations
66 python3 fo_vs_so.py --mode=run-and-compare # run, then print the table
67 python3 fo_vs_so.py --mode=compare-only # re-print the table from existing runs
69The script loops sequentially, within one Python process, over all schemes,
70grid sizes and formulations.
72The option --build-mode=debug|release selects the build (default release; debug
73also enables the generator logging). --schemes (default RK4FD4,RK1FD4,FV), --formulations (default FO,SO; with just one,
74the comparison table lists the lapse error and wall time of that formulation only), --sizes (default 27,81), --end-time (default
750.1) and --cfl (CFL constant of the Finite Volume scheme, default 0.9) override
76the remaining settings.
78@page benchmarks_exagrype_fo_vs_so First-order vs hybrid First-order second-order CCZ4 formulation
82This page has yet to be written.
85See the benchmark benchmarks/exagrype/fo_vs_so. It runs the gauge wave
86with both solvers and prints the maximum and relative L2 difference of the 25
87evolved unknowns at the end of the run.
89Setup (`python3 fo_vs_so.py`, i.e. release build, end time 0.1): gauge wave on the
90periodic unit cube, 27 grid points per axis (patch size 9, 3 patches per axis), fourth-order
91Finite Differences with classic Runge-Kutta 4 and lopsided advection, no dissipation,
92adaptive time step size (CFL), end time 0.1 (about 33 time steps). Both solvers
93use the same numerical scheme. We compare the 25 evolved unknowns at the end of the
94run. The last column shows how far the first-order solution moved away from its
95initial condition, i.e. the scale of the dynamics.
97| unknown | max abs. difference SO vs. FO | relative L2 difference | max abs. change of FO in the run |
99| G (xx, yy, zz) | 7.6e-6 / 4.1e-6 / 4.1e-6 | 3.4e-6 / 1.8e-6 / 1.8e-6 | 4.2e-2 / 2.1e-2 / 2.1e-2 |
100| K (xx, yy, zz) | 7.7e-5 / 4.1e-5 / 4.1e-5 | 2.3e-4 | 1.4e-1 / 7.9e-2 / 7.9e-2 |
101| lapse | 2.5e-6 | 1.0e-6 | 3.1e-2 |
102| phi | 2.0e-6 | 8.7e-7 | 1.1e-2 |
103| Kex | 1.3e-4 | 2.4e-4 | 2.3e-1 |
104| Z (x) | 5.0e-5 | 7.7e-5 | 3.1e-1 |
105| theta | 3.6e-5 | (not meaningful) | 1.9e-5 |
106| all others (off-diagonals, shift, b, Z_y, Z_z) | 0 | 0 | 0 |
108**Reading the table.** The two solvers agree to 1e-6 to 1e-4 in absolute terms,
109which is two to four orders of magnitude below the change of the solution within
110the run. The metric, the lapse and phi agree best (relative 1e-6), the extrinsic
111curvature and its trace worst (relative 2e-4). The remaining entries are
112identically zero for both (the gauge wave does not excite them). Theta (a measure of the
113Hamilton constraint violation) is tiny in the first-order run (it changes by 1.9e-5
114at most), and the two solvers differ by 3.6e-5, i.e. by more than the first-order
115solver's theta moves. The relative difference is therefore not meaningful. We have
116no reference solution for theta yet, so we cannot say which solver is closer to the
119**Caveats.** One resolution, one end time, one test case. The comparison measures
120how close SO is to FO, not how accurate either of them is. A convergence study
121against the analytical gauge wave (@ref benchmarks_exagrype_gauge_wave), a
122longer run, and a black hole run are still missing.
124**Cost.** In the release build with 8 OpenMP threads (machine shared with other
125jobs, so treat with care), one reported TimeStep phase took about 0.15 s for the
126first-order solver and about 0.21 s for the second-order solver on this mesh,
127i.e. SO is about 40% slower per step. This is expected: SO reconstructs the
128derivatives in an extra mesh sweep per Runge-Kutta stage, exchanges an extra
129halo of 33 values per stage, and gathered/scattered the 58 entries in every PDE term
130evaluation (it does not anymore, the kernels take the primary and the secondary
131entries as two pointers). We did not profile it. SO stores fewer values per stage (25 instead of
13258 for the stage input, the right-hand-side estimates and the halo patch). A
133first, finer run (729 patches of 9^3 points) was killed by the operating system
134for the first-order solver (out of memory, 15 GB machine shared with other
135processes), while the second-order solver ran through with a resident set of
136about 3.5 GB. This is an observation, not a measurement.
139## Grid sizes and Finite Volumes
141The benchmark script now takes the scheme (RK4FD4, RK1FD4 or FV), the formulation (FO or SO) and the grid
142size (`python3 fo_vs_so.py`, `--build-mode=debug` for debug builds). Peano refines to at least three patches
143per axis and then in powers of three, and a patch has 9 points per axis, i.e. valid grids are 27^3 and 81^3
144points (a first attempt with 9, 18 and 45 points silently ran on the next larger grid). Setup otherwise as above: gauge wave, periodic unit cube,
145RK4 with lopsided advection, end time 0.1 (the last step overshoots, the time stamp is given). We also compare the lapse of
146both solvers against the analytical lapse
147\f$ \sqrt{1-0.1\sin(4\pi(x-t))} \f$. The wall time is the one of the whole run (setup, plots and about 33 (27^3) or
148100 (81^3) time steps; machine shared with other jobs, 8 threads, treat with care).
150| scheme | grid | t | max abs. diff. SO vs. FO (25 unknowns) | max abs. diff. of the lapse | rel. L2 lapse error FO | rel. L2 lapse error SO | wall time FO | wall time SO |
151|---|---|---|---|---|---|---|---|---|
152| RK4FD4 | 27^3 | 0.102 | 1.3e-4 | 2.5e-6 | 1.1e-6 | 1.6e-6 | 4.8 s | 5.6 s |
153| RK4FD4 | 81^3 | 0.101 | 1.6e-6 | 3.1e-8 | 1.4e-8 | 2.2e-8 | 300 s | 377 s |
155**Reading the table.** The 27^3 row reproduces the numbers of the first table
156(the largest difference is the one of Kex). Refining the grid by a factor of three reduces the
157difference between the two solvers by a factor of about 80, and the error of each solver against the analytical lapse
158by about 80 (FO) and 75 (SO), i.e. \f$ 3^4 \f$: both formulations converge with fourth order, and the SO solver stays within a factor of
1591.5 of the first-order solver's error. On the finer grid, SO is about 25% slower than FO per run (about 15% on the 27^3 grid, where setup and plots matter more).
163The FV variant (second-order central differences, one reconstruction task per step) builds,
164generates and runs, but we could **not** obtain a meaningful FV comparison. The reason is not
165the reconstruction: the Finite Volume time step kernel in 3d that exahype2.api.fv.RusanovWithExplicitEuler generates
166contains neither the non-conservative product, the source, nor the maximum eigenvalue. The kernel template guards these blocks with
167`if nonconservativeProduct:`, `if volumetricSource:`, `if maxEigenvalue:` (and `if flux:`), but
168the DSL parser compares the guard with the class names of the PDE terms
169(NonconservativeProduct, VolumetricSource, MaxEigenvalue, Flux, see exahype2.api.dslhype2.Parser._parse_if()), so the blocks are dropped. The generated kernel
170then only applies the Rusanov diffusion to the unknowns, and it never writes the maximum eigenvalue of the cell,
171so the global time step size is derived from uninitialised memory (time step sizes of 1e-280 or infinity after a few steps,
172for the first-order solver as well). This is a generic Finite Volume issue, independent of CCZ4, and it
173is why the FV runs of both formulations "worked" with an error of about 2e-2 against the analytical lapse (diffusion only) or
174broke down after a few steps. The fix is a rename in the kernel template (2d and 3d); it has not been applied, as it is outside
175of the files of this project. Once done, rerun `python3 fo_vs_so.py` and add the FV rows
196parser = argparse.ArgumentParser(description=
"First-order vs. second-order CCZ4")
199 choices=[
"compare-only",
"run-and-compare",
"run",
"build"],
200 default=
"run-and-compare",
201 help=
"build: generate and compile; run: build and run; "
202 "run-and-compare: build, run, print table; compare-only: print table from existing runs",
206 choices=[
"debug",
"release"],
208 help=
"Build mode of the generated code. Debug also enables the generator logging.",
212 type=
lambda text: [int(size)
for size
in text.split(
",")],
214 help=
"Comma-separated grid sizes (points per axis)",
218 type=
lambda text: text.split(
","),
219 default=[
"RK4FD4",
"RK1FD4",
"FV"],
220 help=
"Comma-separated numerical schemes to build, run and compare (RK4FD4, RK1FD4, FV)",
224 type=
lambda text: text.split(
","),
225 default=[
"FO",
"SO"],
226 help=
"Comma-separated formulations to build, run and compare (FO, SO)",
230 choices=[
"sequential",
"fusion"],
232 help=
"Task graph compiler: one mesh traversal per task (sequential) or fused traversals (fusion)",
234parser.add_argument(
"--end-time", type=float, default=0.1, help=
"Simulation end time")
236 "--cfl", type=float, default=0.9, help=
"CFL constant of the FV scheme"
238arguments = parser.parse_args()
239schemes = arguments.schemes
240formulations = arguments.formulations
241for formulation
in formulations:
242 if formulation
not in [
"FO",
"SO"]:
243 parser.error(f
"unknown formulation {formulation}, use FO and/or SO")
244for scheme
in schemes:
245 if scheme
not in [
"RK4FD4",
"RK1FD4",
"FV"]:
246 parser.error(f
"unknown scheme {scheme}, use RK4FD4, RK1FD4 and/or FV")
248if arguments.build_mode ==
"release":
249 build_mode = peano4.api.output.CompileMode.RELEASE
250 verbosity = peano4.api.LoggerVerbosity.OFF
252 build_mode = peano4.api.output.CompileMode.DEBUG
253 verbosity = peano4.api.LoggerVerbosity.VISUALISATION
254grid_sizes = arguments.sizes
255end_time = arguments.end_time
256time_in_between_plots = end_time / 2.0
261 return f
"run-{scheme}-{formulation}-{cells}"
264def build(scheme, formulation, cells):
267 Generate and build one solver on one grid in its own directory
270 RK4FD4, RK1FD4 or FV.
272 @param formulation: str
276 Grid points per axis. Has to be a multiple of the patch size.
280 assert cells
in [patch_size * 3**k
for k
in range(1, 6)], cells
281 name = f
"{scheme}{formulation}"
283 executable = f
"fo-vs-so-{scheme}-{formulation}-{cells}"
285 shutil.rmtree(directory, ignore_errors=
True)
287 namespace=[
"benchmarks",
"exagrype",
"fo_vs_so", name],
288 project_name=executable,
290 executable=executable,
293 if formulation ==
"FO":
295 solver.add_pde_term(initial_condition)
296 scheme_owner = solver
303 volume_size = 1.01 / cells
305 case
"RK4FD4" |
"RK1FD4":
307 exahype2.api.rkfd4.CentralDifferencesWithRungeKutta.RightHandSideKernel
309 scheme_owner.numerical_scheme = (
313 rk_order=4
if scheme ==
"RK4FD4" else 1,
314 right_hand_side_kernel=Kernel.CentralDifferencesWithLopsidedAdvection,
315 advection_velocity=exagrype.api.FOCCZ4Solver.ADVECTION_VELOCITY,
316 advected_quantities=solver.advected_quantities(),
320 solver, volume_size=volume_size
324 first_plot_time_stamp=0.0,
325 time_in_between_plots=time_in_between_plots,
330 solver, patch_size, cfl_constant=arguments.cfl
333 solver, volume_size=volume_size
337 first_plot_time_stamp=0.0,
338 time_in_between_plots=time_in_between_plots,
340 if formulation ==
"FO":
341 project.add_solver(solver)
343 project.add_solver(pair)
346 peano4.api.taskgraph.compiler.Sequential.translate
347 if arguments.compiler ==
"sequential"
348 else peano4.api.taskgraph.compiler.FuseSteps.translate
350 project.set_global_simulation_parameters(
352 offset=[0.0, 0.0, 0.0],
353 size=[1.0, 1.0, 1.0],
354 min_end_time=end_time,
355 max_end_time=end_time,
356 periodic_BC=[
True,
True,
True],
359 project.set_Peano4_installation(
360 os.path.abspath(
"../../../"),
363 peano4_project = project.generate_Peano4_project(verbosity=verbosity)
364 peano4_project.generate()
365 peano4_project.build(make_clean_first=
True)
368def run(scheme, formulation, cells):
371 Run the executable built by build() and store its wall time
374 RK4FD4, RK1FD4 or FV.
376 @param formulation: str
380 Grid points per axis.
384 executable = f
"fo-vs-so-{scheme}-{formulation}-{cells}"
386 if subprocess.call([f
"./{executable}"], cwd=directory) != 0:
387 sys.exit(f
"{scheme} {formulation} {cells} run failed")
388 wall_time = time.time() - start
389 with open(os.path.join(directory,
"wall-time.json"),
"w")
as file:
390 json.dump({
"wall_time": wall_time}, file)
393def snapshot(scheme, formulation, cells, unknowns, snapshot_index=-1):
396 Return the unknowns of one snapshot of one solver
399 RK4FD4, RK1FD4 or FV.
401 @param formulation: str
405 Grid points per axis.
408 Number of unknowns per grid point in the plot file
410 @param snapshot_index: int
411 Index of the snapshot, -1 is the last one.
413 @return time stamp, values, positions
414 The values and the x coordinates of the grid points, both sorted by the
415 offset of the patches. Values has one row per grid point.
421 name = f
"{scheme}{formulation}"
423 time_stamp, patch_files = read_snapshots(
424 f
"{directory}/solution-{name}.peano-patch-file"
427 for patch_file
in patch_files:
428 parser = PatchFileParser(patch_file,
"", 0)
430 for attributes
in parser.unknown_attributes.values():
431 for patch
in attributes.cell_data:
432 values = np.array(patch.values).reshape(-1, unknowns)
433 n = round(len(values) ** (1.0 / 3.0))
435 x = patch.offset[0] + (np.arange(len(values)) % n + 0.5) * patch.size[0] / n
436 result[tuple(patch.offset)] = (values, x)
437 keys = sorted(result)
440 np.concatenate([result[key][0]
for key
in keys])
if keys
else None,
441 np.concatenate([result[key][1]
for key
in keys])
if keys
else None,
447 """! Analytical lapse, see exagrype::initialvalues::gaugeWave() """
448 return np.sqrt(1.0 - 0.1 * np.sin(2.0 * np.pi * (x - t)))
454 Compare FO and SO on one grid
457 Summary numbers, or None if one of the runs is missing.
460 evolved = sum(exagrype.api.FOSOCCZ4Solver.Unknowns.values())
462 t, fo, x, keys_fo =
snapshot(scheme,
"FO", cells, 58)
463 _, so, _, keys_so =
snapshot(scheme,
"SO", cells, evolved)
464 _, initial, _, _ =
snapshot(scheme,
"FO", cells, 58, 0)
465 except (FileNotFoundError, IndexError):
467 if fo
is None or keys_fo != keys_so:
468 sys.exit(
"FAILED: the plots of FO and SO hold different or no patches")
470 initial = initial[:, :evolved]
474 print(f
"\n{scheme}, {cells}^3 grid points, t={t}")
476 f
"{'unknown':>10} {'max |SO-FO|':>13} {'rel. L2 |SO-FO|':>16} {'max |FO(t)-FO(0)|':>18}"
478 for k, name
in enumerate(names):
479 norm = np.linalg.norm(fo[:, k])
480 relative = np.linalg.norm(difference[:, k]) / norm
if norm > 0
else 0.0
481 movement = np.max(np.abs(fo[:, k] - initial[:, k]))
483 f
"{name:>10} {np.max(np.abs(difference[:, k])):13.3e} {relative:16.3e} {movement:18.3e}"
489 "max_difference":
float(np.max(np.abs(difference))),
490 "lapse_difference":
float(np.max(np.abs(difference[:, lapse]))),
491 "lapse_error_FO":
float(np.linalg.norm(fo[:, lapse] - exact) / np.linalg.norm(exact)),
492 "lapse_error_SO":
float(np.linalg.norm(so[:, lapse] - exact) / np.linalg.norm(exact)),
494 for formulation
in formulations:
495 with open(os.path.join(
directory_of(scheme, formulation, cells),
"wall-time.json"))
as file:
496 summary[
"wall_time_" + formulation] = json.load(file)[
"wall_time"]
503 Summarise one formulation on one grid against the analytical lapse. Used
504 if only one of FO and SO is built, i.e. there is nothing to compare it to.
507 Summary numbers, or None if the run is missing.
510 evolved = sum(exagrype.api.FOSOCCZ4Solver.Unknowns.values())
513 scheme, formulation, cells, 58
if formulation ==
"FO" else evolved
515 with open(os.path.join(
directory_of(scheme, formulation, cells),
"wall-time.json"))
as file:
516 wall_time = json.load(file)[
"wall_time"]
517 except (FileNotFoundError, IndexError):
524 "lapse_error":
float(np.linalg.norm(values[:, 16] - exact) / np.linalg.norm(exact)),
525 "wall_time": wall_time,
530 if len(formulations) == 1:
531 formulation = formulations[0]
532 print(f
"\n{'scheme':>7} {'cells':>6} {'form.':>6} {'t':>7} {'lapse err':>10} {'wall [s]':>9}")
533 for scheme
in schemes:
534 for cells
in grid_sizes:
538 f
"{scheme:>7} {cells:>6} {formulation:>6} {s['time']:7.3f} "
539 f
"{s['lapse_error']:10.2e} {s['wall_time']:9.2f}"
543 for scheme
in schemes:
544 for cells
in grid_sizes:
545 summary =
compare_one(scheme, cells, verbose=len(grid_sizes) == 1)
546 if summary
is not None:
547 rows.append((scheme, cells, summary))
549 f
"\n{'scheme':>7} {'cells':>6} {'t':>7} {'max|SO-FO|':>11} {'max|SO-FO| lapse':>17} "
550 f
"{'lapse err FO':>13} {'lapse err SO':>13} {'wall FO [s]':>12} {'wall SO [s]':>12}"
552 for scheme, cells, s
in rows:
554 f
"{scheme:>7} {cells:>6} {s['time']:7.3f} {s['max_difference']:11.2e} {s['lapse_difference']:17.2e} "
555 f
"{s['lapse_error_FO']:13.2e} {s['lapse_error_SO']:13.2e} "
556 f
"{s['wall_time_FO']:12.2f} {s['wall_time_SO']:12.2f}"
560if arguments.mode !=
"compare-only":
561 for scheme
in schemes:
562 for cells
in grid_sizes:
563 for formulation
in formulations:
564 build(scheme, formulation, cells)
565 if arguments.mode !=
"build":
566 run(scheme, formulation, cells)
567if arguments.mode
in [
"compare-only",
"run-and-compare"]:
Solver for the Einstein equations in the first-order CCZ4 formulation.
Solver for the Einstein equations in the first-/second-order reconstructed CCZ4 formulation.
CCZ4 in the first-/second-order reconstructed formulation as a coupled pair.
Plotting counterpart to RusanovWithExplicitEuler: maps the patch data of a Finite Volume scheme with ...
Finite Volumes with a Rusanov Riemann solver and explicit Euler time stepping, realised over a block-...
Setup phase counterpart to RusanovWithExplicitEuler: sets the initial condition for a Finite Volume s...
Fourth-order central Finite Differences with explicit Runge-Kutta time stepping, realised over a bloc...
Plotting counterpart of the fourth-order Finite Differences with Runge-Kutta time stepping (exahype2....
Setup phase of the fourth-order Finite Differences with Runge-Kutta time stepping (exahype2....
exahype2.api.InitPointWisely gauge_wave()
Gauge wave along the x-axis,.
This file is part of the ExaGRyPE project.
snapshot(scheme, formulation, cells, unknowns, snapshot_index=-1)
Return the unknowns of one snapshot of one solver.
build(scheme, formulation, cells)
Generate and build one solver on one grid in its own directory.
compare_one(scheme, cells, verbose)
Compare FO and SO on one grid.
directory_of(scheme, formulation, cells)
gauge_wave_lapse(x, t)
Analytical lapse, see exagrype.initialvalues.gaugeWave().
compare_single(scheme, formulation, cells)
Summarise one formulation on one grid against the analytical lapse.
run(scheme, formulation, cells)
Run the executable built by build() and store its wall time.
Interactive visualisation of Peano patch files within Jupyter notebooks.