Nektar++
Loading...
Searching...
No Matches
check_time_order.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2
3import argparse
4import math
5import pathlib
6import re
7import subprocess
8import tempfile
9from concurrent.futures import ThreadPoolExecutor
10
11
12MIN_RATES = {1: 0.85, 2: 1.70, 3: 2.30}
13NSTEPS_BY_ORDER = {1: [2, 4], 2: [2, 4], 3: [2, 4]}
14FORMULATIONS = ["semiimplicit", "linearimplicit"]
15VELOCITY_VARS = ["u", "v", "w"]
16
17class Poly:
18 def __init__(self, terms=None):
19 self.terms = {k: v for k, v in (terms or {}).items() if abs(v) > 1e-14}
20
21 @staticmethod
22 def const(value):
23 return Poly({(0, 0, 0): float(value)})
24
25 @staticmethod
26 def var(axis):
27 exp = [0, 0, 0]
28 exp[axis] = 1
29 return Poly({tuple(exp): 1.0})
30
31 def __add__(self, other):
32 other = as_poly(other)
33 terms = dict(self.terms)
34 for exp, coef in other.terms.items():
35 terms[exp] = terms.get(exp, 0.0) + coef
36 return Poly(terms)
37
38 def __radd__(self, other):
39 return self + other
40
41 def __neg__(self):
42 return Poly({exp: -coef for exp, coef in self.terms.items()})
43
44 def __sub__(self, other):
45 return self + (-as_poly(other))
46
47 def __rsub__(self, other):
48 return as_poly(other) - self
49
50 def __mul__(self, other):
51 other = as_poly(other)
52 terms = {}
53 for exp1, coef1 in self.terms.items():
54 for exp2, coef2 in other.terms.items():
55 exp = tuple(exp1[i] + exp2[i] for i in range(3))
56 terms[exp] = terms.get(exp, 0.0) + coef1 * coef2
57 return Poly(terms)
58
59 def __rmul__(self, other):
60 return self * other
61
62 def __pow__(self, power):
63 out = Poly.const(1.0)
64 for _ in range(power):
65 out = out * self
66 return out
67
68 def deriv(self, axis):
69 terms = {}
70 for exp, coef in self.terms.items():
71 if exp[axis] == 0:
72 continue
73 new_exp = list(exp)
74 new_exp[axis] -= 1
75 terms[tuple(new_exp)] = terms.get(tuple(new_exp), 0.0) + coef * exp[axis]
76 return Poly(terms)
77
78 def lap(self):
79 return self.deriv(0).deriv(0) + self.deriv(1).deriv(1) + self.deriv(2).deriv(2)
80
81 def expr(self):
82 if not self.terms:
83 return "0"
84 parts = []
85 names = ["x", "y", "z"]
86 for exp, coef in sorted(self.terms.items()):
87 factors = []
88 abs_coef = abs(coef)
89 if exp == (0, 0, 0) or abs(abs_coef - 1.0) > 1e-14:
90 factors.append(f"{abs_coef:.16g}")
91 for axis, power in enumerate(exp):
92 factors.extend([names[axis]] * power)
93 term = "*".join(factors) if factors else "1"
94 parts.append((coef < 0.0, term))
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)
110z = Poly.var(2)
111
112# Bubble factors for x in [-0.5, 1], y in [-0.5, 1.5], z in [0, 1].
113X = (x + 0.5) * (1.0 - x)
114Y = (y + 0.5) * (1.5 - y)
115Z = z * (1.0 - z)
116phi = (X**2) * (Y**2) * (Z**2)
117phi_x = phi.deriv(0)
118phi_y = phi.deriv(1)
119phi_z = phi.deriv(2)
120q = [phi_y - phi_z, phi_z - phi_x, phi_x - phi_y]
121p0 = x * y + y * z + z * x
122
123def adv(component):
124 return q[0] * component.deriv(0) + q[1] * component.deriv(1) + q[2] * component.deriv(2)
125
126A = "(1+0.1*sin(t))"
127AT = "(0.1*cos(t))"
128A0 = "1"
129
130U0, V0, W0 = [component.expr() for component in q]
131P0 = p0.expr()
132U = f"{A}*{U0}"
133V = f"{A}*{V0}"
134W = f"{A}*{W0}"
135P = P0
136
137ADV_U, ADV_V, ADV_W = [component.expr() for component in [adv(q[0]), adv(q[1]), adv(q[2])]]
138PX, PY, PZ = [p0.deriv(axis).expr() for axis in range(3)]
139LAP_U, LAP_V, LAP_W = [component.lap().expr() for component in q]
140
141FORCE_U = f"{AT}*{U0}+{A}*{A}*{ADV_U}+{PX}-Kinvis*{A}*{LAP_U}"
142FORCE_V = f"{AT}*{V0}+{A}*{A}*{ADV_V}+{PY}-Kinvis*{A}*{LAP_V}"
143FORCE_W = f"{AT}*{W0}+{A}*{A}*{ADV_W}+{PZ}-Kinvis*{A}*{LAP_W}"
144
145MANUFACTURED_FUNCTIONS = f""" <FUNCTION NAME="InitialConditions">
146 <E VAR="u" VALUE="{A0}*{U0}" />
147 <E VAR="v" VALUE="{A0}*{V0}" />
148 <E VAR="w" VALUE="{A0}*{W0}" />
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="w" VALUE="{W}" />
156 <E VAR="p" VALUE="{P}" />
157 </FUNCTION>
158
159 <FUNCTION NAME="BodyForce">
160 <E VAR="u" VALUE="{FORCE_U}" />
161 <E VAR="v" VALUE="{FORCE_V}" />
162 <E VAR="w" VALUE="{FORCE_W}" />
163 <E VAR="p" VALUE="0" />
164 </FUNCTION>"""
165
166FORCING_BLOCK = """ <FORCING>
167 <FORCE TYPE="Body">
168 <BODYFORCE> BodyForce </BODYFORCE>
169 </FORCE>
170 </FORCING>"""
171
172BOUNDARY_CONDITIONS = f""" <BOUNDARYREGIONS>
173 <B ID="0"> C[1-6] </B>
174 </BOUNDARYREGIONS>
175
176 <BOUNDARYCONDITIONS>
177 <REGION REF="0">
178 <D VAR="u" VALUE="0" />
179 <D VAR="v" VALUE="0" />
180 <D VAR="w" VALUE="0" />
181 <D VAR="p" VALUE="{P}" />
182 </REGION>
183 </BOUNDARYCONDITIONS>"""
184
185
187 text = re.sub(
188 r" <BOUNDARYREGIONS>.*?</BOUNDARYCONDITIONS>",
189 BOUNDARY_CONDITIONS,
190 text,
191 flags=re.S,
192 )
193 text = re.sub(
194 r"\n\s*<FUNCTION NAME=\"InitialConditions\">.*?</FUNCTION>\s*"
195 r"<FUNCTION NAME=\"ExactSolution\">.*?</FUNCTION>",
196 "\n" + MANUFACTURED_FUNCTIONS,
197 text,
198 flags=re.S,
199 )
200 text = re.sub(r"\n\s*<(?:FORCING|Forcing)>.*?</(?:FORCING|Forcing)>", "", text, flags=re.S)
201 text = re.sub(r"\n\s*<FILTERS>.*?</FILTERS>", "", text, flags=re.S)
202 text = re.sub(r"\n\s*</NEKTAR>", f"\n{FORCING_BLOCK}\n</NEKTAR>", text)
203 return text
204
205
206def build_session(base_session, workdir, formulation, order, nsteps, final_time):
207 text = base_session.read_text()
208 dt = final_time / nsteps
209
210 text = re.sub(r"<ORDER>\s*\d+\s*</ORDER>", f"<ORDER> {order} </ORDER>", text)
211 text = re.sub(
212 r"<P>\s*TimeStep\s*=\s*[^<]+</P>",
213 f"<P> TimeStep = {dt:.16g} </P>",
214 text,
215 )
216 text = re.sub(
217 r"<P>\s*NumSteps\s*=\s*[^<]+</P>",
218 f"<P> NumSteps = {nsteps} </P>",
219 text,
220 )
221 text = re.sub(
222 r"<P>\s*IO_InfoSteps\s*=\s*[^<]+</P>",
223 f"<P> IO_InfoSteps = {nsteps} </P>",
224 text,
225 )
226 text = re.sub(r'NUMMODES="\d+"', 'NUMMODES="5"', text)
227 text = re.sub(
228 r"<P>\s*IterativeSolverTolerance\s*=\s*[^<]+</P>",
229 "<P> IterativeSolverTolerance = 1e-7 </P>",
230 text,
231 )
232 text = re.sub(
233 r"<P>\s*NekLinSysMaxIterations\s*=\s*[^<]+</P>",
234 "<P> NekLinSysMaxIterations = 1000 </P>",
235 text,
236 )
238
239 session = workdir / f"manufactured3d_order{order}_{formulation}_{nsteps}.xml"
240 session.write_text(text)
241 return session
242
243
244def run_case(args, workdir, formulation, order, nsteps):
245 session = build_session(
246 args.session, workdir, formulation, order, nsteps, args.final_time
247 )
248 cmd = [
249 str(args.solver),
250 f"--opExecSpace={args.op_exec_space}",
251 f"--opImpl={args.op_impl}",
252 "-I",
253 f"Formulation={formulation}",
254 str(session),
255 ]
256 proc = subprocess.run(
257 cmd,
258 cwd=workdir,
259 text=True,
260 stdout=subprocess.PIPE,
261 stderr=subprocess.PIPE,
262 timeout=args.timeout,
263 )
264 if proc.returncode:
265 print(proc.stdout)
266 print(proc.stderr)
267 raise RuntimeError(
268 f"order={order} {formulation} nsteps={nsteps} failed"
269 )
270
271 errors = []
272 for var in VELOCITY_VARS:
273 match = re.search(rf"L 2 error \‍(variable {var}\‍) : ([0-9.eE+-]+)", proc.stdout)
274 if not match:
275 print(proc.stdout)
276 raise RuntimeError(
277 f"order={order} {formulation} nsteps={nsteps} did not report {var} L2"
278 )
279 errors.append(float(match.group(1)))
280 return max(errors)
281
282
283def observed_rates(errors):
284 return [math.log(errors[i - 1] / errors[i], 2.0) for i in range(1, len(errors))]
285
286
287def main():
288 parser = argparse.ArgumentParser()
289 parser.add_argument("--solver", type=pathlib.Path, required=True)
290 parser.add_argument("--session", type=pathlib.Path, required=True)
291 parser.add_argument("--op-exec-space", default="Serial")
292 parser.add_argument("--op-impl", default="SumFac")
293 parser.add_argument("--final-time", type=float, default=0.2)
294 parser.add_argument("--timeout", type=float, default=600.0)
295 parser.add_argument(
296 "--max-workers",
297 type=int,
298 default=4,
299 help=(
300 "Cap on concurrent solver subprocesses. This test runs as a "
301 "single slot under ctest's own -j parallelism, so this must "
302 "stay well below os.cpu_count() to avoid oversubscribing the "
303 "host (see IncNavierStokesSolverRedesign_TimeIntegrationOrders123_* "
304 "PROCESSORS test property, which should match this default)."
305 ),
306 )
307 args = parser.parse_args()
308 args.solver = args.solver.resolve()
309 args.session = args.session.resolve()
310
311 with tempfile.TemporaryDirectory(prefix="incns_time_order_") as tmp:
312 workdir = pathlib.Path(tmp)
313 failed = False
314
315 # Each (order, formulation, nsteps) case below is its own
316 # single-threaded Nektar++ subprocess with no shared state (unique
317 # session file, no output files written) - Nektar++ itself is never
318 # asked to use more than one thread; only the orchestration here is
319 # concurrent.
320 cases = [
321 (order, formulation, nsteps)
322 for order in [1, 2, 3]
323 for formulation in FORMULATIONS
324 for nsteps in NSTEPS_BY_ORDER[order]
325 ]
326 max_workers = min(len(cases), max(1, args.max_workers))
327 with ThreadPoolExecutor(max_workers=max_workers) as pool:
328 case_errors = dict(
329 zip(
330 cases,
331 pool.map(
332 lambda c: run_case(args, workdir, c[1], c[0], c[2]), cases
333 ),
334 )
335 )
336
337 for order in [1, 2, 3]:
338 for formulation in FORMULATIONS:
339 errors = [
340 case_errors[(order, formulation, nsteps)]
341 for nsteps in NSTEPS_BY_ORDER[order]
342 ]
343 rates = observed_rates(errors)
344 min_rate = MIN_RATES[order]
345
346 print(
347 f"order={order} {formulation}: "
348 f"errors={errors} rates={rates}",
349 flush=True,
350 )
351
352 if rates[-1] < min_rate:
353 print(
354 f"order={order} {formulation}: expected final "
355 f"observed order >= {min_rate}, got {rates[-1]}",
356 flush=True,
357 )
358 failed = True
359
360 if failed:
361 raise SystemExit(1)
362
363
364if __name__ == "__main__":
365 main()
__init__(self, terms=None)
run_case(args, workdir, formulation, order, nsteps)
build_session(base_session, workdir, formulation, order, nsteps, final_time)
install_manufactured_solution(text)
Definition main.py:1