|
|
| """
|
| postprocess_to_hdf5.py — 将 OpenFOAM interFoam 原生输出转为 HDF5
|
|
|
| 直接解析 OpenFOAM 原生字段文件(不需要 foamToVTK),提取 u, v, alpha.water
|
| 场数据并写入 HDF5 格式,与训练 pipeline 兼容。
|
|
|
| 网格坐标从 system/blockMeshDict 解析(规则矩形网格)。
|
| 字段值从每个时间步目录的 U, p_rgh, alpha.water 文件解析。
|
|
|
| 输出 HDF5 格式:
|
| {
|
| 'u': float32, shape=(n_frames, nx, ny), # X-速度
|
| 'v': float32, shape=(n_frames, nx, ny), # Y-速度
|
| 'p': float32, shape=(n_frames, nx, ny), # 压力 (p_rgh)
|
| 'alpha': float32, shape=(n_frames, nx, ny), # 相分数 (water=1)
|
| 'x_grid': float64, shape=(nx, ny), # X 坐标网格
|
| 'y_grid': float64, shape=(nx, ny), # Y 坐标网格
|
| }
|
| attrs:
|
| nx, ny, n_saved, times, case_name, mesh_Lx, mesh_Ly
|
|
|
| 用法:
|
| python3 postprocess_to_hdf5.py --input /opt/output/exp-openfoam-001
|
| python3 postprocess_to_hdf5.py --input /opt/output --from-processors
|
| python3 postprocess_to_hdf5.py --input /opt/output --from-processors --times 0,0.5,1,1.5,2
|
|
|
| 参考:
|
| [1] 数据加载兼容: Code/scripts/data_trans/openfoam_dataload.py 的 _read_field 方法
|
| [2] OpenFOAM Foundation. OpenFOAM v9 User Guide, 2021.
|
| """
|
|
|
| import argparse
|
| import os
|
| import re
|
| import struct
|
| import logging
|
|
|
| import numpy as np
|
| import h5py
|
|
|
|
|
|
|
|
|
| def read_foam_field(path, n_cells=None):
|
| """解析 OpenFOAM 字段文件的 internalField
|
|
|
| 支持:
|
| - ASCII: nonuniform List<scalar/vector> N (...数据...)
|
| - ASCII: uniform (值) 或 uniform 值;
|
| - Binary: nonuniform List<scalar/vector> N (binary marker + data)
|
|
|
| 参数:
|
| path: 字段文件路径
|
| n_cells: 网格单元数(可选),uniform 场广播时必需;
|
| 若未提供则尝试从同级 C 文件推断
|
|
|
| 返回:
|
| np.ndarray: 标量场 shape=(N,), 向量场 shape=(N,3)
|
| """
|
|
|
| with open(path, "rb") as fbin:
|
| raw = fbin.read()
|
|
|
|
|
|
|
| try:
|
| header_text = raw.decode("utf-8")
|
| except UnicodeDecodeError:
|
| header_text = raw.decode("latin-1")
|
|
|
| m_head = re.search(
|
| r"internalField\s+nonuniform\s+List<(vector|scalar)>\s*(\d+)",
|
| header_text
|
| )
|
| if not m_head:
|
|
|
| return _read_uniform_field(header_text, path, n_cells)
|
|
|
| ftype = m_head.group(1)
|
| n_decl = int(m_head.group(2))
|
|
|
|
|
| paren_text_pos = header_text.find("(", m_head.end())
|
| if paren_text_pos == -1:
|
| raise ValueError(f"缺失数据起始 '(': {path}")
|
|
|
| paren_raw_pos = len(header_text[:paren_text_pos].encode("latin-1"))
|
|
|
|
|
|
|
|
|
|
|
| check_start = paren_raw_pos + 1
|
| check_end = min(check_start + 200, len(raw))
|
| sample = raw[check_start:check_end]
|
| is_ascii = all(
|
| (0x20 <= b <= 0x7e) or b in (0x09, 0x0a, 0x0d)
|
| for b in sample
|
| )
|
|
|
| if is_ascii:
|
| return _read_ascii_field(header_text, paren_text_pos, ftype, path)
|
| else:
|
| return _read_binary_field(raw, paren_text_pos, ftype, n_decl, path)
|
|
|
|
|
| def _read_binary_field(raw, paren_pos, ftype, n_decl, path):
|
| """解析 OpenFOAM binary 格式字段数据
|
|
|
| OpenFOAM v1906 (ESI) binary format:
|
| '(' + N * data_bytes + ')'
|
|
|
| 数据直接跟在 '(' 之后(无 marker / count),
|
| 为 little-endian float64:
|
| vector: N * 3 * float64 (LE)
|
| scalar: N * float64 (LE)
|
|
|
| 数据块以 ');\n' 结束。
|
| """
|
|
|
| data_start = paren_pos + 1
|
|
|
| if ftype == "vector":
|
| n_bytes = n_decl * 3 * 8
|
| data = np.frombuffer(raw[data_start:data_start + n_bytes], dtype="<f8")
|
| data = data.reshape(n_decl, 3)
|
| return np.array(data, dtype=np.float64)
|
| else:
|
| n_bytes = n_decl * 8
|
| data = np.frombuffer(raw[data_start:data_start + n_bytes], dtype="<f8")
|
| return data.astype(np.float64)
|
|
|
|
|
| def _read_ascii_field(header_text, paren_pos, ftype, path):
|
| """解析 OpenFOAM ASCII 格式字段数据"""
|
|
|
| start = paren_pos
|
| m_end = re.search(r"\n\s*\)\s*;", header_text[start:])
|
| if m_end:
|
| end = start + m_end.start()
|
| else:
|
| end = header_text.rfind(")")
|
| block = header_text[start + 1:end].strip()
|
| lines = [ln.strip() for ln in block.splitlines() if ln.strip()]
|
|
|
| if ftype == "vector":
|
| arr = []
|
| for ln in lines:
|
| nums = re.findall(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", ln)
|
| arr.append([float(x) for x in nums[:3]])
|
| return np.array(arr, dtype=np.float64)
|
| else:
|
| vals = []
|
| for ln in lines:
|
| m = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", ln)
|
| vals.append(float(m.group(0)) if m else 0.0)
|
| return np.array(vals, dtype=np.float64)
|
|
|
|
|
| def _read_uniform_field(header_text, path, n_cells=None):
|
| """解析 OpenFOAM uniform 格式字段"""
|
| m_uni = re.search(
|
| r"internalField\s+uniform\s*(.*?);", header_text, re.DOTALL
|
| )
|
| if not m_uni:
|
| raise ValueError(f"无法解析 internalField: {path}")
|
|
|
| token = m_uni.group(1).strip()
|
| if token.startswith("(") and token.endswith(")"):
|
| inner = token[1:-1].strip()
|
| items = inner.split()
|
| else:
|
| items = token.split()
|
| nums = []
|
| for it in items:
|
| try:
|
| nums.append(float(it))
|
| except ValueError:
|
| pass
|
|
|
| if n_cells is not None:
|
| n_points = n_cells
|
| else:
|
| n_points = _try_read_n_points(path)
|
| if len(nums) == 3:
|
| vec = np.array(nums, dtype=np.float64)
|
| return np.tile(vec, (n_points, 1))
|
| elif len(nums) == 1:
|
| return np.full(n_points, nums[0], dtype=np.float64)
|
| else:
|
| raise ValueError(f"uniform 场解析异常 ({len(nums)} 个数值): {path}")
|
|
|
|
|
| def _try_read_n_points(path):
|
| """尝试从同级目录的 C 文件或上下文推断网格点数"""
|
| parent = os.path.dirname(path)
|
|
|
| c_path = os.path.join(parent, "C")
|
| if not os.path.exists(c_path):
|
|
|
| for d in os.listdir(parent):
|
| if d.startswith("C"):
|
| c_path = os.path.join(parent, d)
|
| break
|
| if os.path.exists(c_path):
|
| with open(c_path, "r", encoding="latin-1") as f:
|
| txt = f.read()
|
| m = re.search(r"nonuniform\s+List<\w+>\s+(\d+)", txt)
|
| if m:
|
| return int(m.group(1))
|
| raise ValueError(f"无法推断网格点数: {path}")
|
|
|
|
|
|
|
|
|
| def parse_block_mesh(case_dir):
|
| """从 system/blockMeshDict 解析网格参数
|
|
|
| 返回: dict {"nx", "ny", "x0", "y0", "dx", "dy", "Lx", "Ly"}
|
| """
|
| bmd_path = os.path.join(case_dir, "system", "blockMeshDict")
|
| with open(bmd_path, "r", encoding="latin-1") as f:
|
| content = f.read()
|
|
|
|
|
| v_start = content.find("vertices")
|
| if v_start == -1:
|
| raise ValueError(f"blockMeshDict 中未找到 vertices: {bmd_path}")
|
| v_paren = content.find("(", v_start)
|
| depth, v_end = 0, v_paren
|
| for ci in range(v_paren, len(content)):
|
| if content[ci] == "(":
|
| depth += 1
|
| elif content[ci] == ")":
|
| depth -= 1
|
| if depth == 0:
|
| v_end = ci
|
| break
|
| v_block = content[v_paren:v_end + 1]
|
|
|
| verts = re.findall(
|
| r"\(\s*([\d.eE+\-]+)\s+([\d.eE+\-]+)\s+([\d.eE+\-]+)\s*\)", v_block
|
| )
|
| if len(verts) < 3:
|
| raise ValueError(f"blockMeshDict vertices 不足: {bmd_path}")
|
|
|
| xs = [float(v[0]) for v in verts]
|
| ys = [float(v[1]) for v in verts]
|
| zs = [float(v[2]) for v in verts]
|
| x0, x1 = min(xs), max(xs)
|
| y0, y1 = min(ys), max(ys)
|
| z0, z1 = min(zs), max(zs)
|
|
|
| m = re.search(r"hex\s+\([^)]+\)\s+\(\s*(\d+)\s+(\d+)\s+(\d+)\s*\)", content)
|
| if not m:
|
| raise ValueError(f"无法解析 blockMeshDict blocks: {bmd_path}")
|
| nx, ny, nz = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
|
|
|
|
| nrows = nz if (ny == 1 and nz > 1) else ny
|
|
|
| Lx = x1 - x0
|
|
|
| if ny == 1 and nz > 1:
|
| Ly = z1 - z0
|
| else:
|
| Ly = y1 - y0
|
| dx = Lx / nx
|
| dy = Ly / nrows
|
|
|
| return {
|
| "nx": nx, "ny": nrows, "nz": nz,
|
| "ny_orig": ny, "nz_orig": nz,
|
| "x0": x0, "y0": y0,
|
| "dx": dx, "dy": dy,
|
| "Lx": Lx, "Ly": Ly,
|
| }
|
|
|
|
|
|
|
|
|
| def find_time_dirs(case_dir):
|
| """发现 case 目录下的所有数值时间步目录(已 reconstructPar 合并)"""
|
| time_dirs = []
|
| for entry in os.listdir(case_dir):
|
| full_path = os.path.join(case_dir, entry)
|
| if os.path.isdir(full_path) and re.match(r"^\d+(\.\d+)?$", entry):
|
|
|
| if os.path.exists(os.path.join(full_path, "U")):
|
| time_dirs.append(entry)
|
| time_dirs.sort(key=lambda x: float(x))
|
| return time_dirs
|
|
|
|
|
| def find_processor_dirs(case_dir):
|
| """发现 case 下所有 processor 子目录
|
|
|
| 每个 processor 目录必须包含至少一个数值时间目录且时间目录含 U 文件。
|
| 返回按编号排序的目录名列表,如 ["processor0", "processor1"]。
|
| """
|
| proc_dirs = []
|
| for entry in os.listdir(case_dir):
|
| full_path = os.path.join(case_dir, entry)
|
| if not os.path.isdir(full_path) or not entry.startswith("processor"):
|
| continue
|
|
|
| for t_entry in os.listdir(full_path):
|
| t_path = os.path.join(full_path, t_entry)
|
| if (os.path.isdir(t_path) and
|
| re.match(r"^\d+(\.\d+)?$", t_entry) and
|
| os.path.exists(os.path.join(t_path, "U"))):
|
| proc_dirs.append(entry)
|
| break
|
|
|
| proc_dirs.sort(key=lambda d: int(re.search(r"\d+", d).group()))
|
| return proc_dirs
|
|
|
|
|
| def find_processor_time_dirs(case_dir, proc_dirs):
|
| """从 processor0 发现所有数值时间目录(并行模式)
|
|
|
| 返回排序后的时间目录名列表(字符串)。
|
| """
|
| ref_dir = os.path.join(case_dir, proc_dirs[0])
|
| time_dirs = []
|
| for entry in os.listdir(ref_dir):
|
| full_path = os.path.join(ref_dir, entry)
|
| if os.path.isdir(full_path) and re.match(r"^\d+(\.\d+)?$", entry):
|
| if os.path.exists(os.path.join(full_path, "U")):
|
| time_dirs.append(entry)
|
| time_dirs.sort(key=lambda x: float(x))
|
| return time_dirs
|
|
|
|
|
| def filter_time_dirs(time_dirs, times_str):
|
| """按用户指定的时间值筛选时间目录(最近匹配)
|
|
|
| 参数:
|
| time_dirs: 可用时间目录名列表(字符串),如 ["0", "0.01", "0.02"]
|
| times_str: 逗号分隔的时间值,如 "0,0.5,1,1.5,2"
|
|
|
| 返回:
|
| 筛选后的时间目录名列表(保持原顺序)
|
|
|
| 匹配容差: max(1e-4, 1e-6 * |t_requested|)(适配 OpenFOAM 输出精度)
|
| """
|
| requested = [float(t.strip()) for t in times_str.split(",")]
|
| available = [(float(t), t) for t in time_dirs]
|
| selected = set()
|
| for req in requested:
|
| best_dir = None
|
| best_diff = float("inf")
|
| for avail_val, avail_dir in available:
|
| diff = abs(avail_val - req)
|
| if diff < best_diff:
|
| best_diff = diff
|
| best_dir = avail_dir
|
| tol = max(1e-4, 1e-6 * abs(req))
|
| if best_dir is not None and best_diff < tol:
|
| selected.add(best_dir)
|
| else:
|
| logging.warning(f" --times: 未找到接近 {req} 的时间目录 (最近距离={best_diff:.6g})")
|
| return [t for t in time_dirs if t in selected]
|
|
|
|
|
| def _detect_decomposition(dict_path, nx, ny, n_procs, cells_per_proc):
|
| """推断 decomposePar 的 (n_x, n_y) 分解模式。
|
|
|
| 优先从 decomposeParDict 读取;若不可用则根据 cell 数推断。
|
| 返回 (n_x, n_y),始终满足 n_x * n_y == n_procs。
|
| """
|
|
|
| if os.path.exists(dict_path):
|
| try:
|
| 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:
|
| n_x_f, n_y_f = int(m.group(1)), int(m.group(2))
|
| if n_x_f * n_y_f == n_procs:
|
| logging.debug(f" decomposeParDict: n=({n_x_f},{n_y_f},1)")
|
| return n_x_f, n_y_f
|
| except Exception:
|
| pass
|
|
|
|
|
| for cand_x in range(1, n_procs + 1):
|
| if n_procs % cand_x != 0:
|
| continue
|
| cand_y = n_procs // cand_x
|
| blk_nx = nx // cand_x if cand_x <= nx else None
|
| blk_ny = ny // cand_y if cand_y <= ny else None
|
| if blk_nx and blk_ny and blk_nx * blk_ny == cells_per_proc:
|
| return cand_x, cand_y
|
|
|
|
|
| logging.warning(f" 无法推断分解模式,默认 n=({n_procs},1,1)")
|
| return n_procs, 1
|
|
|
|
|
| def _read_cell_addressing(path):
|
| """读取 cellProcAddressing 文件,返回全局 cell ID 数组。
|
|
|
| 格式: ASCII labelList(每行一个整数),在 ( 和 ) 之间。
|
| """
|
| with open(path, "r", encoding="latin-1") as f:
|
| text = f.read()
|
| lines = text.split("\n")
|
| data_started = False
|
| ids = []
|
| for line in lines:
|
| s = line.strip()
|
| if s == "(":
|
| data_started = True
|
| continue
|
| if s == ")":
|
| break
|
| if data_started and s:
|
| ids.append(int(s))
|
| return np.array(ids, dtype=np.int64)
|
|
|
|
|
| def _read_proc_field(path, ftype, pnx, pny):
|
| """读取单个 processor 的标量或向量场,返回 reshape 后的数组。
|
|
|
| 标量: shape (pny, pnx) 向量: shape (pny, pnx, 3)
|
| """
|
| raw = read_foam_field(path, n_cells=pnx * pny)
|
| if ftype == "vector":
|
| return raw.reshape(pny, pnx, 3)
|
| else:
|
| return raw.reshape(pny, pnx)
|
|
|
|
|
|
|
|
|
| def process_case(case_dir, h5_path, crop=1.0, from_processors=False, times=None,
|
| case_type=None):
|
| """处理单个 case: 读取所有时间步,写入 HDF5
|
|
|
| 参数:
|
| case_dir: OpenFOAM case 根目录
|
| h5_path: HDF5 输出文件完整路径
|
| crop: 水槽尾部裁剪比例 (0-1),1.0=不裁剪
|
| from_processors: 若为 True,从 processor*/ 目录直接读取(跳过 reconstructPar)
|
| times: 逗号分隔的时间值字符串(如 "0,0.5,1"),None 表示全部时间步
|
| case_type: 案例类型名(如 "dam_break"),用于 HDF5 case_name 属性
|
| """
|
| case_name = case_type if case_type else os.path.basename(case_dir)
|
|
|
|
|
| mesh = parse_block_mesh(case_dir)
|
| nx, ny = mesh["nx"], mesh["ny"]
|
|
|
| is_xz = (mesh.get("ny_orig", ny) == 1 and mesh.get("nz_orig", 1) > 1)
|
| v_comp = 2 if is_xz else 1
|
| logging.info(f" 网格: {nx}x{ny}, 域尺寸: {mesh['Lx']:.4f}x{mesh['Ly']:.4f} m"
|
| f"{' (x-z plane)' if is_xz else ''}")
|
|
|
|
|
| x_1d = np.array([mesh["x0"] + (i + 0.5) * mesh["dx"] for i in range(nx)])
|
| y_1d = np.array([mesh["y0"] + (j + 0.5) * mesh["dy"] for j in range(ny)])
|
| x_grid, y_grid = np.meshgrid(x_1d, y_1d, indexing="ij")
|
|
|
| if from_processors:
|
|
|
| proc_dirs = find_processor_dirs(case_dir)
|
| if not proc_dirs:
|
| logging.warning(f" 未发现 processor 目录: {case_dir}")
|
| return
|
| n_procs = len(proc_dirs)
|
| logging.info(f" 并行模式: {n_procs} 个 processor")
|
|
|
|
|
| time_dirs = find_processor_time_dirs(case_dir, proc_dirs)
|
| if times is not None:
|
| time_dirs = filter_time_dirs(time_dirs, times)
|
| n_frames = len(time_dirs)
|
| if n_frames == 0:
|
| logging.warning(f" 未发现时间步: {case_dir}")
|
| return
|
| logging.info(f" 时间步数: {n_frames}")
|
|
|
|
|
| total_mesh = nx * ny
|
| proc_global_ids = {}
|
| for proc_dir in proc_dirs:
|
| addr_path = os.path.join(case_dir, proc_dir, "constant", "polyMesh",
|
| "cellProcAddressing")
|
| if os.path.exists(addr_path):
|
| proc_global_ids[proc_dir] = _read_cell_addressing(addr_path)
|
| else:
|
| proc_global_ids[proc_dir] = None
|
|
|
|
|
| detect_t = time_dirs[1] if len(time_dirs) > 1 else time_dirs[0]
|
| first_u_path = os.path.join(case_dir, proc_dirs[0], detect_t, "U")
|
| first_u = read_foam_field(first_u_path, n_cells=nx * ny)
|
| first_n_cells = first_u.shape[0]
|
|
|
| if first_n_cells >= total_mesh:
|
|
|
| logging.info(f" processor0 有完整 mesh ({first_n_cells} cells),仅读 processor0")
|
| proc_dirs = [proc_dirs[0]]
|
| proc_ncells_list = [total_mesh]
|
| use_addressing = False
|
| proc_local_blocks = [(nx, ny, slice(0, ny), slice(0, nx))]
|
|
|
| elif all(v is not None for v in proc_global_ids.values()):
|
|
|
| use_addressing = True
|
| proc_ncells_list = [len(proc_global_ids[pd]) for pd in proc_dirs]
|
| logging.info(f" 使用 cellProcAddressing 精确映射 ({n_procs} 个 processor)")
|
|
|
| else:
|
|
|
| use_addressing = False
|
| decomp_dict_path = os.path.join(case_dir, "system", "decomposeParDict")
|
| n_x, n_y = _detect_decomposition(decomp_dict_path, nx, ny, n_procs,
|
| first_n_cells)
|
|
|
| proc_local_blocks = []
|
| if n_y > 1:
|
| logging.info(f" 2D 分解: n=({n_x},{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
|
| proc_local_blocks.append(
|
| (bx1 - bx0, by1 - by0, slice(by0, by1), slice(bx0, bx1))
|
| )
|
| else:
|
| logging.info(f" 1D x-分解: n=({n_x},1,1)")
|
| 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]
|
| proc_local_blocks.append(
|
| (pnx, ny, slice(0, ny), slice(boundaries[pid], boundaries[pid + 1]))
|
| )
|
| proc_ncells_list = [bnx * bny for bnx, bny, _, _ in proc_local_blocks]
|
|
|
|
|
| u_full = np.zeros((n_frames, ny, nx), dtype=np.float32)
|
| v_full = np.zeros((n_frames, ny, nx), dtype=np.float32)
|
| p_full = np.zeros((n_frames, ny, nx), dtype=np.float32)
|
| alpha_full = np.zeros((n_frames, ny, nx), dtype=np.float32)
|
| times_arr = np.zeros(n_frames, dtype=np.float64)
|
|
|
| for i, t_dir in enumerate(time_dirs):
|
| times_arr[i] = float(t_dir)
|
|
|
| for j, proc_dir in enumerate(proc_dirs):
|
| proc_base = os.path.join(case_dir, proc_dir, t_dir)
|
| n_local = proc_ncells_list[j]
|
|
|
| if use_addressing:
|
|
|
| global_ids = proc_global_ids[proc_dir]
|
| g_ix = global_ids % nx
|
| g_iy = global_ids // nx
|
|
|
| u_raw = read_foam_field(os.path.join(proc_base, "U"),
|
| n_cells=n_local)
|
| if u_raw.ndim == 1:
|
| u_raw = u_raw.reshape(-1, 3)
|
| u_full[i, g_iy, g_ix] = u_raw[:, 0].astype(np.float32)
|
| v_full[i, g_iy, g_ix] = u_raw[:, v_comp].astype(np.float32)
|
|
|
| p_raw = read_foam_field(os.path.join(proc_base, "p_rgh"),
|
| n_cells=n_local)
|
| p_full[i, g_iy, g_ix] = p_raw.astype(np.float32)
|
|
|
| a_raw = read_foam_field(os.path.join(proc_base, "alpha.water"),
|
| n_cells=n_local)
|
| alpha_full[i, g_iy, g_ix] = a_raw.astype(np.float32)
|
| else:
|
|
|
| pnx, pny, rows, cols = proc_local_blocks[j]
|
| u_local = _read_proc_field(os.path.join(proc_base, "U"),
|
| "vector", pnx, pny)
|
| u_full[i, rows, cols] = u_local[:, :, 0].astype(np.float32)
|
| v_full[i, rows, cols] = u_local[:, :, 1].astype(np.float32)
|
|
|
| p_local = _read_proc_field(os.path.join(proc_base, "p_rgh"),
|
| "scalar", pnx, pny)
|
| p_full[i, rows, cols] = p_local.astype(np.float32)
|
|
|
| a_local = _read_proc_field(os.path.join(proc_base, "alpha.water"),
|
| "scalar", pnx, pny)
|
| alpha_full[i, rows, cols] = a_local.astype(np.float32)
|
|
|
|
|
| u_data = u_full.transpose(0, 2, 1)
|
| v_data = v_full.transpose(0, 2, 1)
|
| p_data = p_full.transpose(0, 2, 1)
|
| alpha_data = alpha_full.transpose(0, 2, 1)
|
| times = times_arr
|
|
|
| else:
|
|
|
| time_dirs = find_time_dirs(case_dir)
|
| if times is not None:
|
| time_dirs = filter_time_dirs(time_dirs, times)
|
| n_frames = len(time_dirs)
|
| if n_frames == 0:
|
| logging.warning(f" 未发现时间步: {case_dir}")
|
| return
|
| logging.info(f" 时间步数: {n_frames}")
|
|
|
|
|
| u_data = np.zeros((n_frames, nx, ny), dtype=np.float32)
|
| v_data = np.zeros((n_frames, nx, ny), dtype=np.float32)
|
| p_data = np.zeros((n_frames, nx, ny), dtype=np.float32)
|
| alpha_data = np.zeros((n_frames, nx, ny), dtype=np.float32)
|
| times = np.zeros(n_frames, dtype=np.float64)
|
|
|
| for i, t_dir in enumerate(time_dirs):
|
| t_path = os.path.join(case_dir, t_dir)
|
| times[i] = float(t_dir)
|
|
|
|
|
| expected = ny * nx
|
| u_raw = read_foam_field(os.path.join(t_path, "U"), n_cells=expected)
|
|
|
| if u_raw.shape[0] != expected:
|
| raise ValueError(
|
| f"U field size {u_raw.shape[0]} != mesh {expected} ({ny}x{nx})"
|
| )
|
|
|
| u_vec = u_raw.reshape(ny, nx, 3).transpose(1, 0, 2)
|
| u_data[i] = u_vec[:, :, 0].astype(np.float32)
|
| v_data[i] = u_vec[:, :, v_comp].astype(np.float32)
|
|
|
|
|
| p_raw = read_foam_field(os.path.join(t_path, "p_rgh"), n_cells=expected)
|
| p_data[i] = p_raw.reshape(ny, nx).T.astype(np.float32)
|
|
|
|
|
| alpha_raw = read_foam_field(os.path.join(t_path, "alpha.water"), n_cells=expected)
|
| alpha_data[i] = alpha_raw.reshape(ny, nx).T.astype(np.float32)
|
|
|
|
|
| if crop < 1.0:
|
| nx_crop = max(1, int(nx * crop))
|
| logging.info(f" 裁剪: nx {nx} → {nx_crop} (crop={crop})")
|
| u_data = u_data[:, :nx_crop, :]
|
| v_data = v_data[:, :nx_crop, :]
|
| p_data = p_data[:, :nx_crop, :]
|
| alpha_data = alpha_data[:, :nx_crop, :]
|
| x_grid = x_grid[:nx_crop, :]
|
| y_grid = y_grid[:nx_crop, :]
|
| nx = nx_crop
|
|
|
|
|
| os.makedirs(os.path.dirname(h5_path), exist_ok=True)
|
| with h5py.File(h5_path, "w") as f:
|
|
|
| f.create_dataset("u", data=u_data, compression="gzip", compression_opts=4)
|
| f.create_dataset("v", data=v_data, compression="gzip", compression_opts=4)
|
| f.create_dataset("p", data=p_data, compression="gzip", compression_opts=4)
|
| f.create_dataset("alpha", data=alpha_data, compression="gzip", compression_opts=4)
|
| f.create_dataset("x_grid", data=x_grid)
|
| f.create_dataset("y_grid", data=y_grid)
|
|
|
| f.attrs["nx"] = nx
|
| f.attrs["ny"] = ny
|
| f.attrs["n_saved"] = n_frames
|
| f.attrs["times"] = times
|
| f.attrs["case_name"] = case_name
|
| f.attrs["mesh_Lx"] = mesh["Lx"]
|
| f.attrs["mesh_Ly"] = mesh["Ly"]
|
|
|
| logging.info(f" HDF5 写入: {h5_path}")
|
| logging.info(f" u 范围: [{u_data.min():.6f}, {u_data.max():.6f}]")
|
| logging.info(f" alpha 范围: [{alpha_data.min():.6f}, {alpha_data.max():.6f}]")
|
|
|
|
|
| def discover_trajectories(input_dir):
|
| """自动发现 input_dir 下的所有 trajectory,按 case_type 组织
|
|
|
| 发现逻辑: {input_dir}/{case_type}/tNN/ 目录中含 Allrun + system/blockMeshDict
|
|
|
| 返回:
|
| dict: {case_type: [(traj_idx, case_dir), ...], ...}
|
| """
|
| cases_by_type = {}
|
| case_types = ["dam_break", "rising_bubble", "droplet_impact", "stokes_wave"]
|
|
|
| for case_type in case_types:
|
| case_type_dir = os.path.join(input_dir, case_type)
|
| if not os.path.isdir(case_type_dir):
|
| continue
|
| trajectories = []
|
| for entry in sorted(os.listdir(case_type_dir)):
|
| traj_dir = os.path.join(case_type_dir, entry)
|
| if not os.path.isdir(traj_dir):
|
| continue
|
|
|
| if (os.path.exists(os.path.join(traj_dir, "Allrun")) and
|
| os.path.exists(os.path.join(traj_dir, "system", "blockMeshDict"))):
|
|
|
| try:
|
| traj_idx = int(entry.lstrip("t"))
|
| except ValueError:
|
| traj_idx = len(trajectories)
|
| trajectories.append((traj_idx, traj_dir))
|
| if trajectories:
|
| cases_by_type[case_type] = sorted(trajectories, key=lambda x: x[0])
|
|
|
| return cases_by_type
|
|
|
|
|
| def main():
|
| parser = argparse.ArgumentParser(
|
| description="OpenFOAM interFoam 原生输出 → HDF5 转换"
|
| )
|
| parser.add_argument(
|
| "--input", type=str, default="/opt/output",
|
| help="包含 case 目录的根目录(含 dam_break/, rising_bubble/, droplet_impact/ 子目录)"
|
| )
|
| parser.add_argument(
|
| "--output", type=str, default=None,
|
| help="HDF5 输出根目录(默认 = 输入目录)"
|
| )
|
| parser.add_argument(
|
| "--crop", type=float, default=1.0,
|
| help="水槽尾部裁剪比例 (0-1),默认 1.0 不裁剪。仅对波浪案例有效,裁剪 x 方向尾部区域"
|
| )
|
| parser.add_argument(
|
| "--from-processors", action="store_true", default=False,
|
| help="从 processor*/ 目录直接读取,跳过 reconstructPar(并行模式)"
|
| )
|
| parser.add_argument(
|
| "--times", type=str, default=None,
|
| help="仅处理指定时间值(逗号分隔,如 '0,0.5,1,1.5,2'),默认全部时间步"
|
| )
|
| parser.add_argument(
|
| "-v", "--verbose", action="store_true",
|
| help="详细日志输出"
|
| )
|
| args = parser.parse_args()
|
|
|
| logging.basicConfig(
|
| level=logging.DEBUG if args.verbose else logging.INFO,
|
| format="%(asctime)s [%(levelname)s] %(message)s",
|
| datefmt="%Y-%m-%d %H:%M:%S",
|
| )
|
|
|
| output_root = args.output if args.output else args.input
|
|
|
|
|
| cases_by_type = discover_trajectories(args.input)
|
|
|
| if not cases_by_type:
|
| logging.warning(f"未发现任何 case 目录: {args.input}")
|
| return
|
|
|
| total = sum(len(v) for v in cases_by_type.values())
|
| logging.info(f"发现 {total} 个 trajectory: " +
|
| ", ".join(f"{k}={len(v)}" for k, v in cases_by_type.items()))
|
|
|
| success = 0
|
| failed = 0
|
|
|
| for case_type, trajectories in cases_by_type.items():
|
|
|
| h5_dir = os.path.join(output_root, case_type)
|
| os.makedirs(h5_dir, exist_ok=True)
|
|
|
| for traj_idx, case_dir in trajectories:
|
|
|
| h5_path = os.path.join(h5_dir, f"traj_{traj_idx:04d}.h5")
|
| logging.info(f"处理: {case_type}/t{traj_idx:02d} → {os.path.basename(h5_path)}")
|
| try:
|
| process_case(case_dir, h5_path, crop=args.crop, from_processors=args.from_processors, times=args.times, case_type=case_type)
|
| success += 1
|
| except Exception as e:
|
| logging.error(f" 处理失败: {e}")
|
| failed += 1
|
| if args.verbose:
|
| import traceback
|
| traceback.print_exc()
|
|
|
| logging.info(f"=== 后处理完成: 成功 {success}, 失败 {failed} ===")
|
|
|
|
|
| if __name__ == "__main__":
|
| main()
|
|
|