cpp
import numpy as np
import matplotlib.pyplot as plt
import re
# ============================================================
# 1. 解析函数
# ============================================================
def parse_tecplot_file(filepath):
"""
解析TECPLOT BLOCK格式数据文件
参数:
filepath: 文件路径
返回:
data_dict: 数据字典
header_info: 头部信息
"""
with open(filepath, 'r') as f:
full_text = f.read()
# 解析头部
header_info = {}
# 提取变量名
vars_start = full_text.find('VARIABLES = ')
vars_end = full_text.find('ZONE')
if vars_start != -1 and vars_end != -1:
vars_str = full_text[vars_start + 12:vars_end]
header_info['variables'] = vars_str.split()
# 提取网格尺寸
i_match = re.search(r'I\s*=\s*(\d+)', full_text)
j_match = re.search(r'J\s*=\s*(\d+)', full_text)
if i_match:
header_info['I'] = int(i_match.group(1))
if j_match:
header_info['J'] = int(j_match.group(1))
# 提取数值数据
block_pos = full_text.find('DATAPACKING = BLOCK')
if block_pos != -1:
data_str = full_text[block_pos + 20:]
values = []
for token in data_str.split():
try:
values.append(float(token))
except ValueError:
continue
values = np.array(values)
# 按变量分割数据
n_vars = len(header_info['variables'])
n_points = header_info['I'] * header_info['J']
data_dict = {}
for i, var_name in enumerate(header_info['variables']):
start_idx = i * n_points
end_idx = start_idx + n_points
data_dict[var_name] = values[start_idx:end_idx]
return data_dict, header_info
# ============================================================
# 2. 使用示例
# ============================================================
# 读取数据
data_dict, header_info = parse_tecplot_file('result_0040.dat')
# 访问数据
print(X.shape,Y.shape,P.shape)
X = data_dict['X'].reshape(header_info['J'], header_info['I'])
Y = data_dict['Y'].reshape(header_info['J'], header_info['I'])
P = data_dict['P'].reshape(header_info['J'], header_info['I'])
# 可视化
plt.figure(figsize=(10, 8))
plt.contourf(X, Y, P, levels=200, cmap='RdYlBu_r')#,antialiased=True)
plt.colorbar(label='Pressure')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Pressure Distribution')
plt.axis('equal')
plt.show()
# ============================================================
# 3. 导出为其他格式
# ============================================================
# 导出为VTK格式
def export_to_vtk(data_dict, header_info, filename):
"""
导出为VTK格式(可用ParaView打开)
"""
I = header_info['I']
J = header_info['J']
with open(filename, 'w') as f:
f.write("# vtk DataFile Version 3.0\n")
f.write("CFD Data\n")
f.write("ASCII\n")
f.write("DATASET STRUCTURED_GRID\n")
f.write(f"DIMENSIONS {I} {J} 1\n")
f.write(f"POINTS {I*J} float\n")
# 写入坐标
for i in range(I*J):
f.write(f"{data_dict['X'][i]} {data_dict['Y'][i]} 0.0\n")
# 写入数据
f.write(f"POINT_DATA {I*J}\n")
for var in header_info['variables']:
if var not in ['X', 'Y']:
f.write(f"SCALARS {var} float 1\n")
f.write("LOOKUP_TABLE default\n")
for val in data_dict[var]:
f.write(f"{val}\n")
# 导出为CSV格式
def export_to_csv(data_dict, header_info, filename):
"""
导出为CSV格式
"""
I = header_info['I']
J = header_info['J']
n_points = I * J
with open(filename, 'w') as f:
# 写入表头
f.write(','.join(header_info['variables']) + '\n')
# 写入数据
for i in range(n_points):
row = [str(data_dict[var][i]) for var in header_info['variables']]
f.write(','.join(row) + '\n')
re提取变量值
可以通过增大"level"提高分辨率