py读取dat/plt

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"提高分辨率

相关推荐
Eloudy2 小时前
矩阵算子 A 与矩阵算子 B 的 相对熵
线性代数·矩阵·量子计算
AI科技星7 小时前
基于空间光速螺旋归一化的动力学方程推导与数值验证
人工智能·线性代数·算法·机器学习·平面
罗罗攀8 小时前
PyTorch学习笔记|张量的线性代数运算
人工智能·pytorch·笔记·学习·线性代数
无水先生1 天前
理解线性代数的对偶性质
线性代数
历程里程碑2 天前
链表-----
数据结构·线性代数·算法·链表·矩阵·lua·perl
优思学苑2 天前
优思学院:QC新七大手法之「矩阵图法」是?
线性代数·矩阵
phoenix@Capricornus2 天前
样本矩阵、增广样本矩阵与规范化增广样本矩阵
线性代数·矩阵
栗少2 天前
空间计算时代能力矩阵
线性代数·矩阵·空间计算
别或许2 天前
4线性代数之线性方程组(知识总结)
线性代数