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

相关推荐
涉密IT资质笔记9 小时前
2026 涉密资质三类硬性条件对照:军工 / 集成 / 印制参数矩阵与易错点
服务器·线性代数·矩阵·创业创新
BSD_HY10 小时前
薄膜开关矩阵按键的GPIO扩展芯片选型与中断响应延迟
单片机·线性代数·矩阵
数智工坊10 小时前
视觉SLAM第11讲|回环检测:词袋模型、字典构建与相似度计算全解析
人工智能·深度学习·线性代数
数智工坊11 小时前
视觉SLAM第4讲|李群与李代数:位姿优化的数学基石
人工智能·深度学习·线性代数·cnn
数智工坊12 小时前
视觉SLAM第10讲|后端优化(下):位姿图优化、滑动窗口与图优化工程实践
人工智能·深度学习·线性代数·矩阵
数智工坊12 小时前
视觉SLAM第13讲|工程落地:双目视觉里程计系统架构设计与性能优化
人工智能·深度学习·线性代数·性能优化·矩阵·系统架构·机器人
李日华大战鸡红1 天前
FOC状态空间方程模型推导(学习记录)
python·学习·线性代数
for_ever_love__3 天前
线性代数入门——向量、矩阵与点积,Transformer 的运算本质
线性代数·矩阵·transformer
打工仔折腾 AI3 天前
从零写一个CAD 05:以鼠标为中心的滚轮缩放矩阵顺序不能反
后端·python·线性代数·性能优化·矩阵·计算机外设·ai agent 实战
hai3152475435 天前
文本矩阵化拆解与视频矩阵化构建
线性代数·矩阵·音视频