Peano
Loading...
Searching...
No Matches
point-source.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
3r"""!
4
5@page benchmarks_exahype2_euler_point_source Point source (Euler equations)
6
7\tableofcontents
8
9A gas at rest (density one, pressure one) over the unit square is heated by an energy
10source at the origin. The source is a narrow Gaussian that is injected through the
11volumetric source term (exahype2.api.VolumetricSource), as no numerical scheme
12evaluates exahype2.api.PointSource yet. A blast wave runs out of the origin. There is no
13exact solution, so the benchmark is a test of the mesh handling and of the AMR, not of the
14accuracy of the scheme.
15
16## Mesh and memory
17
18Unless --volume-size is given, the script picks the finest regular start grid that fits
19into the available main memory (--memory-fraction of MemAvailable). A regular grid has
20p*3^k volumes per axis (p volumes per patch, 3^k patches). As p is free between 6 and 32,
21the script fills the memory much more closely than 3^d steps in k would allow. The
22footprint of the Finite Volume scheme without AMR was measured as follows (2d, release
23build, peak resident set size):
24
25| volumes | resident set size | per volume |
26|-----------|-------------------|------------|
27| 59 049 | 22 MB | 375 B |
28| 531 441 | 102 MB | 191 B |
29| 4 782 969 | 683 MB | 143 B |
30
31The offset of about 12 MB dominates for small meshes; the slope is 140 B per volume. The
32script assumes 160 B in 2d. For 3d, no measurement is available yet, and the script assumes
33240 B.
34
35## AMR
36
37--amr-levels l:
38
39- l=0: the whole simulation runs on the regular start grid, i.e. the smallest mesh size is
40 --volume-size everywhere.
41- l>0: the simulation starts from the very same regular grid, but the gradient-based
42 refinement criterion (exahype2.api.GradientRefinement) is on throughout. As the start grid
43 is the finest permitted grid, the mesh first coarsens wherever the solution is smooth
44 and refines around the blast wave afterwards. Cells may become l levels (factor 3 each)
45 coarser than the start grid. The criterion looks at the one-sided gradients of density
46 plus energy: it asks for a refinement above --refine-threshold, and for an erase below
47 --erase-threshold.
48
49Result of the runs below (2d, one 8-core workstation, --volume-size 0.001373 --patch-size 9
50--end-time 0.1, i.e. 729^2 volumes, 6561 mesh cells of 9x9 volumes, 343 time steps).
51
52### Volumes coarsened and refined over time
53
54A patch hosts 9x9=81 volumes; the table counts volumes of the leaf cells of the mesh.
55"Coarsened" is the number of volumes that the mesh loses in the interval, "refined" the
56number that it gains. The mesh changes in a few mesh adaptation phases only.
57
58| time interval | l=1 cells | l=1 coarsened | l=1 refined | l=2 cells | l=2 coarsened | l=2 refined |
59|---------------|-----------|---------------|-------------|-----------|---------------|-------------|
60| (0, 0.01] | 6561 -> 1937 | 374 544 | 0 | 6561 -> 1905 | 377 136 | 0 |
61| (0.01, 0.02] | 1937 -> 2385 | 0 | 36 288 | 1905 -> 2353 | 0 | 36 288 |
62| (0.02, 0.06] | 2385 -> 2385 | 0 | 0 | 2353 -> 2353 | 0 | 0 |
63| (0.06, 0.08] | 2385 -> 2801 | 0 | 33 696 | 2353 -> 2801 | 0 | 36 288 |
64| (0.08, 0.10] | 2801 -> 2801 | 0 | 0 | 2801 -> 2801 | 0 | 0 |
65
66l=0 keeps 6561 cells (531 441 volumes) throughout. l=1 ends with 43% of the cells. The
67mesh sizes 0.0123 (start grid) and 0.037 (one level coarser) occur; l=2 allows 0.111 as
68well, but only four such cells exist at t=0.02, and none later. The second level of
69coarsening is hence not exploited yet, and l=2 yields the same final mesh and solution as l=1.
70
71### Quality
72
73Difference of the final solution (t=0.1) between the AMR runs and l=0, evaluated on the
74start grid (a coarse patch is injected piecewise constant into the fine volumes):
75
76| quantity | range of the l=0 solution | maximum difference | root mean square difference |
77|----------|---------------------------|--------------------|-----------------------------|
78| density | 0.162 .. 1.114 | 1.4e-3 | 2.6e-5 |
79| energy | 2.500 .. 2.920 | 5.0e-3 | 9.2e-5 |
80
81AMR hence changes the density by at most 0.15% and the energy by at most 1.2% of their ranges with 43% of the cells. amr-study.py runs this comparison (tolerance 2%) and checks that the mesh has coarsened.
82
83## Run
84
85Configure and build Peano with --enable-exahype --enable-blockstructured
86--enable-loadbalancing, set PYTHONPATH to the repository's src directory, and put the Intel
87compiler on the path. Then
88
89~~~~~~~~~~~~~~~~~~~~~~~
90python3 point-source.py --amr-levels 1 --verbosity text
91~~~~~~~~~~~~~~~~~~~~~~~
92
93generates, builds and compiles the code in the current directory; run ./point-source
94afterwards. The plots are written as Peano patch files. The default end time is short
95(0.01), as the memory-filling mesh takes minutes per time step.
96
97The script uses peano4.api.taskgraph.compiler.FuseSteps rather than the producer-consumer
98task compiler: On meshes of this size, the latter deadlocks in
99tarch::multicore::waitForTasks(), which waits for tasks while it holds the read lock of
100the dependency tracking.
101
102"""
103import argparse
104import os
105
106import peano4.api
107import exahype2.api
108
109
110parser = argparse.ArgumentParser(
111 description="Euler equations with a point source (narrow Gaussian volumetric source)"
112)
113parser.add_argument(
114 "--output-directory",
115 default=".",
116 help="Directory the code is generated and built in (default: .)",
117)
118parser.add_argument(
119 "--amr-levels",
120 type=int,
121 default=0,
122 help="Number of adaptive mesh refinement levels (default: 0). With 0, the "
123 "simulation runs on the regular grid of the smallest volume size. With "
124 "l>0, it starts from the same regular grid, but the gradient-based "
125 "refinement criterion is on and coarsens the mesh by up to l levels (a "
126 "factor of 3 each)",
127)
128parser.add_argument(
129 "--volume-size",
130 type=float,
131 default=None,
132 help="Smallest volume size, i.e. the size on the regular start grid. By "
133 "default, the script picks the finest regular grid that fits into the "
134 "main memory (see --memory-fraction)",
135)
136parser.add_argument(
137 "--memory-fraction",
138 type=float,
139 default=0.8,
140 help="Fraction of the available main memory that the start grid may "
141 "occupy if --volume-size is not given (default: 0.8)",
142)
143parser.add_argument(
144 "--patch-size",
145 type=int,
146 default=None,
147 help="Volumes per mesh cell and axis. By default, the script picks the "
148 "patch size such that the regular start grid fills the memory best",
149)
150parser.add_argument(
151 "--refine-threshold",
152 type=float,
153 default=2.0,
154 help="Mesh cells ask for refinement if the one-sided gradient of density "
155 "plus energy exceeds this value (default: 2)",
156)
157parser.add_argument(
158 "--erase-threshold",
159 type=float,
160 default=0.2,
161 help="Mesh cells ask for coarsening if the one-sided gradient of density "
162 "plus energy falls below this value (default: 0.2)",
163)
164parser.add_argument(
165 "--end-time", type=float, default=0.01, help="Simulated time (default: 0.01)"
166)
167parser.add_argument(
168 "--plots", type=int, default=20, help="Number of snapshots (default: 20)"
169)
170parser.add_argument(
171 "--source-width",
172 type=float,
173 default=0.02,
174 help="Standard deviation of the Gaussian that models the point (default: 0.02)",
175)
176parser.add_argument(
177 "--source-strength",
178 type=float,
179 default=100.0,
180 help="Energy per time and volume at the origin (default: 100)",
181)
182parser.add_argument(
183 "--dimensions", type=int, default=2, choices=[2, 3], help="Dimension (default: 2)"
184)
185parser.add_argument(
186 "--optimistic",
187 action="store_true",
188 help="Use the optimistic Finite Volume scheme",
189)
190parser.add_argument(
191 "--build-mode",
192 default="release",
193 choices=["release", "debug"],
194 help="Peano build flavour to link against (default: release)",
195)
196parser.add_argument(
197 "--peano-root",
198 default=os.path.join(
199 os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", ".."
200 ),
201 help="Configured and built Peano directory (default: the repository this script resides in)",
202)
203parser.add_argument(
204 "--verbosity",
205 default="visualisation",
206 choices=["visualisation", "text"],
207 help="Show the task graphs in a window or print them as text (default: visualisation)",
208)
209args = parser.parse_args()
210
211
212
218BYTES_PER_VOLUME = {2: 160.0, 3: 240.0}
219
220
222 """!
223 Main memory that is available right now (MemAvailable in /proc/meminfo)
224 """
225 with open("/proc/meminfo") as meminfo:
226 for line in meminfo:
227 if line.startswith("MemAvailable:"):
228 return float(line.split()[1]) * 1024.0
229 raise RuntimeError("cannot read MemAvailable from /proc/meminfo")
230
231
232def pick_regular_grid(dimensions: int, budget_in_bytes: float, patch_sizes):
233 """!
234 Pick the finest regular start grid that fits into the budget
235
236 A regular grid over the unit cube consists of 3^k cells per axis, each
237 hosting a patch of p volumes per axis. This yields p*3^k volumes per
238 axis. The patch size p is free within a range, which makes the grid
239 granularity much finer than the factor 3^d between subsequent k.
240
241 @return (patch_size, k)
242 """
243 best = None
244 for patch_size in patch_sizes:
245 k = 0
246 while (patch_size * 3 ** (k + 1)) ** dimensions * BYTES_PER_VOLUME[
247 dimensions
248 ] <= budget_in_bytes:
249 k += 1
250 volumes = (patch_size * 3**k) ** dimensions
251 if volumes * BYTES_PER_VOLUME[dimensions] <= budget_in_bytes and (
252 best is None or volumes > best[0]
253 ):
254 best = (volumes, patch_size, k)
255 return best[1], best[2]
256
257
258if args.volume_size is None:
259 patch_size, k = pick_regular_grid(
260 args.dimensions,
261 args.memory_fraction * available_memory_in_bytes(),
262 [args.patch_size] if args.patch_size is not None else range(6, 33),
263 )
264 # The setup refines every cell whose size is not smaller than
265 # volume_size * patch_size. The factor makes the cell 3^-k the final one.
266 volume_size = 1.001 / (patch_size * 3**k)
267else:
268 patch_size = args.patch_size if args.patch_size is not None else 9
269 volume_size = args.volume_size
270print(
271 f"Start grid: {patch_size} volumes per cell and axis, volume size {volume_size}, "
272 f"AMR levels {args.amr_levels}"
273)
274
275
277 namespace=["benchmarks", "exahype2", "euler", "point_source"],
278 project_name="point-source",
279 directory=args.output_directory,
280 executable="point-source",
281)
282
284 "EulerPointSource", {"rho": 1, "j": args.dimensions, "E": 1}
285)
286solver.add_user_solver_includes(
287 """
288#include <algorithm>
289#include <cmath>
290"""
291)
292
293PRESSURE = """
294 constexpr double gamma = 1.4;
295 const double irho = 1.0 / Q[0];
296 double kineticEnergy = 0.0;
297 for (int d=0; d<Dimensions; d++) {
298 kineticEnergy += 0.5 * irho * Q[1+d] * Q[1+d];
299 }
300 const double p = (gamma - 1.0) * (Q[Dimensions+1] - kineticEnergy);
301"""
302
303solver.add_pde_term(
305 implementation=PRESSURE
306 + """
307 const double velocity = Q[1+normal] * irho;
308 F[0] = Q[1+normal];
309 for (int d=0; d<Dimensions; d++) {
310 F[1+d] = velocity * Q[1+d];
311 }
312 F[1+normal] += p;
313 F[Dimensions+1] = velocity * (Q[Dimensions+1] + p);
314"""
315 )
316)
317solver.add_pde_term(
319 implementation=PRESSURE
320 + """
321 const double c = std::sqrt(gamma * p * irho);
322 const double u = Q[1+normal] * irho;
323 lambdaMax[0] = std::max(std::abs(u + c), std::abs(u - c));
324"""
325 )
326)
327
328# The point is smeared over a few grid cells, as a delta distribution cannot be
329# represented by a Finite Volume scheme. Only the energy equation is fed.
330solver.add_pde_term(
332 implementation=f"""
333 constexpr double sigma = {args.source_width};
334 constexpr double strength = {args.source_strength};
335 for (int i=0; i<NumberOfUnknowns; i++) {{
336 S[i] = 0.0;
337 }}
338 S[Dimensions+1] = strength * std::exp(-0.5 * tarch::la::norm2Squared(x) / (sigma * sigma));
339"""
340 )
341)
342
343# Ambient state: gas at rest with density 1 and pressure 1
344AMBIENT_STATE = """
345 constexpr double gamma = 1.4;
346 Q[0] = 1.0;
347 for (int d=0; d<Dimensions; d++) {
348 Q[1+d] = 0.0;
349 }
350 Q[Dimensions+1] = 1.0 / (gamma - 1.0);
351"""
352solver.add_pde_term(exahype2.api.InitPointWisely(implementation=AMBIENT_STATE))
353solver.add_pde_term(
354 exahype2.api.DirichletBoundaryConditions(implementation=AMBIENT_STATE)
355)
356
357# With AMR, the simulation starts from the finest regular grid, and the
358# gradient criterion is always on. It may only coarsen: the start grid
359# is the finest grid that we allow, and the coarsest volumes are those
360# amr_levels levels (factor 3 each) above the start volumes.
361if args.amr_levels > 0:
362 solver.add_pde_term(
364 implementation=f"""
365 const double indicator = std::abs(gradient[0]) + std::abs(gradient[Dimensions+1]);
366 if (indicator > {args.refine_threshold}) {{
367 *refinementCommand = ::exahype2::RefinementCommand::Refine;
368 }}
369 else if (indicator < {args.erase_threshold}) {{
370 *refinementCommand = ::exahype2::RefinementCommand::Erase;
371 }}
372"""
373 )
374 )
375amr_bounds = dict(
376 min_volume_size=volume_size,
377 max_volume_size=volume_size * 3**args.amr_levels,
378)
379if args.optimistic:
381 solver, patch_size, **amr_bounds
382 )
383else:
384 solver.numerical_scheme = exahype2.api.fv.RusanovWithExplicitEuler(
385 solver, patch_size, **amr_bounds
386 )
388 solver, volume_size=volume_size
389)
391 solver,
392 first_plot_time_stamp=0.0,
393 time_in_between_plots=args.end_time / args.plots,
394)
395project.add_solver(solver)
396
397project.set_global_simulation_parameters(
398 dimensions=args.dimensions,
399 offset=[-0.5] * args.dimensions,
400 size=[1.0] * args.dimensions,
401 min_end_time=args.end_time,
402 max_end_time=args.end_time,
403 periodic_BC=[False] * 3,
404)
405project.set_load_balancing(
406 "toolbox::loadbalancing::strategies::SpreadOutOnceGridStagnates",
407 "new ::exahype2::LoadBalancingConfiguration()",
408)
409# No spawned background tasks: On meshes that fill the main memory, the
410# producer-consumer compiler deadlocks in tarch::multicore::waitForTasks(),
411# which waits for tasks while holding the read lock of the dependency tracking.
412project.compiler = peano4.api.taskgraph.compiler.FuseSteps.translate
413
414project.set_Peano4_installation(
415 args.peano_root,
416 peano4.api.output.CompileMode.RELEASE
417 if args.build_mode == "release"
418 else peano4.api.output.CompileMode.DEBUG,
419)
420peano4_project = project.generate_Peano4_project(
421 verbosity=peano4.api.LoggerVerbosity.TEXT
422 if args.verbosity == "text"
423 else peano4.api.LoggerVerbosity.VISUALISATION
424)
425peano4_project.generate()
426peano4_project.build(make_clean_first=True)
The conservative flux F(Q) of a hyperbolic PDE.
Definition Flux.py:8
Gradient-based refinement criterion: given a one-sided difference quotient of the solution along one ...
Point-wise initial condition: given the physical position of a single degree of freedom,...
The maximum absolute eigenvalue of the flux Jacobian in a given direction, i.e.
ExaHyPE 2 project.
Definition Project.py:15
Abstract base class for all ExaHyPE 2 solvers.
Definition Solver.py:17
The algebraic, volume-distributed source term S(Q) of a hyperbolic PDE - as opposed to PointSource,...
Plotting counterpart to RusanovWithExplicitEuler: maps the patch data of a Finite Volume scheme with ...
Finite Volumes with a Rusanov Riemann solver and explicit Euler time stepping, realised over a block-...
Finite Volumes with a Rusanov Riemann solver and optimistic explicit Euler time stepping,...
Setup phase counterpart to RusanovWithExplicitEuler: sets the initial condition for a Finite Volume s...
float available_memory_in_bytes()
Main memory that is available right now (MemAvailable in /proc/meminfo).
pick_regular_grid(int dimensions, float budget_in_bytes, patch_sizes)
Pick the finest regular start grid that fits into the budget.