Peano
Loading...
Searching...
No Matches
convergence-study.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
5Convergence study of the gauge wave benchmark
6
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
11
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)
15
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.
21
22 python3 convergence-study.py --work-directory /scratch/gauge-wave
23
24Runs which have completed before in the work directory are reused. Remove
25the run's directory (or results.json) to rerun it.
26
27
28## Scheduling
29
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.
38
39
40## Memory
41
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.
46
47"""
48import argparse
49import concurrent.futures
50import contextlib
51import glob
52import io
53import json
54import math
55import os
56import shutil
57import subprocess
58import sys
59import threading
60import time
61
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"))
65
66import matplotlib
67
68matplotlib.use("Agg")
69import matplotlib.pyplot as plt
70import numpy as np
71
73
74EndTime = 0.1
75Amplitude = 0.1
76PatchFile = "solution-CCZ4.peano-patch-file"
77
78
79
82def patch_size_of(volumes_per_axis):
83 return 3 if volumes_per_axis == 9 else 9
84
85
86Schemes = ["fv", "rk1fd4", "rk2fd4", "rk3fd4", "rk4fd4"]
87
88
90Meshes = [9, 27, 81]
91
92
94StagnationCells = 27
95
96
100ExpectedOrders = {
101 "fv": 0.8,
102 "rk1fd4": 0.8,
103 "rk2fd4": 1.8,
104 "rk3fd4": 3.2,
105 "rk4fd4": 3.2,
106}
107
108
109
111LargeRunSlots = threading.Semaphore(2)
112
113
114BuildSlots = threading.Semaphore(3)
115
116
118 """! Number of scheme workers that are still running, and the lock to protect it"""
119
120 alive = 1
121 lock = threading.Lock()
122
123
124def exact_lapse(x, t):
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)))
127
128
129def mesh_cells(volumes_per_axis):
130 """! Number of mesh cells (patches) of a run"""
131 return (volumes_per_axis // patch_size_of(volumes_per_axis)) ** 3
132
133
134def name_of(scheme, volumes_per_axis):
135 return f"{scheme}-{volumes_per_axis}"
136
137
139 with open("/proc/meminfo") as f:
140 for line in f:
141 if line.startswith("MemAvailable"):
142 return int(line.split()[1])
143 return sys.maxsize
144
145
146def build_and_run(scheme, volumes_per_axis, threads, work_directory):
147 """!
148
149 Generate, compile and run gauge-wave.py
150
151 @return dict
152 Runtime, memory footprint, threads and the error against the exact
153 solution at the last snapshot.
154
155 """
156 directory = os.path.join(work_directory, name_of(scheme, volumes_per_axis))
157 # Start from scratch: A previous attempt that was killed leaves generated
158 # files behind which clash with the new ones.
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", "")
165 )
166 with BuildSlots:
167 subprocess.run(
168 [
169 sys.executable,
170 os.path.join(Here, "gauge-wave.py"),
171 "--mode",
172 "release",
173 "--scheme",
174 scheme,
175 "--patch-size",
176 str(patch_size_of(volumes_per_axis)),
177 "--mesh-size",
178 repr(1.0 / volumes_per_axis),
179 "--end-time",
180 repr(EndTime),
181 "--directory",
182 directory,
183 "--threads",
184 str(threads),
185 "--plot-along-x-axis",
186 ],
187 cwd=directory,
188 env=environment,
189 check=True,
190 stdout=open(os.path.join(directory, "generate.log"), "w"),
191 stderr=subprocess.STDOUT,
192 )
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"],
198 cwd=directory,
199 stdout=log,
200 )
201 exceeded = watch_memory(process, name_of(scheme, volumes_per_axis))
202 if exceeded is not None:
203 return {
204 "scheme": scheme,
205 "volumes": volumes_per_axis,
206 "skipped": f"killed at {exceeded / 1e6:.1f} GB, as the machine ran out of memory",
207 }
208 if process.returncode in (-9, 137):
209 # SIGKILL: the kernel's out-of-memory killer was faster than our watchdog
210 return {
211 "scheme": scheme,
212 "volumes": volumes_per_axis,
213 "skipped": "killed by the operating system, i.e. the machine ran out of memory",
214 }
215 if process.returncode != 0:
216 raise RuntimeError(
217 f"{name_of(scheme, volumes_per_axis)} failed, see {directory}/run.log"
218 )
219 with open(time_file) as f:
220 runtime, memory = f.read().split()[-2:]
221 t, error = measure_error(directory, volumes_per_axis)
222 return {
223 "scheme": scheme,
224 "volumes": volumes_per_axis,
225 "threads": threads,
226 "runtime": float(runtime),
227 "memory": int(memory),
228 "time": t,
229 "error": error,
230 }
231
232
233def measure_error(directory, volumes_per_axis):
234 """!
235
236 Maximum error of the lapse along y=z=0.5 in the last snapshot
237
238 Peano's PointProbe samples the lapse in the centre of each volume.
239
240 @return time stamp of the snapshot, error
241
242 """
243 snapshots = len(
244 glob.glob(os.path.join(directory, "solution-CCZ4-*.peano-patch-file"))
245 )
246 x = (np.arange(volumes_per_axis) + 0.5) / volumes_per_axis
247 lapse = []
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,
254 start=snapshots - 1,
255 end=snapshots - 1,
256 )
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)
267
268
269def estimated_order(coarse, fine):
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)
272
273
274
275MemoryFloor = 1500000
276
277
278Footprints = {}
279
280
281def footprint_of(process):
282 """! Resident memory in kilobytes of a process and its children (/usr/bin/time forks the executable)"""
283 footprint = 0
284 for status in glob.glob("/proc/[0-9]*/status"):
285 try:
286 with open(status) as f:
287 content = f.read()
288 except OSError:
289 continue
290 fields = dict(
291 line.split(":", 1) for line in content.splitlines() if ":" in line
292 )
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])
297 return footprint
298
299
300def watch_memory(process, name):
301 """!
302
303 Wait for a process, but kill it if the machine runs out of memory
304
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.
310
311 @return None if the process terminated on its own, otherwise the
312 footprint in kilobytes when it was killed.
313
314 """
315 try:
316 while process.poll() is None:
317 footprint = footprint_of(process)
318 Footprints[name] = footprint
319 if available_memory_in_kilobytes() < MemoryFloor and footprint >= max(
320 Footprints.values()
321 ):
322 subprocess.run(["pkill", "-9", "-P", str(process.pid)])
323 process.kill()
324 process.wait()
325 return footprint
326 time.sleep(1.0)
327 finally:
328 Footprints.pop(name, None)
329 return None
330
331
332def plot(results, schemes, meshes, output_file):
333 """!
334
335 Max error over the volume size
336
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
340 markers.
341
342 """
343 figure, axes = plt.subplots(figsize=(7, 5))
344 markers = {"fv": "o", "rk1fd4": "s", "rk2fd4": "^", "rk3fd4": "D", "rk4fd4": "x"}
345 sizes = {"rk3fd4": 9}
346 volumes = set()
347 errors = []
348 for scheme in schemes:
349 points = sorted(
350 (r for r in results.values() if r["scheme"] == scheme and "error" in r),
351 key=lambda r: r["volumes"],
352 )
353 if points:
354 axes.loglog(
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),
359 label=scheme,
360 )
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)
376 axes.legend()
377 figure.tight_layout()
378 figure.savefig(output_file, dpi=150)
379 plt.close(figure)
380
381
382def table(results, schemes, meshes):
383 lines = [
384 "| scheme | volumes per axis | max error of lapse | order | runtime [s] | threads | memory [MB] |",
385 "|---|---|---|---|---|---|---|",
386 ]
387 for scheme in schemes:
388 previous = None
389 for volumes in meshes:
390 r = results.get(name_of(scheme, volumes))
391 if r is None:
392 continue
393 if "error" not in r:
394 lines.append(
395 f"| {scheme} | {volumes} | skipped: {r['skipped']} | | | | |"
396 )
397 previous = None
398 continue
399 order = "" if previous is None else f"{estimated_order(previous, r):.2f}"
400 lines.append(
401 f"| {scheme} | {volumes} | {r['error']:.3e} | {order} | {r['runtime']:.0f} | {r['threads']} | {r['memory'] / 1024:.0f} |"
402 )
403 previous = r
404 return "\n".join(lines) + "\n"
405
406
407def check_orders(results, schemes, meshes):
408 """! Return the list of schemes whose order between the two finest meshes is too low"""
409 failures = []
410 for scheme in schemes:
411 done = [
412 results[name_of(scheme, v)]
413 for v in meshes
414 if name_of(scheme, v) in results and "error" in results[name_of(scheme, v)]
415 ]
416 if len(done) < 2:
417 failures.append(f"{scheme}: fewer than two meshes")
418 continue
419 order = estimated_order(done[-2], done[-1])
420 if order < ExpectedOrders[scheme]:
421 failures.append(f"{scheme}: order {order:.2f} < {ExpectedOrders[scheme]}")
422 return failures
423
424
425if __name__ == "__main__":
426 parser = argparse.ArgumentParser(
427 description="Convergence study of the gauge wave benchmark"
428 )
429 parser.add_argument(
430 "--work-directory",
431 required=True,
432 help="Directory for builds, outputs and results.json",
433 )
434 parser.add_argument(
435 "--output-directory",
436 default=os.path.join(Here, "example-output"),
437 help="Directory for convergence.png and convergence.md",
438 )
439 parser.add_argument("--schemes", nargs="+", default=Schemes, choices=Schemes)
440 parser.add_argument(
441 "--meshes",
442 nargs="+",
443 type=int,
444 default=Meshes,
445 help="Volumes per axis (9, 27, 81, 243, ...)",
446 )
447 parser.add_argument("--cores", type=int, default=os.cpu_count())
448 parser.add_argument(
449 "--concurrent-large-runs",
450 type=int,
451 default=2,
452 help="Maximum number of runs on meshes with more than 27 cells that run at the same time",
453 )
454 args = parser.parse_args()
455
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")
459 results = {}
460 if os.path.exists(results_file):
461 with open(results_file) as f:
462 results = json.load(f)
463
464 def store():
465 with open(results_file, "w") as f:
466 json.dump(results, f, indent=1)
467
468 meshes = sorted(args.meshes)
469 todo = [
470 (s, v)
471 for s in args.schemes
472 for v in meshes
473 if name_of(s, v) not in results or "skipped" in results[name_of(s, v)]
474 ]
475
476
481 def run_scheme(scheme):
482 try:
483 for v in meshes:
484 if (
485 name_of(scheme, v) in results
486 and "skipped" not in results[name_of(scheme, v)]
487 ):
488 continue
489 with Workers.lock:
490 share = max(1, Workers.alive)
491 threads = (
492 1
493 if mesh_cells(v) <= StagnationCells
494 else max(1, math.ceil(args.cores / share))
495 )
496 if mesh_cells(v) > StagnationCells:
497 with LargeRunSlots:
498 results[name_of(scheme, v)] = build_and_run(
499 scheme, v, threads, work_directory
500 )
501 else:
502 results[name_of(scheme, v)] = build_and_run(
503 scheme, v, threads, work_directory
504 )
505 store()
506 finally:
507 with Workers.lock:
508 Workers.alive -= 1
509
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]:
514 future.result()
515
516 os.makedirs(args.output_directory, exist_ok=True)
517 plot(
518 results,
519 args.schemes,
520 meshes,
521 os.path.join(args.output_directory, "convergence.png"),
522 )
523 markdown = table(results, args.schemes, meshes)
524 with open(os.path.join(args.output_directory, "convergence.md"), "w") as f:
525 f.write(markdown)
526 print(markdown)
527
528 failures = check_orders(results, args.schemes, meshes)
529 if failures:
530 print("FAILED:\n " + "\n ".join(failures))
531 sys.exit(1)
532 print("PASSED")
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.
Definition PointProbe.py:37
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.
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)
-lift-drop-statistics