|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Convergence-rate verification for WENO5 on a 2D axisymmetric (cyl_coord=T) grid. |
| 4 | +
|
| 5 | +Density sine wave in z: rho = 1 + 0.2*sin(2*pi*z), u_z=1, p=1, u_r=0. |
| 6 | +Exact solution at time T: rho_exact(z,T) = 1 + 0.2*sin(2*pi*(z-T)). |
| 7 | +Nr is held fixed; Nz is refined. |
| 8 | +L2 error is computed by averaging density over r then comparing to exact solution. |
| 9 | +""" |
| 10 | + |
| 11 | +import argparse |
| 12 | +import json |
| 13 | +import math |
| 14 | +import os |
| 15 | +import shutil |
| 16 | +import struct |
| 17 | +import subprocess |
| 18 | +import sys |
| 19 | +import tempfile |
| 20 | + |
| 21 | +import numpy as np |
| 22 | + |
| 23 | +CASE = "examples/2D_axisym_convergence/case.py" |
| 24 | +MFC = "./mfc.sh" |
| 25 | +NR = 32 # fixed radial cells (n=31; WENO5 needs n+1 >= num_stcls_min*5 = 25) |
| 26 | +TFINAL = 0.1 # short final time avoids long-time cylindrical instability |
| 27 | + |
| 28 | + |
| 29 | +def read_field(run_dir: str, step: int, var_idx: int, nz: int, nr: int) -> np.ndarray: |
| 30 | + """Read 2D field. In MFC: x=axial(Nz), y=radial(Nr). Fortran col-major -> shape (Nz, Nr).""" |
| 31 | + path = os.path.join(run_dir, "p_all", "p0", str(step), f"q_cons_vf{var_idx}.dat") |
| 32 | + with open(path, "rb") as f: |
| 33 | + rec_len = struct.unpack("i", f.read(4))[0] |
| 34 | + data = np.frombuffer(f.read(rec_len), dtype=np.float64).copy() |
| 35 | + f.read(4) |
| 36 | + if data.size != nr * nz: |
| 37 | + raise ValueError(f"Expected {nr * nz} values, got {data.size}") |
| 38 | + # Fortran stores (x, y) = (axial, radial) in column-major: first index varies fastest |
| 39 | + return data.reshape(nz, nr, order="F") |
| 40 | + |
| 41 | + |
| 42 | +def run_case(tmpdir: str, nz: int, extra_args: list) -> tuple: |
| 43 | + """Run the 2D axisym case at resolution nz. Returns (Nt, run_dir).""" |
| 44 | + result = subprocess.run( |
| 45 | + [sys.executable, CASE, "--mfc", "{}", "-N", str(nz), "--nr", str(NR), "--Tfinal", str(TFINAL)] + extra_args, |
| 46 | + capture_output=True, |
| 47 | + text=True, |
| 48 | + check=False, |
| 49 | + ) |
| 50 | + if result.returncode != 0: |
| 51 | + raise RuntimeError(f"case.py failed:\n{result.stderr}") |
| 52 | + cfg = json.loads(result.stdout) |
| 53 | + Nt = int(cfg["t_step_stop"]) |
| 54 | + dt = float(cfg["dt"]) |
| 55 | + |
| 56 | + cmd = [MFC, "run", CASE, "-t", "pre_process", "simulation", "-n", "1", "--", "-N", str(nz), "--nr", str(NR), "--Tfinal", str(TFINAL)] + extra_args |
| 57 | + result = subprocess.run(cmd, capture_output=True, text=True, cwd=os.getcwd(), check=False) |
| 58 | + if result.returncode != 0: |
| 59 | + print(result.stdout[-3000:]) |
| 60 | + print(result.stderr) |
| 61 | + raise RuntimeError(f"./mfc.sh run failed for Nz={nz}") |
| 62 | + |
| 63 | + case_dir = os.path.dirname(CASE) |
| 64 | + src = os.path.join(case_dir, "p_all") |
| 65 | + dst = os.path.join(tmpdir, f"N{nz}", "p_all") |
| 66 | + if os.path.exists(dst): |
| 67 | + shutil.rmtree(dst) |
| 68 | + shutil.copytree(src, dst) |
| 69 | + shutil.rmtree(src, ignore_errors=True) |
| 70 | + shutil.rmtree(os.path.join(case_dir, "D"), ignore_errors=True) |
| 71 | + return Nt, dt, os.path.join(tmpdir, f"N{nz}") |
| 72 | + |
| 73 | + |
| 74 | +def main(): |
| 75 | + parser = argparse.ArgumentParser() |
| 76 | + parser.add_argument("--resolutions", type=int, nargs="+", default=[64, 128, 256]) |
| 77 | + parser.add_argument("--cfl", type=float, default=0.02) |
| 78 | + parser.add_argument("--order", type=int, default=5) |
| 79 | + args = parser.parse_args() |
| 80 | + |
| 81 | + extra = ["--cfl", str(args.cfl), "--order", str(args.order)] |
| 82 | + |
| 83 | + print(f"\n{'=' * 60}") |
| 84 | + print(f" WENO{args.order} on 2D axisymmetric (cyl_coord=T) grid") |
| 85 | + print(f" Sine wave in z, Nr={NR} fixed, Nz refined, T={TFINAL}") |
| 86 | + print(f"{'=' * 60}") |
| 87 | + |
| 88 | + errors, nts = [], [] |
| 89 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 90 | + for nz in args.resolutions: |
| 91 | + Lx = 5.0 # must match case.py |
| 92 | + dz = Lx / nz |
| 93 | + Nt, dt, run_dir = run_case(tmpdir, nz, extra) |
| 94 | + nts.append(Nt) |
| 95 | + T_actual = Nt * dt # actual final time |
| 96 | + |
| 97 | + # Read final density field (Nz x Nr), average over r |
| 98 | + rhoT = read_field(run_dir, Nt, 1, nz, NR) |
| 99 | + rhoT_z = rhoT.mean(axis=1) # shape (nz,) |
| 100 | + |
| 101 | + # Exact solution: rho(z, T) = 1 + 0.2*sin(2*pi*(z - T)) |
| 102 | + x_cc = (np.arange(nz) + 0.5) * dz |
| 103 | + rho_exact = 1.0 + 0.2 * np.sin(2.0 * np.pi * (x_cc - T_actual)) |
| 104 | + |
| 105 | + err = float(np.sqrt(np.sum((rhoT_z - rho_exact) ** 2) * dz)) |
| 106 | + errors.append(err) |
| 107 | + print(f" Nz={nz:4d}: Nt={Nt}, err={err:.4e}") |
| 108 | + |
| 109 | + Lx = 5.0 |
| 110 | + rates = [None] |
| 111 | + for i in range(1, len(args.resolutions)): |
| 112 | + nz0, nz1 = args.resolutions[i - 1], args.resolutions[i] |
| 113 | + rates.append((math.log(errors[i]) - math.log(errors[i - 1])) / (math.log(Lx / nz1) - math.log(Lx / nz0))) |
| 114 | + |
| 115 | + Lx = 5.0 |
| 116 | + print(f"\n {'Nz':>6} {'Nt':>6} {'dz':>10} {'L2 error':>14} {'rate':>8}") |
| 117 | + print(f" {'-' * 6} {'-' * 6} {'-' * 10} {'-' * 14} {'-' * 8}") |
| 118 | + for i, nz in enumerate(args.resolutions): |
| 119 | + r = f"{rates[i]:>8.2f}" if rates[i] is not None else f"{'---':>8}" |
| 120 | + print(f" {nz:>6} {nts[i]:>6} {Lx / nz:>10.6f} {errors[i]:>14.6e} {r}") |
| 121 | + |
| 122 | + if len(args.resolutions) > 1: |
| 123 | + log_dz = np.log(Lx / np.array(args.resolutions, dtype=float)) |
| 124 | + log_err = np.log(np.array(errors, dtype=float)) |
| 125 | + rate, _ = np.polyfit(log_dz, log_err, 1) |
| 126 | + expected = args.order - 0.2 |
| 127 | + passed = rate >= expected |
| 128 | + print(f"\n Fitted rate: {rate:.2f} (need >= {expected:.1f})") |
| 129 | + print(f" {'PASS' if passed else 'FAIL'}") |
| 130 | + sys.exit(0 if passed else 1) |
| 131 | + |
| 132 | + |
| 133 | +if __name__ == "__main__": |
| 134 | + main() |
0 commit comments