Peano
Loading...
Searching...
No Matches
amr-study.py
Go to the documentation of this file.
1# This file is part of the ExaHyPE2 project. For conditions of distribution and
2# use, please see the copyright notice at www.peano-framework.org
3"""!
4
5AMR check of the point source benchmark
6
7Generates, builds and runs the point source benchmark
8(@ref benchmarks_exahype2_euler_point_source) without AMR (levels 0) and with AMR
9(levels 1 by default), and checks that
10
11- the dynamic AMR works: the mesh has coarsened, i.e. it has fewer cells than the
12 regular start grid at the end of the run, and
13- the AMR does not harm the quality: the final density and energy differ from the
14 solution on the regular grid by at most --tolerance times the range of the
15 latter.
16
17Prints a table of the mesh over time, the differences and PASSED or FAILED, and exits
18non-zero on FAILED. Finished runs in the work directory are reused.
19
20"""
21import argparse
22import math
23import os
24import re
25import subprocess
26import sys
27
28import numpy as np
29
30from tarch.plotter.api.input.PatchFileParser import PatchFileParser
31from tarch.plotter.api.notebook import read_snapshots
32
33HERE = os.path.dirname(os.path.abspath(__file__))
34SOLVER_NAME = "EulerPointSource"
35VOLUMES_PER_PATCH_AXIS = 9
36
37
38def run(work_directory: str, levels: int, arguments):
39 """!
40 Generate, build and run the benchmark with the given number of AMR levels
41
42 @param work_directory: str
43 Directory of all runs. The run of the AMR levels lives in a directory of its own.
44 @param levels: int
45 Number of AMR levels.
46 @param arguments: [str]
47 Further arguments of point-source.py.
48 @return str
49 The run directory.
50 """
51 directory = os.path.join(work_directory, f"levels-{levels}")
52 if os.path.exists(os.path.join(directory, "run.log")):
53 return directory
54 os.makedirs(directory, exist_ok=True)
55 with open(os.path.join(directory, "generate.log"), "w") as log:
56 subprocess.run(
57 [
58 sys.executable,
59 os.path.join(HERE, "point-source.py"),
60 "--output-directory",
61 directory,
62 "--verbosity",
63 "text",
64 "--amr-levels",
65 str(levels),
66 "--patch-size",
67 str(VOLUMES_PER_PATCH_AXIS),
68 ]
69 + arguments,
70 stdout=log,
71 stderr=subprocess.STDOUT,
72 check=True,
73 )
74 with open(os.path.join(directory, "run.log.tmp"), "w") as log:
75 subprocess.run(
76 ["./point-source"],
77 cwd=directory,
78 stdout=log,
79 stderr=subprocess.STDOUT,
80 check=True,
81 )
82 os.rename(
83 os.path.join(directory, "run.log.tmp"), os.path.join(directory, "run.log")
84 )
85 return directory
86
87
88def mesh_over_time(run_directory: str):
89 """!
90 Number of leaf cells after each time step
91
92 @return [(float, int)]
93 Time stamp and number of cells per time step.
94 """
95 result = []
96 time_stamp = None
97 cells = None
98 with open(os.path.join(run_directory, "run.log"), errors="ignore") as log:
99 for line in log:
100 match = re.search(r"t=([0-9.e+-]+), new dt=", line)
101 if match:
102 if time_stamp is not None:
103 result.append((time_stamp, cells))
104 time_stamp = float(match.group(1))
105 match = re.search(r"#local cells=\‍((\d+)/\d+\‍)", line)
106 if match:
107 cells = int(match.group(1))
108 result.append((time_stamp, cells))
109 return result
110
111
112def final_solution(run_directory: str, volumes_per_axis: int):
113 """!
114 Last snapshot, injected piecewise constant onto the regular grid
115
116 @return (float, np.ndarray, int)
117 Time stamp, array [unknown][y][x] and the number of mesh cells of the snapshot.
118 """
119 snapshots = read_snapshots(
120 os.path.join(run_directory, f"solution-{SOLVER_NAME}.peano-patch-file")
121 )
122 time_stamp, files = snapshots[-1]
123 volume_size = 1.0 / volumes_per_axis
124 result = np.full((4, volumes_per_axis, volumes_per_axis), np.nan)
125 cells = 0
126 for file_name in files:
127 parser = PatchFileParser(file_name, "", 0)
128 parser.parse_file()
129 for attributes in parser.unknown_attributes.values():
130 dofs = attributes.dof
131 for patch in attributes.cell_data:
132 cells += 1
133 values = patch.values.reshape(dofs, dofs, attributes.unknowns)
134 factor = int(round(patch.size[0] / dofs / volume_size))
135 x = int(round((patch.offset[0] + 0.5) / volume_size))
136 y = int(round((patch.offset[1] + 0.5) / volume_size))
137 block = np.repeat(np.repeat(values, factor, axis=0), factor, axis=1)
138 for unknown in range(4):
139 result[
140 unknown, y : y + dofs * factor, x : x + dofs * factor
141 ] = block[..., unknown]
142 return time_stamp, result, cells
143
144
145if __name__ == "__main__":
146 parser = argparse.ArgumentParser(description=__doc__.strip().split("\n")[0])
147 parser.add_argument(
148 "--work-directory", required=True, help="Directory for the runs"
149 )
150 parser.add_argument(
151 "--amr-levels",
152 type=int,
153 default=1,
154 help="AMR levels of the AMR run (default: 1)",
155 )
156 parser.add_argument(
157 "--patch-count",
158 type=int,
159 default=81,
160 help="Mesh cells per axis of the regular start grid, a power of three (default: 81)",
161 )
162 parser.add_argument(
163 "--end-time", type=float, default=0.1, help="Simulated time (default: 0.1)"
164 )
165 parser.add_argument(
166 "--tolerance",
167 type=float,
168 default=0.02,
169 help="Allowed maximum difference relative to the range (default: 0.02)",
170 )
171 args = parser.parse_args()
172
173 volumes_per_axis = args.patch_count * VOLUMES_PER_PATCH_AXIS
174 extra = [
175 "--volume-size",
176 str(1.001 / volumes_per_axis),
177 "--end-time",
178 str(args.end_time),
179 "--plots",
180 "5",
181 ]
182 os.makedirs(args.work_directory, exist_ok=True)
183 regular = run(args.work_directory, 0, extra)
184 adaptive = run(args.work_directory, args.amr_levels, extra)
185
186 start_cells = args.patch_count**2
187 timeline = mesh_over_time(adaptive)
188 print(
189 f"Mesh of the run with {args.amr_levels} AMR level(s) (regular start grid: {start_cells} cells)"
190 )
191 print("| time stamp | cells | volumes | coarsened volumes | refined volumes |")
192 print("|------------|-------|---------|-------------------|-----------------|")
193 previous = start_cells
194 last_printed = None
195 coarsened = refined = 0
196 for time_stamp, cells in timeline:
197 delta = (cells - previous) * VOLUMES_PER_PATCH_AXIS**2
198 coarsened += max(-delta, 0)
199 refined += max(delta, 0)
200 if delta != 0:
201 print(
202 f"| {time_stamp:10.4f} | {cells:5d} | {cells * VOLUMES_PER_PATCH_AXIS**2:7d} | {max(-delta, 0):17d} | {max(delta, 0):15d} |"
203 )
204 previous = cells
205 print(f"total coarsened {coarsened} volumes, refined {refined} volumes")
206
207 _, reference, reference_cells = final_solution(regular, volumes_per_axis)
208 time_stamp, solution, cells = final_solution(adaptive, volumes_per_axis)
209 failures = []
210 if reference_cells != start_cells:
211 failures.append(
212 f"the run without AMR holds {reference_cells} instead of {start_cells} cells"
213 )
214 if not cells < start_cells:
215 failures.append(
216 f"the mesh has not coarsened ({cells} cells at the end, {start_cells} at the start)"
217 )
218 if coarsened == 0:
219 failures.append("the mesh never coarsened")
220 print(
221 f"final snapshot t={time_stamp:.4f}: {cells} cells ({100.0 * cells / start_cells:.0f}% of the regular grid)"
222 )
223 for name, unknown in [("density", 0), ("energy", 3)]:
224 difference = np.abs(solution[unknown] - reference[unknown])
225 value_range = np.nanmax(reference[unknown]) - np.nanmin(reference[unknown])
226 maximum = np.nanmax(difference)
227 rms = math.sqrt(np.nanmean(difference**2))
228 print(
229 f"{name}: range {value_range:.3f}, max difference {maximum:.3e}, rms difference {rms:.3e}"
230 )
231 if not np.isfinite(maximum) or maximum > args.tolerance * value_range:
232 failures.append(
233 f"{name} differs by {maximum:.3e}, which is more than {args.tolerance} of its range {value_range:.3f}"
234 )
235 if failures:
236 print("FAILED")
237 for failure in failures:
238 print(" -", failure)
239 sys.exit(1)
240 print("PASSED")
mesh_over_time(str run_directory)
Number of leaf cells after each time step.
Definition amr-study.py:88
final_solution(str run_directory, int volumes_per_axis)
Last snapshot, injected piecewise constant onto the regular grid.
Definition amr-study.py:112
run(str work_directory, int levels, arguments)
Generate, build and run the benchmark with the given number of AMR levels.
Definition amr-study.py:38
Interactive visualisation of Peano patch files within Jupyter notebooks.
Definition notebook.py:1