5Convergence study of the gauge wave benchmark
7The script builds and runs gauge-wave.py for several numerical schemes and
8mesh sizes, measures the maximum error of the lapse along the line y=z=0.5
9at the end of the simulation against the exact solution, estimates the
10convergence orders, and writes
12- convergence.png (error over mesh size),
13- convergence.md (table with errors, orders, runtimes and memory footprint),
14- results.json (everything in machine-readable form, in the work directory)
16into the output directory. The study is the integration test for the
17correctness of the numerical schemes behind the benchmark: The script exits
18with a non-zero status if the estimated convergence order of a scheme falls
19below the one in ExpectedOrders. Runtimes and memory footprints are recorded,
20but are not an acceptance criterion.
22 python3 convergence-study.py --work-directory /scratch/gauge-wave
24Runs which have completed before in the work directory are reused. Remove
25the run's directory (or results.json) to rerun it.
30Every scheme is studied by a worker of its own, and all workers run at the same
31time. A worker walks through the meshes from coarse to fine. Runs on coarse meshes
32cannot exploit many cores: With 27 mesh cells (the minimum, as Peano refines the
33root cell at least once) the scaling stagnates, and these runs use one thread.
34They are done long before the runs on the fine meshes get going, i.e. the biggest
35setups do not start at the same time. A run on a fine mesh gets its share of the
36cores, which grows as workers finish. At most two of them (--concurrent-large-runs)
37run at the same time, as they are memory hungry.
42The memory footprint grows with the number of volumes. A watchdog
43observes the footprint of each run. If less than 1.5 GB remain available on the machine,
44the run with the biggest footprint is killed (typically right after its start, as the
45meshes allocate their memory early) and the study continues without that data point.
49import concurrent.futures
62Here = os.path.dirname(os.path.abspath(__file__))
63PeanoRoot = os.path.abspath(os.path.join(Here,
"..",
"..",
"..",
".."))
64sys.path.insert(0, os.path.join(PeanoRoot,
"src"))
69import matplotlib.pyplot
as plt
76PatchFile =
"solution-CCZ4.peano-patch-file"
82def patch_size_of(volumes_per_axis):
83 return 3
if volumes_per_axis == 9
else 9
86Schemes = [
"fv",
"rk1fd4",
"rk2fd4",
"rk3fd4",
"rk4fd4"]
111LargeRunSlots = threading.Semaphore(2)
114BuildSlots = threading.Semaphore(3)
118 """! Number of scheme workers that are still running, and the lock to protect it"""
121 lock = threading.Lock()
125 """! Lapse of the gauge wave, i.e. sqrt(H) with H = 1 - A sin(2 pi (x-t))"""
126 return np.sqrt(1.0 - Amplitude * np.sin(2.0 * np.pi * (np.asarray(x) - t)))
130 """! Number of mesh cells (patches) of a run"""
131 return (volumes_per_axis //
patch_size_of(volumes_per_axis)) ** 3
134def name_of(scheme, volumes_per_axis):
135 return f
"{scheme}-{volumes_per_axis}"
139 with open(
"/proc/meminfo")
as f:
141 if line.startswith(
"MemAvailable"):
142 return int(line.split()[1])
146def build_and_run(scheme, volumes_per_axis, threads, work_directory):
149 Generate, compile and run gauge-wave.py
152 Runtime, memory footprint, threads and the error against the exact
153 solution at the last snapshot.
156 directory = os.path.join(work_directory,
name_of(scheme, volumes_per_axis))
159 shutil.rmtree(directory, ignore_errors=
True)
160 os.makedirs(directory)
161 print(f
"build {name_of(scheme, volumes_per_axis)} ({threads} threads)", flush=
True)
162 environment = dict(os.environ)
163 environment[
"PYTHONPATH"] = (
164 os.path.join(PeanoRoot,
"src") + os.pathsep + environment.get(
"PYTHONPATH",
"")
170 os.path.join(Here,
"gauge-wave.py"),
178 repr(1.0 / volumes_per_axis),
185 "--plot-along-x-axis",
190 stdout=open(os.path.join(directory,
"generate.log"),
"w"),
191 stderr=subprocess.STDOUT,
193 print(f
"run {name_of(scheme, volumes_per_axis)}", flush=
True)
194 time_file = os.path.join(directory,
"time.txt")
195 with open(os.path.join(directory,
"run.log"),
"w")
as log:
196 process = subprocess.Popen(
197 [
"/usr/bin/time",
"-f",
"%e %M",
"-o", time_file,
"./gauge-wave"],
202 if exceeded
is not None:
205 "volumes": volumes_per_axis,
206 "skipped": f
"killed at {exceeded / 1e6:.1f} GB, as the machine ran out of memory",
208 if process.returncode
in (-9, 137):
212 "volumes": volumes_per_axis,
213 "skipped":
"killed by the operating system, i.e. the machine ran out of memory",
215 if process.returncode != 0:
217 f
"{name_of(scheme, volumes_per_axis)} failed, see {directory}/run.log"
219 with open(time_file)
as f:
220 runtime, memory = f.read().split()[-2:]
224 "volumes": volumes_per_axis,
226 "runtime": float(runtime),
227 "memory":
int(memory),
236 Maximum error of the lapse along y=z=0.5 in the last snapshot
238 Peano's PointProbe samples the lapse in the centre of each volume.
240 @return time stamp of the snapshot, error
244 glob.glob(os.path.join(directory,
"solution-CCZ4-*.peano-patch-file"))
246 x = (np.arange(volumes_per_axis) + 0.5) / volumes_per_axis
248 for i, x_i
in enumerate(x):
249 output_file = os.path.join(directory, f
"probe-{i}.csv")
251 file_name=os.path.join(directory, PatchFile),
252 point=[x_i, 0.5, 0.5],
253 output_file=output_file,
257 with contextlib.redirect_stdout(io.StringIO()):
258 point_probe.display()
259 with open(output_file)
as f:
260 header = f.readline().strip().split(
",")
261 row = f.readline().strip().split(
",")
262 os.remove(output_file)
263 t = float(row[header.index(
"time")])
264 lapse.append(float(row[header.index(
"lapse")]))
265 error = np.max(np.abs(np.array(lapse) -
exact_lapse(x, t)))
266 return t, float(error)
270 """! Order from two meshes whose volume sizes differ by a factor of three"""
271 return math.log(coarse[
"error"] / fine[
"error"]) / math.log(3.0)
282 """! Resident memory in kilobytes of a process and its children (/usr/bin/time forks the executable)"""
284 for status
in glob.glob(
"/proc/[0-9]*/status"):
286 with open(status)
as f:
291 line.split(
":", 1)
for line
in content.splitlines()
if ":" in line
293 if process.pid
in (
int(fields.get(
"PPid",
"0")),
int(fields.get(
"Pid",
"0"))):
294 for line
in content.splitlines():
295 if line.startswith(
"VmRSS"):
296 footprint +=
int(line.split()[1])
303 Wait for a process, but kill it if the machine runs out of memory
305 Several runs go on at the same time. If less than MemoryFloor is available
306 on the machine, the run with the biggest footprint of all runs is killed.
307 The study then continues without that data point. Runs on fine meshes
308 allocate their memory early, i.e. we do not waste hours before we learn
309 that a run does not fit.
311 @return None if the process terminated on its own, otherwise the
312 footprint in kilobytes when it was killed.
316 while process.poll()
is None:
318 Footprints[name] = footprint
322 subprocess.run([
"pkill",
"-9",
"-P", str(process.pid)])
328 Footprints.pop(name,
None)
332def plot(results, schemes, meshes, output_file):
335 Max error over the volume size
337 The gray lines are guides for the orders 1 to 4. The Runge-Kutta schemes
338 of order three and four yield almost the same error, as the error of the
339 fourth-order spatial discretisation dominates. We therefore use different
343 figure, axes = plt.subplots(figsize=(7, 5))
344 markers = {
"fv":
"o",
"rk1fd4":
"s",
"rk2fd4":
"^",
"rk3fd4":
"D",
"rk4fd4":
"x"}
345 sizes = {
"rk3fd4": 9}
348 for scheme
in schemes:
350 (r
for r
in results.values()
if r[
"scheme"] == scheme
and "error" in r),
351 key=
lambda r: r[
"volumes"],
355 [1.0 / r[
"volumes"]
for r
in points],
356 [r[
"error"]
for r
in points],
357 marker=markers[scheme],
358 markersize=sizes.get(scheme, 6),
361 volumes.update(r[
"volumes"]
for r
in points)
362 errors.extend(r[
"error"]
for r
in points)
363 volumes = sorted(volumes)
364 h = np.array([1.0 / volumes[0], 1.0 / volumes[-1]])
365 for order
in [1, 2, 3, 4]:
366 guide = max(errors) * (h / h[0]) ** order
367 axes.loglog(h, guide, color=
"gray", linestyle=
":", linewidth=0.8)
368 axes.annotate(f
"order {order}", (h[-1], guide[-1]), color=
"gray", fontsize=8)
369 axes.set_xticks([1.0 / v
for v
in volumes])
370 axes.set_xticklabels([f
"1/{v}" for v
in volumes])
371 axes.minorticks_off()
372 axes.set_xlabel(
"volume size h")
373 axes.set_ylabel(f
"max error of the lapse at t={EndTime}")
374 axes.set_title(
"Gauge wave convergence")
375 axes.grid(
True, which=
"major", alpha=0.3)
377 figure.tight_layout()
378 figure.savefig(output_file, dpi=150)
382def table(results, schemes, meshes):
384 "| scheme | volumes per axis | max error of lapse | order | runtime [s] | threads | memory [MB] |",
385 "|---|---|---|---|---|---|---|",
387 for scheme
in schemes:
389 for volumes
in meshes:
390 r = results.get(
name_of(scheme, volumes))
395 f
"| {scheme} | {volumes} | skipped: {r['skipped']} | | | | |"
399 order =
"" if previous
is None else f
"{estimated_order(previous, r):.2f}"
401 f
"| {scheme} | {volumes} | {r['error']:.3e} | {order} | {r['runtime']:.0f} | {r['threads']} | {r['memory'] / 1024:.0f} |"
404 return "\n".join(lines) +
"\n"
408 """! Return the list of schemes whose order between the two finest meshes is too low"""
410 for scheme
in schemes:
414 if name_of(scheme, v)
in results
and "error" in results[
name_of(scheme, v)]
417 failures.append(f
"{scheme}: fewer than two meshes")
420 if order < ExpectedOrders[scheme]:
421 failures.append(f
"{scheme}: order {order:.2f} < {ExpectedOrders[scheme]}")
425if __name__ ==
"__main__":
426 parser = argparse.ArgumentParser(
427 description=
"Convergence study of the gauge wave benchmark"
432 help=
"Directory for builds, outputs and results.json",
435 "--output-directory",
436 default=os.path.join(Here,
"example-output"),
437 help=
"Directory for convergence.png and convergence.md",
439 parser.add_argument(
"--schemes", nargs=
"+", default=Schemes, choices=Schemes)
445 help=
"Volumes per axis (9, 27, 81, 243, ...)",
447 parser.add_argument(
"--cores", type=int, default=os.cpu_count())
449 "--concurrent-large-runs",
452 help=
"Maximum number of runs on meshes with more than 27 cells that run at the same time",
454 args = parser.parse_args()
456 work_directory = os.path.abspath(args.work_directory)
457 os.makedirs(work_directory, exist_ok=
True)
458 results_file = os.path.join(work_directory,
"results.json")
460 if os.path.exists(results_file):
461 with open(results_file)
as f:
462 results = json.load(f)
465 with open(results_file,
"w")
as f:
466 json.dump(results, f, indent=1)
468 meshes = sorted(args.meshes)
471 for s
in args.schemes
473 if name_of(s, v)
not in results
or "skipped" in results[
name_of(s, v)]
486 and "skipped" not in results[
name_of(scheme, v)]
490 share = max(1, Workers.alive)
494 else max(1, math.ceil(args.cores / share))
499 scheme, v, threads, work_directory
503 scheme, v, threads, work_directory
510 Workers.alive = len(args.schemes)
511 LargeRunSlots = threading.Semaphore(args.concurrent_large_runs)
512 with concurrent.futures.ThreadPoolExecutor(max_workers=len(args.schemes))
as pool:
513 for future
in [pool.submit(run_scheme, scheme)
for scheme
in args.schemes]:
516 os.makedirs(args.output_directory, exist_ok=
True)
521 os.path.join(args.output_directory,
"convergence.png"),
523 markdown =
table(results, args.schemes, meshes)
524 with open(os.path.join(args.output_directory,
"convergence.md"),
"w")
as f:
530 print(
"FAILED:\n " +
"\n ".join(failures))
Number of scheme workers that are still running, and the lock to protect it.
Probe the data within a Peano patch file at one point over time.
build_and_run(study, volumes_per_axis, threads, work_directory)
Generate, compile and run gauge-wave-with-scalar-field.py.
exact_lapse(x, t)
Lapse of the gauge wave, i.e.
check_orders(results, studies, meshes)
The studies whose order between the two finest meshes is outside the expected range.
footprint_of(process)
Resident memory in kilobytes of a process and its children (/usr/bin/time forks the executable).
measure_error(directory, volumes_per_axis)
Maximum error of the four scalar fields along y=z=0.5 in the last snapshot.
available_memory_in_kilobytes()
estimated_order(coarse, fine)
Order from two meshes whose volume sizes differ by a factor of three.
run_scheme(scheme)
One worker per scheme, all of them at the same time.
patch_size_of(volumes_per_axis)
The patch size does not influence the solution.
watch_memory(process, name)
Wait for a process, but kill it if the machine runs out of memory.
mesh_cells(volumes_per_axis)
Number of mesh cells (patches) of a run.
name_of(study, volumes_per_axis)
table(results, studies, meshes)