#!/usr/bin/env python3 """ gen_init_conditions.py — 从 case 模板生成 N 个 trajectory(不同初始条件) 使用 Latin Hypercube Sampling (LHS) 采样初始条件参数,复制模板目录, 直接生成 0/ 目录下的 alpha.water 和 U 场文件(stokes_wave 除外, 该类型通过修改 waveProperties 和 setFieldsDict 实现参数化)。 四个 case 类型的参数空间: - dam_break: 水柱宽度、高度 - rising_bubble: 气泡半径、水平位置、垂直位置 - droplet_impact: 液滴半径、水平位置、初始高度、撞击速度 - stokes_wave: 波高、波周期、静水位高度(修改 constant/waveProperties 和 system/setFieldsDict,alpha.water 由 setFields 初始化) 用法: python3 gen_init_conditions.py --templates /opt/cases-templates --output /opt/output/exp-openfoam-001 输出目录结构: output_dir/ ├── dam_break/ │ ├── t00/ ← 0/, constant/, system/, Allrun │ ├── t01/ │ └── ... ├── rising_bubble/ │ ├── t00/ │ └── ... ├── droplet_impact/ │ ├── t00/ │ └── ... ├── stokes_wave/ │ ├── t00/ │ └── ... └── manifest.yaml ← 全局 manifest(case 列表 + 参数记录) 参考文献: [1] OpenFOAM Foundation. OpenFOAM v9 User Guide, 2021. [2] Hysing, S. et al. (2009). "Quantitative benchmark computations of two-dimensional bubble dynamics." Int. J. Numer. Meth. Fluids, 60(11), 1259-1288. [3] Pasandideh-Fard, M. et al. (1996). "Capillary effects during droplet impact on a solid surface." Phys. Fluids, 8(3), 650-659. """ import argparse import os import re import shutil import logging from datetime import datetime, timezone import numpy as np from scipy.stats.qmc import LatinHypercube try: import yaml HAS_YAML = True except ImportError: HAS_YAML = False # ─── 全局常量 ──────────────────────────────────────────────────────────── NUM_TRAJS = 50 # 总 trajectory 数(35 train + 8 val + 7 test) GLOBAL_SEED = 42 # 全局随机种子(可复现) # ─── OpenFOAM 字段文件生成 ────────────────────────────────────────────── def write_foam_header(f, obj_name, cls, location="0"): """写入 OpenFOAM FoamFile header 块""" f.write("FoamFile\n{\n") f.write(" version 2.0;\n") f.write(" format ascii;\n") f.write(f" class {cls};\n") f.write(f" location \"{location}\";\n") f.write(f" object {obj_name};\n") f.write("}\n\n") def write_scalar_field(path, header_comment, internal_values, dims="[0 0 0 0 0 0 0]"): """写入 volScalarField(internalField 非均匀列表)""" n = len(internal_values) with open(path, "w") as f: write_foam_header(f, os.path.basename(path), "volScalarField") f.write(f"dimensions {dims};\n\n") f.write(f"internalField nonuniform List\n{n}\n(\n") for val in internal_values: f.write(f" {val:.10e}\n") f.write(")\n;\n\n") # 边界条件从模板复制(此处只写 internalField,BC 已在模板 0/ 中) # 注意:此处覆写整个文件,BC 由 _copy_boundary_conditions 补回 def write_vector_field(path, header_comment, internal_values, dims="[0 1 -1 0 0 0 0]"): """写入 volVectorField(internalField 非均匀列表)""" n = len(internal_values) with open(path, "w") as f: write_foam_header(f, os.path.basename(path), "volVectorField") f.write(f"dimensions {dims};\n\n") f.write(f"internalField nonuniform List\n{n}\n(\n") for vx, vy, vz in internal_values: f.write(f" ({vx:.10e} {vy:.10e} {vz:.10e})\n") f.write(")\n;\n\n") def _copy_boundary_conditions(src_path, dst_path): """从模板文件复制 boundaryField 块追加到目标文件""" with open(src_path, "r") as f: content = f.read() # 提取 boundaryField 块(从 boundaryField 到末尾) m = re.search(r"(boundaryField\s*\{[\s\S]*\})", content) if m: with open(dst_path, "a") as f: f.write("\n") f.write(m.group(1)) f.write("\n") def has_simulation_data(output_dir): """检查目录是否包含仿真结果(log.interFoam 或 0 以外的时间步目录)""" if not os.path.exists(output_dir): return False # 检查 log.interFoam if os.path.exists(os.path.join(output_dir, "log.interFoam")): return True # 检查是否有 0/ 以外的时间步目录 for entry in os.listdir(output_dir): full = os.path.join(output_dir, entry) if os.path.isdir(full) and re.match(r"^\d+(\.\d+)?$", entry): if entry != "0": return True return False def copy_template(template_dir, output_dir, force=False): """复制 case 模板到输出目录(含 0/ 目录下的所有模板场文件) 参数: force: 若为 False 且 output_dir 已有仿真数据,跳过并返回 False; 若为 True,强制覆盖。 返回: bool: True 表示复制成功,False 表示跳过 """ if os.path.exists(output_dir): if not force and has_simulation_data(output_dir): logging.info(f" 跳过(已有仿真数据): {output_dir}") return False shutil.rmtree(output_dir) shutil.copytree(template_dir, output_dir) return True # ─── blockMeshDict 解析 ───────────────────────────────────────────────── def parse_block_mesh(case_dir): """从 system/blockMeshDict 解析网格参数 返回: dict: { "nx": int, "ny": int, "nz": int, "x0": float, "y0": float, "dx": float, "dy": float, "Lx": float, "Ly": float } """ bmd_path = os.path.join(case_dir, "system", "blockMeshDict") with open(bmd_path, "r") as f: content = f.read() # 解析 vertices:取第 0 号 (x0, y0, z0) 和第 2 号 (x1, y1, z0) verts = re.findall(r"\(\s*([\d.eE+\-]+)\s+([\d.eE+\-]+)\s+([\d.eE+\-]+)\s*\)", content) if len(verts) < 3: raise ValueError(f"blockMeshDict vertices 不足: {bmd_path}") x0, y0 = float(verts[0][0]), float(verts[0][1]) x1, y1 = float(verts[2][0]), float(verts[2][1]) # 解析 blocks hex (... ) (nx ny nz) 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)) Lx = x1 - x0 Ly = y1 - y0 dx = Lx / nx dy = Ly / ny return { "nx": nx, "ny": ny, "nz": nz, "x0": x0, "y0": y0, "dx": dx, "dy": dy, "Lx": Lx, "Ly": Ly } def compute_cell_centers(mesh): """计算 cell 中心坐标 返回: x_centers: np.ndarray, shape (ny, nx) — X 坐标 y_centers: np.ndarray, shape (ny, nx) — Y 坐标 flat_idx: np.ndarray, shape (ny*nx,) — 展平索引(行主序) """ nx, ny = mesh["nx"], mesh["ny"] dx, dy = mesh["dx"], mesh["dy"] x0, y0 = mesh["x0"], mesh["y0"] # Cell 中心: x_i = x0 + (i + 0.5) * dx, y_j = y0 + (j + 0.5) * dy # 行主序: k = j * nx + i (j=Y方向索引, i=X方向索引) x_1d = np.array([x0 + (i + 0.5) * dx for i in range(nx)]) y_1d = np.array([y0 + (j + 0.5) * dy for j in range(ny)]) # meshgrid: x_centers[j, i], y_centers[j, i] x_centers, y_centers = np.meshgrid(x_1d, y_1d) # shape (ny, nx) flat_idx = np.arange(nx * ny) return x_centers, y_centers, flat_idx # ─── Case 特定场生成 ─────────────────────────────────────────────────── def _generate_dam_break_fields(case_dir, params, mesh, x_centers, y_centers): """生成 dam_break 的 alpha.water 和 U 初始场 参数: params: dict {"width": float, "height": float} - width: 水柱宽度 [m], 默认 (0.08, 0.40) - height: 水柱高度 [m], 默认 (0.15, 0.50) """ nx, ny = mesh["nx"], mesh["ny"] x0, y0 = mesh["x0"], mesh["y0"] Lx, Ly = mesh["Lx"], mesh["Ly"] width = params["width"] height = params["height"] x_wall = x0 + width # 水柱右边界 # alpha.water: 水柱区域内 = 1, 外部 = 0 alpha = np.where( (x_centers <= x_wall) & (y_centers <= y0 + height), 1.0, 0.0 ).ravel() # U: 全零初始速度 u_field = np.zeros((nx * ny, 3)) # 写入场文件 alpha_path = os.path.join(case_dir, "0", "alpha.water") template_alpha = os.path.join(case_dir, "0", "alpha.water.template") write_scalar_field(alpha_path, "alpha.water", alpha) _copy_boundary_conditions(template_alpha, alpha_path) u_path = os.path.join(case_dir, "0", "U") template_u = os.path.join(case_dir, "0", "U.template") write_vector_field(u_path, "U", u_field) _copy_boundary_conditions(template_u, u_path) def _generate_rising_bubble_fields(case_dir, params, mesh, x_centers, y_centers): """生成 rising_bubble 的 alpha.water 和 U 初始场 参数: params: dict {"radius": float, "cx": float, "cy": float} - radius: 气泡半径 [m], 固定 0.25(对齐 Hysing Case 1) - cx: 水平中心 [m], 默认 (0.30, 0.70) - cy: 垂直中心 [m], 默认 (0.30, 0.80) """ nx, ny = mesh["nx"], mesh["ny"] radius = params["radius"] cx = params["cx"] cy = params["cy"] # alpha.water: 气泡内部 (alpha=0), 外部 (alpha=1) dist = np.sqrt((x_centers - cx)**2 + (y_centers - cy)**2) alpha = np.where(dist <= radius, 0.0, 1.0).ravel() # U: 全零初始速度 u_field = np.zeros((nx * ny, 3)) # 写入场文件 alpha_path = os.path.join(case_dir, "0", "alpha.water") template_alpha = os.path.join(case_dir, "0", "alpha.water.template") write_scalar_field(alpha_path, "alpha.water", alpha) _copy_boundary_conditions(template_alpha, alpha_path) u_path = os.path.join(case_dir, "0", "U") template_u = os.path.join(case_dir, "0", "U.template") write_vector_field(u_path, "U", u_field) _copy_boundary_conditions(template_u, u_path) def _generate_droplet_impact_fields(case_dir, params, mesh, x_centers, y_centers): """生成 droplet_impact 的 alpha.water 和 U 初始场 参数: params: dict {"radius": float, "cx": float, "cy": float, "v_impact": float} - radius: 液滴半径 [m], 默认 (0.015, 0.06) - cx: 水平中心 [m], 默认域宽 0.4-0.6 - cy: 初始高度 [m] (液滴中心 Y 坐标), 默认 (0.10, 0.25) - v_impact: 撞击速度 [m/s], 默认 (0.5, 2.0) 参考: Pasandideh-Fard et al. (1996) 液滴为完整圆形,底部距壁面留有 1.5 cell 间隙,避免与壁面单元重叠。 """ nx, ny = mesh["nx"], mesh["ny"] radius = params["radius"] cx = params["cx"] v_impact = params["v_impact"] # 完整圆形液滴,底部距壁面 = 1.5 个网格高度(确保 VOF 界面有足够空间) dy = mesh["dy"] gap = dy * 1.5 cy = radius + gap # alpha.water: 完整圆形液滴 (alpha=1), 外部 (alpha=0) dist = np.sqrt((x_centers - cx)**2 + (y_centers - cy)**2) is_droplet = dist <= radius alpha = np.where(is_droplet, 1.0, 0.0).ravel() # U: 液滴区域有向下的初始速度 is_droplet_flat = is_droplet.ravel() u_field = np.zeros((nx * ny, 3)) u_field[is_droplet_flat, 1] = -v_impact # Uy = -v_impact # 写入场文件 alpha_path = os.path.join(case_dir, "0", "alpha.water") template_alpha = os.path.join(case_dir, "0", "alpha.water.template") write_scalar_field(alpha_path, "alpha.water", alpha) _copy_boundary_conditions(template_alpha, alpha_path) u_path = os.path.join(case_dir, "0", "U") template_u = os.path.join(case_dir, "0", "U.template") write_vector_field(u_path, "U", u_field) _copy_boundary_conditions(template_u, u_path) def _generate_stokes_wave_fields(case_dir, params, mesh, x_centers, y_centers): """生成 stokes_wave 的 waveProperties 和 setFieldsDict 配置 stokes_wave 不直接生成 alpha.water / U 场文件,而是通过修改 constant/waveProperties 和 system/setFieldsDict 来参数化波浪初始条件。 alpha.water 由 setFields 在运行时初始化(Allrun 中已含 runParallel setFields)。 参数: params: dict {"waveHeight": float, "wavePeriod": float, "waterLevel": float} - waveHeight: 波高 [m], 默认 (0.04, 0.16) - wavePeriod: 波周期 [s], 默认 (1.2, 3.0) - waterLevel: 静水位高度 [m], 默认 (0.30, 0.50) """ wave_height = params["waveHeight"] wave_period = params["wavePeriod"] water_level = params["waterLevel"] # --- 修改 constant/waveProperties --- wp_path = os.path.join(case_dir, "constant", "waveProperties") with open(wp_path, "r") as f: wp_content = f.read() # 替换 waveHeight 值(保留缩进和尾部注释/分号) wp_content = re.sub( r"(waveHeight\s+)[\d.eE+-]+(\s*;.*)", lambda m: f"{m.group(1)}{wave_height}{m.group(2)}", wp_content, ) # 替换 wavePeriod 值 wp_content = re.sub( r"(wavePeriod\s+)[\d.eE+-]+(\s*;.*)", lambda m: f"{m.group(1)}{wave_period}{m.group(2)}", wp_content, ) with open(wp_path, "w") as f: f.write(wp_content) # --- 修改 system/setFieldsDict --- sf_path = os.path.join(case_dir, "system", "setFieldsDict") with open(sf_path, "r") as f: sf_content = f.read() # 替换 box 定义中的 z 坐标(第三个分量) # box 格式: box (0 0 0) (30.0 1.0 0.4) —— 替换最后一个数字 sf_content = re.sub( r"(box\s+\([^)]+\)\s+\(\s*[\d.eE+-]+\s+[\d.eE+-]+\s+)[\d.eE+-]+(\s*\))", lambda m: f"{m.group(1)}{water_level}{m.group(2)}", sf_content, ) with open(sf_path, "w") as f: f.write(sf_content) # ─── 参数空间定义 ──────────────────────────────────────────────────────── PARAM_BOUNDS = { # 参考: OpenFOAM Foundation. OpenFOAM v9 User Guide, 2021. "dam_break": { "width": (0.08, 0.40), # 水柱宽度 [m] "height": (0.15, 0.50), # 水柱高度 [m] }, # 参考: Hysing, S. et al. (2009). Int. J. Numer. Meth. Fluids, 60(11), 1259-1288. "rising_bubble": { "radius": (0.25, 0.25), # 气泡半径 [m],固定 R=0.25m(对齐 Hysing Case 1) "cx": (0.30, 0.70), # 水平中心 [m] (域宽 1m, R=0.25 → cx∈[0.25,0.75]) "cy": (0.30, 0.80), # 垂直中心 [m](域高 2m,Hysing 初始 y=0.5;采样域下半部确保有上升空间) }, # 参考: Pasandideh-Fard, M. et al. (1996). Phys. Fluids, 8(3), 650-659. "droplet_impact": { "radius": (0.002, 0.004), # 液滴半径 [m],下界确保 ≥20 cells 直径 "cx": (0.016, 0.034), # 水平中心 [m] (域宽 0.05m) "v_impact": (0.5, 1.5), # 撞击速度 [m/s](Pasandideh-Fard 1996 范围) }, "stokes_wave": { "waveHeight": (0.04, 0.16), # 波高 [m], deep water limit H < 0.78*d=0.624m, keep small "wavePeriod": (1.2, 3.0), # 波周期 [s], keep within 5th-order Stokes range "waterLevel": (0.30, 0.50), # 静水位高度 [m], domain height=0.8m }, } # 约束条件:避免参数组合导致数值问题 CONSTRAINTS = { "dam_break": lambda p: p["width"] * p["height"] < 0.20, "rising_bubble": lambda p: True, # R 固定 0.25m,cx/cy 范围已约束,无需额外过滤 "droplet_impact": lambda p: p["radius"] > 0, # cy 由函数内部自动计算 "stokes_wave": lambda p: True, # waveHeight/wavePeriod/waterLevel 相互独立 } # Case 类型 → 场生成函数 FIELD_GENERATORS = { "dam_break": _generate_dam_break_fields, "rising_bubble": _generate_rising_bubble_fields, "droplet_impact": _generate_droplet_impact_fields, "stokes_wave": _generate_stokes_wave_fields, } def generate_case_params(case_type, n_samples, seed=GLOBAL_SEED): """使用 LHS 生成 case 参数 返回: list[dict]: 每个元素是一个参数字典,键为参数名,值为采样值 """ bounds = PARAM_BOUNDS[case_type] param_names = list(bounds.keys()) n_dims = len(param_names) sampler = LatinHypercube(d=n_dims, seed=seed) raw_samples = sampler.random(n=n_samples) # 缩放到实际参数范围 params_list = [] for row in raw_samples: p = {} for i, name in enumerate(param_names): lo, hi = bounds[name] p[name] = lo + row[i] * (hi - lo) params_list.append(p) # 应用约束过滤(不满足约束的重新采样) constraint = CONSTRAINTS.get(case_type) if constraint: rng = np.random.default_rng(seed + 1000) for i, p in enumerate(params_list): attempts = 0 while not constraint(p) and attempts < 100: # 重新采样该点 new_sample = rng.random(n_dims) for j, name in enumerate(param_names): lo, hi = bounds[name] p[name] = lo + new_sample[j] * (hi - lo) attempts += 1 if attempts >= 100: logging.warning(f" 约束过滤超时: sample {i}, 使用当前参数") return params_list # ─── 主流程 ───────────────────────────────────────────────────────────── def generate_trajectories(templates_dir, output_dir, num_trajs=NUM_TRAJS, case_types=None, force=False): """为指定 case 类型生成 trajectory 参数: templates_dir: 模板根目录 output_dir: 输出目录 num_trajs: 每个 case 类型的 trajectory 数 case_types: 要生成的 case 类型列表(None = 全部四个) 流程: 1. 从模板复制 constant/ 和 system/ 目录 2. 复制 0/ 模板作为 .template 备份 3. 解析 blockMeshDict 获取网格参数 4. LHS 采样初始条件参数 5. 直接生成 0/alpha.water 和 0/U 场文件 6. 写入 manifest.yaml """ os.makedirs(output_dir, exist_ok=True) all_case_types = ["dam_break", "rising_bubble", "droplet_impact", "stokes_wave"] if case_types is None: case_types = all_case_types else: # 验证输入 for ct in case_types: if ct not in all_case_types: raise ValueError(f"未知 case 类型: {ct},可选: {all_case_types}") manifest_entries = [] for case_type in case_types: template_path = os.path.join(templates_dir, case_type, "base") if not os.path.isdir(template_path): logging.error(f"模板目录不存在: {template_path}") continue logging.info(f"=== 生成 {case_type} ({num_trajs} trajectories) ===") # 生成参数 params_list = generate_case_params(case_type, num_trajs) # 打印参数统计 for name in params_list[0].keys(): vals = [p[name] for p in params_list] logging.info(f" {name}: min={min(vals):.6f}, max={max(vals):.6f}, " f"mean={np.mean(vals):.6f}") skipped = 0 for traj_idx, params in enumerate(params_list): traj_name = f"t{traj_idx:02d}" case_dir = os.path.join(output_dir, case_type, traj_name) # 1. 复制模板(已有仿真数据时跳过,除非 --force) if not copy_template(template_path, case_dir, force=force): skipped += 1 continue # 2. 复制 0/ 模板文件作为 .template 备份 template_0 = os.path.join(template_path, "0") for fname in ["alpha.water", "U"]: src = os.path.join(template_0, fname) if os.path.exists(src): dst = os.path.join(case_dir, "0", f"{fname}.template") shutil.copy2(src, dst) # 3. 解析网格 mesh = parse_block_mesh(case_dir) x_centers, y_centers, _ = compute_cell_centers(mesh) # 4. 生成初始场 generator = FIELD_GENERATORS[case_type] generator(case_dir, params, mesh, x_centers, y_centers) # 5. 记录 manifest entry = { "traj_idx": traj_idx, "traj_name": traj_name, "case_type": case_type, "case_dir": case_dir, "params": {k: float(v) for k, v in params.items()}, "mesh": { "nx": mesh["nx"], "ny": mesh["ny"], "Lx": mesh["Lx"], "Ly": mesh["Ly"], }, "split": "train" if traj_idx < 35 else ("val" if traj_idx < 43 else "test"), } manifest_entries.append(entry) logging.info(f" {case_type} 完成: {num_trajs - skipped} trajectories 生成, {skipped} 跳过") # 写入 manifest manifest = { "generated_at": datetime.now(timezone.utc).isoformat(), "generator": "gen_init_conditions.py", "global_seed": GLOBAL_SEED, "num_trajs_per_case": num_trajs, "split": { "train": "indices 0-34", "val": "indices 35-42", "test": "indices 43-49", }, "references": [ "OpenFOAM Foundation. OpenFOAM v9 User Guide, 2021.", "Hysing, S. et al. (2009). Int. J. Numer. Meth. Fluids, 60(11), 1259-1288.", "Pasandideh-Fard, M. et al. (1996). Phys. Fluids, 8(3), 650-659.", ], "cases": manifest_entries, } if HAS_YAML: manifest_path = os.path.join(output_dir, "manifest.yaml") with open(manifest_path, "w") as f: yaml.dump(manifest, f, default_flow_style=False, allow_unicode=True, sort_keys=False) logging.info(f"Manifest 写入: {manifest_path}") else: # 无 yaml 模块时写入 JSON 格式 import json manifest_path = os.path.join(output_dir, "manifest.json") with open(manifest_path, "w") as f: json.dump(manifest, f, indent=2) logging.info(f"Manifest 写入 (JSON): {manifest_path}") def main(): parser = argparse.ArgumentParser( description="从 case 模板生成 N 个 trajectory(LHS 参数采样)" ) parser.add_argument( "--templates", type=str, default="/mnt/f/agent-workspace/paper2/Exp/data/templates", help="Case 模板根目录(含 dam_break/, rising_bubble/, droplet_impact/, stokes_wave/ 子目录)" ) parser.add_argument( "--output", type=str, default="/mnt/f/agent-workspace/paper2/Exp/data/raw", help="输出目录" ) parser.add_argument( "--num-trajs", type=int, default=NUM_TRAJS, help=f"每个 case 的 trajectory 数(默认 {NUM_TRAJS})" ) parser.add_argument( "--seed", type=int, default=GLOBAL_SEED, help=f"全局随机种子(默认 {GLOBAL_SEED})" ) parser.add_argument( "--case-types", type=str, nargs="+", default=None, choices=["dam_break", "rising_bubble", "droplet_impact", "stokes_wave"], help="要生成的 case 类型(默认全部)。可选: dam_break, rising_bubble, droplet_impact, stokes_wave" ) parser.add_argument( "--force", action="store_true", help="强制覆盖已有仿真数据(默认跳过已有数据的 case)" ) 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", ) logging.info(f"模板目录: {args.templates}") logging.info(f"输出目录: {args.output}") logging.info(f"Trajectory 数: {args.num_trajs}") logging.info(f"随机种子: {args.seed}") if args.case_types: logging.info(f"Case 类型: {args.case_types}") generate_trajectories(args.templates, args.output, args.num_trajs, case_types=args.case_types, force=args.force) logging.info("=== 全部完成 ===") if __name__ == "__main__": main()