| |
| """ |
| Visualize one rotating-cube sample as an mp4. |
| |
| Reads a DECOMPOSED OpenFOAM case directly (no reconstructPar), takes a z=0 slice, |
| and renders an animation of the in-plane wake. The mesh is stored once at t=0 and |
| the cube spins rigidly, so the inner co-rotating cylinder (r < c) is rotated by |
| theta = omega * t per frame to put every cell back at its physical location |
| (omega = 0.25 rad/s about +z, per CLAUDE.md). Velocity is stored in the absolute |
| frame, so scalar fields (vorticity_z, |U|, p) are correct after the point rotation. |
| |
| Headless: matplotlib (Agg) renders frames, imageio-ffmpeg writes the mp4. No display, |
| no system ffmpeg, no ParaView needed. |
| |
| uv run python visualize_sample.py runs/Re100_psi30 |
| uv run python visualize_sample.py runs/Re300_psi0 --field Umag --t0 120 --t1 200 --nframes 300 --fps 30 |
| """ |
| import argparse, glob, os, re, sys |
| import numpy as np |
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| from matplotlib.tri import Triangulation |
| import pyvista as pv |
| import imageio.v2 as imageio |
|
|
| OMEGA = 0.25 |
| R_ROT = 1.0 |
| FIELDS = { |
| "vorticity": ("Spanwise vorticity $\\omega_z$", "RdBu_r", True), |
| "Umag": ("Velocity magnitude $|U|$", "viridis", False), |
| "p": ("Pressure $p$", "coolwarm", True), |
| } |
|
|
|
|
| def parse_case(path): |
| name = os.path.basename(os.path.normpath(path)) |
| re_m = re.search(r"Re(\d+)", name) |
| psi_m = re.search(r"psi(\d+)", name) |
| return name, (re_m.group(1) if re_m else "?"), (psi_m.group(1) if psi_m else "?") |
|
|
|
|
| def make_reader(case): |
| foam = os.path.join(case, os.path.basename(os.path.normpath(case)) + ".foam") |
| if not os.path.exists(foam): |
| open(foam, "w").close() |
| r = pv.POpenFOAMReader(foam) |
| r.case_type = "decomposed" |
| return r |
|
|
|
|
| def slice_at(reader, t, field): |
| reader.set_active_time_value(float(t)) |
| internal = reader.read()["internalMesh"] |
| if field == "vorticity": |
| |
| internal = internal.compute_derivative(scalars="U", vorticity=True) |
| sl = internal.slice(normal="z", origin=(0, 0, 0)) |
| if field == "vorticity" and "vorticity" not in sl.point_data: |
| sl = sl.cell_data_to_point_data() |
| sl = sl.triangulate() |
| if field == "vorticity": |
| vals = np.asarray(sl.point_data["vorticity"])[:, 2] |
| elif field == "Umag": |
| vals = np.linalg.norm(sl.point_data["U"], axis=1) |
| else: |
| vals = np.asarray(sl.point_data["p"]).ravel() |
| sl.point_data["fld"] = vals |
| return sl, vals |
|
|
|
|
| def rotated_parts(sl, t): |
| """Split the slice into rotating (r<R_ROT) and static (r>=R_ROT) meshes by cell |
| centre, with INDEPENDENT points (extract_cells duplicates the interface ring), then |
| rotate only the inner part by theta=OMEGA*t. This keeps the rigid cube spin exact |
| while never bridging the AMI interface -> no torn/dragged triangles across r=1. |
| Returns [(Triangulation, values), ...] to contour separately.""" |
| rc = np.linalg.norm(sl.cell_centers().points[:, :2], axis=1) |
| th = OMEGA * t |
| c, s = np.cos(th), np.sin(th) |
| out = [] |
| for mask, rotate in ((rc < R_ROT, True), (rc >= R_ROT, False)): |
| part = sl.extract_cells(mask) |
| if part.n_cells == 0: |
| continue |
| x, y = part.points[:, 0], part.points[:, 1] |
| if rotate: |
| x, y = c * x - s * y, s * x + c * y |
| cells = part.cells.reshape(-1, 4) |
| tris = cells[cells[:, 0] == 3][:, 1:] |
| out.append((Triangulation(x, y, tris), np.asarray(part.point_data["fld"]))) |
| return out |
|
|
|
|
| def color_limits(reader, field, times, signed): |
| """Robust, stable color scale sampled across a few frames.""" |
| sample = times[:: max(1, len(times) // 5)][:5] |
| sls = [slice_at(reader, t, field) for t in sample] |
| if field == "vorticity": |
| |
| |
| vv = [] |
| for sl, vals in sls: |
| x, y = sl.points[:, 0], sl.points[:, 1] |
| vv.append(np.abs(vals[(x * x + y * y) > 1.3 ** 2])) |
| m = np.percentile(np.concatenate(vv), 98) |
| return -m, m |
| allv = np.concatenate([v for _, v in sls]) |
| if signed: |
| m = np.percentile(np.abs(allv), 98) |
| return -m, m |
| return np.percentile(allv, 2), np.percentile(allv, 98) |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser(description=__doc__, |
| formatter_class=argparse.RawDescriptionHelpFormatter) |
| ap.add_argument("case", help="path to a case dir, e.g. runs/Re100_psi30") |
| ap.add_argument("--field", choices=list(FIELDS), default="vorticity") |
| ap.add_argument("--t0", type=float, default=100.0, help="start time* (default 100)") |
| ap.add_argument("--t1", type=float, default=200.0, help="end time* (default 200)") |
| ap.add_argument("--nframes", type=int, default=250) |
| ap.add_argument("--fps", type=int, default=25) |
| ap.add_argument("--out", default=None, help="output mp4 (default <case>_<field>.mp4)") |
| args = ap.parse_args() |
|
|
| if not os.path.isdir(args.case): |
| sys.exit(f"no such case dir: {args.case}") |
| name, Re, psi = parse_case(args.case) |
| label, cmap, signed = FIELDS[args.field] |
| out = args.out or f"{name}_{args.field}.mp4" |
|
|
| reader = make_reader(args.case) |
| tv = np.asarray(reader.time_values) |
| tv = tv[(tv >= args.t0) & (tv <= args.t1)] |
| if len(tv) == 0: |
| sys.exit(f"no snapshots in [{args.t0}, {args.t1}]; available {reader.time_values[0]}..{reader.time_values[-1]}") |
| idx = np.linspace(0, len(tv) - 1, min(args.nframes, len(tv))).round().astype(int) |
| times = np.unique(tv[idx]) |
| print(f"{name}: Re={Re}, psi={psi}deg | {len(times)} frames over t*=[{times[0]:.2f},{times[-1]:.2f}] | field={args.field}") |
|
|
| vmin, vmax = color_limits(reader, args.field, times, signed) |
| print(f"color scale: [{vmin:.3g}, {vmax:.3g}]") |
|
|
| fig, ax = plt.subplots(figsize=(9, 4.2), dpi=120) |
| levels = np.linspace(vmin, vmax, 41) |
| writer = imageio.get_writer(out, fps=args.fps, codec="libx264", |
| quality=8, macro_block_size=None) |
| for k, t in enumerate(times): |
| sl, _ = slice_at(reader, t, args.field) |
| ax.clear() |
| cf = None |
| for tri, pv in rotated_parts(sl, t): |
| cf = ax.tricontourf(tri, np.clip(pv, vmin, vmax), levels=levels, |
| cmap=cmap, extend="both") |
| ax.set_aspect("equal"); ax.set_xlim(-2.5, 5); ax.set_ylim(-1.5, 1.5) |
| ax.set_xlabel("x/c"); ax.set_ylabel("y/c") |
| ax.set_title(f"{name} (Re={Re}, $\\psi$={psi}$^\\circ$) " |
| f"{label} $t^*$={t:.1f}", fontsize=10) |
| if k == 0: |
| cb = fig.colorbar(cf, ax=ax, fraction=0.025, pad=0.02) |
| cb.set_label(label) |
| fig.tight_layout() |
| fig.canvas.draw() |
| frame = np.asarray(fig.canvas.buffer_rgba())[..., :3] |
| writer.append_data(frame) |
| if k % 25 == 0 or k == len(times) - 1: |
| print(f" frame {k+1}/{len(times)} t*={t:.1f}", flush=True) |
| writer.close() |
| print(f"wrote {out} ({len(times)} frames @ {args.fps} fps)") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|