5Create the PNG illustrations of the tutorial 523_higher-order-fd.ipynb
7The script builds the single black hole setup of the tutorial with several
8numerical schemes, runs them one after the other, extracts the lapse and
9the conformal factor along the x-axis with Peano's PointProbe, and writes
10all pictures into the directory of this script. All runs use Sommerfeld
11boundary conditions, a domain decomposition and four OpenMP threads, i.e.
12the final setup of 522_single-black-hole.ipynb, over 9x9x9 mesh cells with
1310x10x10 volumes or grid cells each:
15- fv: exahype2.api.fv.RusanovWithExplicitEuler;
16- fd4: exahype2.api.rkfd4.CentralDifferencesWithRungeKutta with the classic
17 fourth-order Runge-Kutta scheme and without dissipation;
18- fd4-ko-{sigma}: exagrype.api.FD4WithKODissipation with the Kreiss-Oliger
19 dissipation scaled by sigma, for sigma 0.3, 1 and 8;
20- fd4-lop: the fourth-order Finite Differences with the kernel
21 CentralDifferencesWithLopsidedAdvection, i.e. with the advection terms
22 which exagrype::ccz4::ncp() omits;
23- fd4-lop-ko-8.0: the same with the Kreiss-Oliger dissipation (sigma=8) on
25- fd4-lop-ko-8.0-subset: the same with the dissipation on Q0-Q24 only (DissipationSubset).
27The dictionary Runs holds the configurations.
31 python3 tutorials/exahype2/exagrype/illustrations/523_higher-order-fd.py
33Peano has to be configured with --with-gsl, as the initial data stems from
34TwoPunctures. All builds and outputs go into a temporary directory (or
35--work-directory). If you pass a work directory, a run which has completed
36before is reused, i.e. you can rerun the script to redraw the pictures
37without recomputing. A run which crashes or produces NaNs is reported, and
38its output up to that point is used.
51Here = os.path.dirname(os.path.abspath(__file__))
52PeanoRoot = os.path.abspath(os.path.join(Here,
"..",
"..",
"..",
".."))
53sys.path.insert(0, os.path.join(PeanoRoot,
"src"))
58import matplotlib.pyplot
as plt
67PatchFile =
"solution-CCZ4.peano-patch-file"
73VolumesPerAxis = CellsPerAxis * PatchSize
74H = DomainSize / VolumesPerAxis
76TimeInBetweenPlots = 0.5
80DissipationSubset = list(range(0, 25))
85 "fv": (
None,
False,
None),
86 "fd4": (
None,
False,
None),
87 "fd4-ko-0.3": (0.3,
False,
None),
88 "fd4-ko-1.0": (1.0,
False,
None),
89 "fd4-ko-8.0": (8.0,
False,
None),
90 "fd4-lop": (
None,
True,
None),
91 "fd4-lop-ko-8.0": (8.0,
True,
None),
92 "fd4-lop-ko-8.0-subset": (8.0,
True, DissipationSubset),
97 "fv": (
"tab:blue",
"o",
"Finite Volumes"),
98 "fd4": (
"tab:red",
"s",
"FD4, no dissipation"),
99 "fd4-ko-0.3": (
"tab:green",
"^",
r"FD4, KO $\sigma=0.3$"),
100 "fd4-ko-1.0": (
"tab:purple",
"v",
r"FD4, KO $\sigma=1$"),
101 "fd4-ko-8.0": (
"tab:orange",
"D",
r"FD4, KO $\sigma=8$"),
102 "fd4-lop": (
"tab:brown",
"P",
"FD4, lopsided, no dissipation"),
103 "fd4-lop-ko-8.0": (
"tab:pink",
"X",
r"FD4, lopsided, KO $\sigma=8$ (all)"),
104 "fd4-lop-ko-8.0-subset": (
107 r"FD4, lopsided, KO $\sigma=8$ (Q0-Q24)",
113 """! The numerical scheme, grid construction and plotter of one run"""
121 sigma, lopsided, dissipative_quantities = Runs[name]
122 Kernel = exahype2.api.rkfd4.CentralDifferencesWithRungeKutta.RightHandSideKernel
126 right_hand_side_kernel=Kernel.CentralDifferencesWithLopsidedAdvection,
127 advection_velocity=exagrype.api.FOCCZ4Solver.ADVECTION_VELOCITY,
128 advected_quantities=solver.advected_quantities(),
131 solver.numerical_scheme = (
133 solver, PatchSize, rk_order=4, **arguments
141 kreiss_oliger_sigma=sigma,
142 quantities=dissipative_quantities,
145 solver.grid_construction = package.SetupSimulationOverRegularGrid(
146 solver, volume_size=1.01 * H
148 solver.plotter = package.PlotAsVTKFile(
150 first_plot_time_stamp=0.0,
151 time_in_between_plots=TimeInBetweenPlots,
152 plotter_precision=10,
154 solver.plotter.add_plot_filter(
155 offset=[DomainOffset, 0.1, 0.1], size=[DomainSize, 0.1, 0.1]
162 Generate, compile and run one setup within directory
164 Returns the runtime of the executable in seconds and whether it
165 terminated successfully. If the directory holds the result of a
166 previous run, we do not rerun but return the stored values.
169 runtime_file = os.path.join(directory,
"runtime.txt")
170 if os.path.exists(runtime_file):
171 with open(runtime_file)
as f:
172 runtime, success = f.read().split()
173 return float(runtime), success ==
"True"
175 os.makedirs(directory, exist_ok=
True)
176 print(
"build and run {} until t={} in {}".format(name, end_time, directory))
178 namespace=[
"tutorials",
"exagrype",
"higherorderfd"],
179 project_name=
"HigherOrderFD",
181 executable=
"single-black-hole",
185 parameters={
"CCZ4b": 1,
"CCZ4s": 1},
189 exahype2.api.SommerfeldBoundaryConditions(
190 implementation=
"::exagrype::initialvalues::flat(Q, x, 0.0);"
194 project.add_solver(solver)
195 project.set_global_simulation_parameters(
197 offset=[DomainOffset] * 3,
198 size=[DomainSize] * 3,
199 min_end_time=end_time,
200 max_end_time=end_time,
201 periodic_BC=[
False,
False,
False],
203 project.set_load_balancing(
204 "toolbox::loadbalancing::strategies::SpreadOutOnceGridStagnates",
205 "new ::exahype2::LoadBalancingConfiguration()",
207 project.set_Peano4_installation(
208 peano_installation, peano4.api.output.CompileMode.RELEASE
210 with contextlib.redirect_stdout(io.StringIO()):
211 peano4_project = project.generate_Peano4_project(
212 verbosity=peano4.api.LoggerVerbosity.TEXT
214 peano4_project.generate()
217 [
"make",
"-j{}".format(Threads)],
220 stdout=subprocess.DEVNULL,
221 stderr=subprocess.DEVNULL,
224 with open(os.path.join(directory,
"run.log"),
"w")
as log:
225 environment = dict(os.environ)
226 environment[
"OMP_NUM_THREADS"] = str(Threads)
227 result = subprocess.run(
228 [
"./single-black-hole"],
231 stderr=subprocess.STDOUT,
234 runtime = time.time() - start
235 success = result.returncode == 0
236 with open(runtime_file,
"w")
as f:
237 f.write(
"{} {}".format(runtime, success))
238 return runtime, success
241def probe(directory, point, output_file):
244 Probe all snapshots at one point
246 Returns the time stamps, the lapse and the conformal factor phi.
250 file_name=os.path.join(directory, PatchFile),
252 output_file=os.path.join(directory, output_file),
256 with contextlib.redirect_stdout(io.StringIO()):
257 point_probe.display()
258 with open(os.path.join(directory, output_file))
as csv_file:
259 rows = list(csv.DictReader(csv_file))
261 np.array([
float(row[
"time"])
for row
in rows]),
262 np.array([
float(row[
"lapse"])
for row
in rows]),
263 np.array([
float(row[
"phi"])
for row
in rows]),
270 Probe lapse and phi in the centre of each volume or grid cell along the
271 line y=z=h/2, i.e. through the centres next to the puncture
273 Returns the x coordinates, the time stamps and two 2d arrays
274 lapse[snapshot,x] and phi[snapshot,x].
277 x = DomainOffset + (np.arange(VolumesPerAxis) + 0.5) * H
279 for i, x_i
in enumerate(x):
280 t, lapse_over_time, phi_over_time =
probe(
281 directory, [x_i, H / 2.0, H / 2.0],
"profile-{}.csv".format(i)
283 lapse.append(lapse_over_time)
284 phi.append(phi_over_time)
285 snapshots = min(len(entry)
for entry
in lapse)
289 np.array([entry[:snapshots]
for entry
in lapse]).T,
290 np.array([entry[:snapshots]
for entry
in phi]).T,
295 return np.sqrt(np.asarray(x) ** 2 + 2.0 * (H / 2.0) ** 2)
301 Number of time steps and average wall clock time per time step
303 Both stem from the final report of peano4::DefaultStepReport in run.log,
304 i.e. from the line "TimeStep: ...s (avg=...,#measurements=...". Returns
305 None if the run did not terminate regularly.
308 with open(os.path.join(directory,
"run.log"))
as log:
310 if "reportFinalResults" in line
and "TimeStep:" in line:
311 statistics = line.split(
"(avg=")[1]
312 average =
float(statistics.split(
",")[0])
313 count = int(statistics.split(
"#measurements=")[1].split(
",")[0])
314 return count, average
321 Lapse next to the puncture over time (left) and along the x-axis at the
322 last snapshot all runs share (right)
325 fig, axes = plt.subplots(1, 2, figsize=(11, 4))
326 centre = VolumesPerAxis // 2
327 last = min(len(runs[name][
"t"])
for name
in names) - 1
329 colour, marker, label = Style[name]
333 run[
"lapse"][:, centre],
349 axes[0].set_xlabel(
"t")
350 axes[0].set_ylabel(
"lapse")
352 "Lapse next to the puncture (r={:.2f})".format(
353 radius(runs[names[0]][
"x"][centre])
356 axes[1].set_xlabel(
"x (along y=z={:.2f})".format(H / 2.0))
357 axes[1].set_ylabel(
"lapse")
359 "Lapse along the x-axis at t={:.1f}".format(runs[names[0]][
"t"][last])
363 ax.set_ylim(0.0, 1.0)
364 axes[0].set_xlim(0.0, max(runs[name][
"t"][-1]
for name
in names))
365 axes[1].legend(loc=
"lower right")
366 fig.savefig(os.path.join(Here, file_name), dpi=100, bbox_inches=
"tight")
373 Fourier analysis of the fourth-order central differences and of the
374 Kreiss-Oliger dissipation
376 A Fourier mode exp(i k x) on a grid with spacing h is characterised by
377 theta = k h between 0 (smooth) and pi (changes sign from grid cell to
378 grid cell). The left picture shows the wave number which the
379 fourth-order central difference "sees", i.e. theta_eff = (8 sin theta -
380 sin 2 theta) / 6, against the exact one. The right picture shows the
381 rate h/sigma * lambda with which the Kreiss-Oliger term
382 sigma/(64 h) * (Q_{i-3} - 6 Q_{i-2} + ... + Q_{i+3}) damps the mode
383 along one axis, i.e. (4 sin^2(theta/2))^3 / 64.
386 theta = np.linspace(0.0, np.pi, 400)
387 fig, axes = plt.subplots(1, 2, figsize=(11, 4))
388 axes[0].
plot(theta, theta,
"--", color=
"black", linewidth=1, label=
"exact")
391 (8.0 * np.sin(theta) - np.sin(2.0 * theta)) / 6.0,
395 label=
"fourth-order central difference",
397 axes[0].set_xlabel(
r"$\theta = k h$")
398 axes[0].set_ylabel(
"effective wave number times h")
399 axes[0].set_title(
"How the derivative sees a Fourier mode")
400 axes[0].legend(loc=
"upper left")
403 (4.0 * np.sin(theta[1:] / 2.0) ** 2) ** 3 / 64.0,
408 axes[1].set_xlabel(
r"$\theta = k h$")
409 axes[1].set_ylabel(
r"damping rate $\times\, h / \sigma$")
410 axes[1].set_title(
"Kreiss-Oliger damping per axis")
411 axes[1].set_ylim(1e-6, 2.0)
413 ax.set_xticks([0.0, np.pi / 4, np.pi / 2, 3 * np.pi / 4, np.pi])
414 ax.set_xticklabels([
"0",
r"$\pi/4$",
r"$\pi/2$",
r"$3\pi/4$",
r"$\pi$"])
416 os.path.join(Here,
"523_higher-order-fd-fourier.png"),
423if __name__ ==
"__main__":
424 parser = argparse.ArgumentParser(
425 description=
"Create the PNGs of the tutorial 523_higher-order-fd.ipynb"
430 help=
"Directory for builds and outputs (default: temporary directory)",
435 help=
"Configured (--with-gsl) and built Peano installation to link against (default: the repository holding this script)",
438 "--end-time", type=float, default=10.0, help=
"Simulated time span (default: 10)"
444 help=
"Runs to perform (default: all, i.e. {})".format(
" ".join(Runs)),
446 args = parser.parse_args()
450 with contextlib.ExitStack()
as stack:
451 work_directory = args.work_directory
or stack.enter_context(
452 tempfile.TemporaryDirectory()
455 for name
in args.runs:
456 directory = os.path.join(os.path.abspath(work_directory), name)
458 name, directory, os.path.abspath(args.peano_root), args.end_time
461 runs[name] = dict(x=x, t=t, lapse=lapse, phi=phi)
462 centre = VolumesPerAxis // 2
465 "{}: {}, runtime {:.1f}s, {}".format(
467 "terminated" if success
else "FAILED",
470 "{} time steps of {:.3f}s".format(*statistics)
472 else "no time step statistics"
477 "{}: snapshots until t={:.2f}, next to the puncture (r={:.3f}) lapse {:.4f} -> {:.4f}, phi {:.4f} -> {:.4f}, min lapse at t_end {:.4f}, NaN: {}".format(
485 np.nanmin(lapse[-1]),
486 np.isnan(lapse).any(),
489 for i
in [centre, centre + 5, centre + 15, VolumesPerAxis - 1]:
491 "{}: r={:.2f}: lapse {}".format(
494 " ".join(
"{:.3f}".format(value)
for value
in lapse[::4, i]),
498 if "fv" in runs
and "fd4" in runs:
500 runs, [
"fv",
"fd4"],
"523_higher-order-fd-fv-vs-fd4.png"
502 ko_runs = [name
for name
in Style
if name.startswith(
"fd4-ko")
and name
in runs]
503 if "fv" in runs
and "fd4" in runs
and ko_runs:
506 [
"fv",
"fd4"] + ko_runs,
507 "523_higher-order-fd-kreiss-oliger.png",
510 name
for name
in Style
if name.startswith(
"fd4-lop")
and name
in runs
512 if "fv" in runs
and "fd4" in runs
and lopsided_runs:
515 [
"fv",
"fd4"] + lopsided_runs,
516 "523_higher-order-fd-lopsided.png",
Fourth-order Finite Differences with Kreiss-Oliger dissipation.
Solver for the Einstein equations in the first-order CCZ4 formulation.
Finite Volumes with a Rusanov Riemann solver and explicit Euler time stepping, realised over a block-...
Fourth-order central Finite Differences with explicit Runge-Kutta time stepping, realised over a bloc...
Probe the data within a Peano patch file at one point over time.
plot_over_time_and_profile(runs, names, file_name)
Lapse next to the puncture over time (left) and along the x-axis at the last snapshot all runs share ...
time_steps(directory)
Number of time steps and average wall clock time per time step.
plot_fourier_analysis()
Fourier analysis of the fourth-order central differences and of the Kreiss-Oliger dissipation.
build_and_run(name, directory, peano_installation, end_time)
Generate, compile and run one setup within directory.
profile(directory)
Probe lapse and phi in the centre of each volume or grid cell along the line y=z=h/2,...
create_scheme(name, solver)
The numerical scheme, grid construction and plotter of one run.
exahype2.api.InitPointWisely single_black_hole(float mass=1.0)
Single Schwarzschild black hole at the origin.
This file is part of the ExaGRyPE project.
Fourth-order Finite Differences with explicit Runge-Kutta time stepping over block-structured meshes.