File size: 90,147 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 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 | """
OpenFOAM 数据加载模块
----------------------
实现 Dataset 和 DataLoader 类,用于将 OpenFOAM 仿真数据转换为结构化张量,供神经网络训练使用。(另有可视化静态方法)
DATASET 输出 (单个样本)
fields_list = [field_dict_t0, field_dict_t1, ..., field_dict_t{S-1}] # S = number_of_steps_to_get
field_dict_tk = {
'Ux' : (Ny, Nx)
'Uy' : (Ny, Nx)
'p' : (Ny, Nx)
'xGrid': (Ny, Nx)
'yGrid': (Ny, Nx)
'mask' : (Ny, Nx)
}
infos_list = [info_dict_t0, info_dict_t1, ..., info_dict_t{S-1}]
info_dict_tk = {
'dt' : float
'dt_simulation': float
'time' : float
'fluid' : { 'rho': float, 'mu': float, 'nu': float, 'Re': float }
'geometry' : { 'structure_length_y': float,
'structure_length_x': float,
'bbox': (4,) }
'solid_velocity': (vector_dim,)
'boundary' : dict
}
DataLoader 批次输出(同名变量)
fields_seq = [batch_field_dict_t0, batch_field_dict_t1, ..., batch_field_dict_t{S-1}]
batch_field_dict_tk = {
key: torch.Tensor (B, C, Ny, Nx) # C=1 for scalar fields
} # 张量位于 Dataset 指定的 device,上层代码可直接送入 CNN
infos_seq = [batch_info_dict_t0, batch_info_dict_t1, ..., batch_info_dict_t{S-1}]
batch_info_dict_tk = {
'dt' : torch.Tensor (B, 1) 设备 = Dataset 指定 device
'dt_simulation': torch.Tensor (B, 1) 设备 = CPU
'time' : torch.Tensor (B, 1) 设备 = CPU
'fluid' : { 同名键 -> torch.Tensor (B, 1) 设备 = CPU }
'geometry' : { 'bbox': torch.Tensor (B, 4),
其它键 -> torch.Tensor (B, 1) 设备 = CPU }
'solid_velocity': torch.Tensor (B, vector_dim) 设备 = CPU
'boundary' : list[dict] (dict 保留 Dataset 一致的原始结构)
}
NOTE
场的张量的维度:(B, C, H or Ny, W or Nx)
dataloader/dataset给的是一个列表,每个元素是一个时间步的数据(所需的时间步数由属性self._number_of_steps_to_get控制)
场的张量数据的i方向(H)和j方向(W)分别对应物理场的-y和x方向
bbox的格式为(xmin,ymin,xmax,ymax)
Re = rho*v*d/mu = v*d/nu
注意p在OpenFOAM场文件中的单位是m^2/s^2(即此处实则为p/rho)
推荐使用: create_dataloader_cat (ConcatDatasetsWrapper), 可以同时加载多个数据集并作为一个整体进行训练
TODO
流线图获取方法(参考phiflow库的stream lines绘制,如from phi.vis import plot)
"""
import os
import re
import shutil
import numpy as np
import warnings
import random
from collections.abc import Sequence
try:
import torch
from torch.utils.data import Dataset, DataLoader
HAVE_TORCH = True
except Exception:
torch = None
HAVE_TORCH = False
# minimal stand-ins so class definition still works when torch absent
class Dataset(object):
pass
class DataLoader(object):
pass
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import Normalize
import subprocess
try:
from scipy.interpolate import RegularGridInterpolator
HAVE_SCIPY_INTERP = True
except Exception:
RegularGridInterpolator = None
HAVE_SCIPY_INTERP = False
def _to_numpy(array):
if HAVE_TORCH and isinstance(array, torch.Tensor):
return array.detach().cpu().numpy()
return np.asarray(array)
class OpenfoamDataset(Dataset):
def __init__(self, root_dir, number_of_steps_to_get=2,
vector_field='U', scalar_field='p',
vector_dim=2, vector_keep_dims=None,
device='cpu', # ✅ NOTE 建议使用cpu模式(在训练循环中手动to(device)), 因为 dataloader 启用 pin-memory 时要求 CPU tensor
dtype=None, coord_digits=8):
"""
root_dir: OpenFOAM case 目录(包含 0, 1, 2... 等时间步文件夹)
number_of_steps_to_get: 每个样本连续采样的时间步数量(默认 2)
vector_field: 速度场名(如 'U')
scalar_field: 压力场名(如 'p')
vector_dim: 速度场维度(2 或 3)
vector_keep_dims: 需要保留的速度分量索引列表,例如 ``[0, 1]`` 表示仅取 x/y 分量,``None`` 时默认取 ``range(min(2, vector_dim))``
device: torch 设备
dtype: torch 数据类型
coord_digits: 构建结构化网格时对坐标取 round 的小数位数,避免由浮点误差导致的索引错配
"""
# 流体网格点数量与时间步数量(会在实例化时更新)
self.n_fluid_points = 0
self.n_time_steps = 0
self.root_dir = root_dir
self._number_of_steps_to_get = number_of_steps_to_get
self.vector_field = vector_field
self.scalar_field = scalar_field
self.vector_dim = vector_dim
# vector_keep_dims: which components to keep from vector fields (e.g. [0,1] -> x,y)
if vector_keep_dims is None:
self.vector_keep_dims = list(range(min(2, vector_dim)))
else:
self.vector_keep_dims = list(vector_keep_dims)
self.device = device
# dtype 决定在 runtime,如果 torch 可用则默认 torch.float32
if HAVE_TORCH:
self.dtype = dtype if dtype is not None else torch.float32
else:
self.dtype = None
# 坐标舍入精度(用于索引匹配)
self.coord_digits = coord_digits
self.time_dirs = self._find_time_dirs()
self.fluid_info = self._load_fluid_info()
# 以第一个时间步的C文件为网格中心
self.grid_points, self.Nx, self.Ny, self.xs, self.ys = self._load_structured_grid()
# 更新类属性(实例级信息): n_fluid_points = Nx * Ny, n_time_steps = len(time_dirs)
try:
self.n_fluid_points = int(self.Nx * self.Ny)
except Exception:
self.n_fluid_points = 0
self.n_time_steps = len(self.time_dirs)
# check len
if self._number_of_steps_to_get <= 0:
raise ValueError('number_of_steps_to_get must be a positive integer.')
if self.__len__() <= 0:
raise ValueError('Dataset is empty, or number_of_steps_to_get is larger than available time steps.')
def _find_time_dirs(self):
# 查找所有时间步文件夹(数字命名),若当前目录本身就是时间步(如0/1/2),则返回['.']
dirs = [d for d in os.listdir(self.root_dir) if d.isdigit()]
if not dirs:
# 当前目录本身就是单一时间步
return ['.']
dirs = sorted(dirs, key=lambda x: float(x))
return dirs
def _load_structured_grid(self):
# 用C文件(网格中心)定义结构化网格
first_time = self._find_time_dirs()[0]
if first_time == '.':
c_path = os.path.join(self.root_dir, 'C')
else:
c_path = os.path.join(self.root_dir, first_time, 'C')
# 读取 C 文件为 point list (n, n_dim)
# 先尝试读取 header 中声明的数量并保存到类属性
declared_n = self._parse_internal_list_count(c_path) or 0
if declared_n > 0:
self.n_fluid_points = int(declared_n)
c_arr = np.array(self._read_field(c_path, vector=True))
# 保证只取 x,y 或者用户指定的分量
if c_arr.ndim == 1:
c_arr = c_arr.reshape(-1, 1)
if c_arr.shape[1] >= max(self.vector_keep_dims) + 1:
c_arr = c_arr[:, self.vector_keep_dims]
# 只保留前两列作为 x,y(如果用户只保留了一维也兼容)
if c_arr.shape[1] >= 2:
c_arr = c_arr[:, :2]
xs = np.unique(np.round(c_arr[:,0], self.coord_digits))
ys = np.unique(np.round(c_arr[:,1], self.coord_digits))
# 我们的张量约定:i 方向对应 -y(从上到下),j 方向对应 x(从左到右)
# 因此让 i 对应于 ys 的降序索引
ys_desc = ys[::-1]
Nx = len(ys_desc) # number of i (rows)
Ny = len(xs) # number of j (cols)
# 生成结构化网格点 (Nx, Ny, 2)
grid_points = np.zeros((Nx, Ny, 2))
for i, y in enumerate(ys_desc):
for j, x in enumerate(xs):
grid_points[i, j, 0] = x
grid_points[i, j, 1] = y
# 返回时仍然给出原始 xs, ys(xs 升序,ys 升序)以便上层使用
return grid_points, Nx, Ny, xs, ys
def _parse_internal_list_count(self, path):
# 从文件中解析 nonuniform List<...> 后面的数量(用于 uniform 时推断点数)
if not os.path.exists(path):
return None
with open(path, 'r') as f:
txt = f.read()
m = re.search(r'internalField\s+nonuniform\s+List<[^>]+>\s+(\d+)', txt)
if m:
return int(m.group(1))
return None
def _read_field(self, path, vector=True):
"""
解析 OpenFOAM 字段文件的 internalField 区块。
支持 nonuniform List<vector|scalar> 和 uniform(...)
返回 numpy 数组:vector -> (N, k), scalar -> (N,)
若 header 中声明的数量与实际解析行数不一致,会抛出 RuntimeError。
"""
if not os.path.exists(path):
raise FileNotFoundError(f"未找到字段文件: {path}")
with open(path, 'r') as f:
content = f.read()
# nonuniform List 区块优先:header 可能是两行(类型/数量换行),随后是括号包裹的列表
m_head = re.search(r'internalField\s+nonuniform\s+List<(vector|scalar)>\s*(\d+)', content)
if m_head:
ftype = m_head.group(1)
n_decl = int(m_head.group(2))
# 更稳健地提取括号块:匹配单独一行的 '(' 和相应的 ')'(DOTALL + MULTILINE)
# 首先尝试匹配 ( ... ) ; 这种情况,确保 ) 后面紧跟 ; 或随后的换行再是 ;
m_block = re.search(r"\(\s*\n(.*?)\n\s*\)\s*;", content[m_head.end():], re.DOTALL | re.MULTILINE)
if not m_block:
# 回退到查找从 '(' 到紧接着的 ')' 并可能后接 ';' 的区域
start_pos = content.find('(', m_head.end())
if start_pos == -1:
raise ValueError(f"无法解析 nonuniform List 块(缺失 '('): {path}")
# 找到第一个单独的行起始的 ')' 后面跟着可选空白与 ';'
# 为保险,查找 pattern '\n)\s*;'
rel = content[m_head.end():]
m_end = re.search(r"\n\s*\)\s*;", rel)
if m_end:
end_pos = m_head.end() + m_end.start()
block = content[start_pos+1:end_pos].strip()
else:
# 最后回退到最近的 ')' 之前
end_pos = content.rfind(')')
if end_pos == -1:
raise ValueError(f"无法解析 nonuniform List 块(缺失 ')'): {path}")
block = content[start_pos+1:end_pos].strip()
else:
block = m_block.group(1).strip()
lines = [ln.strip() for ln in block.splitlines() if ln.strip()]
if len(lines) != n_decl:
# 这里仍旧发出警告,但我们将使用 header 中的 n_decl 作为 n_fluid_points
warnings.warn(f"文件 {os.path.basename(path)} 声明 {n_decl} 个 internalField 条目,但解析到 {len(lines)} 行。将以解析到的 {len(lines)} 行为准。", RuntimeWarning)
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])
arr = np.array(arr)
# 截取用户指定分量
if arr.ndim == 2 and len(self.vector_keep_dims) > 0:
max_idx = max(self.vector_keep_dims)
if arr.shape[1] > max_idx:
arr = arr[:, self.vector_keep_dims]
# 当这是 C 文件(vector 且对象名为 C)时,我们希望记录 header 中的点数作为 n_fluid_points
return arr
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)
# uniform 情形:匹配 internalField uniform ... ;(值可以是 0 或者 (a b c))
m_uni = re.search(r'internalField\s+uniform\s*(.*?);', content, re.DOTALL)
if m_uni:
token = m_uni.group(1).strip()
# token 可能是 '0' 或者 '(0)' 或 '(0 0 0)'
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 Exception:
# 如果无法转换,跳过
pass
# 尝试从 C 文件推断点数
first_time = self.time_dirs[0]
if first_time == '.':
c_path = os.path.join(self.root_dir, 'C')
else:
c_path = os.path.join(self.root_dir, first_time, 'C')
npts = self._parse_internal_list_count(c_path) or 1
if vector:
vec = np.array(nums)
if vec.size == 0:
vec = np.zeros((1,))
# 截取感兴趣分量
if len(vec) > 0 and len(self.vector_keep_dims) > 0:
max_idx = max(self.vector_keep_dims)
if vec.size > max_idx:
vec = vec[self.vector_keep_dims]
arr = np.tile(vec.reshape(1, -1), (npts, 1))
return arr
else:
val = nums[0] if len(nums) > 0 else 0.0
return np.full((npts,), val)
raise ValueError(f"无法解析 internalField: {path}")
def _load_fluid_info(self):
# 从 system/transportProperties 文件中提取物性参数或其他标识(例如 rho, mu, nu, Re)
# 默认 rho = 1.0(若文件中未找到则使用默认)
rho, mu, nu = 1.0, None, None
Re_val = None
# search both constant/ and system/ directories (transportProperties often lives in constant/)
files = []
for dname in ['constant', 'system', '']:
dpath = os.path.join(self.root_dir, dname) if dname else self.root_dir
if os.path.exists(dpath) and os.path.isdir(dpath):
tp = os.path.join(dpath, 'transportProperties')
if os.path.exists(tp) and os.path.isfile(tp):
files.append(tp)
# also scan other files in this dir for Re-like comments/values
for fname in os.listdir(dpath):
p = os.path.join(dpath, fname)
if os.path.isfile(p) and p not in files:
files.append(p)
for p in files:
try:
txt = open(p, 'r', encoding='utf-8', errors='ignore').read()
except Exception:
continue
# 查找 Re 或 Re_blockage(注释里也可能出现)
m_re = re.search(r'\bRe_blockage\b\s*(?:=|:)\s*([0-9eE+\-.]+)', txt)
if not m_re:
m_re = re.search(r'\bRe\b\s*(?:=|:)\s*([0-9eE+\-.]+)', txt)
if m_re:
try:
Re_val = float(m_re.group(1))
except Exception:
Re_val = None
# 查找 nu,兼容 transportProperties 中的形式:nu [units] 5e-3; 或 nu 5e-3;
m_nu = re.search(r'\bnu\b\s*(?:\[.*?\])?\s*([0-9eE+\-.]+)', txt)
if not m_nu:
m_nu = re.search(r'kinematicViscosity\s*([0-9eE+\-.]+)', txt)
if m_nu:
try:
nu = float(m_nu.group(1))
except Exception:
nu = None
# mu, rho:transportProperties 中可能以 mu 或 rho 名义出现
m_mu = re.search(r'\bmu\b\s*(?:[\[\(].*?[\]\)])?\s*([0-9eE+\-.]+)', txt)
if m_mu:
try:
mu = float(m_mu.group(1))
except Exception:
pass
m_rho = re.search(r'\brho\b\s*(?:[\[\(].*?[\]\)])?\s*([0-9eE+\-.]+)', txt)
if m_rho:
try:
rho = float(m_rho.group(1))
except Exception:
pass
# 如果未找到,则尝试计算,实在无数据,则使用默认 1.0 填充
if rho is None:
rho = 1.0
if mu is None:
# 尝试用 rho*nu 计算
try:
mu = float(rho) * float(nu)
except Exception:
mu = 1.0
if nu is None:
# 尝试用 mu/rho 计算
try:
nu = float(mu) / float(rho) if rho != 0 else 1.0
except Exception:
nu = 1.0
info = {'rho': rho, 'mu': mu, 'nu': nu}
# 统一使用 'Re' 键;如果在文件中找到 Re 或 Re_blockage,则写入
if Re_val is not None:
try:
info['Re'] = float(Re_val)
except Exception:
info['Re'] = None
else:
info['Re'] = None
return info
def parse_solid_velocity(self, *args, **kwargs):
"""占位函数:未来用于解析固体速度,目前返回全零(自适应维度)。"""
return tuple([0.0] * self.vector_dim)
def _parse_inlet_velocity(self, u_path):
"""尝试从 U 文件的 boundaryField 中解析 inlet 的 value(向量)。返回 None 或长度为 self.vector_dim 的 tuple。"""
if not os.path.exists(u_path):
return None
try:
txt = open(u_path, 'r', encoding='utf-8', errors='ignore').read()
except Exception:
return None
# 更稳健地提取 boundaryField 块(处理嵌套花括号)
def _extract_brace_block(s, start_idx):
# start_idx 指向 '{'
depth = 0
for i in range(start_idx, len(s)):
if s[i] == '{':
depth += 1
elif s[i] == '}':
depth -= 1
if depth == 0:
return s[start_idx+1:i], i
return None, None
m_bf = re.search(r'boundaryField\s*\{', txt)
if not m_bf:
return None
bf_start = m_bf.end() - 1
bf_block, bf_end = _extract_brace_block(txt, bf_start)
if bf_block is None:
return None
# 在 boundaryField 块中寻找以 'inlet' 为 patch 名或包含 'inlet' 的块,提取其 value 字段
# 更简单的做法:在 bf_block 中按块级别查找包含 'inlet' 关键字的子块并使用其 value
inlet_block = None
for m in re.finditer(r'([A-Za-z0-9_\-]+)\s*\{', bf_block):
name = m.group(1)
# 如果名字包含 inlet(更宽松匹配),提取该块
if 'inlet' in name.lower():
global_pos = bf_start + 1 + m.start()
brace_pos = txt.find('{', global_pos)
if brace_pos != -1:
blk, _ = _extract_brace_block(txt, brace_pos)
inlet_block = blk
break
if inlet_block is None:
# 无明确 patch 名含 inlet,则在 boundaryField 中寻找第一个包含 value 且类型为 fixedValue 的 patch
m_any = re.search(r'([A-Za-z0-9_\-]+)\s*\{', bf_block)
if m_any:
global_pos = bf_start + 1 + m_any.start()
brace_pos = txt.find('{', global_pos)
if brace_pos != -1:
blk, _ = _extract_brace_block(txt, brace_pos)
inlet_block = blk
if not inlet_block:
return None
# 在 inlet_block 中寻找 value 字段
m_val = re.search(r'value\s+(?:uniform\s*)?\(?\s*([\-+0-9eE\.\s]+)\s*\)?\s*;', inlet_block)
if not m_val:
return None
nums = re.findall(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?', m_val.group(1))
try:
vals = [float(x) for x in nums]
if len(vals) < self.vector_dim:
vals += [0.0] * (self.vector_dim - len(vals))
# 返回时只保留 value(不要返回 patch 名称,避免把 outlet 等误识别带入上层)
return {'value': tuple(vals[:self.vector_dim])}
except Exception:
return None
def _compute_structure_length(self, mask, xGrid, yGrid):
"""基于固体掩码计算结构物的纵向长度:掩码中 0 表示固体、1 表示流体。
返回沿 y 方向的跨度(也返回 x/y 的 bbox)。若没有固体则返回 0。
说明:这里假设 "纵向" 是垂直方向(y);如需改为流向,请告知。
"""
try:
arr_mask = np.asarray(mask)
if arr_mask.dtype == bool:
solid_mask = ~arr_mask
else:
solid_mask = arr_mask < 0.5
if not np.any(solid_mask):
return 0.0, 0.0, None
x_coords = np.asarray(xGrid)[solid_mask]
y_coords = np.asarray(yGrid)[solid_mask]
if x_coords.size == 0 or y_coords.size == 0:
return 0.0, 0.0, None
xmin = float(np.min(x_coords))
xmax = float(np.max(x_coords))
ymin = float(np.min(y_coords))
ymax = float(np.max(y_coords))
x_span = float(xmax - xmin)
y_span = float(ymax - ymin)
# return bbox in (xmin, ymin, xmax, ymax) order
bbox = (xmin, ymin, xmax, ymax)
return y_span, x_span, bbox
except Exception:
return 0.0, 0.0, None
def _get_dt(self, case_dir):
"""
尝试读取 case 的 system/controlDict 中的 deltaT;若未找到则返回默认 1.0
"""
# 优先在 root_dir/system/controlDict 查找,再在 case_dir/system/controlDict
candidates = [os.path.join(self.root_dir, 'system', 'controlDict'),
os.path.join(case_dir, 'system', 'controlDict'),
os.path.join(case_dir, 'uniform', 'time'),
os.path.join(case_dir, 'time')]
for p in candidates:
if os.path.exists(p):
try:
with open(p, 'r') as f:
txt = f.read()
m = re.search(r'deltaT\s+([0-9eE+\-.]+)', txt)
if m:
return float(m.group(1))
except Exception:
pass
return 1.0
def _get_write_interval(self, case_dir):
"""
尝试从 controlDict 中解析 writeInterval 的值;若未找到返回 None
"""
candidates = [os.path.join(self.root_dir, 'system', 'controlDict'),
os.path.join(case_dir, 'system', 'controlDict')]
for p in candidates:
if os.path.exists(p):
try:
with open(p, 'r') as f:
txt = f.read()
m = re.search(r'writeInterval\s+([0-9eE+\-.]+)', txt)
if m:
try:
return float(m.group(1))
except Exception:
return None
except Exception:
pass
return None
def _get_time_value(self, case_dir):
"""读取当前时间步下的 uniform/time 文件以获取 value(物理时间)。"""
candidates = [os.path.join(case_dir, 'uniform', 'time'), os.path.join(case_dir, 'time'), os.path.join(case_dir, 'uniform', 'timeFile')]
for p in candidates:
if os.path.exists(p):
with open(p, 'r') as f:
txt = f.read()
m = re.search(r'value\s+([0-9eE+\-.]+)', txt)
if m:
try:
return float(m.group(1))
except Exception:
pass
# fallback: try numeric time_dir name
try:
return float(os.path.basename(case_dir))
except Exception:
return 0.0
def __len__(self):
total_frames = len(self.time_dirs)
window = max(int(self._number_of_steps_to_get), 1)
if total_frames == 0 or window > total_frames:
return 0
return total_frames - window + 1
def _get_one_frame(self, idx):
# 读取 C, U, p 文件,使用统一的解析器
time_dir = self.time_dirs[idx]
if time_dir == '.':
case_dir = self.root_dir
else:
case_dir = os.path.join(self.root_dir, time_dir)
c_path = os.path.join(case_dir, 'C')
U_path = os.path.join(case_dir, self.vector_field)
p_path = os.path.join(case_dir, self.scalar_field)
# 读取点坐标列表 (n, ndim)
point_list = np.array(self._read_field(c_path, vector=True))
if point_list.ndim == 1:
point_list = point_list.reshape(-1, 1)
# 只保留用户感兴趣的分量作为 x,y
if point_list.shape[1] > max(self.vector_keep_dims):
point_list = point_list[:, self.vector_keep_dims]
if point_list.shape[1] >= 2:
point_list = point_list[:, :2]
# 读取速度(vector)和压力(scalar)
U = np.array(self._read_field(U_path, vector=True))
p = np.array(self._read_field(p_path, vector=False))
# 校验:U, p 与 C 的点数一致
n_pts = point_list.shape[0]
# 如果 C 文件声明了 internalField 的点数(nonuniform List<...> 后的整数),使用该声明进行严格校验
try:
declared_n = self._parse_internal_list_count(c_path)
if declared_n and declared_n > 0:
# 记录为类属性
self.n_fluid_points = declared_n
if declared_n != n_pts:
raise RuntimeError(f"C 文件声明 {declared_n} 个 internalField 条目,但解析到 {n_pts} 行。请检查解析器或文件格式。")
except FileNotFoundError:
# 若找不到 C 文件则在后续的点匹配处会触发其它错误,继续让原有错误抛出
pass
if U.shape[0] != n_pts:
raise RuntimeError(f"点数不匹配: C 中 {n_pts} 个点, 但 {self.vector_field} 中 {U.shape[0]} 个点")
if p.shape[0] != n_pts:
raise RuntimeError(f"点数不匹配: C 中 {n_pts} 个点, 但 {self.scalar_field} 中 {p.shape[0]} 个点")
# 构造结构化网格 (xs, ys)
xs = np.unique(np.round(point_list[:, 0], self.coord_digits))
ys = np.unique(np.round(point_list[:, 1], self.coord_digits))
# i 对应 -y(从上到下),因此使用 ys 的降序作为 i 方向
ys_desc = ys[::-1]
Nx = len(ys_desc) # i dimension (rows)
Ny = len(xs) # j dimension (cols)
# 生成 xGrid/yGrid,使得 xGrid[i,j]=xs[j], yGrid[i,j]=ys_desc[i]
xGrid = np.zeros((Nx, Ny), dtype=float)
yGrid = np.zeros((Nx, Ny), dtype=float)
for i, y in enumerate(ys_desc):
for j, x in enumerate(xs):
xGrid[i, j] = x
yGrid[i, j] = y
# 建立从坐标到结构化索引的映射(以 round 精确匹配):注意 i 使用 ys_desc
idx_map = {(round(x, self.coord_digits), round(y, self.coord_digits)): (i, j)
for i, y in enumerate(ys_desc) for j, x in enumerate(xs)}
# 初始化场与掩码
Ux = np.zeros((Nx, Ny), dtype=float)
Uy = np.zeros((Nx, Ny), dtype=float)
p_grid = np.zeros((Nx, Ny), dtype=float)
solid_mask = np.zeros((Nx, Ny), dtype=bool) # True=fluid, False=solid(初始化为全固体)
# 建立映射字典:point index -> (ix,iy)
fluid_points = {}
fluid_grid_to_pt = {}
for k, (x, y) in enumerate(point_list):
key = (round(float(x), self.coord_digits), round(float(y), self.coord_digits))
if key in idx_map:
i, j = idx_map[key]
fluid_points[k] = (i, j)
fluid_grid_to_pt[(i, j)] = k
# 将值写入结构化网格
if U.ndim == 1:
Ux[i, j] = float(U[k])
Uy[i, j] = 0.0
else:
if U.shape[1] > max(self.vector_keep_dims):
uvals = U[k, self.vector_keep_dims]
else:
uvals = U[k, :len(self.vector_keep_dims)]
Ux[i, j] = float(uvals[0])
Uy[i, j] = float(uvals[1]) if len(uvals) > 1 else 0.0
p_grid[i, j] = float(p[k])
solid_mask[i, j] = True
# solid_points 列表 (未使用但保留)
solid_points = [tuple(idx) for idx in np.argwhere(~solid_mask)]
# 对固体区域填充:速度 0,压力用最近流体点插值
from scipy.spatial import cKDTree
fluid_idx = np.array(list(fluid_grid_to_pt.keys())) if len(fluid_grid_to_pt) > 0 else np.zeros((0, 2), dtype=int)
if fluid_idx.size > 0:
tree = cKDTree(fluid_idx)
solid_idx = np.argwhere(~solid_mask)
for si in solid_idx:
dist, nearest = tree.query(si)
ni, nj = fluid_idx[nearest]
p_grid[si[0], si[1]] = p_grid[ni, nj]
Ux[si[0], si[1]] = 0.0
Uy[si[0], si[1]] = 0.0
# 生成输出:统一把 numpy 数组转换为 contiguous numpy 后用 torch.from_numpy 转为 torch.Tensor
def _to_tensor(arr):
# 将数组转换为 contiguous numpy 并在 Dataset 层转为 torch.Tensor
a = np.ascontiguousarray(np.asarray(arr))
if HAVE_TORCH:
# 按要求使用 torch.from_numpy(np.ascontiguousarray(np.asarray(v))).float()
t = torch.from_numpy(a).float().to(device=self.device)
return t
else:
return a
Ux = _to_tensor(Ux)
Uy = _to_tensor(Uy)
p_grid = _to_tensor(p_grid)
xGrid_t = _to_tensor(xGrid)
yGrid_t = _to_tensor(yGrid)
# mask: 保证语义为 1=fluid, 0=solid(solid_mask: True 表示流体)
fluid_mask = solid_mask.astype(np.float32)
mask = _to_tensor(fluid_mask)
# 将固体速度占位放入 info(自适应维度,默认 0)
solid_velocity = tuple([0.0] * self.vector_dim)
# 读取 inlet 边界条件,_parse_inlet_velocity 返回 {'patch': name, 'value': (vx,vy)} 或 None
inlet_info = self._parse_inlet_velocity(U_path)
# 只保留 value(如果有),不要把 patch 名传上层
bc_info = {'inlet': inlet_info}
inlet_side = None
if inlet_info is not None and isinstance(inlet_info, dict):
vals = inlet_info.get('value', None)
# 简单策略:默认 inlet 在 x- 侧(j=0)。如果需要更复杂的匹配,可改进。
inlet_side = 'x-'
if vals is not None:
# x-: j_idx=0; x+: j_idx=Ny-1; y+: i_idx=0; y-: i_idx=Nx-1
if inlet_side == 'x-':
j_idx = 0
for i in range(Nx):
Ux[i, j_idx] = float(vals[0]) if len(vals) > 0 else 0.0
Uy[i, j_idx] = float(vals[1]) if len(vals) > 1 else 0.0
elif inlet_side == 'x+':
j_idx = Ny - 1
for i in range(Nx):
Ux[i, j_idx] = float(vals[0]) if len(vals) > 0 else 0.0
Uy[i, j_idx] = float(vals[1]) if len(vals) > 1 else 0.0
elif inlet_side == 'y+':
i_idx = 0
for j in range(Ny):
Ux[i_idx, j] = float(vals[0]) if len(vals) > 0 else 0.0
Uy[i_idx, j] = float(vals[1]) if len(vals) > 1 else 0.0
elif inlet_side == 'y-':
i_idx = Nx - 1
for j in range(Ny):
Ux[i_idx, j] = float(vals[0]) if len(vals) > 0 else 0.0
Uy[i_idx, j] = float(vals[1]) if len(vals) > 1 else 0.0
# 现在继续 __getitem__ 的后半部分:时间步信息、info 字典填充等
dt = self._get_dt(case_dir)
write_interval = self._get_write_interval(case_dir)
field = {'Ux': Ux, 'Uy': Uy, 'p': p_grid, 'xGrid': xGrid_t, 'yGrid': yGrid_t, 'mask': mask}
# 使用时间目录下的 uniform/time 或 time 文件中的 value 字段作为物理时间(fallback 为目录名数值)
time_value = self._get_time_value(case_dir)
mask_np = None
xGrid_np = None
yGrid_np = None
try:
if HAVE_TORCH:
mask_np = mask.detach().cpu().numpy()
xGrid_np = xGrid_t.detach().cpu().numpy()
yGrid_np = yGrid_t.detach().cpu().numpy()
else:
mask_np = np.asarray(mask)
xGrid_np = np.asarray(xGrid_t)
yGrid_np = np.asarray(yGrid_t)
except Exception:
pass
if mask_np is None:
mask_np = np.asarray(mask)
if xGrid_np is None:
xGrid_np = np.asarray(xGrid_t)
if yGrid_np is None:
yGrid_np = np.asarray(yGrid_t)
try:
length_y, length_x, bbox = self._compute_structure_length(mask_np, xGrid_np, yGrid_np)
except Exception:
length_y, length_x, bbox = 0.0, 0.0, None
# 保存两个时间尺度:dt_simulation(origin simulation deltaT)和 dt(writeInterval)
fluid_info = dict(self.fluid_info) if isinstance(self.fluid_info, dict) else {}
info_dict = {
'dt': float(write_interval) if write_interval is not None else float(dt),
'dt_simulation': float(dt),
'time': float(time_value),
'fluid': fluid_info,
'geometry': None,
'solid_velocity': solid_velocity,
'boundary': bc_info
}
# 如果 fluid['Re'] 未指定,则用入口速度幅值 * 结构物纵向跨度 / nu 计算 Re
try:
if fluid_info.get('Re') is None:
nu = fluid_info.get('nu')
if inlet_info is not None and nu and (length_y is not None) and nu != 0 and length_y > 0:
vals = inlet_info.get('value', (0.0, 0.0)) if isinstance(inlet_info, dict) else (0.0, 0.0)
u_in = float(np.sqrt(sum([float(x)**2 for x in vals[:self.vector_dim]])))
Re_calc = u_in * float(length_y) / float(nu)
fluid_info['Re'] = float(Re_calc)
except Exception:
pass
geometry_data = {
'structure_length_y': float(length_y) if length_y is not None else 0.0,
'structure_length_x': float(length_x) if length_x is not None else 0.0,
'bbox': tuple(float(x) for x in bbox) if bbox is not None else None
}
info_dict['geometry'] = geometry_data
# 记录 inlet side
try:
info_dict['boundary']['inlet']['side'] = inlet_side
except Exception:
try:
if isinstance(inlet_info, dict):
inlet_info['side'] = inlet_side
info_dict['boundary'] = {'inlet': inlet_info}
except Exception:
pass
return field, info_dict
def __getitem__(self, idx):
total_available = len(self.time_dirs)
window = int(self._number_of_steps_to_get)
max_start = total_available - window
if total_available == 0 or idx < 0 or idx > max_start:
raise IndexError('index out of range for the configured number_of_steps_to_get.')
fields_seq = []
infos_seq = []
for offset in range(window):
field, info = self._get_one_frame(idx + offset)
fields_seq.append(field)
infos_seq.append(info)
return fields_seq, infos_seq
@staticmethod
def _stack_field(values, *, device, dtype):
if not values:
return values
if not HAVE_TORCH:
arrays = [np.ascontiguousarray(np.asarray(v)) for v in values]
stacked = np.stack(arrays, axis=0)
if stacked.ndim == 3:
stacked = stacked[:, None, ...]
return stacked
tensors = []
target_dtype = dtype if dtype is not None else torch.float32
target_device = device if device is not None else torch.device('cpu')
for value in values:
tensor = value if torch.is_tensor(value) else torch.as_tensor(value, dtype=target_dtype)
tensor = tensor.to(device=target_device, dtype=target_dtype)
if tensor.ndim == 2:
tensor = tensor.unsqueeze(0)
if tensor.ndim != 3:
raise ValueError(f'Expected field tensor with 3 dims per sample (C, Ny, Nx); got {tuple(tensor.shape)}')
tensors.append(tensor.contiguous())
stacked = torch.stack(tensors, dim=0)
return stacked.contiguous()
@staticmethod
def _collate_info(infos, *, batch_size, data_device):
if not HAVE_TORCH:
raise RuntimeError('torch is required for collating info dictionaries.')
cpu_device = torch.device('cpu')
info_list = [dict(info) if isinstance(info, dict) else {} for info in infos]
def _collect_scalar(key, *, device, default=0.0):
values = []
for data in info_list:
value = data.get(key, default)
if value is None:
value = default
values.append(float(value))
tensor = torch.tensor(values, dtype=torch.float32, device=device)
return tensor.view(len(values), 1)
info_out = {
'dt': _collect_scalar('dt', device=data_device, default=0.0),
'dt_simulation': _collect_scalar('dt_simulation', device=cpu_device, default=0.0),
'time': _collect_scalar('time', device=cpu_device, default=0.0),
'fluid': {},
'geometry': {},
'solid_velocity': None,
'boundary': []
}
fluid_keys = set()
for data in info_list:
fluid = data.get('fluid')
if isinstance(fluid, dict):
fluid_keys.update(fluid.keys())
for key in sorted(fluid_keys):
values = []
for data in info_list:
fluid = data.get('fluid') if isinstance(data.get('fluid'), dict) else {}
value = fluid.get(key, 0.0) if isinstance(fluid, dict) else 0.0
if value is None:
value = 0.0
values.append(float(value))
tensor = torch.tensor(values, dtype=torch.float32, device=cpu_device)
info_out['fluid'][key] = tensor.view(len(values), 1)
geometry_keys = set()
for data in info_list:
geometry = data.get('geometry')
if isinstance(geometry, dict):
geometry_keys.update(geometry.keys())
for key in sorted(geometry_keys):
if key == 'bbox':
bbox_vals = []
for data in info_list:
geometry = data.get('geometry') if isinstance(data.get('geometry'), dict) else {}
bbox = geometry.get('bbox') if isinstance(geometry, dict) else None
if bbox is None:
bbox_vals.append([0.0, 0.0, 0.0, 0.0])
else:
bbox_vals.append([float(x) for x in bbox])
info_out['geometry']['bbox'] = torch.tensor(bbox_vals, dtype=torch.float32, device=cpu_device)
else:
values = []
for data in info_list:
geometry = data.get('geometry') if isinstance(data.get('geometry'), dict) else {}
value = geometry.get(key, 0.0) if isinstance(geometry, dict) else 0.0
if value is None:
value = 0.0
values.append(float(value))
tensor = torch.tensor(values, dtype=torch.float32, device=cpu_device)
info_out['geometry'][key] = tensor.view(len(values), 1)
solid_velocities = []
max_dim = 0
for data in info_list:
vel = data.get('solid_velocity', ())
vel_list = list(vel) if vel is not None else []
max_dim = max(max_dim, len(vel_list))
solid_velocities.append([float(x) for x in vel_list])
if max_dim == 0:
info_out['solid_velocity'] = torch.zeros((batch_size, 0), dtype=torch.float32, device=cpu_device)
else:
padded = []
for vel in solid_velocities:
vel = vel + [0.0] * (max_dim - len(vel))
padded.append(vel)
info_out['solid_velocity'] = torch.tensor(padded, dtype=torch.float32, device=cpu_device)
info_out['boundary'] = [data.get('boundary') for data in info_list]
return info_out
@staticmethod
def collate_fn(batch): # b, f -> f, b
if not batch:
return [], []
field_sequences, info_sequences = zip(*batch)
steps = len(field_sequences[0]) if field_sequences else 0
for seq in field_sequences:
if len(seq) != steps:
raise ValueError('All samples must contain the same number of frames.')
for seq in info_sequences:
if len(seq) != steps:
raise ValueError('All samples must contain the same number of frames.')
collated_fields = []
collated_infos = []
for step_idx in range(steps):
step_fields = [seq[step_idx] for seq in field_sequences]
step_infos = [seq[step_idx] for seq in info_sequences]
data_device = None
data_dtype = None
if HAVE_TORCH:
for sample in step_fields:
for value in sample.values():
if torch.is_tensor(value):
data_device = value.device
data_dtype = value.dtype
break
if data_device is not None:
break
first_field = step_fields[0]
field_dict = {}
for key in first_field.keys():
values = [sample[key] for sample in step_fields]
field_dict[key] = OpenfoamDataset._stack_field(values, device=data_device, dtype=data_dtype)
if HAVE_TORCH:
batch_size = len(step_fields)
info_dict = OpenfoamDataset._collate_info(step_infos, batch_size=batch_size, data_device=data_device or torch.device('cpu'))
else:
info_dict = {}
collated_fields.append(field_dict)
collated_infos.append(info_dict)
return collated_fields, collated_infos
@staticmethod
def plot_streamlines(field,
ax=None,
seed_density=0.6,
seeds=None,
step_size=None,
max_steps=2000,
min_speed=1e-5,
color_mode='speed',
cmap='viridis',
linewidth=1.4,
background='velocity',
background_cmap='Greys',
background_alpha=0.35,
add_colorbar=True,
mask_boundary=True,
title=None):
"""
绘制速度场流线,思路参考 ``phi.vis.plot`` 中针对流线的处理流程(phi.torch.flow)。
通过 Runge-Kutta 积分追踪多条流线,支持根据速度着色、掩码约束和背景叠加。
参数:
field: dict,至少包含 ``Ux``、``Uy``、``xGrid``、``yGrid``,可选 ``mask``、``p``。
ax: Matplotlib Axes,若为 None 会创建新的图像。
seed_density: 生成种子点的密度(基于网格尺寸,内部会自动限制总数量)。
seeds: 手动指定种子点 (N,2),单位与网格坐标一致。给定后忽略 seed_density。
step_size: 空间步长,None 时自动取网格最小间距的一半。
max_steps: 每个方向的积分步数上限。
min_speed: 速度模低于该阈值即停止积分,避免停滞点振荡。
color_mode: 'speed' 根据速度模着色;'constant' 使用 cmap 作为单一颜色。
cmap: 着色方案;当 color_mode='constant' 时可为颜色字符串。
linewidth: 流线宽度。
background: 背景着色方式,'pressure' | 'velocity' | 'none' | ndarray。
background_cmap/background_alpha: 背景 colormap 及透明度。
add_colorbar: 是否为速度着色添加 colorbar。
mask_boundary: 是否绘制固体边界轮廓。
title: 可选标题。
返回:
Matplotlib LineCollection 或 None。
"""
if field is None:
raise ValueError('field is required for plot_streamlines().')
if color_mode not in ('speed', 'constant'):
raise ValueError("color_mode must be either 'speed' or 'constant'.")
if max_steps <= 0:
raise ValueError('max_steps 必须为正整数。')
fig = None
if ax is None:
fig, ax = plt.subplots(figsize=(6, 5))
else:
fig = ax.figure
Ux_raw = _to_numpy(field.get('Ux')) if field.get('Ux') is not None else None
Uy_raw = _to_numpy(field.get('Uy')) if field.get('Uy') is not None else None
xGrid_raw = _to_numpy(field.get('xGrid')) if field.get('xGrid') is not None else None
yGrid_raw = _to_numpy(field.get('yGrid')) if field.get('yGrid') is not None else None
if Ux_raw is None or Uy_raw is None or xGrid_raw is None or yGrid_raw is None:
raise ValueError("field must provide 'Ux', 'Uy', 'xGrid', 'yGrid'.")
mask_raw = _to_numpy(field.get('mask')) if field.get('mask') is not None else np.zeros_like(Ux_raw, dtype=float)
Ux = np.array(Ux_raw, dtype=float, copy=True)
Uy = np.array(Uy_raw, dtype=float, copy=True)
mask = np.array(mask_raw, dtype=float, copy=True)
xGrid = np.array(xGrid_raw, dtype=float, copy=True)
yGrid = np.array(yGrid_raw, dtype=float, copy=True)
flip_x = xGrid.shape[1] > 1 and xGrid[0, 0] > xGrid[0, -1]
flip_y = yGrid.shape[0] > 1 and yGrid[0, 0] > yGrid[-1, 0]
if flip_x:
Ux = np.flip(Ux, axis=1)
Uy = np.flip(Uy, axis=1)
mask = np.flip(mask, axis=1)
xGrid = np.flip(xGrid, axis=1)
yGrid = np.flip(yGrid, axis=1)
if flip_y:
Ux = np.flip(Ux, axis=0)
Uy = np.flip(Uy, axis=0)
mask = np.flip(mask, axis=0)
xGrid = np.flip(xGrid, axis=0)
yGrid = np.flip(yGrid, axis=0)
xs = xGrid[0, :].astype(float)
ys = yGrid[:, 0].astype(float)
if xs.size < 2 or ys.size < 2:
raise ValueError('流线绘制需要至少 2x2 的网格。')
dx = float(np.median(np.diff(xs))) if xs.size > 1 else 1.0
dy = float(np.median(np.diff(ys))) if ys.size > 1 else 1.0
grid_step = min(abs(dx) if dx != 0 else np.inf, abs(dy) if dy != 0 else np.inf)
if not np.isfinite(grid_step) or grid_step == 0:
grid_step = 1.0
if step_size is None:
step_size = 0.5 * grid_step
if not HAVE_SCIPY_INTERP:
raise RuntimeError('scipy.interpolate.RegularGridInterpolator 未安装,无法使用高级流线整合。')
fluid_mask = mask > 0.5
if not np.any(fluid_mask):
raise ValueError('未检测到流体区域,无法绘制流线。')
Ux_interp = RegularGridInterpolator((ys, xs), Ux, bounds_error=False, fill_value=np.nan)
Uy_interp = RegularGridInterpolator((ys, xs), Uy, bounds_error=False, fill_value=np.nan)
mask_interp = RegularGridInterpolator((ys, xs), mask, method='nearest', bounds_error=False, fill_value=0.0)
seed_density = float(seed_density)
if seed_density <= 0:
raise ValueError('seed_density 必须为正。')
fluid_indices = np.argwhere(fluid_mask)
y_idx_min, x_idx_min = fluid_indices.min(axis=0)
y_idx_max, x_idx_max = fluid_indices.max(axis=0)
domain_x = (xs[x_idx_min], xs[x_idx_max])
domain_y = (ys[y_idx_min], ys[y_idx_max])
if seeds is None:
n_seed_x = max(3, int(len(xs) * seed_density))
n_seed_y = max(3, int(len(ys) * seed_density))
max_total_seeds = 600
while n_seed_x * n_seed_y > max_total_seeds and (n_seed_x > 3 or n_seed_y > 3):
if n_seed_x >= n_seed_y and n_seed_x > 3:
n_seed_x -= 1
elif n_seed_y > 3:
n_seed_y -= 1
else:
break
seed_x = np.linspace(domain_x[0], domain_x[1], n_seed_x)
seed_y = np.linspace(domain_y[0], domain_y[1], n_seed_y)
sx, sy = np.meshgrid(seed_x, seed_y)
seeds = np.stack([sx.ravel(), sy.ravel()], axis=-1)
else:
seeds = np.asarray(seeds, dtype=float)
if seeds.ndim != 2 or seeds.shape[1] != 2:
raise ValueError('seeds 需要形状 (N, 2)。')
def _interp(interpolator, pos):
return interpolator(np.array([[pos[1], pos[0]]], dtype=float))[0]
def inside(pos):
return xs[0] <= pos[0] <= xs[-1] and ys[0] <= pos[1] <= ys[-1]
def mask_value(pos):
val = _interp(mask_interp, pos)
return float(val) if np.isfinite(val) else 1.0
valid_seed_list = []
for seed in seeds:
if not inside(seed):
continue
if mask_value(seed) <= 0.5:
continue
valid_seed_list.append(seed.astype(float))
seeds = np.array(valid_seed_list, dtype=float)
if seeds.size == 0:
warnings.warn('未找到有效的流线起始点。', RuntimeWarning)
return None
visited = np.zeros_like(fluid_mask, dtype=bool)
def grid_index(pos):
ix = np.searchsorted(xs, pos[0], side='left') - 1
iy = np.searchsorted(ys, pos[1], side='left') - 1
ix = int(np.clip(ix, 0, len(xs) - 1))
iy = int(np.clip(iy, 0, len(ys) - 1))
return iy, ix
def already_covered(pos):
iy, ix = grid_index(pos)
return visited[iy, ix]
def mark_path(points):
if points.size == 0:
return
ix = np.clip(np.searchsorted(xs, points[:, 0], side='left') - 1, 0, len(xs) - 1).astype(int)
iy = np.clip(np.searchsorted(ys, points[:, 1], side='left') - 1, 0, len(ys) - 1).astype(int)
visited[iy, ix] = True
def velocity(pos):
if not inside(pos):
return None
if mask_value(pos) <= 0.5:
return None
u = _interp(Ux_interp, pos)
v = _interp(Uy_interp, pos)
if not np.isfinite(u) or not np.isfinite(v):
return None
return np.array([float(u), float(v)], dtype=float)
def rk4_step(pos, dt):
k1 = velocity(pos)
if k1 is None:
return None, None
k2 = velocity(pos + 0.5 * dt * k1)
if k2 is None:
return None, None
k3 = velocity(pos + 0.5 * dt * k2)
if k3 is None:
return None, None
k4 = velocity(pos + dt * k3)
if k4 is None:
return None, None
vel_avg = (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0
new_pos = pos + dt * vel_avg
return new_pos, np.linalg.norm(vel_avg)
def integrate_direction(seed_point, direction):
pos = np.array(seed_point, dtype=float)
path_points = [pos.copy()]
segment_speeds = []
for _ in range(int(max_steps)):
vel = velocity(pos)
if vel is None:
break
speed = np.linalg.norm(vel)
if not np.isfinite(speed) or speed < min_speed:
break
dt = direction * (step_size / max(speed, min_speed))
new_pos, avg_speed = rk4_step(pos, dt)
if new_pos is None or not inside(new_pos):
break
if mask_value(new_pos) <= 0.5:
break
path_points.append(new_pos)
segment_speeds.append(float(avg_speed if avg_speed is not None else speed))
pos = new_pos
return np.array(path_points, dtype=float), np.array(segment_speeds, dtype=float)
def trace(seed_point):
forward_pts, forward_speeds = integrate_direction(seed_point, 1.0)
backward_pts, backward_speeds = integrate_direction(seed_point, -1.0)
if forward_pts.shape[0] < 2 and backward_pts.shape[0] < 2:
return None
if backward_pts.shape[0] > 1:
back_pts = backward_pts[::-1]
back_speeds = backward_speeds[::-1]
pts = np.vstack((back_pts[:-1], forward_pts))
speeds = np.concatenate((back_speeds, forward_speeds))
else:
pts = forward_pts
speeds = forward_speeds
return pts, speeds
segments = []
segment_values = []
rng = np.random.default_rng(42)
rng.shuffle(seeds)
for seed in seeds:
if already_covered(seed):
continue
traced = trace(seed)
if traced is None:
continue
pts, speeds = traced
if pts.shape[0] < 2:
continue
segments.append(np.stack([pts[:-1], pts[1:]], axis=1))
if color_mode == 'speed':
if speeds.size == 0:
speeds = np.zeros(pts.shape[0] - 1, dtype=float)
segment_values.append(speeds)
mark_path(pts)
background_data = None
if isinstance(background, str):
key = background.lower()
if key in ('pressure', 'p') and field.get('p') is not None:
background_data = _to_numpy(field.get('p'))
elif key in ('velocity', 'speed', 'magnitude'):
background_data = np.sqrt(Ux ** 2 + Uy ** 2)
elif background is not None:
background_data = np.asarray(background, dtype=float)
if background_data is not None:
background_arr = np.array(background_data, dtype=float, copy=True)
if background_arr.shape != Ux.shape:
if background_arr.size == 1:
background_arr = np.full(Ux.shape, float(background_arr.ravel()[0]), dtype=float)
else:
background_arr = None
if background_arr is not None:
if flip_x:
background_arr = np.flip(background_arr, axis=1)
if flip_y:
background_arr = np.flip(background_arr, axis=0)
background_masked = np.ma.array(background_arr, mask=mask <= 0.5)
try:
ax.pcolormesh(xGrid, yGrid, background_masked, shading='auto', cmap=background_cmap, alpha=background_alpha)
except Exception:
ax.imshow(background_masked.T, origin='lower', cmap=background_cmap, alpha=background_alpha)
if mask_boundary:
try:
ax.contour(xGrid, yGrid, mask, levels=[0.5], colors='k', linewidths=0.5, alpha=0.6)
except Exception:
pass
line_collection = None
if segments:
seg_array = np.concatenate(segments, axis=0)
if color_mode == 'speed' and segment_values:
values = np.concatenate(segment_values, axis=0)
if not np.isfinite(values).any():
values = np.zeros(seg_array.shape[0], dtype=float)
vmin = float(np.nanmin(values))
vmax = float(np.nanmax(values))
if not np.isfinite(vmin):
vmin = 0.0
if not np.isfinite(vmax):
vmax = 1.0
if abs(vmax - vmin) < 1e-12:
vmax = vmin + 1e-12
norm = Normalize(vmin=vmin, vmax=vmax)
line_collection = LineCollection(seg_array, linewidths=linewidth, cmap=cmap, norm=norm)
line_collection.set_array(values)
ax.add_collection(line_collection)
if add_colorbar and fig is not None:
fig.colorbar(line_collection, ax=ax, fraction=0.046, pad=0.04, label='|u|')
else:
color_value = cmap if isinstance(cmap, str) else 'k'
line_collection = LineCollection(seg_array, linewidths=linewidth, colors=color_value)
ax.add_collection(line_collection)
ax.set_xlim(xs[0], xs[-1])
ax.set_ylim(ys[0], ys[-1])
if flip_y:
ax.invert_yaxis()
ax.set_aspect('equal', adjustable='box')
ax.set_xlabel('x')
ax.set_ylabel('y')
if title:
ax.set_title(title)
if not segments:
warnings.warn('未生成有效流线,已仅绘制背景。', RuntimeWarning)
return line_collection
@staticmethod
def visualize(dataset, indices=None, mask_mode='nan', save_dir=None,
to_video=False, video_name='out.mp4', fps=10,
cmap='viridis', pressure_cmap='plasma', show=False,
clip_percentile=99, add_contours=False, contour_levels=10,
add_streamlines=False, stream_density=1.0, ffmpeg_path='./',
stream_kwargs=None):
"""
静态可视化方法:接受一个 dataset 实例(或任何具有 __getitem__ 的对象)和若干时间步索引,
将每一帧绘制为基于坐标的伪彩图(使用 pcolormesh),并可选择保存每帧到磁盘并用 ffmpeg 合成视频。
参数:
- dataset: OpenfoamDataset 实例或兼容接口
- indices: None 或索引列表(None 表示全部时间步)
- mask_mode: 固体区域掩码处理方式,支持 'nan'(默认)或 'zero'
- save_dir: 若指定则保存逐帧 PNG 到该目录
- to_video: 若 True 则在保存完帧后调用 ffmpeg 合成视频 (需要系统安装 ffmpeg)
- video_name: 生成的视频文件名(位于 save_dir)
- fps: 视频帧率
- cmap / pressure_cmap: 颜色映射
- show: 是否在每帧显示窗口(会阻塞,适用于交互)
- ffmpeg_path: ffmpeg/bin 的路径(用于添加环境变量,确保ffmpeg命令可运行)
- stream_kwargs: dict,可选流线绘制参数,透传给 plot_streamlines()
"""
# 处理 indices
if indices is None:
try:
n = len(dataset)
indices = list(range(n))
except Exception:
indices = [0]
if save_dir:
os.makedirs(save_dir, exist_ok=True)
def to_numpy(x):
try:
return x.cpu().numpy()
except Exception:
return np.array(x)
def _fallback_streamplot(ax, x_grid, y_grid, pressure_field, Ux_field, Uy_field,
density_value, contour_flag, contour_levels_value):
try:
ax.pcolormesh(x_grid, y_grid, pressure_field, shading='auto', cmap=pressure_cmap, alpha=0.25)
except Exception:
pass
xs_local = np.unique(x_grid[0, :]) if x_grid.ndim == 2 else np.linspace(np.min(x_grid), np.max(x_grid), Ux_field.shape[1])
ys_local = np.unique(y_grid[:, 0]) if y_grid.ndim == 2 else np.linspace(np.min(y_grid), np.max(y_grid), Ux_field.shape[0])
if ys_local[0] > ys_local[-1]:
ys_for_plot = ys_local[::-1]
U_plot = np.flipud(Ux_field)
V_plot = np.flipud(Uy_field)
else:
ys_for_plot = ys_local
U_plot = Ux_field
V_plot = Uy_field
try:
ax.streamplot(xs_local, ys_for_plot, U_plot, V_plot, density=density_value, color='k', linewidth=0.6, arrowsize=1.0)
except Exception:
pass
if contour_flag:
try:
ax.contour(x_grid, y_grid, pressure_field, levels=contour_levels_value, colors='k', linewidths=0.5)
except Exception:
pass
base_stream_kwargs = dict(stream_kwargs) if stream_kwargs is not None else {}
frame_paths = []
frame_counter = 0
for idx in indices:
sample = dataset[idx]
if not isinstance(sample, (list, tuple)) or len(sample) != 2:
raise TypeError('Dataset __getitem__ must return (fields_seq, infos_seq).')
fields_seq, infos_seq = sample
if len(fields_seq) != len(infos_seq):
raise ValueError('fields_seq and infos_seq must have the same length.')
for step_offset, (field, info) in enumerate(zip(fields_seq, infos_seq)):
Ux = to_numpy(field.get('Ux'))
Uy = to_numpy(field.get('Uy'))
p = to_numpy(field.get('p'))
xGrid = to_numpy(field.get('xGrid'))
yGrid = to_numpy(field.get('yGrid'))
mask = to_numpy(field.get('mask'))
def apply_mask(arr):
a = arr.copy()
try:
mask_arr = np.asarray(mask)
if mask_arr.dtype == bool:
solid_region = ~mask_arr
else:
solid_region = mask_arr < 0.5
if mask_mode == 'zero':
a[solid_region] = 0.0
elif mask_mode == 'keep':
pass
else:
a = np.where(solid_region, np.nan, a)
except Exception:
pass
return a
p_vis = apply_mask(p)
vel = np.sqrt(np.nan_to_num(Ux)**2 + np.nan_to_num(Uy)**2)
vel_vis = apply_mask(vel)
try:
x_1d = xGrid[0, :]
y_1d = yGrid[:, 0]
dudx = np.gradient(Ux, x_1d, axis=1)
dudy = np.gradient(Ux, y_1d, axis=0)
dvdx = np.gradient(Uy, x_1d, axis=1)
dvdy = np.gradient(Uy, y_1d, axis=0)
vorticity = dvdx - dudy
except Exception:
vorticity = np.zeros_like(Ux)
vort_vis = apply_mask(vorticity)
fig = plt.figure(figsize=(12, 10))
gs = fig.add_gridspec(2, 2, left=0.07, right=0.95, top=0.96, bottom=0.05, wspace=0.12, hspace=0.18)
ax_vort = fig.add_subplot(gs[0, 0])
ax_press = fig.add_subplot(gs[0, 1])
ax_stream = fig.add_subplot(gs[1, 0])
ax_vel = fig.add_subplot(gs[1, 1])
try:
if clip_percentile is not None and clip_percentile > 0:
valid = p_vis[~np.isnan(p_vis)] if np.any(~np.isnan(p_vis)) else np.array([])
if valid.size > 0:
vmin = np.percentile(valid, 100 - clip_percentile)
vmax = np.percentile(valid, clip_percentile)
else:
vmin, vmax = None, None
else:
vmin, vmax = None, None
pcm_press = ax_press.pcolormesh(xGrid, yGrid, p_vis, shading='auto', cmap=pressure_cmap, vmin=vmin, vmax=vmax)
except Exception:
pcm_press = ax_press.imshow(p_vis.T if p_vis.ndim == 2 else p_vis, origin='lower', cmap=pressure_cmap)
ax_press.set_title(f'Pressure (sample={idx}, step={step_offset}, time={info.get("time")})')
fig.colorbar(pcm_press, ax=ax_press, fraction=0.046, pad=0.04)
try:
ax_press.set_aspect('equal', adjustable='box')
except Exception:
pass
try:
pcm_vort = ax_vort.pcolormesh(xGrid, yGrid, vort_vis, shading='auto', cmap='bwr')
except Exception:
pcm_vort = ax_vort.imshow(vort_vis.T if vort_vis.ndim == 2 else vort_vis, origin='lower', cmap='bwr')
ax_vort.set_title(f'Vorticity (sample={idx}, step={step_offset})')
fig.colorbar(pcm_vort, ax=ax_vort, fraction=0.046, pad=0.04)
try:
ax_vort.set_aspect('equal', adjustable='box')
except Exception:
pass
stream_field = {
'Ux': field.get('Ux'),
'Uy': field.get('Uy'),
'xGrid': field.get('xGrid'),
'yGrid': field.get('yGrid'),
'mask': field.get('mask'),
'p': field.get('p')
}
if add_streamlines:
local_stream_kwargs = dict(base_stream_kwargs)
local_stream_kwargs.setdefault('seed_density', stream_density)
local_stream_kwargs.setdefault('background', 'pressure')
local_stream_kwargs.setdefault('cmap', cmap)
local_stream_kwargs.setdefault('add_colorbar', False)
local_stream_kwargs.setdefault('mask_boundary', True)
local_stream_kwargs.setdefault('title', f'Streamlines (sample={idx}, step={step_offset})')
try:
OpenfoamDataset.plot_streamlines(stream_field, ax=ax_stream, **local_stream_kwargs)
except Exception as exc:
warnings.warn(f'plot_streamlines failed ({exc!r}); falling back to matplotlib.streamplot()', RuntimeWarning)
_fallback_streamplot(ax_stream, xGrid, yGrid, p_vis, Ux, Uy, stream_density, add_contours, contour_levels)
ax_stream.set_title(f'Streamlines (sample={idx}, step={step_offset})')
else:
_fallback_streamplot(ax_stream, xGrid, yGrid, p_vis, Ux, Uy, stream_density, add_contours, contour_levels)
ax_stream.set_title(f'Streamlines (sample={idx}, step={step_offset})')
try:
ax_stream.set_aspect('equal', adjustable='box')
except Exception:
pass
try:
pcm_vel = ax_vel.pcolormesh(xGrid, yGrid, vel_vis, shading='auto', cmap=cmap)
except Exception:
pcm_vel = ax_vel.imshow(vel_vis.T if vel_vis.ndim == 2 else vel_vis, origin='lower', cmap=cmap)
ax_vel.set_title(f'Velocity magnitude (sample={idx}, step={step_offset})')
fig.colorbar(pcm_vel, ax=ax_vel, fraction=0.046, pad=0.04)
try:
ax_vel.set_aspect('equal', adjustable='box')
except Exception:
pass
if save_dir:
out_path = os.path.join(save_dir, f'frame_{frame_counter:06d}.png')
fig.savefig(out_path, dpi=150)
frame_paths.append(out_path)
print(f'[visualize] saved {out_path}')
if show:
plt.show()
else:
plt.close(fig)
frame_counter += 1
# 调用 ffmpeg 合成视频(如果需要)
if to_video:
os.environ["PATH"] = ffmpeg_path + os.pathsep + os.environ["PATH"]
if not save_dir:
raise ValueError('to_video=True 时必须提供 save_dir 用于存放帧')
out_video = os.path.join(save_dir, video_name)
input_pattern = os.path.join(save_dir, 'frame_%06d.png')
scale_filter = 'scale=iw/2:ih/2'
cmd = ['ffmpeg', '-y', '-framerate', str(fps), '-i', input_pattern, '-vf', scale_filter, '-c:v', 'libx264', '-pix_fmt', 'yuv420p', out_video]
try:
print('[visualize] running ffmpeg to create video...')
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f'[visualize] video saved to {out_video}')
except FileNotFoundError:
raise RuntimeError('ffmpeg 未找到:请在系统路径中安装 ffmpeg,或将其可执行文件路径添加到 PATH')
except subprocess.CalledProcessError as e:
raise RuntimeError(f'ffmpeg failed: {e.stderr.decode(errors="ignore")}')
class OpenfoamDataset_Only4AE(OpenfoamDataset):
def __getitem__(self, index):
fields_seq, _ = super().__getitem__(index)
return fields_seq
# 基于多个Dataset实例的包装类,用于多数据集联合训练等场景
# 将多个数据集拼成一个更大的数据集,并视作一个整体
# 在内部如何准确找到样本:将 样本的外部编号 动态映射到 样本所在数据集编号及其在数据集内部的编号
# 可以组装不同的Dataset类,但是这些类必须有统一的的接口和一致的 collate_fn
class ConcatDatasetsWrapper(Dataset):
"""Wrap multiple dataset instances (possibly heterogeneous) into a single dataset.
datasets_descriptors: sequence where each element can be either:
- a path (str/Path) -> will be constructed using dataset_cls (default OpenfoamDataset)
- a tuple (path, dataset_cls) -> constructed with dataset_cls(path, number_of_steps_to_get, ...)
- a tuple (path, dataset_cls, kwargs_dict) -> constructed with dataset_cls(path, number_of_steps_to_get, **kwargs_dict)
This allows assembling heterogeneous dataset classes into one virtual dataset.
"""
def __init__(self, datasets_descriptors, number_of_steps_to_get, *args, **kwargs):
self.datasets_descriptors = list(datasets_descriptors)
self._number_of_steps_to_get = number_of_steps_to_get
# 默认 Dataset 类为 OpenfoamDataset;若 descriptor 为 tuple 则可指定类
self._default_dataset_cls = OpenfoamDataset
self._default_args = args
self._default_kwargs = dict(kwargs)
self.datasets_list = []
for desc in self.datasets_descriptors:
if isinstance(desc, (str, os.PathLike)):
path = os.fspath(desc)
cls = self._default_dataset_cls
k = dict(self._default_kwargs)
elif isinstance(desc, Sequence) and len(desc) >= 2:
path = os.fspath(desc[0])
cls = desc[1] or self._default_dataset_cls
k = dict(self._default_kwargs)
if len(desc) >= 3 and isinstance(desc[2], dict):
k.update(desc[2])
else:
raise TypeError('Each datasets_descriptors element must be path or (path, cls[, kwargs])')
ds = cls(path, self._number_of_steps_to_get, *self._default_args, **k)
self.datasets_list.append(ds)
# expose collate helpers from first dataset for convenience
if self.datasets_list:
# expose a collate function from the first dataset; default to OpenfoamDataset.collate_fn
self.collate_fn = getattr(self.datasets_list[0], 'collate_fn', OpenfoamDataset.collate_fn)
def __len__(self):
return sum(len(i) for i in self.datasets_list)
def __getitem__(self, idx):
idx_sample_internal = idx
for i, ds in enumerate(self.datasets_list):
if idx_sample_internal < len(ds):
return ds[idx_sample_internal]
idx_sample_internal -= len(ds)
raise IndexError('index out of range')
def create_dataloader_of(data_path,
number_of_steps_to_get=2,
batch_size=1,
shuffle=True,
num_workers=0,
pin_memory=True, # ✅ 要求 CPU tensor
drop_last=False,
collate_fn=None,
distributed=False,
world_size=1,
rank=0,
seed=None,
persistent_workers=False,
prefetch_factor=2,
generator=None,
device=None,
dtype=None,
**dataset_kwargs):
"""Create a DataLoader for a single OpenfoamDataset.
Args:
data_path: Path to OpenFOAM case directory (single dataset).
number_of_steps_to_get: Number of time steps to load per sample.
batch_size: Batch size for DataLoader.
shuffle: Whether to shuffle the dataset.
num_workers: Number of worker processes for data loading.
pin_memory: Pin memory for faster GPU transfer.
drop_last: Drop last incomplete batch.
collate_fn: Custom collate function (defaults to OpenfoamDataset.collate_fn).
distributed: Enable distributed sampler.
world_size: Number of distributed processes.
rank: Rank of current process.
seed: Random seed for reproducibility.
persistent_workers: Keep workers alive between epochs.
prefetch_factor: Number of batches to prefetch per worker.
generator: Random generator for sampling.
device: torch 设备(覆盖 Dataset 初始化时的 device 参数)。
dtype: torch dtype(覆盖 Dataset 初始化时的 dtype 参数)。
**dataset_kwargs: Additional arguments passed to OpenfoamDataset constructor.
Returns:
torch.utils.data.DataLoader instance.
"""
if not HAVE_TORCH:
raise RuntimeError('torch is required to create a DataLoader.')
dataset_kwargs = dict(dataset_kwargs)
if device is not None:
dataset_kwargs.setdefault('device', device)
if dtype is not None:
dataset_kwargs.setdefault('dtype', dtype)
# Create single OpenfoamDataset instance
dataset = OpenfoamDataset(
root_dir=data_path,
number_of_steps_to_get=number_of_steps_to_get,
**dataset_kwargs
)
# Use dataset's collate_fn if not provided
if collate_fn is None:
collate_fn = OpenfoamDataset.collate_fn
# Setup distributed sampler if needed
sampler = None
final_world_size = max(1, int(world_size))
if distributed or final_world_size > 1:
sampler = torch.utils.data.distributed.DistributedSampler(
dataset,
num_replicas=final_world_size,
rank=int(rank),
shuffle=bool(shuffle)
)
shuffle = False
# Setup worker initialization function with seeding
worker_init_fn = None
if seed is not None:
base_seed = int(seed)
def _init_fn(worker_id):
worker_seed = base_seed + worker_id
np.random.seed(worker_seed)
random.seed(worker_seed)
torch.manual_seed(worker_seed)
worker_init_fn = _init_fn
if generator is None:
generator = torch.Generator()
generator.manual_seed(base_seed)
batch_size = min(batch_size, len(dataset))
nd = torch.cuda.device_count() # number of CUDA devices
num_workers = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, num_workers]) # number of workers
# Build DataLoader kwargs
loader_kwargs = dict(
dataset=dataset,
batch_size=batch_size,
shuffle=bool(shuffle) if sampler is None else False,
sampler=sampler,
num_workers=num_workers,
pin_memory=pin_memory,
drop_last=drop_last,
collate_fn=collate_fn,
worker_init_fn=worker_init_fn,
generator=generator
)
if num_workers > 0:
loader_kwargs['persistent_workers'] = bool(persistent_workers)
if prefetch_factor is not None:
loader_kwargs['prefetch_factor'] = prefetch_factor
return DataLoader(**loader_kwargs)
def create_dataloader_cat(datasets_descriptors,
number_of_steps_to_get=2,
batch_size=1,
shuffle=True,
num_workers=0,
pin_memory=True, # ✅ 要求 CPU tensor
drop_last=False,
collate_fn=None,
distributed=False,
world_size=1,
rank=0,
seed=None,
persistent_workers=False,
prefetch_factor=2,
generator=None,
device=None,
dtype=None,
**dataset_kwargs):
"""Create a DataLoader backed by ConcatDatasetsWrapper for multiple datasets.
Args:
datasets_descriptors: Sequence of dataset descriptors, each can be:
- a path (str/PathLike) -> constructed with OpenfoamDataset
- a tuple (path, dataset_cls) -> constructed with custom class
- a tuple (path, dataset_cls, kwargs_dict) -> with extra kwargs
number_of_steps_to_get: Number of time steps to load per sample.
batch_size: Batch size for DataLoader.
shuffle: Whether to shuffle the dataset.
num_workers: Number of worker processes for data loading.
pin_memory: Pin memory for faster GPU transfer.
drop_last: Drop last incomplete batch.
collate_fn: Custom collate function (defaults to first dataset's collate_fn).
distributed: Enable distributed sampler.
world_size: Number of distributed processes.
rank: Rank of current process.
seed: Random seed for reproducibility.
persistent_workers: Keep workers alive between epochs.
prefetch_factor: Number of batches to prefetch per worker.
generator: Random generator for sampling.
device: torch 设备(覆盖内部 Dataset 初始化的 device 参数)。
dtype: torch dtype(覆盖内部 Dataset 初始化的 dtype 参数)。
**dataset_kwargs: Additional arguments passed to dataset constructors.
Returns:
torch.utils.data.DataLoader instance.
"""
if not HAVE_TORCH:
raise RuntimeError('torch is required to create a DataLoader.')
# Create ConcatDatasetsWrapper instance
dataset_kwargs = dict(dataset_kwargs)
if device is not None:
dataset_kwargs.setdefault('device', device)
if dtype is not None:
dataset_kwargs.setdefault('dtype', dtype)
dataset = ConcatDatasetsWrapper(
datasets_descriptors=datasets_descriptors,
number_of_steps_to_get=number_of_steps_to_get,
**dataset_kwargs
)
# Use wrapper's collate_fn if not provided
if collate_fn is None:
collate_fn = getattr(dataset, 'collate_fn', OpenfoamDataset.collate_fn)
# Setup distributed sampler if needed
sampler = None
final_world_size = max(1, int(world_size))
if distributed or final_world_size > 1:
sampler = torch.utils.data.distributed.DistributedSampler(
dataset,
num_replicas=final_world_size,
rank=int(rank),
shuffle=bool(shuffle)
)
shuffle = False
# Setup worker initialization function with seeding
worker_init_fn = None
if seed is not None:
base_seed = int(seed)
def _init_fn(worker_id):
worker_seed = base_seed + worker_id
np.random.seed(worker_seed)
random.seed(worker_seed)
torch.manual_seed(worker_seed)
worker_init_fn = _init_fn
if generator is None:
generator = torch.Generator()
generator.manual_seed(base_seed)
batch_size = min(batch_size, len(dataset))
nd = torch.cuda.device_count() # number of CUDA devices
num_workers = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, num_workers]) # number of workers
# Build DataLoader kwargs
loader_kwargs = dict(
dataset=dataset,
batch_size=batch_size,
shuffle=bool(shuffle) if sampler is None else False,
sampler=sampler,
num_workers=num_workers,
pin_memory=pin_memory,
drop_last=drop_last,
collate_fn=collate_fn,
worker_init_fn=worker_init_fn,
generator=generator
)
if num_workers > 0:
loader_kwargs['persistent_workers'] = bool(persistent_workers)
if prefetch_factor is not None:
loader_kwargs['prefetch_factor'] = prefetch_factor
return DataLoader(**loader_kwargs)
# 可视化测试与命令行入口
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='OpenFOAM dataloader quick sanity checks')
parser.add_argument('--data', type=str, default='./env19', help='OpenFOAM case 路径')
parser.add_argument('--step', type=int, default=0, help='预览的时间步索引')
# parser.add_argument('--visualize', action='store_true', help='是否可视化')
parser.add_argument('--save-dir', type=str, default='./test_loader', help='可视化输出目录 (若启用)')
args = parser.parse_args()
#%%
print('\n[Example 1] OpenfoamDataset 使用示例')
dataset = OpenfoamDataset(args.data, number_of_steps_to_get=2, device="cuda") # ✅ NOTE 建议使用cpu模式(在训练循环中手动to(device)), 因为 dataloader 启用 pin-memory 时要求 CPU tensor
print(' 总样本数:', len(dataset))
fields_seq, infos_seq = dataset[args.step]
print(' 样本时间序列长度:', len(fields_seq))
if fields_seq:
print(' 第 0 帧字段键:', list(fields_seq[0].keys()))
for key, value in fields_seq[0].items():
if HAVE_TORCH and torch.is_tensor(value):
print(f' {key}: tensor shape={tuple(value.shape)} dtype={value.dtype}')
else:
print(f' {key}: type={type(value)}')
if infos_seq:
print(' 第 0 帧 info 键:', list(infos_seq[0].keys()))
# if args.visualize:
# if True:
# os.makedirs(args.save_dir, exist_ok=True)
# OpenfoamDataset.visualize(dataset, indices=[args.step], save_dir=args.save_dir)
# print(f' 可视化结果保存在 {args.save_dir}')
#%%
print('\n[Example 2] create_dataloader_of 使用示例')
dataloader = create_dataloader_of(args.data, batch_size=2, shuffle=False, num_workers=0, device='cpu')
batch_fields, batch_infos = next(iter(dataloader))
print(' 批次时间序列长度:', len(batch_fields))
if batch_fields:
print(' 第 0 步字段键:', list(batch_fields[0].keys()))
for key, value in batch_fields[0].items():
if HAVE_TORCH and torch.is_tensor(value):
print(f' {key}: tensor shape={tuple(value.shape)} dtype={value.dtype}')
if batch_infos:
print(' 第 0 步 info 键:', list(batch_infos[0].keys()))
#%%
print('\n[Example 3] ConcatDatasetsWrapper 使用示例')
concat_dataset = ConcatDatasetsWrapper([args.data, args.data], number_of_steps_to_get=2)
print(' 总样本数:', len(concat_dataset))
concat_fields, concat_infos = concat_dataset[args.step]
print(' 样本时间序列长度:', len(concat_fields))
if concat_fields:
print(' 第 0 帧字段键:', list(concat_fields[0].keys()))
for key, value in concat_fields[0].items():
if HAVE_TORCH and torch.is_tensor(value):
print(f' {key}: tensor shape={tuple(value.shape)} dtype={value.dtype}')
if concat_infos:
print(' 第 0 帧 info 键:', list(concat_infos[0].keys()))
os.makedirs(args.save_dir, exist_ok=True)
OpenfoamDataset.visualize(concat_dataset, indices=None, save_dir=args.save_dir, show=False)
print(f' 可视化结果保存在 {args.save_dir}')
frame_pattern = os.path.join(args.save_dir, 'frame_%06d.png')
video_path = os.path.join(args.save_dir, 'preview.mp4')
if shutil.which('ffmpeg'):
cmd = ['ffmpeg', '-y', '-framerate', '5', '-i', frame_pattern, '-c:v', 'libx264', '-pix_fmt', 'yuv420p', video_path]
try:
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f' 已合成视频: {video_path}')
except subprocess.CalledProcessError as exc:
err_msg = exc.stderr.decode(errors='ignore') if exc.stderr else str(exc)
print(f' ⚠️ ffmpeg 合成失败: {err_msg[:200]}')
else:
print(' ⚠️ 未检测到 ffmpeg,跳过视频合成')
#%%
print('\n[Example 4] create_dataloader_cat 使用示例')
concat_loader = create_dataloader_cat([args.data, args.data], batch_size=2, shuffle=False, num_workers=0)
cat_fields, cat_infos = next(iter(concat_loader))
print(' 批次时间序列长度:', len(cat_fields))
if cat_fields:
print(' 第 0 步字段键:', list(cat_fields[0].keys()))
for key, value in cat_fields[0].items():
if HAVE_TORCH and torch.is_tensor(value):
print(f' {key}: tensor shape={tuple(value.shape)} dtype={value.dtype}')
if cat_infos:
print(' 第 0 步 info 键:', list(cat_infos[0].keys()))
#%%
print('\n✅ 示例执行完毕')
|