Peano
Loading...
Searching...
No Matches
single-black-hole.py
Go to the documentation of this file.
1"""
2
3Single black hole benchmark for the ExaGRyPE Python API
4
5A single Schwarzschild black hole at the origin of the domain [-243,243]^3,
6as described in README.dox. The initial data stems from TwoPunctures, the
7boundaries are Sommerfeld boundaries. The script uses exagrype.api, i.e. the
8CCZ4 solver of the new Python API. Everything that matters for the benchmark
9is configurable on the command line:
10
11- the numerical scheme (--scheme, --rk-order, --ko-sigma, --lopsided),
12- the adaptive mesh refinement (--amr-levels, --amr-radius),
13- the task graph compiler (--compiler),
14- the build variant (--variant), which picks the compile mode and the size of
15 the setup, and
16- the final time (--end-time).
17
18The build variants are
19
20- debug: Peano's debug build with a tiny setup to check that the code works,
21- profile: Peano's build with statistics counters and a reduced setup
22 (domain 172, volumes of size 1) which is small enough to profile on one
23 node, and
24- production: the release build with the setup of README.dox (domain 486,
25 volumes of size 0.4, t=100). This one is far too big for a workstation.
26
27Each variant fixes the defaults of --domain-size, --volume-size and
28--end-time. Pass them explicitly to override them.
29
30Adaptive mesh refinement respects the constraints of README.dox: the
31maximum volume size (--volume-size) is a hard bound, i.e. the mesh is never
32coarser than the regular mesh of this size. The refinement only ever
33subdivides cells around the black hole further, by --amr-levels levels of
34factor three each within --amr-radius of the puncture. It is available for
35both schemes. The fd4 scheme starts on the regular mesh and refines it while
36it time steps; it cannot combine AMR with the Kreiss-Oliger dissipation yet.
37
38It requires a Peano build with
39
40 --enable-exahype --enable-blockstructured --enable-loadbalancing --enable-exagrype --with-gsl
41
42A run of the fourth-order Finite Differences with lopsided advection and
43the Kreiss-Oliger dissipation looks like
44
45 python3 single-black-hole.py --scheme fd4 --rk-order 4 --lopsided --ko-sigma 8.0 \
46 --compiler producer-consumer-fusion --variant profile
47
48and Finite Volumes with two additional levels of adaptive mesh refinement
49around the black hole are
50
51 python3 single-black-hole.py --scheme fv --amr-levels 2 --variant profile
52
53The script writes two kinds of output into the output directory: binary
54checkpoints (--checkpoint-interval, every 10 time units by default) holding
55the whole solver state, and visualisation snapshots in Peano's patch file
56format (--plot-interval, every 1 time unit by default), i.e.
57solution-CCZ4.peano-patch-file and its companion files. The snapshots
58contain all unknowns. probe-single-black-hole.py extracts profiles from
59them. Pass 0 to switch either kind off.
60
61"""
62
63import argparse
64import os
65
66import peano4.api
67import exahype2.api
68import exagrype.api
70import toolbox.loadbalancing.api.strategies.SplitTrees as SplitTrees
71import toolbox.loadbalancing.api.strategies.Decomposition as Decomposition
72import toolbox.loadbalancing.api.output.Hardcoded as Hardcoded
73
74
75Compilers = {
76 "sequential": peano4.api.taskgraph.compiler.Sequential.translate,
77 "fusion-only": peano4.api.taskgraph.compiler.FuseSteps.translate,
78 "producer-consumer-sequential": peano4.api.taskgraph.compiler.CellTaskProducerConsumer.translate_with_sequential,
79 "producer-consumer-fusion": peano4.api.taskgraph.compiler.CellTaskProducerConsumer.translate_with_fusion,
80}
81
82EnforceModes = {
83 mode.name.lower(): mode
84 for mode in exagrype.api.FOCCZ4Solver.EnforceCCZ4Constraint
85}
86
87
88Variants = {
89 "debug": dict(
90 mode=peano4.api.output.CompileMode.DEBUG,
91 domain_size=18.0,
92 volume_size=1.2,
93 end_time=0.5,
94 ),
95 "profile": dict(
96 mode=peano4.api.output.CompileMode.STATS,
97 domain_size=172.0,
98 volume_size=1.2,
99 end_time=1.0,
100 ),
101 "production": dict(
102 mode=peano4.api.output.CompileMode.RELEASE,
103 domain_size=486.0,
104 volume_size=0.4,
105 end_time=100.0,
106 ),
107}
108
109SplitModes = {
110 "bottom-up": Hardcoded.BottomUp,
111 "top-down": Hardcoded.TopDown,
112 "inferred": None,
113}
114
115Verbosities = {
116 mode.name.lower(): mode for mode in peano4.api.LoggerVerbosity
117}
118
119
121 parser = argparse.ArgumentParser(
122 description="Single Schwarzschild black hole with ExaGRyPE",
123 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
124 )
125
126 scheme = parser.add_argument_group("numerical scheme")
127 scheme.add_argument(
128 "--scheme",
129 choices=["fv", "fd4"],
130 default="fd4",
131 help="fv: Rusanov Finite Volumes with explicit Euler. fd4: fourth-order Finite Differences with Runge-Kutta.",
132 )
133 scheme.add_argument(
134 "--rk-order",
135 type=int,
136 choices=[1, 2, 3, 4],
137 default=4,
138 help="Order of the Runge-Kutta time integrator (fd4 only).",
139 )
140 scheme.add_argument(
141 "--ko-sigma",
142 type=float,
143 default=0.0,
144 help="Scaling of the Kreiss-Oliger dissipation (fd4 only). 0 switches the dissipation off.",
145 )
146 scheme.add_argument(
147 "--ko-quantities",
148 type=int,
149 nargs="+",
150 default=None,
151 metavar="Q",
152 help="Indices of the unknowns which are damped by the Kreiss-Oliger dissipation. Default: all.",
153 )
154 scheme.add_argument(
155 "--lopsided",
156 action="store_true",
157 help="Discretise the advection terms along the shift with lop-sided stencils (fd4 only). "
158 "Without it, the solver adds them with central differences.",
159 )
160 scheme.add_argument(
161 "--enforce-constraints",
162 choices=list(EnforceModes),
163 default="no",
164 help="When to push the solution back onto the algebraic CCZ4 constraints.",
165 )
166
167 mesh = parser.add_argument_group("domain and mesh")
168 mesh.add_argument(
169 "--domain-size",
170 type=float,
171 default=None,
172 help="Edge length of the domain. Default: depends on --variant.",
173 )
174 mesh.add_argument(
175 "--volume-size",
176 type=float,
177 default=None,
178 help="Maximum size of a volume or grid cell. The mesh is a regular 3-adic grid, i.e. the actual size is smaller. Default: depends on --variant.",
179 )
180 mesh.add_argument(
181 "--amr-levels",
182 type=int,
183 default=0,
184 help="Number of additional mesh refinement levels (factor 3 each) around the black hole. 0 yields the regular mesh.",
185 )
186 mesh.add_argument(
187 "--amr-radius",
188 type=float,
189 default=12.0,
190 help="Radius around the puncture within which the mesh is refined to the finest level.",
191 )
192 mesh.add_argument(
193 "--patch-size",
194 type=int,
195 default=6,
196 help="Volumes/grid cells per axis per mesh cell. Has to be even, so no volume centre hits the puncture.",
197 )
198 mesh.add_argument("--mass", type=float, default=1.0, help="Mass of the black hole.")
199
200 time = parser.add_argument_group("time and checkpoints")
201 time.add_argument(
202 "--end-time",
203 type=float,
204 default=None,
205 help="Final time. Default: depends on --variant.",
206 )
207 time.add_argument(
208 "--checkpoint-interval",
209 type=float,
210 default=10.0,
211 help="Time between two binary checkpoints. 0 switches checkpointing off.",
212 )
213 time.add_argument(
214 "--plot-interval",
215 type=float,
216 default=1.0,
217 help="Time between two visualisation snapshots. 0 switches the snapshots off.",
218 )
219 time.add_argument(
220 "--first-checkpoint",
221 type=float,
222 default=0.0,
223 help="Time stamp of the first checkpoint and of the first snapshot.",
224 )
225 time.add_argument(
226 "--checkpoint-precision",
227 type=int,
228 default=10,
229 help="Significant digits per value in the visualisation snapshots. Checkpoints are lossless.",
230 )
231
232 balancing = parser.add_argument_group("load balancing")
233 balancing.add_argument(
234 "--load-balancing",
235 choices=["hardcoded", "spread-out"],
236 default="hardcoded",
237 help="hardcoded: decomposition of the regular mesh, computed offline. spread-out: SpreadOutOnceGridStagnates decides at runtime.",
238 )
239 balancing.add_argument(
240 "--decomposition",
241 choices=["equidistant", "quantised"],
242 default="equidistant",
243 help="Chunk sizes of the hardcoded load balancing. equidistant: every tree gets the same number of cells. quantised: chunk sizes are multiples of 3^(k*d) cells, i.e. trees hold (almost) complete subtrees and few virtual cells, but they might be imbalanced.",
244 )
245 balancing.add_argument(
246 "--split-mode",
247 choices=["bottom-up", "top-down", "inferred"],
248 default="bottom-up",
249 help="How Peano picks the cells of a split (hardcoded load balancing only).",
250 )
251 balancing.add_argument(
252 "--trees",
253 type=int,
254 default=os.cpu_count(),
255 help="Number of trees (subdomains) of the hardcoded load balancing. They all live on rank 0, i.e. one tree per thread.",
256 )
257
258 build = parser.add_argument_group("build")
259 build.add_argument(
260 "--compiler",
261 choices=list(Compilers),
262 default="producer-consumer-fusion",
263 help="Task graph compiler, i.e. how time step tasks are mapped onto mesh traversals.",
264 )
265 build.add_argument(
266 "--variant",
267 choices=list(Variants),
268 default="production",
269 help="Build variant: compile mode and default size of the setup.",
270 )
271 build.add_argument(
272 "--verbosity", choices=list(Verbosities), default="text"
273 )
274 build.add_argument(
275 "--output-directory",
276 default=".",
277 help="Directory the code is generated into and the checkpoints are written to.",
278 )
279 build.add_argument(
280 "--peano-directory",
281 default="../../../",
282 help="Root of the Peano installation.",
283 )
284 build.add_argument(
285 "--no-build",
286 action="store_true",
287 help="Generate the code but do not compile it.",
288 )
289 build.add_argument(
290 "--no-clean",
291 action="store_true",
292 help="Do not run make clean before the build.",
293 )
294
295 arguments = parser.parse_args()
296
297 for key, value in Variants[arguments.variant].items():
298 if key != "mode" and getattr(arguments, key) is None:
299 setattr(arguments, key, value)
300
301 if arguments.patch_size % 2 != 0:
302 parser.error("--patch-size has to be even")
303 if arguments.scheme == "fv" and (arguments.ko_sigma > 0.0 or arguments.lopsided):
304 parser.error("--ko-sigma and --lopsided require --scheme fd4")
305 if arguments.ko_quantities is not None and arguments.ko_sigma <= 0.0:
306 parser.error("--ko-quantities requires --ko-sigma > 0")
307 if arguments.amr_levels < 0:
308 parser.error("--amr-levels must not be negative")
309 if arguments.amr_levels > 0 and arguments.scheme == "fd4" and arguments.ko_sigma > 0.0:
310 parser.error("--amr-levels with --scheme fd4 does not support --ko-sigma yet")
311 if arguments.load_balancing == "hardcoded" and arguments.trees < 2:
312 parser.error("--trees has to be at least 2 for the hardcoded load balancing")
313 if arguments.checkpoint_interval < 0.0 or arguments.plot_interval < 0.0:
314 parser.error("--checkpoint-interval and --plot-interval must not be negative")
315 return arguments
316
317
318def create_numerical_scheme(solver, arguments):
319 """! Assign numerical scheme, grid construction and checkpoint plotter to solver"""
320 if arguments.scheme == "fv":
321 package = exahype2.api.fv
322 solver.numerical_scheme = exahype2.api.fv.RusanovWithExplicitEuler(
323 solver,
324 arguments.patch_size,
325 min_volume_size=min_volume_size(arguments),
326 max_volume_size=arguments.volume_size,
327 )
328 else:
329 package = exahype2.api.rkfd4
330 Kernel = exahype2.api.rkfd4.CentralDifferencesWithRungeKutta.RightHandSideKernel
331 options = {}
332 if arguments.lopsided:
333 options = dict(
334 right_hand_side_kernel=Kernel.CentralDifferencesWithLopsidedAdvection,
335 advection_velocity=exagrype.api.FOCCZ4Solver.ADVECTION_VELOCITY,
336 advected_quantities=solver.advected_quantities(),
337 )
338 if arguments.ko_sigma > 0.0:
339 solver.numerical_scheme = exagrype.api.FD4WithKODissipation(
340 solver,
341 arguments.patch_size,
342 rk_order=arguments.rk_order,
343 kreiss_oliger_sigma=arguments.ko_sigma,
344 quantities=arguments.ko_quantities,
345 **options,
346 )
347 else:
348 solver.numerical_scheme = (
349 exahype2.api.rkfd4.CentralDifferencesWithRungeKutta(
350 solver,
351 arguments.patch_size,
352 rk_order=arguments.rk_order,
353 min_volume_size=min_volume_size(arguments),
354 max_volume_size=arguments.volume_size,
355 **options,
356 )
357 )
358
359 if arguments.scheme == "fv":
360 solver.grid_construction = package.SetupSimulationWithUserCodedRefinementCriterion(
361 solver,
362 volume_size=arguments.volume_size,
363 min_volume_size=min_volume_size(arguments),
364 )
365 else:
366 # fd4 has no refinement in the setup: It starts on the regular mesh
367 # and the time stepping refines it
368 solver.grid_construction = package.SetupSimulationOverRegularGrid(
369 solver, volume_size=arguments.volume_size
370 )
371 if arguments.checkpoint_interval > 0.0:
372 solver.add_plotter(
373 package.WriteCheckpoint(
374 solver,
375 first_plot_time_stamp=arguments.first_checkpoint,
376 time_in_between_plots=arguments.checkpoint_interval,
377 output_path=arguments.output_directory,
378 )
379 )
380 if arguments.plot_interval > 0.0:
381 solver.add_plotter(
382 package.PlotAsVTKFile(
383 solver,
384 first_plot_time_stamp=arguments.first_checkpoint,
385 time_in_between_plots=arguments.plot_interval,
386 plotter_precision=arguments.checkpoint_precision,
387 output_path=arguments.output_directory,
388 )
389 )
390
391
392def actual_volume_size(arguments):
393 """! Size of a volume/grid cell the regular 3-adic mesh yields"""
394 cell_size = arguments.domain_size
395 while cell_size >= arguments.volume_size * arguments.patch_size:
396 cell_size /= 3.0
397 return cell_size / arguments.patch_size
398
399
400def min_volume_size(arguments):
401 """! Volumes of this size or bigger may still be refined.
402
403 The regular mesh of --volume-size is the coarsest mesh the benchmark
404 allows (README.dox), so the AMR levels sit on top of its actual volume
405 size. Refining a cell yields volumes strictly smaller than the bound, so
406 the bound is the volume size of the second-finest level, slightly
407 reduced to be robust against rounding. Without AMR levels, the bound
408 would exceed the --volume-size. It is capped there, which is still above the
409 volume size of the regular mesh, i.e. the mesh stays regular.
410 """
411 return min(
412 actual_volume_size(arguments) / 3.0 ** (arguments.amr_levels - 1) * 0.99,
413 arguments.volume_size,
414 )
415
416
417def regular_mesh_levels(arguments):
418 """! Number of refinement levels of the regular 3-adic mesh (see actual_volume_size())"""
419 levels = 0
420 cell_size = arguments.domain_size
421 while cell_size >= arguments.volume_size * arguments.patch_size:
422 cell_size /= 3.0
423 levels += 1
424 return levels
425
426
427def create_load_balancing(arguments):
428 """! Name and constructor arguments of the load balancing strategy
429
430 The hardcoded strategy splits the regular mesh into arguments.trees trees
431 of the same number of cells, i.e. the outcome SpreadOutOnceGridStagnates
432 aims for. The splits are computed offline on a synthetic regular tree
433 along the space-filling curve, and all trees live on rank 0. AMR levels
434 do not enter, as the splits fire once the mesh has reached the regular
435 mesh and are bottom-up.
436 """
437 if arguments.load_balancing == "spread-out":
438 return (
439 "toolbox::loadbalancing::strategies::SpreadOutOnceGridStagnates",
440 "new ::exahype2::LoadBalancingConfiguration()",
441 )
442
443 tree = RegularGridGenerator.RegularGridGenerator(
444 max_level=regular_mesh_levels(arguments), dimensions=3
445 )
446 if arguments.decomposition == "quantised":
447 decomposition = Decomposition.quantised_splitting(
448 peano_tree=tree, number_of_subtrees=arguments.trees, dimension=3
449 )
450 else:
451 decomposition = Decomposition.equidistant_splitting(
452 peano_tree=tree, number_of_subtrees=arguments.trees
453 )
454 SplitTrees.split_tree(
455 tree, decomposition=decomposition, periodic_BC=[False, False, False]
456 )
457 destination_ranks = Hardcoded.assign_trees_to_ranks_round_Robin(
458 number_of_subtrees=tree.number_of_subtrees, max_ranks=1
459 )
460 configuration, _ = Hardcoded.create_constructor_initialisation_string(
461 tree, destination_ranks, modes=SplitModes[arguments.split_mode]
462 )
463 return "toolbox::loadbalancing::strategies::Hardcoded", configuration
464
465
466def main():
467 arguments = parse_arguments()
468
469 project = exahype2.api.Project(
470 namespace=["benchmarks", "exagrype", "singleblackhole"],
471 project_name="single-black-hole",
472 directory=arguments.output_directory,
473 executable="single-black-hole",
474 )
475
476 solver = exagrype.api.FOCCZ4Solver(
477 "CCZ4",
478 parameters={"CCZ4b": 1, "CCZ4s": 1},
479 )
480 solver.add_pde_term(
481 exagrype.api.initialvalues.single_black_hole(mass=arguments.mass)
482 )
483 solver.enforce_ccz4_constraint(EnforceModes[arguments.enforce_constraints])
484 solver.add_pde_term(
485 exahype2.api.SommerfeldBoundaryConditions(
486 implementation="::exagrype::initialvalues::flat(Q, x, 0.0);"
487 )
488 )
489 # The criterion never asks for an erase. The mesh is a function of the
490 # position only, i.e. it is static, and it never coarsens below the
491 # regular mesh anyway. Without AMR levels, the volume size bound keeps
492 # the mesh regular.
493 solver.add_pde_term(
494 exahype2.api.RefineErasePointwisely(
495 implementation=f"""
496 const double r2 = tarch::la::norm2Squared(x);
497 if (r2 < {arguments.amr_radius ** 2}) *refinementCommand = ::exahype2::RefinementCommand::Refine;
498"""
499 )
500 )
501 create_numerical_scheme(solver, arguments)
502 project.add_solver(solver)
503
504 project.compiler = Compilers[arguments.compiler]
505
506 half_size = arguments.domain_size / 2.0
507 project.set_global_simulation_parameters(
508 dimensions=3,
509 offset=[-half_size] * 3,
510 size=[arguments.domain_size] * 3,
511 min_end_time=arguments.end_time,
512 max_end_time=arguments.end_time,
513 periodic_BC=[False, False, False],
514 )
515
516 project.set_load_balancing(*create_load_balancing(arguments))
517
518 project.set_Peano4_installation(
519 arguments.peano_directory, Variants[arguments.variant]["mode"]
520 )
521 peano4_project = project.generate_Peano4_project(
522 verbosity=Verbosities[arguments.verbosity]
523 )
524 peano4_project.generate()
525
526 h = actual_volume_size(arguments)
527 print(
528 f"Volume size {h:.6g} ({round(arguments.domain_size / h)} volumes per axis), "
529 f"scheme {arguments.scheme}, {arguments.amr_levels} AMR levels, "
530 f"variant {arguments.variant}, compiler {arguments.compiler}, "
531 f"end time {arguments.end_time}"
532 )
533
534 if not arguments.no_build:
535 peano4_project.build(make_clean_first=not arguments.no_clean)
536
537
538if __name__ == "__main__":
539 main()
Controls how much detail Logger.log()/new_section() print to the console.
Definition Logger.py:20
This file is part of the ExaGRyPE project.
Definition __init__.py:1
create_numerical_scheme(solver, arguments)
Assign numerical scheme, grid construction and checkpoint plotter to solver.