File size: 25,973 Bytes
ed552fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
#!/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<scalar>\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<vector>\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()