5Convergence study of the gauge wave with a scalar field
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.
15 python3 convergence-study.py --work-directory /scratch/gauge-wave-with-scalar-field
17Runs which have completed before in the work directory are reused. Remove the run's
18directory (or results.json) to rerun it.
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.
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"))
47import matplotlib.pyplot
as plt
54PatchFile =
"solution-ScalarField.peano-patch-file"
62 return 3
if volumes_per_axis == 9
else 9
67 (
"rk4fd4",
"outer-multiplicative"),
68 (
"rk4fd4",
"inner-additive"),
69 (
"rk4fd4",
"inner-multiplicative"),
70 (
"fv",
"outer-multiplicative"),
71 (
"fv",
"inner-additive"),
72 (
"fv",
"inner-multiplicative"),
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,
88MaximumOrders = {(
"rk4fd4",
"outer-multiplicative"): 1.6}
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)
99 scheme, coupling = study
100 return f
"{scheme}-{coupling}-{volumes_per_axis}"
106 Generate, compile and run gauge-wave-with-scalar-field.py
109 Runtime, memory footprint, threads and the error against the exact
110 solution at the last snapshot.
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",
"")
126 os.path.join(Here,
"gauge-wave-with-scalar-field.py"),
129 "--coupling", coupling,
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",
140 stdout=open(os.path.join(directory,
"generate.log"),
"w"),
141 stderr=subprocess.STDOUT,
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"],
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:]
158 "coupling": coupling,
159 "volumes": volumes_per_axis,
161 "runtime": float(runtime),
162 "memory":
int(memory),
171 Maximum error of the four scalar fields along y=z=0.5 in the last snapshot
173 Peano's PointProbe samples the unknowns in the centre of each volume.
175 @return time stamp of the snapshot, error
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
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,
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)
200 np.max(np.abs(values[:, c] -
exact_solution(x, t, c)))
for c
in range(4)
202 return t, float(error)
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)
210def plot(results, studies, output_file):
211 figure, axes = plt.subplots(figsize=(7, 5))
214 for study
in studies:
216 (r
for r
in results.values()
if (r[
"scheme"], r[
"coupling"]) == study),
217 key=
lambda r: r[
"volumes"],
221 [1.0 / r[
"volumes"]
for r
in points],
222 [r[
"error"]
for r
in points],
224 label=
" ".join(study),
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)
249 "| scheme | coupling | volumes per axis | max error of the scalar field | order | runtime [s] | threads | memory [MB] |",
250 "|---|---|---|---|---|---|---|---|",
252 for study
in studies:
254 for volumes
in meshes:
255 r = results.get(
name_of(study, volumes))
258 order =
"" if previous
is None else f
"{estimated_order(previous, r):.2f}"
260 f
"| {study[0]} | {study[1]} | {volumes} | {r['error']:.3e} | {order} | {r['runtime']:.0f} | {r['threads']} | {r['memory'] / 1024:.0f} |"
263 return "\n".join(lines) +
"\n"
267 """! The studies whose order between the two finest meshes is outside the expected range """
269 for study
in studies:
271 results[
name_of(study, v)]
for v
in meshes
if name_of(study, v)
in results
274 failures.append(f
"{' '.join(study)}: fewer than two meshes")
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]}")
284if __name__ ==
"__main__":
285 parser = argparse.ArgumentParser(
286 description=
"Convergence study of the gauge wave with a scalar field"
288 parser.add_argument(
"--work-directory", required=
True, help=
"Directory for builds, outputs and results.json")
290 "--output-directory",
291 default=os.path.join(Here,
"example-output"),
292 help=
"Directory for convergence.png and convergence.md",
297 default=[f
"{s}:{c}" for s, c
in Studies],
298 help=
"scheme:coupling pairs, e.g. rk4fd4:inner-additive",
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()
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")
310 if os.path.exists(results_file):
311 with open(results_file)
as f:
312 results = json.load(f)
314 for study
in studies:
316 if name_of(study, v)
not in results:
318 study, v, 1
if patch_size_of(v) == 3
or v == 27
else args.threads, work_directory
320 with open(results_file,
"w")
as f:
321 json.dump(results, f, indent=1)
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:
332 print(
"FAILED:\n " +
"\n ".join(failures))
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.
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)