Peano
Loading...
Searching...
No Matches
523_higher-order-fd.py
Go to the documentation of this file.
1# This file is part of the Peano project. For conditions of distribution and
2# use, please see the copyright notice at www.peano-framework.org
3"""!
4
5Create the PNG illustrations of the tutorial 523_higher-order-fd.ipynb
6
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:
14
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
24 all unknowns;
25- fd4-lop-ko-8.0-subset: the same with the dissipation on Q0-Q24 only (DissipationSubset).
26
27The dictionary Runs holds the configurations.
28
29Call it from anywhere:
30
31 python3 tutorials/exahype2/exagrype/illustrations/523_higher-order-fd.py
32
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.
39
40"""
41import argparse
42import contextlib
43import csv
44import io
45import os
46import subprocess
47import sys
48import tempfile
49import time
50
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"))
54
55import matplotlib
56
57matplotlib.use("Agg")
58import matplotlib.pyplot as plt
59import numpy as np
60
61import peano4.api
62import exahype2.api
63import exagrype.api
65
66
67PatchFile = "solution-CCZ4.peano-patch-file"
68Mass = 1.0
69DomainOffset = -9.0
70DomainSize = 18.0
71CellsPerAxis = 9
72PatchSize = 10
73VolumesPerAxis = CellsPerAxis * PatchSize
74H = DomainSize / VolumesPerAxis
75Threads = 4
76TimeInBetweenPlots = 0.5
77
78
80DissipationSubset = list(range(0, 25))
81
82
84Runs = {
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),
93}
94
95
96Style = {
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": (
105 "tab:olive",
106 "*",
107 r"FD4, lopsided, KO $\sigma=8$ (Q0-Q24)",
108 ),
109}
110
111
112def create_scheme(name, solver):
113 """! The numerical scheme, grid construction and plotter of one run"""
114 if name == "fv":
115 package = exahype2.api.fv
116 solver.numerical_scheme = exahype2.api.fv.RusanovWithExplicitEuler(
117 solver, PatchSize
118 )
119 else:
120 package = exahype2.api.rkfd4
121 sigma, lopsided, dissipative_quantities = Runs[name]
122 Kernel = exahype2.api.rkfd4.CentralDifferencesWithRungeKutta.RightHandSideKernel
123 arguments = {}
124 if lopsided:
125 arguments = dict(
126 right_hand_side_kernel=Kernel.CentralDifferencesWithLopsidedAdvection,
127 advection_velocity=exagrype.api.FOCCZ4Solver.ADVECTION_VELOCITY,
128 advected_quantities=solver.advected_quantities(),
129 )
130 if sigma is None:
131 solver.numerical_scheme = (
133 solver, PatchSize, rk_order=4, **arguments
134 )
135 )
136 else:
137 solver.numerical_scheme = exagrype.api.FD4WithKODissipation(
138 solver,
139 PatchSize,
140 rk_order=4,
141 kreiss_oliger_sigma=sigma,
142 quantities=dissipative_quantities,
143 **arguments,
144 )
145 solver.grid_construction = package.SetupSimulationOverRegularGrid(
146 solver, volume_size=1.01 * H
147 )
148 solver.plotter = package.PlotAsVTKFile(
149 solver,
150 first_plot_time_stamp=0.0,
151 time_in_between_plots=TimeInBetweenPlots,
152 plotter_precision=10,
153 )
154 solver.plotter.add_plot_filter(
155 offset=[DomainOffset, 0.1, 0.1], size=[DomainSize, 0.1, 0.1]
156 )
157
158
159def build_and_run(name, directory, peano_installation, end_time):
160 """!
161
162 Generate, compile and run one setup within directory
163
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.
167
168 """
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"
174
175 os.makedirs(directory, exist_ok=True)
176 print("build and run {} until t={} in {}".format(name, end_time, directory))
177 project = exahype2.api.Project(
178 namespace=["tutorials", "exagrype", "higherorderfd"],
179 project_name="HigherOrderFD",
180 directory=directory,
181 executable="single-black-hole",
182 )
184 "CCZ4",
185 parameters={"CCZ4b": 1, "CCZ4s": 1},
186 initial_condition=exagrype.api.initialvalues.single_black_hole(mass=Mass),
187 )
188 solver.add_pde_term(
189 exahype2.api.SommerfeldBoundaryConditions(
190 implementation="::exagrype::initialvalues::flat(Q, x, 0.0);"
191 )
192 )
193 create_scheme(name, solver)
194 project.add_solver(solver)
195 project.set_global_simulation_parameters(
196 dimensions=3,
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],
202 )
203 project.set_load_balancing(
204 "toolbox::loadbalancing::strategies::SpreadOutOnceGridStagnates",
205 "new ::exahype2::LoadBalancingConfiguration()",
206 )
207 project.set_Peano4_installation(
208 peano_installation, peano4.api.output.CompileMode.RELEASE
209 )
210 with contextlib.redirect_stdout(io.StringIO()):
211 peano4_project = project.generate_Peano4_project(
212 verbosity=peano4.api.LoggerVerbosity.TEXT
213 )
214 peano4_project.generate()
215
216 subprocess.run(
217 ["make", "-j{}".format(Threads)],
218 cwd=directory,
219 check=True,
220 stdout=subprocess.DEVNULL,
221 stderr=subprocess.DEVNULL,
222 )
223 start = time.time()
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"],
229 cwd=directory,
230 stdout=log,
231 stderr=subprocess.STDOUT,
232 env=environment,
233 )
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
239
240
241def probe(directory, point, output_file):
242 """!
243
244 Probe all snapshots at one point
245
246 Returns the time stamps, the lapse and the conformal factor phi.
247
248 """
250 file_name=os.path.join(directory, PatchFile),
251 point=point,
252 output_file=os.path.join(directory, output_file),
253 start=0,
254 end=sys.maxsize,
255 )
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))
260 return (
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]),
264 )
265
266
267def profile(directory):
268 """!
269
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
272
273 Returns the x coordinates, the time stamps and two 2d arrays
274 lapse[snapshot,x] and phi[snapshot,x].
275
276 """
277 x = DomainOffset + (np.arange(VolumesPerAxis) + 0.5) * H
278 lapse, phi = [], []
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)
282 )
283 lapse.append(lapse_over_time)
284 phi.append(phi_over_time)
285 snapshots = min(len(entry) for entry in lapse)
286 return (
287 x,
288 t[:snapshots],
289 np.array([entry[:snapshots] for entry in lapse]).T,
290 np.array([entry[:snapshots] for entry in phi]).T,
291 )
292
293
294def radius(x):
295 return np.sqrt(np.asarray(x) ** 2 + 2.0 * (H / 2.0) ** 2)
296
297
298def time_steps(directory):
299 """!
300
301 Number of time steps and average wall clock time per time step
302
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.
306
307 """
308 with open(os.path.join(directory, "run.log")) as log:
309 for line in 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
315 return None
316
317
318def plot_over_time_and_profile(runs, names, file_name):
319 """!
320
321 Lapse next to the puncture over time (left) and along the x-axis at the
322 last snapshot all runs share (right)
323
324 """
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
328 for name in names:
329 colour, marker, label = Style[name]
330 run = runs[name]
331 axes[0].plot(
332 run["t"],
333 run["lapse"][:, centre],
334 marker + "-",
335 color=colour,
336 markersize=3,
337 linewidth=1,
338 label=label,
339 )
340 axes[1].plot(
341 run["x"],
342 run["lapse"][last],
343 marker + "-",
344 color=colour,
345 markersize=2,
346 linewidth=1,
347 label=label,
348 )
349 axes[0].set_xlabel("t")
350 axes[0].set_ylabel("lapse")
351 axes[0].set_title(
352 "Lapse next to the puncture (r={:.2f})".format(
353 radius(runs[names[0]]["x"][centre])
354 )
355 )
356 axes[1].set_xlabel("x (along y=z={:.2f})".format(H / 2.0))
357 axes[1].set_ylabel("lapse")
358 axes[1].set_title(
359 "Lapse along the x-axis at t={:.1f}".format(runs[names[0]]["t"][last])
360 )
361 # Runs which collapse write nonsensical values into their last snapshot
362 for ax in axes:
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")
367 plt.close(fig)
368
369
371 """!
372
373 Fourier analysis of the fourth-order central differences and of the
374 Kreiss-Oliger dissipation
375
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.
384
385 """
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")
389 axes[0].plot(
390 theta,
391 (8.0 * np.sin(theta) - np.sin(2.0 * theta)) / 6.0,
392 "-",
393 color="tab:red",
394 linewidth=2,
395 label="fourth-order central difference",
396 )
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")
401 axes[1].semilogy(
402 theta[1:],
403 (4.0 * np.sin(theta[1:] / 2.0) ** 2) ** 3 / 64.0,
404 "-",
405 color="tab:green",
406 linewidth=2,
407 )
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)
412 for ax in axes:
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$"])
415 fig.savefig(
416 os.path.join(Here, "523_higher-order-fd-fourier.png"),
417 dpi=100,
418 bbox_inches="tight",
419 )
420 plt.close(fig)
421
422
423if __name__ == "__main__":
424 parser = argparse.ArgumentParser(
425 description="Create the PNGs of the tutorial 523_higher-order-fd.ipynb"
426 )
427 parser.add_argument(
428 "--work-directory",
429 default=None,
430 help="Directory for builds and outputs (default: temporary directory)",
431 )
432 parser.add_argument(
433 "--peano-root",
434 default=PeanoRoot,
435 help="Configured (--with-gsl) and built Peano installation to link against (default: the repository holding this script)",
436 )
437 parser.add_argument(
438 "--end-time", type=float, default=10.0, help="Simulated time span (default: 10)"
439 )
440 parser.add_argument(
441 "--runs",
442 nargs="+",
443 default=list(Runs),
444 help="Runs to perform (default: all, i.e. {})".format(" ".join(Runs)),
445 )
446 args = parser.parse_args()
447
449
450 with contextlib.ExitStack() as stack:
451 work_directory = args.work_directory or stack.enter_context(
452 tempfile.TemporaryDirectory()
453 )
454 runs = {}
455 for name in args.runs:
456 directory = os.path.join(os.path.abspath(work_directory), name)
457 runtime, success = build_and_run(
458 name, directory, os.path.abspath(args.peano_root), args.end_time
459 )
460 x, t, lapse, phi = profile(directory)
461 runs[name] = dict(x=x, t=t, lapse=lapse, phi=phi)
462 centre = VolumesPerAxis // 2
463 statistics = time_steps(directory)
464 print(
465 "{}: {}, runtime {:.1f}s, {}".format(
466 name,
467 "terminated" if success else "FAILED",
468 runtime,
469 (
470 "{} time steps of {:.3f}s".format(*statistics)
471 if statistics
472 else "no time step statistics"
473 ),
474 )
475 )
476 print(
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(
478 name,
479 t[-1],
480 radius(x[centre]),
481 lapse[0, centre],
482 lapse[-1, centre],
483 phi[0, centre],
484 phi[-1, centre],
485 np.nanmin(lapse[-1]),
486 np.isnan(lapse).any(),
487 )
488 )
489 for i in [centre, centre + 5, centre + 15, VolumesPerAxis - 1]:
490 print(
491 "{}: r={:.2f}: lapse {}".format(
492 name,
493 radius(x[i]),
494 " ".join("{:.3f}".format(value) for value in lapse[::4, i]),
495 )
496 )
497
498 if "fv" in runs and "fd4" in runs:
500 runs, ["fv", "fd4"], "523_higher-order-fd-fv-vs-fd4.png"
501 )
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:
505 runs,
506 ["fv", "fd4"] + ko_runs,
507 "523_higher-order-fd-kreiss-oliger.png",
508 )
509 lopsided_runs = [
510 name for name in Style if name.startswith("fd4-lop") and name in runs
511 ]
512 if "fv" in runs and "fd4" in runs and lopsided_runs:
514 runs,
515 ["fv", "fd4"] + lopsided_runs,
516 "523_higher-order-fd-lopsided.png",
517 )
Fourth-order Finite Differences with Kreiss-Oliger dissipation.
Solver for the Einstein equations in the first-order CCZ4 formulation.
ExaHyPE 2 project.
Definition Project.py:15
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.
Definition PointProbe.py:37
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.
Definition __init__.py:1
Fourth-order Finite Differences with explicit Runge-Kutta time stepping over block-structured meshes.
Definition __init__.py:1
-lift-drop-statistics
-single-black-hole