Nektar++
Loading...
Searching...
No Matches
check_imexdirk_forced_mms_2d.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2
3import argparse
4import pathlib
5import re
6import subprocess
7import tempfile
8from concurrent.futures import ThreadPoolExecutor
9
10VELOCITY_VARS = ["u", "v"]
11DEFAULT_METHOD_BY_ORDER = {2: "IMEXdirk23", 3: "IMEXdirk23"}
12DEFAULT_STEPS_BY_ORDER = {2: 4, 3: 4}
13
14
15class Poly:
16 def __init__(self, terms=None):
17 self.terms = {k: v for k, v in (terms or {}).items() if abs(v) > 1e-14}
18
19 @staticmethod
20 def const(value):
21 return Poly({(0, 0): float(value)})
22
23 @staticmethod
24 def var(axis):
25 exp = [0, 0]
26 exp[axis] = 1
27 return Poly({tuple(exp): 1.0})
28
29 def __add__(self, other):
30 other = as_poly(other)
31 terms = dict(self.terms)
32 for exp, coef in other.terms.items():
33 terms[exp] = terms.get(exp, 0.0) + coef
34 return Poly(terms)
35
36 def __radd__(self, other):
37 return self + other
38
39 def __neg__(self):
40 return Poly({exp: -coef for exp, coef in self.terms.items()})
41
42 def __sub__(self, other):
43 return self + (-as_poly(other))
44
45 def __rsub__(self, other):
46 return as_poly(other) - self
47
48 def __mul__(self, other):
49 other = as_poly(other)
50 terms = {}
51 for exp1, coef1 in self.terms.items():
52 for exp2, coef2 in other.terms.items():
53 exp = tuple(exp1[i] + exp2[i] for i in range(2))
54 terms[exp] = terms.get(exp, 0.0) + coef1 * coef2
55 return Poly(terms)
56
57 def __rmul__(self, other):
58 return self * other
59
60 def __pow__(self, power):
61 out = Poly.const(1.0)
62 for _ in range(power):
63 out = out * self
64 return out
65
66 def deriv(self, axis):
67 terms = {}
68 for exp, coef in self.terms.items():
69 if exp[axis] == 0:
70 continue
71 new_exp = list(exp)
72 new_exp[axis] -= 1
73 new_exp = tuple(new_exp)
74 terms[new_exp] = terms.get(new_exp, 0.0) + coef * exp[axis]
75 return Poly(terms)
76
77 def lap(self):
78 return self.deriv(0).deriv(0) + self.deriv(1).deriv(1)
79
80 def expr(self):
81 if not self.terms:
82 return "0"
83 parts = []
84 names = ["x", "y"]
85 for exp, coef in sorted(self.terms.items()):
86 factors = []
87 abs_coef = abs(coef)
88 if exp == (0, 0) or abs(abs_coef - 1.0) > 1e-14:
89 factors.append(f"{abs_coef:.16g}")
90 for axis, power in enumerate(exp):
91 factors.extend([names[axis]] * power)
92 term = "*".join(factors) if factors else "1"
93 parts.append((coef < 0.0, term))
94
95 expr = ""
96 for is_negative, term in parts:
97 if not expr:
98 expr = f"-{term}" if is_negative else term
99 else:
100 expr += f" - {term}" if is_negative else f" + {term}"
101 return f"({expr})"
102
103
104def as_poly(value):
105 return value if isinstance(value, Poly) else Poly.const(value)
106
107
108x = Poly.var(0)
109y = Poly.var(1)
110
111# Domain is [0,3] x [0,3]. This stream-function gives a non-trivial
112# divergence-free velocity field with homogeneous velocity boundary values.
113X = x * (3.0 - x)
114Y = y * (3.0 - y)
115psi = (X**2) * (Y**2)
116u0 = psi.deriv(1)
117v0 = -psi.deriv(0)
118p0 = (x - 1.5) * (y - 1.5)
119
120
121def adv(component):
122 return u0 * component.deriv(0) + v0 * component.deriv(1)
123
124
125A = "(1+0.1*sin(t))"
126AT = "(0.1*cos(t))"
127A0 = "1"
128
129U0 = u0.expr()
130V0 = v0.expr()
131P0 = p0.expr()
132U = f"{A}*{U0}"
133V = f"{A}*{V0}"
134P = P0
135
136ADV_U = adv(u0).expr()
137ADV_V = adv(v0).expr()
138PX = p0.deriv(0).expr()
139PY = p0.deriv(1).expr()
140LAP_U = u0.lap().expr()
141LAP_V = v0.lap().expr()
142
143FORCE_U = f"{AT}*{U0}+{A}*{A}*{ADV_U}+{PX}-Kinvis*{A}*{LAP_U}"
144FORCE_V = f"{AT}*{V0}+{A}*{A}*{ADV_V}+{PY}-Kinvis*{A}*{LAP_V}"
145
146MANUFACTURED_FUNCTIONS = f""" <FUNCTION NAME="InitialConditions">
147 <E VAR="u" VALUE="{A0}*{U0}" />
148 <E VAR="v" VALUE="{A0}*{V0}" />
149 <E VAR="p" VALUE="{P0}" />
150 </FUNCTION>
151
152 <FUNCTION NAME="ExactSolution">
153 <E VAR="u" VALUE="{U}" />
154 <E VAR="v" VALUE="{V}" />
155 <E VAR="p" VALUE="{P}" />
156 </FUNCTION>
157
158 <FUNCTION NAME="BodyForce">
159 <E VAR="u" VALUE="{FORCE_U}" />
160 <E VAR="v" VALUE="{FORCE_V}" />
161 <E VAR="p" VALUE="0" />
162 </FUNCTION>"""
163
164FORCING_BLOCK = """ <FORCING>
165 <FORCE TYPE="Body">
166 <BODYFORCE> BodyForce </BODYFORCE>
167 </FORCE>
168 </FORCING>"""
169
170BOUNDARY_CONDITIONS = f""" <BOUNDARYREGIONS>
171 <B ID="0"> C[2-5] </B>
172 </BOUNDARYREGIONS>
173
174 <BOUNDARYCONDITIONS>
175 <REGION REF="0">
176 <D VAR="u" VALUE="{U}" />
177 <D VAR="v" VALUE="{V}" />
178 <D VAR="p" VALUE="{P}" />
179 </REGION>
180 </BOUNDARYCONDITIONS>"""
181
182
184 text = re.sub(
185 r" <BOUNDARYREGIONS>.*?</BOUNDARYCONDITIONS>",
186 BOUNDARY_CONDITIONS,
187 text,
188 flags=re.DOTALL,
189 )
190 text = re.sub(
191 r"\n\s*<FUNCTION NAME=\"InitialConditions\">.*?</FUNCTION>\s*"
192 r"<FUNCTION NAME=\"ExactSolution\">.*?</FUNCTION>",
193 "\n" + MANUFACTURED_FUNCTIONS,
194 text,
195 flags=re.DOTALL,
196 )
197 text = re.sub(
198 r"\n\s*<(?:FORCING|Forcing)>.*?</(?:FORCING|Forcing)>",
199 "",
200 text,
201 flags=re.DOTALL,
202 )
203 text = re.sub(r"\n\s*<FILTERS>.*?</FILTERS>", "", text, flags=re.DOTALL)
204 text = re.sub(r"\n\s*</NEKTAR>", f"\n{FORCING_BLOCK}\n</NEKTAR>", text)
205 return text
206
207
208def check_mixed_tri_quad_mesh(text, session):
209 ntri = len(re.findall(r"<T\s+ID=", text))
210 nquad = len(re.findall(r"<Q\s+ID=", text))
211 if ntri == 0 or nquad == 0:
212 raise RuntimeError(
213 f"{session} must contain both triangles and quads; "
214 f"found {ntri} triangles and {nquad} quads"
215 )
216
217
218def set_time_integration(text, method, order):
219 replacement = f""" <TIMEINTEGRATIONSCHEME>
220 <METHOD> {method} </METHOD>
221 <ORDER> {order} </ORDER>
222 </TIMEINTEGRATIONSCHEME>"""
223 return re.sub(
224 r" <TIMEINTEGRATIONSCHEME>.*?</TIMEINTEGRATIONSCHEME>",
225 replacement,
226 text,
227 flags=re.DOTALL,
228 )
229
230
231def replace_parameter(text, name, value):
232 return re.sub(
233 rf"<P>\s*{name}\s*=\s*[^<]+</P>",
234 f"<P> {name} = {value} </P>",
235 text,
236 )
237
238
239def build_session(args, workdir, order, formulation):
240 text = args.session.read_text()
241 check_mixed_tri_quad_mesh(text, args.session)
242 method = args.method_by_order.get(order, DEFAULT_METHOD_BY_ORDER[order])
243 nsteps = args.steps_by_order.get(order, DEFAULT_STEPS_BY_ORDER[order])
244 dt = args.final_time / nsteps
245
246 text = set_time_integration(text, method, order)
247 text = replace_parameter(text, "TimeStep", f"{dt:.16g}")
248 text = replace_parameter(text, "NumSteps", str(nsteps))
249 text = replace_parameter(text, "IO_InfoSteps", str(nsteps))
250 text = replace_parameter(text, "Kinvis", f"{args.kinvis:.16g}")
251 text = replace_parameter(text, "IterativeSolverTolerance", "1e-10")
252 text = re.sub(r'NUMMODES="\d+"', f'NUMMODES="{args.num_modes}"', text)
254
255 # formulation is baked into the filename (not the file content - it's
256 # applied via -I on the command line) purely so concurrent cases that
257 # share an order never write/read the same path.
258 session = workdir / f"forced_mms_2d_{method}_order{order}_{formulation}.xml"
259 session.write_text(text)
260 return session
261
262
263def run_case(args, workdir, order, formulation):
264 session = build_session(args, workdir, order, formulation)
265 cmd = [
266 str(args.solver),
267 f"--opExecSpace={args.op_exec_space}",
268 f"--opImpl={args.op_impl}",
269 "-I",
270 f"Formulation={formulation}",
271 str(session),
272 ]
273 proc = subprocess.run(
274 cmd,
275 cwd=workdir,
276 text=True,
277 stdout=subprocess.PIPE,
278 stderr=subprocess.PIPE,
279 timeout=args.timeout,
280 )
281
282 if proc.returncode:
283 return False, proc
284
285 missing = []
286 for var in VELOCITY_VARS:
287 if not re.search(rf"L 2 error \‍(variable {var}\‍) : ([0-9.eE+-]+)", proc.stdout):
288 missing.append(var)
289 if missing:
290 proc.stderr += "\nMissing L2 output for: " + ", ".join(missing)
291 return False, proc
292
293 return True, proc
294
295
296def parse_int_map(values):
297 out = {}
298 for value in values:
299 key, val = value.split("=", 1)
300 out[int(key)] = int(val)
301 return out
302
303
304def parse_str_map(values):
305 out = {}
306 for value in values:
307 key, val = value.split("=", 1)
308 out[int(key)] = val
309 return out
310
311
312def main():
313 parser = argparse.ArgumentParser()
314 parser.add_argument("--solver", type=pathlib.Path, required=True)
315 parser.add_argument("--session", type=pathlib.Path, required=True)
316 parser.add_argument("--op-exec-space", default="Serial")
317 parser.add_argument("--op-impl", default="SumFac")
318 parser.add_argument("--orders", nargs="+", type=int, default=[2, 3])
319 parser.add_argument("--formulations", nargs="+", default=["linearimplicit"])
320 parser.add_argument("--steps", action="append", default=[], metavar="ORDER=N")
321 parser.add_argument("--method", action="append", default=[], metavar="ORDER=METHOD")
322 parser.add_argument("--final-time", type=float, default=0.02)
323 parser.add_argument("--kinvis", type=float, default=0.05)
324 parser.add_argument("--num-modes", type=int, default=7)
325 parser.add_argument("--timeout", type=float, default=600.0)
326 parser.add_argument(
327 "--max-workers",
328 type=int,
329 default=4,
330 help=(
331 "Cap on concurrent solver subprocesses. This test runs as a "
332 "single slot under ctest's own -j parallelism, so this must "
333 "stay well below the host core count to avoid oversubscribing "
334 "it (see the matching PROCESSORS test property in "
335 "CMakeLists.txt, and check_time_order.py which uses the same "
336 "pattern)."
337 ),
338 )
339 args = parser.parse_args()
340
341 args.solver = args.solver.resolve()
342 args.session = args.session.resolve()
343 args.steps_by_order = parse_int_map(args.steps)
344 args.method_by_order = parse_str_map(args.method)
345
346 failed = False
347 with tempfile.TemporaryDirectory(prefix="incns_imexdirk_mms2d_") as tmp:
348 workdir = pathlib.Path(tmp)
349
350 # Each (order, formulation) case below is its own single-threaded
351 # Nektar++ subprocess with its own uniquely-named session file (see
352 # build_session) - Nektar++ itself is never asked to use more than
353 # one thread; only the orchestration here is concurrent.
354 cases = [
355 (order, formulation)
356 for order in args.orders
357 for formulation in args.formulations
358 ]
359 max_workers = min(len(cases), max(1, args.max_workers))
360 with ThreadPoolExecutor(max_workers=max_workers) as pool:
361 results = list(
362 pool.map(lambda c: run_case(args, workdir, c[0], c[1]), cases)
363 )
364
365 for (order, formulation), (ok, proc) in zip(cases, results):
366 label = f"order={order} formulation={formulation}"
367 if ok:
368 print(f"{label}: passed", flush=True)
369 else:
370 print(f"{label}: failed", flush=True)
371 print("=== stdout ===", flush=True)
372 print(proc.stdout, flush=True)
373 print("=== stderr ===", flush=True)
374 print(proc.stderr, flush=True)
375 failed = True
376
377 if failed:
378 raise SystemExit(1)
379
380
381if __name__ == "__main__":
382 main()
run_case(args, workdir, order, formulation)
build_session(args, workdir, order, formulation)
Definition main.py:1