Peano
Loading...
Searching...
No Matches
Solver.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
3from __future__ import annotations
4
5import abc
6import re
7from typing import Callable, Dict, List, Tuple, Union
8
9import peano4.api
11
12from .PDETerm import PDETerm
13
14VariableSpecification = Union[int, Dict[str, int]]
15
16
17class Solver(abc.ABC):
18 """!
19
20 Abstract base class for all ExaHyPE 2 solvers
21
22 Every discretisation ExaHyPE 2 ships (Finite Volumes, ADER-DG, Runge-Kutta
23 Discontinuous Galerkin, Runge-Kutta Finite Differences, ...) is, from the
24 project's point of view, a black box that has to answer a small set of
25 questions: what data does it need on the mesh, which action sets realise
26 its algorithmic steps, and how does it plug into the code generation. This
27 class holds exactly that common contract plus the bits of bookkeeping
28 (name, includes, solver constants, the unknowns and the
29 auxiliary variables) that every concrete solver has historically
30 reimplemented identically. It does not know anything about a concrete
31 discretisation - it neither creates the actual mesh data structures nor
32 the actual action sets, as this remains solver-specific and thus has to be
33 added by all subclasses.
34
35 A concrete solver typically extends the constructor with its own
36 discretisation-specific parameters (patch size, polynomial order, time
37 stepping scheme, ...), calls `Solver.__init__()` for the shared part, and
38 then implements the abstract methods below.
39
40 @see exahype2.api.Project
41
42 """
43
45 """!
46
47 Turns a Solver into actual classes.
48
49 """
50
51 def __init__(self, solver: "Solver"):
52 self._solver = solver
53
54 @abc.abstractmethod
55 def construct_output(self, exahype2_project, peano_project):
56 """!
57 Has to be implemented by subclass
58 """
59
60 class NumericalScheme(abc.ABC):
61 """!
62
63 The concrete discretisation (Finite Volumes, ADER-DG, ...) realised
64 by a Solver. Abstract - concrete solvers have to provide a subclass
65 that implements construct_output().
66
67 """
68
69
73 DYNAMIC_MESH_REFINEMENT_TASK_NAME = "Dynamic mesh refinement and load balancing"
74
75 def __init__(self, solver: "Solver"):
76 """!
77
78 @param solver: exahype2.api.Solver
79 The solver which the scheme discretises.
80
81 """
82 self._solver = solver
84
85 @abc.abstractmethod
87 self, exahype2_project, peano_project, time_step, add_global_tasks=True
88 ):
89 """!
90 Has to be implemented by subclass
91
92 time_step: peano4.api.taskgraph.Graph
93 The task graph of the surrounding exahype2_project's time
94 stepping phase, so the numerical scheme can add its own tasks
95 into it.
96
97 @param add_global_tasks: bool
98 Whether the scheme adds the tasks that belong to the mesh as a
99 whole rather than to the solver: it switches the load
100 balancing off at the begin of the time step, and its last task
101 evaluates the adaptivity criterion and switches the load
102 balancing on again. If set, the scheme adds these tasks by calling
103 wrap_task_graph_in_load_balancing_and_amr_tasks() as its very
104 last step. A host that couples several solvers passes False,
105 as it wraps the concatenated graph itself.
106 """
107
109 """!
110
111 Embed the time step's task graph into the global load balancing and AMR tasks
112
113 The routine adds two tasks to time_step:
114
115 - {SolverName}_Disable load balancing: switches the load
116 balancing off throughout the time step. All tasks of the graph
117 that do not depend on anything else wait for it.
118 - {SolverName}_Dynamic mesh refinement and load balancing
119 (DYNAMIC_MESH_REFINEMENT_TASK_NAME): evaluates the adaptivity
120 criterion if the solver has one, i.e. it collects the refine and
121 erase requests for the mesh adaptation phase, and then
122 switches the load balancing on again and informs it that the
123 time step has finished. It waits for all tasks of the graph that
124 nothing else waits for. Global tasks do not count: The
125 task runs last in the step, so no other task may wait for it.
126
127 The tasks pick up whatever is in time_step when the routine is
128 called. Consequently, construct_output() calls it last if its flag
129 add_global_tasks is set, i.e. after all tasks of the scheme have
130 been added. A coupling that merges the graphs of several solvers
131 (@ref page_exahype_programmers_guide_coupling) calls it on the merged graph
132 instead.
133
134 Schemes that do not own a mesh override the routine with an empty
135 one.
136
137 @param time_step: peano4.api.taskgraph.Graph
138 The graph to wrap. It receives the two tasks.
139
140 """
141 import toolbox.loadbalancing.api.actionsets
142 from .blockstructured.create_dynamic_mesh_refinement_action_set import (
143 create_dynamic_mesh_refinement_action_set,
144 )
145
146 Entity = peano4.api.taskgraph.Task.GridEntity
147 Access = peano4.api.taskgraph.Task.DataAccess
148 solver = self._solver
149
150 def is_global(task):
151 return task.entity.is_global
152
153 sources = [
154 task
155 for task in time_step.tasks
156 if not is_global(task) and not task.dependencies
157 ]
158 sinks = [
159 task
160 for task in time_step.tasks
161 if not is_global(task)
162 and not any(
163 task in other.dependencies
164 for other in time_step.tasks
165 if not other.entity == Entity.GLOBAL_END_OF_STEP
166 )
167 ]
168
169 disable_task = peano4.api.taskgraph.Task(
170 name=f"{solver.name}_Disable load balancing", entity=Entity.CELL
171 )
172 disable_task.add_action_set(
173 toolbox.loadbalancing.api.actionsets.ToggleLoadBalancing(
174 enable_load_balancing=False, plug_into_prepare_traversal=True
175 )
176 )
177 for source in sources:
178 source.add_dependency(disable_task)
179 time_step.add_task(disable_task)
180
181 refinement_task = peano4.api.taskgraph.Task(
182 name=f"{solver.name}_{self.DYNAMIC_MESH_REFINEMENT_TASK_NAME}",
183 entity=Entity.CELL,
184 may_spawn_background_tasks=False,
185 )
186 refinement_task.use_cell(solver._patch, Access.READ_AND_WRITE)
187 dynamic_mesh_refinement = create_dynamic_mesh_refinement_action_set(
188 solver,
189 self.patch_size,
190 guard=solver.grid_selector.createCellGuard(),
191 min_volume_size=self.min_volume_size,
192 max_volume_size=self.max_volume_size,
193 )
194 if dynamic_mesh_refinement is not None:
195 refinement_task.add_action_set(dynamic_mesh_refinement)
196 refinement_task.add_action_set(
197 toolbox.loadbalancing.api.actionsets.LoadBalancing(
198 enable_load_balancing=True
199 )
200 )
201 for sink in sinks:
202 refinement_task.add_dependency(sink)
203 time_step.add_task(refinement_task)
204
205 def create_default_mesh_adaptation(self) -> "Solver.MeshAdaptation":
206 """!
207
208 The mesh adaptation a solver uses if the user does not assign
209 one to solver.mesh_adaptation
210
211 @return Solver.MeshAdaptation or None
212 The default returns None, i.e. the solver does not contribute
213 to the mesh adaptation phase.
214
215 """
216 return None
217
219 """!
220 Specify which versions of a numerical scheme should be generated here.
221 Each configuration specifies the target architecture and whether the variant
222 is stateless.
223 The multiple configurations can generate multiple verisons of a function for
224 the purpose of microbenchmarking, but a kernel call is only generated for one
225 at a time.
226 """
227 def __init__(self, solver: Solver, configurations: list[tuple[Target, bool]]):
228 self._solver = solver
229 self._configurations = configurations
230
231 def reset_configurations(self, target: Target, stateless: bool):
232 self._configurations.clear()
233
234 def add_configuration(self, target: Target, stateless: bool):
235 self._configurations.append((target, stateless))
236
238 self, exahype2_project, peano_project, time_step, add_global_tasks=True
239 ):
240 pass
241
242 class GridConstruction(abc.ABC):
243 """!
244
245 How a Solver drives the construction of the mesh it runs on.
246 Abstract - concrete solvers have to provide a subclass that
247 implements construct_output().
248
249 """
250
251 def __init__(self, solver: "Solver"):
252 self._solver = solver
253
254 @abc.abstractmethod
255 def construct_output(self, exahype2_project, peano_project, setup_simulation):
256 """!
257 Has to be implemented by subclass
258
259 setup_simulation: peano4.api.taskgraph.Graph
260 The task graph of the surrounding exahype2_project's setup
261 phase, so the grid construction can add its own tasks into it.
262 """
263
264 class Plotter(abc.ABC):
265 """!
266
267 How a Solver writes out its solution. Abstract - concrete solvers
268 have to provide a subclass that implements construct_output().
269
270 A solver can have an arbitrary number of plotters
271 (@ref exahype2.api.Solver.Solver.add_plotter()), e.g. one which
272 writes VTK files for visualisation and one which writes
273 checkpoints. Each plotter has a name which is unique per solver,
274 and it decides itself when it is active. For this, it gives its
275 solver's C++ class a method
276
277 ~~~~~~~~~~~~~~~~~~~~~~~
278 bool is<Name>Active() const;
279 ~~~~~~~~~~~~~~~~~~~~~~~
280
281 The solver's
282
283 ~~~~~~~~~~~~~~~~~~~~~~~
284 bool wantsToPlot() const;
285 ~~~~~~~~~~~~~~~~~~~~~~~
286
287 holds if any of its plotters is active. The generated main asks all
288 solvers with a plotter (repositories::wantsToPlot()) and runs the
289 plot phase if any of them wants to plot. The task graphs of all
290 plotters of all solvers are added to the one plot graph, which the
291 graph compiler then maps onto grid sweeps. Within the plot phase,
292 every action set of a plotter is guarded by its plotter's
293 is<Name>Active(), so only the active plotters do any work.
294
295 is<Name>Active() must not change throughout the plot phase. Each
296 plotter therefore calls its
297
298 ~~~~~~~~~~~~~~~~~~~~~~~
299 void finish<Name>();
300 ~~~~~~~~~~~~~~~~~~~~~~~
301
302 which moves it on to its next output, in the unprepareTraversal() of
303 its last task, i.e. after all of its tasks have run.
304
305 The class provides this bookkeeping for plotters which write output
306 in regular time intervals (_add_time_interval_bookkeeping_to_solver()).
307
308 """
309
310 def __init__(self, solver: "Solver", name: str = None):
311 """!
312
313 @param solver: exahype2.api.Solver
314 The solver whose solution is written.
315
316 @param name: str or None
317 Name of the plotter, which is unique per solver. It becomes
318 part of the generated C++ method names, i.e. it has to be a
319 valid C++ identifier. If None, the solver derives a name from
320 the plotter's class name once the plotter is added
321 (@ref exahype2.api.Solver.Solver.add_plotter()).
322
323 """
324 self._solver = solver
325 if name is not None and not name.isidentifier():
326 raise ValueError(f"Plotter name {name} is no valid C++ identifier")
327 self.name = name
328
329 @abc.abstractmethod
330 def construct_output(self, exahype2_project, peano_project, plot):
331 """!
332 Has to be implemented by subclass
333
334 plot: peano4.api.taskgraph.Graph
335 The task graph of the surrounding exahype2_project's plotting
336 phase, so the plotter can add its own tasks into it.
337 """
338
339 def output_file_prefix(self) -> str:
340 """!
341
342 Prefix of the files the plotter writes, including the path
343
344 The solver uses it to ensure that no two plotters write into
345 the same files. Plotters which write no files return None.
346
347 """
348 return None
349
351 """!
352
353 C++ predicate which holds if the plotter is active
354
355 Combine the guards of all of the plotter's action sets with it.
356
357 """
358 return (
359 "repositories::"
361 + ".is"
362 + self.name
363 + "Active()"
364 )
365
366 def create_finish_call(self) -> str:
367 """!
368
369 C++ statement which moves the plotter on to its next output
370
371 Insert it into the unprepareTraversal() of the plotter's last
372 task.
373
374 """
375 return (
376 "repositories::"
378 + ".finish"
379 + self.name
380 + "();\n"
381 )
382
384 self, first_time_stamp: float, time_in_between: float
385 ):
386 """!
387
388 Make the plotter active in regular time intervals
389
390 Add the attribute _next<Name>TimeStamp plus the methods
391 is<Name>Active() and finish<Name>() to the solver's C++ class.
392 The plotter is active as soon as the solver's min time stamp has
393 reached _next<Name>TimeStamp. finish<Name>() then increments
394 _next<Name>TimeStamp by time_in_between.
395
396 The solver keeps these members once added, so we add them only
397 once, even if the Peano 4 project is generated multiple times.
398
399 @param first_time_stamp: float
400 Time stamp of the first output.
401
402 @param time_in_between: float
403 Time in between two outputs. Has to be positive.
404
405 """
406 attribute = (
407 "double _next"
408 + self.name
409 + "TimeStamp = "
410 + repr(float(first_time_stamp))
411 + ";"
412 )
413 if attribute in self._solver._abstract_solver_attributes:
414 return
415
418 "bool is" + self.name + "Active() const;",
419 lambda qualified_class_name: "bool "
420 + qualified_class_name
421 + "::is"
422 + self.name
423 + "Active() const {\n"
424 " return tarch::la::greaterEquals(getMinTimeStamp(), _next"
425 + self.name
426 + "TimeStamp);\n"
427 "}\n",
428 )
430 "void finish" + self.name + "();",
431 lambda qualified_class_name: "void "
432 + qualified_class_name
433 + "::finish"
434 + self.name
435 + "() {\n"
436 " if (is" + self.name + "Active()) {\n"
437 " _next"
438 + self.name
439 + "TimeStamp += "
440 + repr(float(time_in_between))
441 + ";\n"
442 " }\n"
443 "}\n",
444 )
445
446 class MeshAdaptation(abc.ABC):
447 """!
448
449 How a Solver adapts its mesh and rebalances its load between two
450 time steps. Abstract - concrete solvers have to provide a subclass
451 that implements construct_output().
452
453 The mesh adaptation is the fourth phase of an ExaHyPE 2 project
454 next to the setup, the time stepping and the plotting. The
455 generated main runs it right after a time step, and only if this
456 time step has asked for a mesh refinement or erase, or if the load
457 balancing has split recently (@ref exahype2::isMeshAdaptationRequired()).
458 The phase is optional: Solvers without a MeshAdaptation do not
459 contribute to it, and the main never runs an empty phase.
460
461 The mesh adaptation does not decide where to refine or erase. The
462 numerical scheme's last task of the time step collects these
463 requests (@ref exahype2.api.blockstructured.DynamicMeshRefinement),
464 and the mesh adaptation realises them.
465
466 """
467
468 def __init__(self, solver: "Solver"):
469 self._solver = solver
470
471 @abc.abstractmethod
472 def construct_output(self, exahype2_project, peano_project, mesh_adaptation):
473 """!
474 Has to be implemented by subclass
475
476 mesh_adaptation: peano4.api.taskgraph.Graph
477 The task graph of the surrounding exahype2_project's mesh
478 adaptation phase, so the mesh adaptation can add its own tasks
479 into it.
480 """
481
482
483
504 SolutionUpdateTaskTag = "exahype2.api.Solver.SolutionUpdateTaskTag"
505
506
513 IntermediateSolutionUpdateTag = "exahype2.api.Solver.IntermediateSolutionUpdateTag"
514
516 self,
517 name: str,
518 unknowns: VariableSpecification,
519 ):
520 """!
521
522 Create solver
523
524 name: str
525 A unique name for the solver. This one is used for all generated
526 classes. The generated C++ object instance also incorporates this
527 name.
528
529 unknowns: int or dict
530 Number of unknowns per mesh entry (Finite Volume voxel, DG degree of
531 freedom, ...). Can be specified either as a plain int, or as a dict
532 mapping variable name onto multiplicity (e.g.
533 `{"rho": 1, "j": 3}` for a scalar density plus a 3d momentum). If
534 dicts are used, the generated Abstract<SolverName> class hosts a
535 nested struct Variables with one constant per name, so user code
536 can write Q[Variables::j+1] instead of having to remember the
537 offset into the unknowns array by hand.
538
539 Quantities which are space-dependent yet do not change over time are
540 not unknowns. Attach them to the solver as auxiliary variables via
541 add_auxiliary_variables().
542
543 The unknowns cannot be changed after construction: the numerical
544 scheme sizes its data structures from them as soon as it is assigned
545 to the solver.
546
547 """
548 self._name = name
549
550 # Offset of each named unknown within Q. Empty if no names are used.
551 self._variable_positions: Dict[str, int] = {}
552
553 self._unknowns = self._register_variables(unknowns, 0)
554
555 # All sets of auxiliary variables in the order of their attachment
556 self._auxiliary_variables: List["AuxiliaryVariables"] = []
557
560
561 self._pde_terms: Dict[Tuple[str, bool], PDETerm] = {}
562
563 # Raw C++ member declarations/methods to splice into the generated
564 # Abstract<SolverName> class, on top of the PDE terms above -
565 # nothing here by default, @see add_abstract_solver_attribute()/
566 # add_abstract_solver_method().
567 self._abstract_solver_attributes: List[str] = []
568 self._abstract_solver_methods: List[Tuple[str, Callable[[str], str]]] = []
569
570 # Deferred/local imports: these classes all subclass either one of
571 # the Solver.* nested classes above or a class from a sibling
572 # exahype2 subpackage, and some of those in turn import Solver at
573 # their own module top-level. Importing them here too (at Solver.py's
574 # top level) would be a genuine circular import, since this module's
575 # own import of them would then run before class Solver is even
576 # defined.
577 from .SolverToCPPFiles import SolverToCPPFiles
578
580
581 # NumericalScheme has no default realisation - concrete solver
582 # subclasses have to assign their own subclass instance to it,
583 # through the numerical_scheme property below.
584 self._numerical_scheme: "Solver.NumericalScheme" = None
585
586 # GridConstruction has no default realisation - concrete solver
587 # subclasses (or their users) have to assign their own
588 # Solver.GridConstruction subclass instance to it, e.g.
589 # exahype2.api.fv.SetupSimulationOverRegularGrid, through the
590 # grid_construction attribute below.
591 self.grid_construction: "Solver.GridConstruction" = None
592
593 # Plotters have no default realisation - users add their own
594 # Solver.Plotter subclass instances, e.g.
595 # exahype2.api.fv.PlotAsVTKFile, via add_plotter().
596 self._plotters: List["Solver.Plotter"] = []
597
598 # MeshAdaptation is optional. Without one, the solver does not
599 # contribute to the mesh adaptation phase. Users can assign their
600 # own Solver.MeshAdaptation subclass instance to it through the
601 # mesh_adaptation attribute below.
602 self.mesh_adaptation: "Solver.MeshAdaptation" = None
603
604 # Selects the mesh entities on which all action sets of this solver
605 # act: Each action set's guard is the corresponding output of this
606 # selector. By default, the solver works on the finest mesh level
607 # only. Users can assign any other peano4.api.toolbox.GridSelector.
610 )
611
612 # The kernel function calls are generated as late as possible, to
613 # ensure that all PDE terms and the numerical scheme have been
614 # specified
615 self.compute_kernel_call: str = None
616
617 def _register_variables(self, variables: VariableSpecification, offset: int) -> int:
618 """!
619
620 Translate a plain int or a name-to-multiplicity dict into a total
621 variable count, and - for the dict case - add each name's position
622 within Q to _variable_positions. Called once for unknowns (offset 0)
623 so the names end up in one name/offset table.
624
625 """
626 if isinstance(variables, dict):
627 for variable_name, multiplicity in variables.items():
628 if variable_name in self._variable_positions:
629 raise ValueError(
630 f"Solver {self._name}: variable name {variable_name} is used twice"
631 )
632 self._variable_positions[variable_name] = offset
633 offset += multiplicity
634 return sum(variables.values())
635 elif isinstance(variables, int):
636 return variables
637 else:
638 raise TypeError(
639 "unknowns have to be an int or a dict "
640 "mapping variable name onto multiplicity, but got "
641 f"{type(variables)}"
642 )
643
644 def __str__(self) -> str:
645 return (
646 "Name: " + self._name + "\n"
647 "Type: " + self.__class__.__module__ + "\n"
648 "Unknowns: " + str(self._unknowns) + "\n"
649 "Auxiliary vars: " + ", ".join(str(m) for m in self._auxiliary_variables)
650 )
651
652 @property
653 def name(self) -> str:
654 """!
655 Unique solver name. Feeds into all generated class and instance names.
656 """
657 return self._name
658
659 @property
660 def numerical_scheme(self) -> "Solver.NumericalScheme":
661 return self._numerical_scheme
662
663 @numerical_scheme.setter
664 def numerical_scheme(self, value: "Solver.NumericalScheme"):
665 if not isinstance(value, Solver.NumericalScheme):
666 raise TypeError(
667 "numerical_scheme has to be a Solver.NumericalScheme, but got "
668 f"{type(value)}"
669 )
670 self._numerical_scheme = value
671
672 @property
673 def plotters(self) -> List["Solver.Plotter"]:
674 """!
675 All plotters of the solver, in the order they have been added.
676 """
677 return list(self._plotters)
678
679 def add_plotter(self, plotter: "Solver.Plotter"):
680 """!
681
682 Add a plotter to the solver
683
684 A solver can have an arbitrary number of plotters, which are
685 independent of each other (@ref exahype2.api.Solver.Solver.Plotter).
686 If the plotter has no name yet, it gets the name of its class,
687 followed by a number if the solver has another plotter of that name
688 already.
689
690 @param plotter: exahype2.api.Solver.Plotter
691 The plotter. Its solver has to be this solver.
692
693 """
694 if not isinstance(plotter, Solver.Plotter):
695 raise TypeError(
696 f"plotter has to be a Solver.Plotter, but got {type(plotter)}"
697 )
698 if plotter._solver is not self:
699 raise ValueError(
700 f"Plotter {type(plotter).__name__} belongs to another solver than {self._name}"
701 )
702 names = [p.name for p in self._plotters]
703 if plotter.name is None:
704 name = type(plotter).__name__
705 counter = 2
706 while name in names:
707 name = type(plotter).__name__ + str(counter)
708 counter += 1
709 plotter.name = name
710 elif plotter.name in names:
711 raise ValueError(
712 f"Solver {self._name} has a plotter named {plotter.name} already"
713 )
714 prefix = plotter.output_file_prefix()
715 if prefix is not None and prefix in [
716 p.output_file_prefix() for p in self._plotters
717 ]:
718 raise ValueError(
719 f"Plotter {plotter.name} of solver {self._name} would write into "
720 f"the files {prefix}* of another plotter. Give it another file "
721 "name or output path."
722 )
723 self._plotters.append(plotter)
724
725 @property
726 def plotter(self) -> "Solver.Plotter":
727 """!
728
729 Shorthand for solvers with at most one plotter
730
731 Reading it yields the solver's only plotter, or None if it has none.
732 Assigning a plotter replaces all plotters of the solver by this one,
733 assigning None removes all plotters. Use add_plotter() to give a
734 solver more than one plotter.
735
736 """
737 if len(self._plotters) > 1:
738 raise RuntimeError(
739 f"Solver {self._name} has {len(self._plotters)} plotters. Use the plotters property."
740 )
741 return self._plotters[0] if self._plotters else None
742
743 @plotter.setter
744 def plotter(self, value: "Solver.Plotter"):
745 self._plotters = []
746 if value is not None:
747 self.add_plotter(value)
748
749 @property
750 def unknowns(self) -> int:
751 return self._unknowns
752
753 @property
754 def auxiliary_variables(self) -> List["AuxiliaryVariables"]:
755 """! All sets of auxiliary variables in the order they have been attached """
756 return list(self._auxiliary_variables)
757
758 @property
760 """! Total number of entries of all sets of auxiliary variables """
761 return sum(auxiliary.size for auxiliary in self._auxiliary_variables)
762
763 def auxiliary_variable_offset(self, auxiliary: "AuxiliaryVariables") -> int:
764 """!
765 Offset of the first entry of a set within the buffer the compute
766 kernels work on, i.e. the unknowns are followed by the sets in the
767 order of their attachment.
768 """
769 offset = self._unknowns
770 for candidate in self._auxiliary_variables:
771 if candidate is auxiliary:
772 return offset
773 offset += candidate.size
774 raise ValueError(f"{auxiliary.name} is not attached to solver {self._name}")
775
776 def add_auxiliary_variables(self, auxiliary: "AuxiliaryVariables"):
777 """!
778
779 Attach a set of auxiliary variables to the solver
780
781 Any number of sets can be attached. They have to be attached before
782 the code is generated. Each set is held by its own cell data object.
783 The first solver which a set is attached to owns it and initialises
784 it. Further solvers can attach the same set object and thereby share
785 the data. @ref exahype2.api.AuxiliaryVariables explains the impact
786 on the C++ signatures.
787
788 @param auxiliary: exahype2.api.AuxiliaryVariables
789
790 """
791 from .AuxiliaryVariables import AuxiliaryVariables
792
793 if not isinstance(auxiliary, AuxiliaryVariables):
794 raise TypeError(
795 f"auxiliary has to be a AuxiliaryVariables, but got {type(auxiliary)}"
796 )
797 if any(m is auxiliary for m in self._auxiliary_variables):
798 raise ValueError(
799 f"Solver {self._name} has the auxiliary variables {auxiliary.name} already"
800 )
801 if any(m.name == auxiliary.name for m in self._auxiliary_variables):
802 raise ValueError(
803 f"Solver {self._name} has other auxiliary variables of name {auxiliary.name} already"
804 )
805 if auxiliary.argument_name == auxiliary.name:
806 raise ValueError(f"Auxiliary variables {auxiliary.name} are not distinguishable from their argument")
807 if auxiliary.owner is None:
808 auxiliary._owner = self
809 self._auxiliary_variables.append(auxiliary)
810
811 def signature_of(self, term: PDETerm) -> str:
812 """! The signature of a PDE term including the pointers to the auxiliary variables """
813 from .AuxiliaryVariables import extend_signature
814
815 return extend_signature(term.SIGNATURE, self)
816
817 @property
818 def user_solver_includes(self) -> str:
819 """!
820 Add further includes to this property, if your solver requires some
821 additional routines from other header files.
822 """
823 return self._user_solver_includes
824
825 def add_user_solver_includes(self, value: str):
826 """!
827 Add further includes to this property, if your solver requires some
828 additional routines from other header files.
829 """
830 self._user_solver_includes += value
831
832 def _get_default_includes(self) -> str:
833 """!
834 Includes every generated action set can rely on being available,
835 regardless of which action sets a concrete discretisation (e.g.
836 exahype2.api.fv) actually attaches - @see
837 exahype2.api.fv.actionsets.AbstractFVActionSet.get_includes().
838 """
839 return """
840#include "tarch/la/Vector.h"
841
842#include "peano4/utils/Globals.h"
843#include "peano4/utils/Loop.h"
844
845#include "repositories/SolverRepository.h"
846"""
847
848 def set_solver_constants(self, datastring: str):
849 self._solver_constants = datastring
850
851 def add_solver_constants(self, datastring: str):
852 self._solver_constants += datastring + "\n"
853
854 def _unknown_identifier(self) -> str:
855 return self._name + "Q"
856
857 def variable_names_per_entry(self) -> List[str]:
858 """!
859
860 One name per entry of Q, i.e. for the unknowns, or the empty list if
861 the unknowns carry no names. A variable with multiplicity one keeps
862 its name, whereas a variable v with multiplicity k yields the names
863 v[0], ..., v[k-1], i.e. the entries Q[Variables::v+0], ...,
864 Q[Variables::v+k-1]. Plotters use these names to label the entries in
865 their output. The names of the auxiliary variables are available
866 from the sets.
867
868 """
869 positions = list(self._variable_positions.items())
870 names = []
871 for i, (variable_name, position) in enumerate(positions):
872 next_position = (
873 positions[i + 1][1] if i + 1 < len(positions) else self._unknowns
874 )
875 multiplicity = next_position - position
876 if multiplicity == 1:
877 names.append(variable_name)
878 else:
879 names += [f"{variable_name}[{j}]" for j in range(multiplicity)]
880 return names
881
883 return "instanceOf" + self._name
884
885 @property
886 def pde_terms(self) -> List[PDETerm]:
887 """!
888 All PDE terms (flux, eigenvalues, ...) registered with this solver,
889 in registration order. A given name can appear at most twice - once
890 stateless, once not, @see add_pde_term() - since each generates a
891 different C++ method. Read-only - use add_pde_term() to add one and
892 remove_pde_term() to take one away again.
893 """
894 return list(self._pde_terms.values())
895
896 @property
897 def requires_user_class(self) -> bool:
898 """!
899 True iff at least one PDE term has no implementation. Only then
900 does the user have to provide one, i.e. only then is a
901 <SolverName> class derived from Abstract<SolverName> generated
902 and added to the Makefile (@see exahype2.api.SolverToCPPFiles).
903 Otherwise, Abstract<SolverName> is complete and the solver
904 repository instantiates it directly. Stateless terms always carry
905 an implementation (@see PDETerm), so they never require one.
906 """
907 return any(term.implementation is None for term in self.pde_terms)
908
909 def get_name_of_solver_class(self) -> str:
910 """!
911 Name of the C++ class the solver repository instantiates:
912 <SolverName> if requires_user_class, Abstract<SolverName> otherwise.
913 """
914 return self._name if self.requires_user_class else "Abstract" + self._name
915
916 def add_pde_term(self, term: PDETerm):
917 """!
918
919 Register a PDE term with this solver, or replace the one already
920 registered under the same name and statelessness. A solver
921 aggregates an arbitrary number of terms - the well-known ones
922 (Flux(), MaxEigenvalue(), ...) as well as new, solver-specific ones
923 users construct themselves via PDETerm(name=..., implementation=...).
924
925 Each term generates exactly one C++ method: the static,
926 GPU-offloadable overload if term.stateless, otherwise the virtual
927 instance method (@see PDETerm.Generator.generate_declaration()),
928 never both. To get both variants of the same conceptual operation
929 (e.g. a stateless flux for GPU kernels and a stateful one for
930 everything else), add the term twice - once with stateless=True,
931 once without - which is why terms are keyed by (name, stateless)
932 rather than by name alone.
933
934 """
935 if not isinstance(term, PDETerm):
936 raise TypeError(f"term has to be a PDETerm, but got {type(term)}")
937 self._pde_terms[(term.name, term.stateless)] = term
938
939 def remove_pde_term(self, name: str, stateless: bool = False):
940 """! Remove a previously registered PDE term by name and statelessness."""
941 del self._pde_terms[(name, stateless)]
942
943 def get_pde_term(self, name: str, stateless: bool = False) -> PDETerm:
944 """! Look up a previously registered PDE term by name and statelessness."""
945 return self._pde_terms[(name, stateless)]
946
947 def add_abstract_solver_attribute(self, declaration: str):
948 """!
949
950 Add a raw C++ member attribute declaration to the generated
951 Abstract<SolverName> class (@see exahype2.api.SolverToCPPFiles),
952 e.g. "double _timeStamp = 0.0;" - use an in-class initialiser if
953 the attribute needs one, since there is no hook into the generated
954 constructor for this.
955
956 Nothing calls this unconditionally: a plain Solver carries no
957 attributes beyond what PDE terms need. It is up to whichever
958 NumericalScheme/GridConstruction/Plotter a solver uses to call
959 this, if it needs solver-level state of its own that genuinely
960 has no home on exahype2::Solver already - e.g.
961 exahype2.api.fv.RusanovWithExplicitEuler deliberately does *not*
962 use this for time stamp/time step size bookkeeping, since
963 ::exahype2::Solver (which every generated Abstract<SolverName>
964 already inherits from) already carries
965 _minTimeStamp/_maxTimeStamp/_minTimeStepSize/_maxTimeStepSize and
966 the updateCell()/startTimeStep()/finishTimeStep() lifecycle to
967 maintain them - @see exahype2.api.fv.actionsets.
968 ComputeGlobalCFLCondition, which drives that
969 lifecycle instead of introducing parallel state via this method.
970
971 """
972 self._abstract_solver_attributes.append(declaration)
973
975 self, declaration: str, definition_generator: Callable[[str], str]
976 ):
977 """!
978
979 Add a raw C++ method to the generated Abstract<SolverName> class:
980 declaration goes into the class body (public section), verbatim.
981 definition_generator is called with the class' fully qualified
982 name once it is known (@see exahype2.api.SolverToCPPFiles,
983 exactly the way PDETerm.Generator.generate_out_of_class_definitions()
984 already is) and has to return the out-of-class definition - a
985 plain string with a "{qualified_class_name}" placeholder is
986 deliberately not supported here, since a C++ method body is full
987 of literal braces of its own; build the string with concatenation
988 instead, e.g.:
989
990 ~~~~~~~~~~~~~~~~~~~~~~~
991 solver.add_abstract_solver_method(
992 "void increaseTimestamp(double dt);",
993 lambda qualified_class_name:
994 "void " + qualified_class_name + "::increaseTimestamp(double dt) {\\n"
995 " _timeStamp += dt;\\n"
996 "}\\n"
997 )
998 ~~~~~~~~~~~~~~~~~~~~~~~
999
1000 @see add_abstract_solver_attribute() for the attribute counterpart,
1001 and exahype2.api.PDETerm.Generator for the more structured
1002 alternative this deliberately is not (that one is for PDE terms a
1003 user implements; this one is for solver-level bookkeeping a
1004 NumericalScheme/etc. needs that has no equivalent on
1005 ::exahype2::Solver already - @see add_abstract_solver_attribute()'s
1006 own note on why RusanovWithExplicitEuler does not actually use
1007 either method for time stamp/time step size bookkeeping).
1008
1009 """
1010 self._abstract_solver_methods.append((declaration, definition_generator))
1011
1013 """!
1014
1015 Add wantsToPlot() to the solver's C++ class: It holds if any of the
1016 solver's plotters is active (@ref exahype2.api.Solver.Solver.Plotter).
1017 Solvers without plotters do not get the method, as nobody asks them.
1018 The method is added only once, even if the Peano 4 project is
1019 generated multiple times, and it evaluates the plotters the solver
1020 has when the C++ code is written.
1021
1022 """
1023 declaration = "bool wantsToPlot() const;"
1024 if not self._plotters or declaration in [
1025 existing for existing, _ in self._abstract_solver_methods
1026 ]:
1027 return
1029 declaration,
1030 lambda qualified_class_name: "bool "
1031 + qualified_class_name
1032 + "::wantsToPlot() const {\n"
1033 " return "
1034 + " or ".join("is" + p.name + "Active()" for p in self._plotters)
1035 + ";\n"
1036 "}\n",
1037 )
1038
1040 """!
1041
1042 Override exahype2::Solver::toCheckpointMetaData() in the solver's
1043 C++ class such that it also writes the attributes added through
1044 add_abstract_solver_attribute(), e.g. the time stamps of the next
1045 outputs of the plotters. Only attributes of type double, float or
1046 int are written, with their name without leading underscore as key.
1047
1048 The counterpart override of exahype2::Solver::fromCheckpointMetaData()
1049 restores these attributes. Afterwards, it calls finish<Name>() of
1050 all plotters: A plotter which has written output at the time of the
1051 checkpoint has done so before it has moved on to its next output, as
1052 it only moves on at the end of the plot phase
1053 (@ref exahype2.api.Solver.Solver.Plotter). The checkpoint hence holds
1054 the time stamp of an output which has already been written.
1055 finish<Name>() moves such a plotter on, exactly as the original run
1056 has done after the checkpoint, so the restarted simulation does not
1057 write this output again.
1058
1059 The overrides evaluate the attributes and plotters the solver has
1060 when the C++ code is written, and they are added only once, even if
1061 several checkpoints use them or the Peano 4 project is generated
1062 multiple times.
1063
1064 """
1065 declaration = "std::string toCheckpointMetaData() const override;"
1066 if declaration in [existing for existing, _ in self._abstract_solver_methods]:
1067 return
1068
1069 def checkpointed_attributes():
1070 for attribute in self._abstract_solver_attributes:
1071 match = re.match(r"\s*(?:double|float|int)\s+(\w+)\s*(=|;)", attribute)
1072 if match is not None:
1073 yield match.group(1)
1074
1075 def to_definition(qualified_class_name):
1076 result = (
1077 "std::string "
1078 + qualified_class_name
1079 + "::toCheckpointMetaData() const {\n"
1080 " return ::exahype2::Solver::toCheckpointMetaData()"
1081 )
1082 for attribute_name in checkpointed_attributes():
1083 result += (
1084 '\n + "\\n" + toCheckpointMetaDataEntry("'
1085 + attribute_name.lstrip("_")
1086 + '", '
1087 + attribute_name
1088 + ")"
1089 )
1090 return result + ";\n}\n"
1091
1092 def from_definition(qualified_class_name):
1093 result = (
1094 "void "
1095 + qualified_class_name
1096 + "::fromCheckpointMetaData(const std::string& metaData) {\n"
1097 " ::exahype2::Solver::fromCheckpointMetaData(metaData);\n"
1098 " double value;\n"
1099 )
1100 for attribute_name in checkpointed_attributes():
1101 result += (
1102 ' if (getCheckpointMetaDataEntry(metaData, "'
1103 + attribute_name.lstrip("_")
1104 + '", value)) {\n'
1105 " "
1106 + attribute_name
1107 + " = static_cast<decltype("
1108 + attribute_name
1109 + ")>(value);\n"
1110 " }\n"
1111 )
1112 for plotter in self._plotters:
1113 result += " finish" + plotter.name + "();\n"
1114 return result + "}\n"
1115
1116 self.add_abstract_solver_method(declaration, to_definition)
1118 "void fromCheckpointMetaData(const std::string& metaData) override;",
1119 from_definition,
1120 )
1121
1122 # @todo This one is important
1123 def create_readme_descriptor(self, domain_offset, domain_size) -> str:
1124 """!
1125 Return a human-readable description of this solver instance, to be
1126 embedded into the generated project's README.
1127 """
1128 pass
1129
1131 self,
1132 exahype2_project,
1133 peano_project,
1134 setup_simulation,
1135 time_step,
1136 plot,
1137 mesh_adaptation,
1138 add_global_tasks=True,
1139 ):
1140 """!
1141 Turn this solver specification into a task graph and create the required C++ kernels/stubs
1142
1143 peano_project: peano4.api.Project
1144 The Peano 4 project that exahype2_project.generate_Peano4_project() is
1145 currently assembling. It is a local variable there, not an attribute -
1146 merely passed through here, so this solver can add its own artefacts to it.
1147
1148 setup_simulation, time_step, plot, mesh_adaptation: peano4.api.taskgraph.Graph
1149 The task graphs of the four algorithmic phases of the surrounding
1150 exahype2_project. They are owned by exahype2_project.generate_Peano4_project()
1151 and merely passed through here, so this solver can add its own
1152 tasks into them.
1153
1154 @param add_global_tasks: bool
1155 Passed on to the numerical scheme, @see Solver.NumericalScheme.construct_output().
1156 A host that realises several solvers into graphs of their own and
1157 concatenates them (@ref page_exahype_programmers_guide_coupling)
1158 passes False, i.e. the solver is realised as an intermediate step.
1159 The host then wraps the concatenated graph.
1160 Without the global tasks, the solver does not contribute to the
1161 mesh adaptation phase either: The host constructs it.
1162
1163 @return peano4.api.taskgraph.Graph
1164 """
1165 peano4.api.Logger().new_section("Solver " + self._name)
1166
1167 assert self.grid_construction is not None, (
1168 f"Solver {self._name} has no grid_construction set. Assign a "
1169 "Solver.GridConstruction subclass instance to grid_construction "
1170 "before calling generate_solver_realisation()."
1171 )
1172 assert self.numerical_scheme is not None, (
1173 f"Solver {self._name} has no numerical_scheme set. Assign a "
1174 "Solver.NumericalScheme subclass instance to numerical_scheme "
1175 "before calling generate_solver_realisation()."
1176 )
1177
1178 # First, as the numerical scheme might ask for the mesh adaptation
1179 if self.mesh_adaptation is None:
1180 self.mesh_adaptation = (
1181 self.numerical_scheme.create_default_mesh_adaptation()
1182 )
1183
1184 self.grid_construction.construct_output(
1185 exahype2_project, peano_project, setup_simulation
1186 )
1187 self.numerical_scheme.construct_output(
1188 exahype2_project, peano_project, time_step, add_global_tasks
1189 )
1190 for plotter in self._plotters:
1191 plotter.construct_output(exahype2_project, peano_project, plot)
1192 self._add_wants_to_plot_to_solver()
1193 if self.mesh_adaptation is not None and add_global_tasks:
1194 self.mesh_adaptation.construct_output(
1195 exahype2_project, peano_project, mesh_adaptation
1196 )
1197 # Last, so grid construction, numerical scheme, plotter and mesh
1198 # adaptation can add their own members to the solver class first
1199 # (@see add_abstract_solver_attribute()/add_abstract_solver_method()).
1200 self.solver_generator.construct_output(exahype2_project, peano_project)
construct_output(self, exahype2_project, peano_project, setup_simulation)
Has to be implemented by subclass.
Definition Solver.py:255
How a Solver adapts its mesh and rebalances its load between two time steps.
Definition Solver.py:446
construct_output(self, exahype2_project, peano_project, mesh_adaptation)
Has to be implemented by subclass.
Definition Solver.py:472
__init__(self, "Solver" solver)
Definition Solver.py:468
Specify which versions of a numerical scheme should be generated here.
Definition Solver.py:218
__init__(self, Solver solver, list[tuple[Target, bool]] configurations)
Definition Solver.py:227
reset_configurations(self, Target target, bool stateless)
Definition Solver.py:231
construct_output(self, exahype2_project, peano_project, time_step, add_global_tasks=True)
Definition Solver.py:239
The concrete discretisation (Finite Volumes, ADER-DG, ...) realised by a Solver.
Definition Solver.py:60
wrap_task_graph_in_load_balancing_and_amr_tasks(self, time_step)
Embed the time step's task graph into the global load balancing and AMR tasks.
Definition Solver.py:108
construct_output(self, exahype2_project, peano_project, time_step, add_global_tasks=True)
Has to be implemented by subclass.
Definition Solver.py:88
__init__(self, "Solver" solver)
Definition Solver.py:75
"Solver.MeshAdaptation" create_default_mesh_adaptation(self)
The mesh adaptation a solver uses if the user does not assign one to solver.mesh_adaptation.
Definition Solver.py:205
Solver.NumericalScheme.NumericalSchemeGenerator _generator
Definition Solver.py:83
How a Solver writes out its solution.
Definition Solver.py:264
__init__(self, "Solver" solver, str name=None)
Definition Solver.py:310
str output_file_prefix(self)
Prefix of the files the plotter writes, including the path.
Definition Solver.py:339
_add_time_interval_bookkeeping_to_solver(self, float first_time_stamp, float time_in_between)
Make the plotter active in regular time intervals.
Definition Solver.py:385
str create_is_active_predicate(self)
C++ predicate which holds if the plotter is active.
Definition Solver.py:350
construct_output(self, exahype2_project, peano_project, plot)
Has to be implemented by subclass.
Definition Solver.py:330
str create_finish_call(self)
C++ statement which moves the plotter on to its next output.
Definition Solver.py:366
Turns a Solver into actual classes.
Definition Solver.py:44
__init__(self, "Solver" solver)
Definition Solver.py:51
construct_output(self, exahype2_project, peano_project)
Has to be implemented by subclass.
Definition Solver.py:55
Abstract base class for all ExaHyPE 2 solvers.
Definition Solver.py:17
int number_of_auxiliary_variables(self)
Total number of entries of all sets of auxiliary variables.
Definition Solver.py:759
str _unknown_identifier(self)
Definition Solver.py:854
str get_name_of_global_instance(self)
Definition Solver.py:882
_add_wants_to_plot_to_solver(self)
Add wantsToPlot() to the solver's C++ class: It holds if any of the solver's plotters is active (exah...
Definition Solver.py:1012
add_abstract_solver_method(self, str declaration, Callable[[str], str] definition_generator)
Add a raw C++ method to the generated Abstract<SolverName> class: declaration goes into the class bod...
Definition Solver.py:976
PDETerm get_pde_term(self, str name, bool stateless=False)
Look up a previously registered PDE term by name and statelessness.
Definition Solver.py:943
"Solver.NumericalScheme" numerical_scheme(self)
Definition Solver.py:660
add_abstract_solver_attribute(self, str declaration)
Add a raw C++ member attribute declaration to the generated Abstract<SolverName> class (.
Definition Solver.py:947
_add_checkpoint_meta_data_to_solver(self)
Override exahype2.Solver.toCheckpointMetaData() in the solver's C++ class such that it also writes th...
Definition Solver.py:1039
str signature_of(self, PDETerm term)
The signature of a PDE term including the pointers to the auxiliary variables.
Definition Solver.py:811
set_solver_constants(self, str datastring)
Definition Solver.py:848
str _get_default_includes(self)
Includes every generated action set can rely on being available, regardless of which action sets a co...
Definition Solver.py:832
add_pde_term(self, PDETerm term)
Register a PDE term with this solver, or replace the one already registered under the same name and s...
Definition Solver.py:916
add_user_solver_includes(self, str value)
Add further includes to this property, if your solver requires some additional routines from other he...
Definition Solver.py:825
dict _variable_positions
Translate a plain int or a name-to-multiplicity dict into a total variable count, and - for the dict ...
Definition Solver.py:551
remove_pde_term(self, str name, bool stateless=False)
Remove a previously registered PDE term by name and statelessness.
Definition Solver.py:939
List[str] variable_names_per_entry(self)
One name per entry of Q, i.e.
Definition Solver.py:857
bool requires_user_class(self)
True iff at least one PDE term has no implementation.
Definition Solver.py:897
add_solver_constants(self, str datastring)
Definition Solver.py:851
__init__(self, str name, VariableSpecification unknowns)
Create solver.
Definition Solver.py:519
str _name
Create solver.
Definition Solver.py:548
str create_readme_descriptor(self, domain_offset, domain_size)
Return a human-readable description of this solver instance, to be embedded into the generated projec...
Definition Solver.py:1123
add_plotter(self, "Solver.Plotter" plotter)
Add a plotter to the solver.
Definition Solver.py:679
str get_name_of_solver_class(self)
Name of the C++ class the solver repository instantiates: <SolverName> if requires_user_class,...
Definition Solver.py:909
pde_terms
True iff at least one PDE term has no implementation.
Definition Solver.py:907
str user_solver_includes(self)
Add further includes to this property, if your solver requires some additional routines from other he...
Definition Solver.py:818
generate_solver_realisation(self, exahype2_project, peano_project, setup_simulation, time_step, plot, mesh_adaptation, add_global_tasks=True)
Turn this solver specification into a task graph and create the required C++ kernels/stubs.
Definition Solver.py:1139
int auxiliary_variable_offset(self, "AuxiliaryVariables" auxiliary)
Offset of the first entry of a set within the buffer the compute kernels work on, i....
Definition Solver.py:763
add_auxiliary_variables(self, "AuxiliaryVariables" auxiliary)
Attach a set of auxiliary variables to the solver.
Definition Solver.py:776
str name(self)
Unique solver name.
Definition Solver.py:653
List["Solver.Plotter"] plotters(self)
All plotters of the solver, in the order they have been added.
Definition Solver.py:673
tuple mesh_adaptation
Turn this solver specification into a task graph and create the required C++ kernels/stubs.
Definition Solver.py:602
"Solver.Plotter" plotter(self)
Shorthand for solvers with at most one plotter.
Definition Solver.py:726
list _plotters
Turn this solver specification into a task graph and create the required C++ kernels/stubs.
Definition Solver.py:596
int _register_variables(self, VariableSpecification variables, int offset)
Translate a plain int or a name-to-multiplicity dict into a total variable count, and - for the dict ...
Definition Solver.py:617
List["AuxiliaryVariables"] auxiliary_variables(self)
All sets of auxiliary variables in the order they have been attached.
Definition Solver.py:754
list _auxiliary_variables
All sets of auxiliary variables in the order they have been attached.
Definition Solver.py:556
Singleton logger for the Peano 4 Python API.
Definition Logger.py:37
One task within a peano4.api.taskgraph.Graph.
Definition Task.py:8
Select a subset of the mesh entities.