Peano
Loading...
Searching...
No Matches
PDETerm.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
5
6class PDETerm:
7 """!
8
9 Represents one named, point-wise PDE operator that a solver exposes for
10 the user to implement: a C++ method name, its parameter list, and an
11 implementation. flux(), eigenvalues(), the nonconservative product,
12 algebraic/point sources, boundary conditions, ... all have this same
13 shape (see python/exahype2/solvers/fv/riemann/kernels.py for how they
14 are actually declared in the generated abstract solver header).
15
16 Well-known terms should get their own PDETerm subclass which pins down
17 name and signature and adds any term-specific behaviour - @see Flux for
18 a fully worked example. Use the plain PDETerm constructor directly only
19 for a new, solver-specific term that does not warrant its own subclass
20 (yet).
21
22 A term's implementation is a C++ code snippet that becomes the generated
23 method's body verbatim - including the empty string, which generates a
24 method that does nothing (a no-op, not "contributes zero": it does not
25 zero out the output for you) - or None (the default), which leaves the
26 method pure virtual for you to implement by hand in your solver
27 subclass instead of generating it. A term you don't want at all is
28 simply never passed to solver.add_pde_term() in the first place.
29
30 implementation must not be None when stateless is True: the constructor
31 raises ValueError in that case, since a stateless term's generated
32 method is static, and static methods cannot be pure virtual - there
33 would be no declaration left to signal "implement this by hand".
34
35 PDETerm only models *what* the term is (name, signature, implementation).
36 It deliberately knows nothing about Jinja2 or the code generator: turning
37 a solver's collection of terms into the generated abstract solver header
38 remains the code generator's job, exactly as it is today.
39
40 @see exahype2.api.Solver.add_pde_term()
41
42 """
43
44 NAME: str
45 SIGNATURE: str
46
48 self,
49 name: str,
50 implementation: str = None,
51 stateless: bool = False,
52 ):
53 """!
54
55 name: str
56 The C++ method name, e.g. "flux" or "eigenvalues". Used by
57 exahype2.api.Solver to key its collection of terms, i.e. has to be
58 unique per solver.
59
60 implementation: str
61 A C++ snippet that becomes the method's body verbatim (the empty
62 string is a valid, generated no-op body), or None (the default) to
63 leave the method pure virtual for you to implement by hand. Must
64 not be None if stateless is True: the generated method is then
65 static, and static methods cannot be pure virtual, so there would
66 be nothing left to tell you to implement it by hand.
67
68 """
69 if stateless and implementation is None:
70 raise ValueError(
71 f"PDETerm {name!r} is stateless, so its generated method is static - "
72 "static methods cannot be pure virtual, so implementation must not be "
73 "None (pass a C++ snippet, or the empty string for a no-op body)."
74 )
75 self.name = name
76 self.implementation = implementation
77 self.stateless = stateless
78
79 def __repr__(self) -> str:
80 return f"{self.__class__.__name__}(name={self.name!r}, implementation={self.implementation!r})"
81
82 def __str__(self) -> str:
83 return f"{self.name}: {self.implementation}"
84
85 class Generator:
86 """!
87
88 Turns a PDETerm into the C++ text for its generated method: exactly
89 one method - the static, GPU-offloadable overload if the term is
90 stateless, otherwise the virtual instance method. Never both from
91 the same term; @see exahype2.api.Solver.add_pde_term() for how to
92 get both variants of the same conceptual operation.
93
94 If term.implementation is None, the method is left for the user to
95 implement by hand: pure virtual (" = 0") for the non-stateless case,
96 or - since static methods cannot be pure virtual - simply declared
97 without a matching out-of-class definition for the stateless case.
98 Otherwise the method is generated non-overridable ("final") with
99 term.implementation as its body.
100
101 Embedded into PDETerm (reachable as term.generator) so that a term
102 subclass can supply its own Generator - @see Flux.Generator - and
103 term.generator resolves to the right one automatically, since it is
104 looked up on the term's actual class rather than hardcoded to
105 PDETerm.Generator.
106
107 """
108
109 def __init__(self, term: "PDETerm", solver=None):
110 """!
111 @param term: PDETerm
112 @param solver: exahype2.api.Solver
113 If the solver has auxiliary variables, the generated signature
114 contains pointers to them (@ref exahype2.api.AuxiliaryVariables).
115 """
116 self.term = term
117 self.solver = solver
118
119 @property
120 def _has_auxiliary_variables(self) -> bool:
121 return self.solver is not None and len(self.solver.auxiliary_variables) > 0
122
123 @property
124 def kernel_signature(self) -> str:
125 """!
126 The signature without the auxiliary variables. This is the
127 signature which the compute kernels call.
128 """
129 return getattr(self.term, "SIGNATURE")
130
131 @property
132 def signature(self) -> str:
133 """!
134 The term's C++ parameter list. Looked up as a SIGNATURE attribute
135 on the owning term (e.g. Flux.SIGNATURE); a plain, custom PDETerm
136 has to set term.SIGNATURE itself before it can generate code.
137 """
138 signature = getattr(self.term, "SIGNATURE", None)
139 if signature is None:
140 raise AttributeError(
141 f"{self.term!r} (or its class) has no SIGNATURE to generate code from; "
142 "either subclass PDETerm and provide one (see Flux), or set "
143 "term.SIGNATURE explicitly."
144 )
146 from .AuxiliaryVariables import extend_signature
147
148 return extend_signature(signature, self.solver)
149 return signature
150
151 def _needs_kernel_adapter(self) -> bool:
152 """!
153 The compute kernels know nothing about auxiliary variables. They
154 call the stateless terms with the original signature. If the
155 solver has auxiliary variables, we thus add static overloads with
156 the original signature that forward to the term with parameters.
157 """
158 from .AuxiliaryVariables import split_signature
159
160 return (
161 self.term.stateless
163 and any(
164 p.split()[-1] in ("Q", "deltaQ")
165 for p in split_signature(self.kernel_signature)
166 )
167 )
168
170 from .AuxiliaryVariables import forwarding_arguments
171
172 return ", ".join(forwarding_arguments(self.kernel_signature, self.solver))
173
175 if not self._needs_kernel_adapter():
176 return ""
177 return (
178 "#if defined(GPUOffloadingOMP)\n"
179 "#pragma omp declare target\n"
180 "#endif\n"
181 f"static GPUCallableMethod void {self.term.name}(\n"
182 f" {self.kernel_signature},\n"
183 " Offloadable\n"
184 ");\n"
185 "#if defined(GPUOffloadingOMP)\n"
186 "#pragma omp end declare target\n"
187 "#endif\n"
188 )
189
190 def _generate_kernel_adapter_definition(self, qualified_class_name: str) -> str:
191 if not self._needs_kernel_adapter():
192 return ""
193 return (
194 "#if defined(GPUOffloadingOMP)\n"
195 "#pragma omp declare target\n"
196 "#endif\n"
197 f"GPUCallableMethod void {qualified_class_name}::{self.term.name}(\n"
198 f" {self.kernel_signature},\n"
199 " Offloadable\n"
200 f") {{\n {self.term.name}({self._kernel_adapter_arguments()}, Offloadable::Yes);\n}}\n"
201 "#if defined(GPUOffloadingOMP)\n"
202 "#pragma omp end declare target\n"
203 "#endif\n"
204 )
205
207 """!
208 static GPU-offloadable declaration, or the empty string if the
209 term isn't stateless. exahype2::Solver::Offloadable is a dummy
210 tag argument that exists precisely because C++ cannot overload on
211 staticness alone - it is what lets this static method coexist
212 with the same-named, non-static, no-Offloadable-argument method
213 that registering the same term name again without stateless
214 would produce.
215 """
216 if not self.term.stateless:
217 return ""
218 return (
219 "#if defined(GPUOffloadingOMP)\n"
220 "#pragma omp declare target\n"
221 "#endif\n"
222 f"static GPUCallableMethod void {self.term.name}(\n"
223 f" {self.signature},\n"
224 " Offloadable\n"
225 ");\n"
226 "#if defined(GPUOffloadingOMP)\n"
227 "#pragma omp end declare target\n"
228 "#endif\n"
229 )
230
231 def generate_declaration(self) -> str:
232 """!
233 Declaration text for the abstract solver header: the static,
234 GPU-offloadable overload if this term is stateless, otherwise
235 the virtual instance method - never both from one term. Pure
236 virtual (" = 0") if term.implementation is None, "final"
237 otherwise; the static, stateless overload is unaffected by this
238 distinction (static methods cannot be pure virtual) - @see
239 generate_out_of_class_definitions for how it is left for the
240 user to implement by hand instead.
241 """
242 if self.term.stateless:
243 return (
246 )
247 body_suffix = " = 0" if self.term.implementation is None else " final"
248 return (
249 f"virtual void {self.term.name}(\n"
250 f" {self.signature}\n"
251 f"){body_suffix};\n"
252 )
253
254 def generate_definition(self) -> str:
255 """!
256 Body of the generated method: the term's implementation verbatim.
257 Only meaningful when term.implementation is not None - @see
258 generate_out_of_class_definitions, which never calls this
259 otherwise.
260 """
261 return self.term.implementation
262
263 def generate_out_of_class_definitions(self, qualified_class_name: str) -> str:
264 """!
265 Out-of-class method body for the solver's .cpp file: the static,
266 GPU-offloadable overload if this term is stateless, otherwise
267 the virtual instance method - mirrors generate_declaration(),
268 never both from one term. The empty string if
269 term.implementation is None: the user implements that method by
270 hand instead, whether as an override of the pure virtual
271 instance method or, for a stateless term, as an ordinary static
272 method matching the declaration (name hiding, not override -
273 static methods cannot be virtual).
274
275 qualified_class_name: str
276 Fully qualified class name the definition is attached to,
277 e.g. "examples::MySolver::AbstractMySolver".
278 """
279 if self.term.implementation is None:
280 return ""
281 body = self.generate_definition()
282 if self.term.stateless:
283 return (
284 "#if defined(GPUOffloadingOMP)\n"
285 "#pragma omp declare target\n"
286 "#endif\n"
287 f"GPUCallableMethod void {qualified_class_name}::{self.term.name}(\n"
288 f" {self.signature},\n"
289 " Offloadable\n"
290 f") {{\n {body}\n}}\n"
291 "#if defined(GPUOffloadingOMP)\n"
292 "#pragma omp end declare target\n"
293 "#endif\n"
294 ) + self._generate_kernel_adapter_definition(qualified_class_name)
295 return (
296 f"void {qualified_class_name}::{self.term.name}(\n"
297 f" {self.signature}\n"
298 f") {{\n {body}\n}}\n"
299 )
300
302 """!
303 Override declaration for the concrete solver class that the
304 Python API generates when the user hasn't provided their own
305 implementation of this term - the empty string if the term
306 isn't left abstract (term.implementation is not None; a
307 stateless term's method is static and thus never overridable
308 in the first place, but that combination cannot occur anyway,
309 @see PDETerm.__init__).
310 """
311 if self.term.implementation is not None or self.term.stateless:
312 return ""
313 return (
314 f"virtual void {self.term.name}(\n"
315 f" {self.signature}\n"
316 ") override;\n"
317 )
318
319 def generate_stub_definition(self, qualified_class_name: str) -> str:
320 """!
321 Out-of-class body for generate_stub_declaration(): a trace-in
322 (with x, and normal too if the term's signature has one), a
323 logWarning noting the method is unimplemented, a
324 "// @todo implement" comment, and logTraceOut - or the empty
325 string under the same condition as generate_stub_declaration().
326
327 qualified_class_name: str
328 Fully qualified class name the definition is attached to,
329 e.g. "examples::MySolver::MySolver".
330 """
331 if self.term.implementation is not None or self.term.stateless:
332 return ""
333 method_name = f"{self.term.name}(...)"
334 log_trace_in = (
335 f'logTraceInWith2Arguments("{method_name}", x, normal);'
336 if "normal" in self.signature
337 else f'logTraceInWith1Argument("{method_name}", x);'
338 )
339 return (
340 f"void {qualified_class_name}::{self.term.name}(\n"
341 f" {self.signature}\n"
342 f") {{\n"
343 f" {log_trace_in}\n"
344 f' logWarning("{method_name}", "not implemented yet");\n'
345 f" // @todo implement\n"
346 f' logTraceOut("{method_name}");\n'
347 f"}}\n"
348 )
349
350 def generator_for(self, solver) -> "PDETerm.Generator":
351 """!
352 Code generator for this term within a solver, i.e. one that respects
353 the solver's auxiliary variables.
354 """
355 return self.__class__.Generator(self, solver)
356
357 @property
358 def generator(self) -> "PDETerm.Generator":
359 """!
360 Code generator for this term: an instance of this term's own
361 (possibly subclass-specific) Generator. @see PDETerm.Generator
362 """
363 return self.__class__.Generator(self)
Turns a PDETerm into the C++ text for its generated method: exactly one method - the static,...
Definition PDETerm.py:85
bool _needs_kernel_adapter(self)
The compute kernels know nothing about auxiliary variables.
Definition PDETerm.py:151
__init__(self, "PDETerm" term, solver=None)
Definition PDETerm.py:109
str _generate_kernel_adapter_definition(self, str qualified_class_name)
Definition PDETerm.py:190
str generate_declaration(self)
Declaration text for the abstract solver header: the static, GPU-offloadable overload if this term is...
Definition PDETerm.py:231
str generate_definition(self)
Body of the generated method: the term's implementation verbatim.
Definition PDETerm.py:254
str generate_out_of_class_definitions(self, str qualified_class_name)
Out-of-class method body for the solver's .cpp file: the static, GPU-offloadable overload if this ter...
Definition PDETerm.py:263
str _generate_static_offloadable_declaration(self)
static GPU-offloadable declaration, or the empty string if the term isn't stateless.
Definition PDETerm.py:206
str generate_stub_declaration(self)
Override declaration for the concrete solver class that the Python API generates when the user hasn't...
Definition PDETerm.py:301
str signature(self)
The term's C++ parameter list.
Definition PDETerm.py:132
str generate_stub_definition(self, str qualified_class_name)
Out-of-class body for generate_stub_declaration(): a trace-in (with x, and normal too if the term's s...
Definition PDETerm.py:319
Represents one named, point-wise PDE operator that a solver exposes for the user to implement: a C++ ...
Definition PDETerm.py:6
__init__(self, str name, str implementation=None, bool stateless=False)
name: str The C++ method name, e.g.
Definition PDETerm.py:52
"PDETerm.Generator" generator_for(self, solver)
Code generator for this term within a solver, i.e.
Definition PDETerm.py:350
"PDETerm.Generator" generator(self)
Code generator for this term: an instance of this term's own (possibly subclass-specific) Generator.
Definition PDETerm.py:358