#!/usr/bin/env python3 """ foam_viz.py — OpenFOAM 2D VOF 场可视化。 从 OpenFOAM case 目录读取 alpha.water 与 U 场, 调用 viz_common.plot_snapshots 生成出版质量快照图。 支持串行和并行 (processor*/) case。 用法: from foam_viz import parse_scalar, parse_vector, parse_mesh, plot_foam python3 foam_viz.py # 直接运行生成全部案例可视化 """ import os import sys import re import struct import numpy as np from viz_common import CASES, plot_snapshots, SUBPLOT_BASE_W # ── OpenFOAM 字段解析 ───────────────────────────────────────────────────────── def parse_scalar(path): """读取 OpenFOAM volScalarField,支持 ASCII 和 binary。""" with open(path, "rb") as f: raw = f.read() uniform_marker = b"internalField" uniform_pos = raw.find(uniform_marker) if uniform_pos != -1: after = raw[uniform_pos + len(uniform_marker):] j = 0 while j < len(after) and after[j:j+1] in b" \t\n\r": j += 1 if after[j:j+7] == b"uniform": val_str = after[j + 7:] semi = val_str.find(b";") if semi != -1: val_text = val_str[:semi].decode("ascii", errors="replace").strip() try: return float(val_text) except ValueError: pass marker = b"nonuniform List" pos = raw.find(marker) if pos == -1: raise ValueError(f"未找到 nonuniform List: {path}") rest = raw[pos + len(marker):] paren = rest.find(b"(") if paren == -1: raise ValueError(f"未找到 '(': {path}") data_start = pos + len(marker) + paren + 1 i = data_start while i < len(raw) and raw[i:i+1] in b" \t\n\r": i += 1 line_end = raw.find(b"\n", i) if line_end == -1: line_end = len(raw) first_token = raw[i:line_end].decode("ascii", errors="ignore").strip() try: float(first_token) return _parse_ascii_scalar(raw, data_start) except (ValueError, UnicodeDecodeError): return _parse_binary_scalar(raw, data_start) def _parse_ascii_scalar(raw, data_start): text = raw[data_start:].decode("ascii", errors="replace") values = [] for line in text.split("\n"): s = line.strip() if s == "" or s.startswith("//"): continue if s.startswith(")"): break s = s.lstrip("(") if not s: continue try: values.append(float(s)) except ValueError: break return np.array(values, dtype=np.float64) def _parse_binary_scalar(raw, data_start): paren_pos = data_start - 1 line_end = paren_pos while line_end > 0 and raw[line_end - 1:line_end] in b"\n\r": line_end -= 1 num_end = line_end while num_end > 0 and raw[num_end - 1:num_end].isdigit(): num_end -= 1 n_cells = int(raw[num_end:line_end]) p = data_start while p < len(raw) and raw[p:p + 1] in b"\n\r": p += 1 data_end = p + n_cells * 8 values = struct.unpack(f"{n_cells}d", raw[p:data_end]) return np.array(values, dtype=np.float64) def parse_vector(path): """读取 OpenFOAM volVectorField,支持 ASCII 和 binary。""" with open(path, "rb") as f: raw = f.read() uniform_marker = b"internalField" uniform_pos = raw.find(uniform_marker) if uniform_pos != -1: after = raw[uniform_pos + len(uniform_marker):] j = 0 while j < len(after) and after[j:j+1] in b" \t\n\r": j += 1 if after[j:j+7] == b"uniform": val_str = after[j + 7:] semi = val_str.find(b";") if semi != -1: val_text = val_str[:semi].decode("ascii", errors="replace").strip() if val_text.startswith("(") and val_text.endswith(")"): parts = val_text[1:-1].split() if len(parts) >= 2: try: uz_val = float(parts[2]) if len(parts) >= 3 else 0.0 return float(parts[0]), float(parts[1]), uz_val except ValueError: pass marker = b"nonuniform List" pos = raw.find(marker) if pos == -1: raise ValueError(f"未找到 nonuniform List: {path}") rest = raw[pos + len(marker):] paren = rest.find(b"(") if paren == -1: raise ValueError(f"未找到 '(': {path}") data_start = pos + len(marker) + paren + 1 i = data_start while i < len(raw) and raw[i:i+1] in b" \t\n\r": i += 1 if i < len(raw) and raw[i:i+1] == b"(": return _parse_ascii_vector(raw, data_start) else: return _parse_binary_vector(raw, data_start) def _parse_ascii_vector(raw, data_start): text = raw[data_start:].decode("ascii", errors="replace") ux, uy, uz = [], [], [] for line in text.split("\n"): s = line.strip() if s == "" or s.startswith("//"): continue if s.startswith(")"): break s = s.strip("()") s = s.strip() if not s: continue try: parts = s.split() ux.append(float(parts[0])) uy.append(float(parts[1])) uz.append(float(parts[2]) if len(parts) >= 3 else 0.0) except (ValueError, IndexError): break return np.array(ux, dtype=np.float64), np.array(uy, dtype=np.float64), np.array(uz, dtype=np.float64) def _parse_binary_vector(raw, data_start): paren_pos = data_start - 1 line_end = paren_pos while line_end > 0 and raw[line_end - 1:line_end] in b"\n\r": line_end -= 1 num_end = line_end while num_end > 0 and raw[num_end - 1:num_end].isdigit(): num_end -= 1 n_cells = int(raw[num_end:line_end]) p = data_start while p < len(raw) and raw[p:p + 1] in b"\n\r": p += 1 data_end = p + n_cells * 24 all_vals = struct.unpack(f"{n_cells * 3}d", raw[p:data_end]) arr = np.array(all_vals, dtype=np.float64).reshape(n_cells, 3) return arr[:, 0], arr[:, 1], arr[:, 2] # ── 网格解析 ────────────────────────────────────────────────────────────────── def parse_mesh(case_dir): """从 blockMeshDict 解析网格信息。""" bmd = os.path.join(case_dir, "system", "blockMeshDict") if not os.path.isfile(bmd): raise FileNotFoundError(f"blockMeshDict 不存在: {bmd}") with open(bmd, "r", encoding="utf-8", errors="replace") as f: content = f.read() v_start = content.find("vertices") if v_start == -1: raise ValueError("blockMeshDict 中未找到 vertices") bracket = content.find("(", v_start) depth = 0 end = bracket for ci in range(bracket, len(content)): if content[ci] == "(": depth += 1 elif content[ci] == ")": depth -= 1 if depth == 0: end = ci break v_block = content[bracket + 1:end] verts = [] for m in re.finditer(r"\(([^()]+)\)", v_block): parts = m.group(1).split() if len(parts) >= 3: verts.append([float(parts[0]), float(parts[1]), float(parts[2])]) elif len(parts) >= 2: verts.append([float(parts[0]), float(parts[1]), 0.0]) verts = np.array(verts) x0, y0, z0 = verts.min(axis=0) x1, y1, z1 = verts.max(axis=0) b_start = content.find("blocks") if b_start == -1: raise ValueError("blockMeshDict 中未找到 blocks") b_bracket = content.find("(", b_start) depth = 0 b_end = b_bracket for ci in range(b_bracket, len(content)): if content[ci] == "(": depth += 1 elif content[ci] == ")": depth -= 1 if depth == 0: b_end = ci break b_block = content[b_bracket + 1:b_end] b_tokens = re.findall(r"\(([^()]+)\)", b_block) if len(b_tokens) >= 2: nums = b_tokens[1].split() nx = int(nums[0]) ny = int(nums[1]) nz = int(nums[2]) if len(nums) >= 3 else 1 return {"nx": nx, "ny": ny, "nz": nz, "x0": x0, "y0": y0, "x1": x1, "y1": y1, "z0": z0, "z1": z1} raise ValueError("blockMeshDict 中未解析到 hex block") # ── 并行 case 支持 ──────────────────────────────────────────────────────────── def _detect_parallel(case_dir, nx, ny): """检测并行 case,返回 (proc_dirs, proc_blocks) 或 None。""" proc_dirs = sorted( [d for d in os.listdir(case_dir) if os.path.isdir(os.path.join(case_dir, d)) and d.startswith("processor")], key=lambda d: int(re.search(r"\d+", d).group()), ) if not proc_dirs: return None ref_dir = os.path.join(case_dir, proc_dirs[0]) t_entries = sorted(os.listdir(ref_dir)) first_n = nx * ny for entry in t_entries: if entry == "0": continue u_path = os.path.join(ref_dir, entry, "U") if os.path.isdir(os.path.join(ref_dir, entry)) and os.path.exists(u_path): with open(u_path, "rb") as f: raw = f.read() m = re.search(r"nonuniform\s+List<\w+>\s+(\d+)", raw.decode("latin-1")) if m: first_n = int(m.group(1)) break else: return None n_procs = len(proc_dirs) total = nx * ny if first_n >= total: return proc_dirs[:1], [(nx, ny, slice(0, ny), slice(0, nx))] dict_path = os.path.join(case_dir, "system", "decomposeParDict") n_x, n_y = n_procs, 1 if os.path.exists(dict_path): with open(dict_path, "r", encoding="latin-1") as f: content = f.read() m = re.search(r"n\s*\(\s*(\d+)\s+(\d+)\s+(\d+)\s*\)", content) if m: nx_f, ny_f = int(m.group(1)), int(m.group(2)) if nx_f * ny_f == n_procs: n_x, n_y = nx_f, ny_f blocks = [] if n_y > 1: block_nx = nx // n_x block_ny = ny // n_y for pid in range(n_procs): gx = pid % n_x gy = pid // n_x bx0, by0 = gx * block_nx, gy * block_ny bx1 = min(bx0 + block_nx, nx) if gx < n_x - 1 else nx by1 = min(by0 + block_ny, ny) if gy < n_y - 1 else ny blocks.append((bx1 - bx0, by1 - by0, slice(by0, by1), slice(bx0, bx1))) else: boundaries = [0] base, rem = divmod(nx, n_x) for p in range(n_x): boundaries.append(boundaries[-1] + base + (1 if p < rem else 0)) for pid in range(n_procs): pnx = boundaries[pid + 1] - boundaries[pid] blocks.append((pnx, ny, slice(0, ny), slice(boundaries[pid], boundaries[pid + 1]))) return proc_dirs, blocks def _read_parallel_field(proc_dirs, blocks, case_dir, t_dir, field_name, is_vector, ny, nx): """从 processor 目录组装完整场。""" if is_vector: full = np.zeros((ny, nx, 3), dtype=np.float64) else: full = np.zeros((ny, nx), dtype=np.float64) for proc_dir, (pnx, pny, rows, cols) in zip(proc_dirs, blocks): fpath = os.path.join(case_dir, proc_dir, t_dir, field_name) if is_vector: ux, uy, uz = parse_vector(fpath) if isinstance(ux, (float, int)): ux = np.full(pnx * pny, ux) uy = np.full(pnx * pny, uy) uz = np.full(pnx * pny, uz) expected = pnx * pny if len(ux) > expected: ux_2d = ux.reshape(ny, nx) uy_2d = uy.reshape(ny, nx) uz_2d = uz.reshape(ny, nx) ux = ux_2d[rows, cols].ravel() uy = uy_2d[rows, cols].ravel() uz = uz_2d[rows, cols].ravel() local = np.column_stack([ux, uy, uz]).reshape(pny, pnx, 3) full[rows, cols, :] = local else: val = parse_scalar(fpath) if isinstance(val, (float, int)): val = np.full(pnx * pny, val) expected = pnx * pny if len(val) > expected: val_2d = val.reshape(ny, nx) val = val_2d[rows, cols].ravel() full[rows, cols] = val.reshape(pny, pnx) return full def _find_parallel_timesteps(case_dir, proc_dirs): """从 processor0 发现所有数值时间步目录名。""" ref = os.path.join(case_dir, proc_dirs[0]) t_dirs = [] for entry in os.listdir(ref): if os.path.isdir(os.path.join(ref, entry)): try: float(entry) t_dirs.append(entry) except ValueError: continue t_dirs.sort(key=lambda x: float(x)) return t_dirs def _find_closest_parallel_timestep(t_dirs, t): best, best_diff = t_dirs[0], abs(float(t_dirs[0]) - t) for td in t_dirs: diff = abs(float(td) - t) if diff < best_diff: best, best_diff = td, diff return best, float(best) def _find_closest_timestep(case_dir, t): available = [] for name in os.listdir(case_dir): full = os.path.join(case_dir, name) if os.path.isdir(full): try: available.append((float(name), name)) except ValueError: continue if not available: raise FileNotFoundError(f"无时间步目录: {case_dir}") closest_val, closest_name = min(available, key=lambda x: abs(x[0] - t)) return closest_name, closest_val # ── 绘图入口 ────────────────────────────────────────────────────────────────── def plot_foam(case_dir, timesteps, title, outpath, max_aspect=None, axis_labels=("x", "y"), arrow_cfg=None): """从 OpenFOAM case 目录生成快照图。""" mesh = parse_mesh(case_dir) nx, ny = mesh["nx"], mesh["ny"] nz = mesh.get("nz", 1) is_xz = (ny == 1 and nz > 1) if is_xz: ncols, nrows = nx, nz d0, d1 = mesh["x0"], mesh["z0"] d2, d3 = mesh["x1"], mesh["z1"] mesh_label = f"{nx}x{nz}" else: ncols, nrows = nx, ny d0, d1 = mesh["x0"], mesh["y0"] d2, d3 = mesh["x1"], mesh["y1"] mesh_label = f"{nx}x{ny}" Ld = d2 - d0 Lh = d3 - d1 domain_label = f"{Ld:.3f}x{Lh:.3f}" # 检测并行 parallel = _detect_parallel(case_dir, nx, ny if not is_xz else nz) par_t_dirs = None if parallel: proc_dirs, proc_blocks = parallel par_t_dirs = _find_parallel_timesteps(case_dir, proc_dirs) # 组装 frames frames = [] for t in timesteps: if parallel: ts_name, ts_val = _find_closest_parallel_timestep(par_t_dirs, t) alpha_flat = _read_parallel_field( proc_dirs, proc_blocks, case_dir, ts_name, "alpha.water", False, nrows, ncols, ) u_full = _read_parallel_field( proc_dirs, proc_blocks, case_dir, ts_name, "U", True, nrows, ncols, ) if is_xz: alpha_2d = alpha_flat if alpha_flat.ndim == 2 else alpha_flat[:, :, 0] u_2d, v_2d = u_full[:, :, 0], u_full[:, :, 2] else: alpha_2d = alpha_flat if alpha_flat.ndim == 2 else alpha_flat[:, :, 0] u_2d, v_2d = u_full[:, :, 0], u_full[:, :, 1] else: ts_name, ts_val = _find_closest_timestep(case_dir, t) ts_dir = os.path.join(case_dir, ts_name) n_cells = ncols * nrows alpha_raw = parse_scalar(os.path.join(ts_dir, "alpha.water")) if isinstance(alpha_raw, (float, int)): alpha_raw = np.full(n_cells, alpha_raw) alpha_2d = alpha_raw.reshape(nrows, ncols) ux, uy, uz = parse_vector(os.path.join(ts_dir, "U")) if isinstance(ux, (float, int)): ux = np.full(n_cells, ux) uy = np.full(n_cells, uy) uz = np.full(n_cells, uz) if is_xz: u_2d = ux.reshape(nrows, ncols) v_2d = uz.reshape(nrows, ncols) else: u_2d = ux.reshape(nrows, ncols) v_2d = uy.reshape(nrows, ncols) frames.append({"alpha": alpha_2d, "u": u_2d, "v": v_2d, "t": ts_val}) plot_snapshots( frames, outpath, title, mesh_label, domain_label, extent=[d0, d2, d1, d3], axis_labels=axis_labels, max_aspect=max_aspect, arrow_cfg=arrow_cfg, ) # ── 测试入口 ────────────────────────────────────────────────────────────────── if __name__ == "__main__": _cwd = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..")) _candidate = os.path.join(_cwd, "Exp", "data") if os.path.isdir(os.path.join(_candidate, "raw")): BASE_DIR = os.path.join(_candidate, "raw") OUT_DIR = os.path.join(_candidate, "visualizations") elif sys.platform == "win32": BASE_DIR = r"F:\agent-workspace\paper2\Exp\data\raw" OUT_DIR = r"F:\agent-workspace\paper2\Exp\data\visualizations" else: BASE_DIR = "/mnt/f/agent-workspace/paper2/Exp/data/raw" OUT_DIR = "/mnt/f/agent-workspace/paper2/Exp/data/visualizations" os.makedirs(OUT_DIR, exist_ok=True) def _auto_select_timesteps(case_dir, requested, nx, ny): parallel = _detect_parallel(case_dir, nx, ny) if parallel: proc_dirs, _ = parallel available = sorted([float(t) for t in _find_parallel_timesteps(case_dir, proc_dirs)]) else: available = [] for name in os.listdir(case_dir): full = os.path.join(case_dir, name) if os.path.isdir(full): try: available.append(float(name)) except ValueError: continue available.sort() if not available: return requested t_min, t_max = available[0], available[-1] valid = [t for t in requested if t_min - 0.01 <= t <= t_max + 0.01] if len(valid) >= 3: return valid n_show = min(5, len(available)) indices = np.linspace(0, len(available) - 1, n_show, dtype=int) return [available[i] for i in indices] for case_name, cfg in CASES.items(): print(f"\n{'='*60}") print(f" {cfg['title']} ({case_name})") print(f"{'='*60}") case_dir = os.path.join(BASE_DIR, case_name, "t00") if not os.path.isdir(case_dir): print(f" [SKIP] {case_dir}") continue mesh = parse_mesh(case_dir) nz = mesh.get("nz", 1) ncols_vis = mesh["nx"] nrows_vis = nz if (mesh["ny"] == 1 and nz > 1) else mesh["ny"] if nz > 1: print(f" mesh: {mesh['nx']}x{mesh['ny']}x{nz}, " f"domain: {mesh['x1']-mesh['x0']:.3f}x{mesh['y1']-mesh['y0']:.3f}x{mesh['z1']-mesh['z0']:.3f} m") else: print(f" mesh: {mesh['nx']}x{mesh['ny']}, " f"domain: {mesh['x1']-mesh['x0']:.3f}x{mesh['y1']-mesh['y0']:.3f} m") timesteps = _auto_select_timesteps(case_dir, cfg["timesteps"], ncols_vis, nrows_vis) if timesteps != cfg["timesteps"]: print(f" 可用时间步: [{timesteps[0]:.2f}...{timesteps[-1]:.2f}], 选取 {len(timesteps)} 个") outpath = os.path.join(OUT_DIR, f"{case_name}_foam.png") plot_foam( case_dir=case_dir, timesteps=timesteps, title=cfg["title"], outpath=outpath, max_aspect=cfg.get("max_aspect"), axis_labels=cfg.get("axis_labels", ("x", "y")), arrow_cfg=cfg.get("arrow_cfg"), ) print(f" -> {outpath}") print(f"\n全部完成。输出: {OUT_DIR}")