File size: 32,814 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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
#!/usr/bin/env python3
"""

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


# ─── OpenFOAM 字段文件解析 ─────────────────────────────────────────────

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)

    """
    # 先以二进制模式读取,用于检测 ASCII/binary 格式
    with open(path, "rb") as fbin:
        raw = fbin.read()

    # 检测 internalField nonuniform List 头部
    # 尝试 UTF-8,失败则 latin-1
    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:
        # uniform 场处理
        return _read_uniform_field(header_text, path, n_cells)

    ftype = m_head.group(1)
    n_decl = int(m_head.group(2))

    # 找到 '(' 数据起始位置(在头部文本中的偏移 = 在 raw 中的偏移)
    paren_text_pos = header_text.find("(", m_head.end())
    if paren_text_pos == -1:
        raise ValueError(f"缺失数据起始 '(': {path}")
    # 转换为 raw 字节偏移(latin-1 下 1:1 映射)
    paren_raw_pos = len(header_text[:paren_text_pos].encode("latin-1"))

    # 检测 binary vs ASCII 格式
    # 策略: 检查 '(' 后的前 100 字节是否全部为可打印 ASCII 或空白
    # ASCII 格式: \n + 数字行 (全部为可打印字符)
    # Binary 格式: 包含非打印字节 (< 0x20 且不是 \n \r \t)
    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)  # printable + whitespace
        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  # 3 * float64
        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  # float64
        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 文件
    c_path = os.path.join(parent, "C")
    if not os.path.exists(c_path):
        # 查找 processor* 目录(并行模式)
        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}")


# ─── blockMeshDict 解析 ─────────────────────────────────────────────────

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()

    # 仅在 vertices 块内匹配顶点坐标,避免匹配 blocks 行的网格尺寸
    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}")
    # 取所有顶点的 min/max 作为域边界
    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))

    # 有效行维度:2D 案例用 ny,3D 薄方向案例(ny=1, nz>1)用 nz
    nrows = nz if (ny == 1 and nz > 1) else ny

    Lx = x1 - x0
    # 3D 薄方向案例用 z 方向尺寸作为 Ly
    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):
            # 确认包含 U 文件
            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
        # 验证至少有一个含 U 文件的数值时间目录
        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
    # 按 processor 编号排序(processor0 < processor1 < ...)
    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

    # 从 cell 数推断:尝试所有 (n_x, n_y) 对
    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

    # 退化:全部切 x
    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"]
    # x-z 平面案例 (ny_orig=1, nz>1): 垂直速度是 Uz (index=2) 而非 Uy (index=1)
    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 ''}")

    # 生成 cell 中心坐标网格 (indexing='ij' -> shape (nx, ny), 匹配旧数据约定)
    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")  # shape (nx, ny)

    if from_processors:
        # -- 并行模式:从 processor*/ 目录直接读取 --
        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")

        # 发现时间步(从 processor0)并按 --times 筛选
        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}")

        # 读取 cellProcAddressing 获取每个 processor 的 local→global 映射
        total_mesh = nx * ny
        proc_global_ids = {}  # {proc_dir: np.array of global cell 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

        # 检测每个 processor 的实际 cell 数(从第一个非 uniform 时间步)
        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:
            # 每个 processor 有完整 mesh(decomposePar 未实际分割)
            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()):
            # 使用 cellProcAddressing 做精确映射
            use_addressing = True
            proc_ncells_list = [len(proc_global_ids[pd]) for pd in proc_dirs]
            logging.info(f"  使用 cellProcAddressing 精确映射 ({n_procs} 个 processor)")

        else:
            # 回退: 从 decomposeParDict 推断分解模式
            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]

        # 预分配数组 — shape (n_frames, ny, nx),与 OpenFOAM cell-major 行主序一致
        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:
                    # cellProcAddressing 精确映射
                    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)

        # 转置为 (nx, ny) 输出约定
        u_data = u_full.transpose(0, 2, 1)     # (n_frames, nx, ny)
        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}")

        # 预分配数组 - shape (T, nx, ny), 与旧数据 (data_generation.py) 轴序一致
        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)

            # 读取速度场 U (vector)
            expected = ny * nx
            u_raw = read_foam_field(os.path.join(t_path, "U"), n_cells=expected)
            # u_raw shape: (nx*ny, 3),行主序 (j*nx+i)
            if u_raw.shape[0] != expected:
                raise ValueError(
                    f"U field size {u_raw.shape[0]} != mesh {expected} ({ny}x{nx})"
                )
            # reshape -> (ny, nx, 3),再转置为 (nx, ny, 3) 匹配旧约定
            u_vec = u_raw.reshape(ny, nx, 3).transpose(1, 0, 2)
            u_data[i] = u_vec[:, :, 0].astype(np.float32)  # X-速度
            v_data[i] = u_vec[:, :, v_comp].astype(np.float32)  # 垂直速度 (Y 或 Z)

            # 读取压力场 p_rgh (scalar)
            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.water (scalar)
            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

    # 写入 HDF5(格式兼容训练 pipeline 的 MultiphaseFlowDataset)
    os.makedirs(os.path.dirname(h5_path), exist_ok=True)
    with h5py.File(h5_path, "w") as f:
        # 训练 pipeline 核心数据集: u, v, alpha, p
        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
            # 检查是否为有效的 OpenFOAM case
            if (os.path.exists(os.path.join(traj_dir, "Allrun")) and
                os.path.exists(os.path.join(traj_dir, "system", "blockMeshDict"))):
                # 从目录名提取索引 (t00 → 0, t01 → 1, ...)
                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

    # 发现所有 trajectory
    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():
        # 输出目录: {output_root}/{case_type}/traj_{NNNN}.h5
        h5_dir = os.path.join(output_root, case_type)
        os.makedirs(h5_dir, exist_ok=True)

        for traj_idx, case_dir in trajectories:
            # HDF5 文件名: traj_{NNNN}.h5(兼容 MultiphaseFlowDataset)
            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()