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 with a scalar field
6
7The script builds and runs gauge-wave-with-scalar-field.py for several couplings
8and mesh sizes. It measures the maximum error of the scalar field along the line y=z=0.5
9at the end of the simulation against the exact solution, estimates the convergence
10orders, and writes convergence.png (error over mesh size) and convergence.md (table)
11into the output directory. The study doubles as the integration test of the couplings:
12The script exits with a non-zero status if the estimated order between the two finest meshes
13falls below the one in ExpectedOrders.
14
15 python3 convergence-study.py --work-directory /scratch/gauge-wave-with-scalar-field
16
17Runs which have completed before in the work directory are reused. Remove the run's
18directory (or results.json) to rerun it.
19
20## Exact solution
21
22The scalar field obeys @f$ \\partial_t q + H \\partial_x q = 0 @f$ with @f$ H = 1 - A \\sin(2 \\pi (x-t)) @f$,
23the g_xx of the gauge wave. With @f$ \\theta = \\pi (x - t) @f$, the characteristics fulfil
24@f$ \\tan \\theta(t) = \\tan \\theta_0 \\ e^{-2 \\pi A t} @f$. The initial data are q_m = sin(2 pi x + m pi/4),
25m=0,...,3, i.e. q_m(x,t) = sin(2 theta_0 + m pi/4), where theta_0 is the foot point of the characteristic.
26See DESIGN.md.
27
28"""
29import argparse
30import contextlib
31import glob
32import io
33import json
34import math
35import os
36import shutil
37import subprocess
38import sys
39
40Here = os.path.dirname(os.path.abspath(__file__))
41PeanoRoot = os.path.abspath(os.path.join(Here, "..", "..", ".."))
42sys.path.insert(0, os.path.join(PeanoRoot, "src"))
43
44import matplotlib
45
46matplotlib.use("Agg")
47import matplotlib.pyplot as plt
48import numpy as np
49
51
52EndTime = 0.1
53Amplitude = 0.1
54PatchFile = "solution-ScalarField.peano-patch-file"
55
56
58Meshes = [9, 27, 81]
59
60
61def patch_size_of(volumes_per_axis):
62 return 3 if volumes_per_axis == 9 else 9
63
64
65
66Studies = [
67 ("rk4fd4", "outer-multiplicative"),
68 ("rk4fd4", "inner-additive"),
69 ("rk4fd4", "inner-multiplicative"),
70 ("fv", "outer-multiplicative"),
71 ("fv", "inner-additive"),
72 ("fv", "inner-multiplicative"),
73]
74
75
79ExpectedOrders = {
80 ("rk4fd4", "outer-multiplicative"): 0.8,
81 ("rk4fd4", "inner-additive"): 3.2,
82 ("rk4fd4", "inner-multiplicative"): 3.2,
83 ("fv", "outer-multiplicative"): 0.7,
84 ("fv", "inner-additive"): 0.7,
85 ("fv", "inner-multiplicative"): 0.7,
86}
87
88MaximumOrders = {("rk4fd4", "outer-multiplicative"): 1.6}
89
90
91def exact_solution(x, t, component):
92 """! Component 0, ..., 3 of the scalar field: sin(2 pi x + m pi/4) transported along the characteristics """
93 theta = np.pi * (np.asarray(x) - t)
94 foot = np.arctan2(np.exp(2.0 * np.pi * Amplitude * t) * np.sin(theta), np.cos(theta))
95 return np.sin(2.0 * foot + 0.25 * np.pi * component)
96
97
98def name_of(study, volumes_per_axis):
99 scheme, coupling = study
100 return f"{scheme}-{coupling}-{volumes_per_axis}"
101
102
103def build_and_run(study, volumes_per_axis, threads, work_directory):
104 """!
105
106 Generate, compile and run gauge-wave-with-scalar-field.py
107
108 @return dict
109 Runtime, memory footprint, threads and the error against the exact
110 solution at the last snapshot.
111
112 """
113 scheme, coupling = study
114 name = name_of(study, volumes_per_axis)
115 directory = os.path.join(work_directory, name)
116 shutil.rmtree(directory, ignore_errors=True)
117 os.makedirs(directory)
118 print(f"build {name} ({threads} threads)", flush=True)
119 environment = dict(os.environ)
120 environment["PYTHONPATH"] = (
121 os.path.join(PeanoRoot, "src") + os.pathsep + environment.get("PYTHONPATH", "")
122 )
123 subprocess.run(
124 [
125 sys.executable,
126 os.path.join(Here, "gauge-wave-with-scalar-field.py"),
127 "--mode", "release",
128 "--scheme", scheme,
129 "--coupling", coupling,
130 "--patch-size", str(patch_size_of(volumes_per_axis)),
131 "--mesh-size", repr(1.0 / volumes_per_axis),
132 "--end-time", repr(EndTime),
133 "--directory", directory,
134 "--threads", str(threads),
135 "--plot-along-x-axis",
136 ],
137 cwd=directory,
138 env=environment,
139 check=True,
140 stdout=open(os.path.join(directory, "generate.log"), "w"),
141 stderr=subprocess.STDOUT,
142 )
143 print(f"run {name}", flush=True)
144 time_file = os.path.join(directory, "time.txt")
145 with open(os.path.join(directory, "run.log"), "w") as log:
146 process = subprocess.run(
147 ["/usr/bin/time", "-f", "%e %M", "-o", time_file, "./gauge-wave-with-scalar-field"],
148 cwd=directory,
149 stdout=log,
150 )
151 if process.returncode != 0:
152 raise RuntimeError(f"{name} failed, see {directory}/run.log")
153 with open(time_file) as f:
154 runtime, memory = f.read().split()[-2:]
155 t, error = measure_error(directory, volumes_per_axis)
156 return {
157 "scheme": scheme,
158 "coupling": coupling,
159 "volumes": volumes_per_axis,
160 "threads": threads,
161 "runtime": float(runtime),
162 "memory": int(memory),
163 "time": t,
164 "error": error,
165 }
166
167
168def measure_error(directory, volumes_per_axis):
169 """!
170
171 Maximum error of the four scalar fields along y=z=0.5 in the last snapshot
172
173 Peano's PointProbe samples the unknowns in the centre of each volume.
174
175 @return time stamp of the snapshot, error
176
177 """
178 snapshots = len(glob.glob(os.path.join(directory, "solution-ScalarField-*.peano-patch-file")))
179 x = (np.arange(volumes_per_axis) + 0.5) / volumes_per_axis
180 values = []
181 for i, x_i in enumerate(x):
182 output_file = os.path.join(directory, f"probe-{i}.csv")
184 file_name=os.path.join(directory, PatchFile),
185 point=[x_i, 0.5, 0.5],
186 output_file=output_file,
187 start=snapshots - 1,
188 end=snapshots - 1,
189 )
190 with contextlib.redirect_stdout(io.StringIO()):
191 point_probe.display()
192 with open(output_file) as f:
193 header = f.readline().strip().split(",")
194 row = f.readline().strip().split(",")
195 os.remove(output_file)
196 t = float(row[header.index("time")])
197 values.append([float(row[header.index(f"phi[{c}]")]) for c in range(4)])
198 values = np.array(values)
199 error = max(
200 np.max(np.abs(values[:, c] - exact_solution(x, t, c))) for c in range(4)
201 )
202 return t, float(error)
203
204
205def estimated_order(coarse, fine):
206 """! Order from two meshes whose volume sizes differ by a factor of three"""
207 return math.log(coarse["error"] / fine["error"]) / math.log(3.0)
208
209
210def plot(results, studies, output_file):
211 figure, axes = plt.subplots(figsize=(7, 5))
212 volumes = set()
213 errors = []
214 for study in studies:
215 points = sorted(
216 (r for r in results.values() if (r["scheme"], r["coupling"]) == study),
217 key=lambda r: r["volumes"],
218 )
219 if points:
220 axes.loglog(
221 [1.0 / r["volumes"] for r in points],
222 [r["error"] for r in points],
223 marker="o",
224 label=" ".join(study),
225 )
226 volumes.update(r["volumes"] for r in points)
227 errors.extend(r["error"] for r in points)
228 volumes = sorted(volumes)
229 h = np.array([1.0 / volumes[0], 1.0 / volumes[-1]])
230 for order in [1, 2, 3, 4]:
231 guide = max(errors) * (h / h[0]) ** order
232 axes.loglog(h, guide, color="gray", linestyle=":", linewidth=0.8)
233 axes.annotate(f"order {order}", (h[-1], guide[-1]), color="gray", fontsize=8)
234 axes.set_xticks([1.0 / v for v in volumes])
235 axes.set_xticklabels([f"1/{v}" for v in volumes])
236 axes.minorticks_off()
237 axes.set_xlabel("volume size h")
238 axes.set_ylabel(f"max error of the scalar field at t={EndTime}")
239 axes.set_title("Gauge wave with a scalar field: convergence")
240 axes.grid(True, which="major", alpha=0.3)
241 axes.legend(fontsize=8)
242 figure.tight_layout()
243 figure.savefig(output_file, dpi=150)
244 plt.close(figure)
245
246
247def table(results, studies, meshes):
248 lines = [
249 "| scheme | coupling | volumes per axis | max error of the scalar field | order | runtime [s] | threads | memory [MB] |",
250 "|---|---|---|---|---|---|---|---|",
251 ]
252 for study in studies:
253 previous = None
254 for volumes in meshes:
255 r = results.get(name_of(study, volumes))
256 if r is None:
257 continue
258 order = "" if previous is None else f"{estimated_order(previous, r):.2f}"
259 lines.append(
260 f"| {study[0]} | {study[1]} | {volumes} | {r['error']:.3e} | {order} | {r['runtime']:.0f} | {r['threads']} | {r['memory'] / 1024:.0f} |"
261 )
262 previous = r
263 return "\n".join(lines) + "\n"
264
265
266def check_orders(results, studies, meshes):
267 """! The studies whose order between the two finest meshes is outside the expected range """
268 failures = []
269 for study in studies:
270 done = [
271 results[name_of(study, v)] for v in meshes if name_of(study, v) in results
272 ]
273 if len(done) < 2:
274 failures.append(f"{' '.join(study)}: fewer than two meshes")
275 continue
276 order = estimated_order(done[-2], done[-1])
277 if order < ExpectedOrders[study]:
278 failures.append(f"{' '.join(study)}: order {order:.2f} < {ExpectedOrders[study]}")
279 if order > MaximumOrders.get(study, math.inf):
280 failures.append(f"{' '.join(study)}: order {order:.2f} > {MaximumOrders[study]}")
281 return failures
282
283
284if __name__ == "__main__":
285 parser = argparse.ArgumentParser(
286 description="Convergence study of the gauge wave with a scalar field"
287 )
288 parser.add_argument("--work-directory", required=True, help="Directory for builds, outputs and results.json")
289 parser.add_argument(
290 "--output-directory",
291 default=os.path.join(Here, "example-output"),
292 help="Directory for convergence.png and convergence.md",
293 )
294 parser.add_argument(
295 "--studies",
296 nargs="+",
297 default=[f"{s}:{c}" for s, c in Studies],
298 help="scheme:coupling pairs, e.g. rk4fd4:inner-additive",
299 )
300 parser.add_argument("--meshes", nargs="+", type=int, default=Meshes, help="Volumes per axis (9, 27, 81, 243, ...)")
301 parser.add_argument("--threads", type=int, default=os.cpu_count())
302 args = parser.parse_args()
303
304 studies = [tuple(s.split(":")) for s in args.studies]
305 meshes = sorted(args.meshes)
306 work_directory = os.path.abspath(args.work_directory)
307 os.makedirs(work_directory, exist_ok=True)
308 results_file = os.path.join(work_directory, "results.json")
309 results = {}
310 if os.path.exists(results_file):
311 with open(results_file) as f:
312 results = json.load(f)
313
314 for study in studies:
315 for v in meshes:
316 if name_of(study, v) not in results:
317 results[name_of(study, v)] = build_and_run(
318 study, v, 1 if patch_size_of(v) == 3 or v == 27 else args.threads, work_directory
319 )
320 with open(results_file, "w") as f:
321 json.dump(results, f, indent=1)
322
323 os.makedirs(args.output_directory, exist_ok=True)
324 plot(results, studies, os.path.join(args.output_directory, "convergence.png"))
325 markdown = table(results, studies, meshes)
326 with open(os.path.join(args.output_directory, "convergence.md"), "w") as f:
327 f.write(markdown)
328 print(markdown)
329
330 failures = check_orders(results, studies, meshes)
331 if failures:
332 print("FAILED:\n " + "\n ".join(failures))
333 sys.exit(1)
334 print("PASSED")
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.
check_orders(results, studies, meshes)
The studies whose order between the two finest meshes is outside the expected range.
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.
patch_size_of(volumes_per_axis)
The patch size does not influence the solution.
exact_solution(x, t, component)
Component 0, ..., 3 of the scalar field: sin(2 pi x + m pi/4) transported along the characteristics.
name_of(study, volumes_per_axis)
table(results, studies, meshes)
-lift-drop-statistics