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

相关推荐
AI科技星12 小时前
基于四维速率恒为c公设的北斗GEO卫星昼夜钟差模型修正与实测验证
开发语言·人工智能·线性代数·算法·数学建模
Jasmine_llq2 天前
《B3865 [GESP202309 二级] 小杨的 X 字矩阵》
线性代数·矩阵·条件判断算法·枚举算法(遍历算法)·规律模拟算法
阿Y加油吧2 天前
二分查找进阶:搜索二维矩阵 & 查找元素首尾位置 深度解析
线性代数·算法·矩阵
MediaTea2 天前
AI 术语通俗词典:矩阵乘法
人工智能·线性代数·矩阵
AI科技星3 天前
基于三维空间合速度恒为光速公理的统一动力学与热力学理论:温度本质的第一性原理诠释与物质全物态实验验证
开发语言·线性代数·机器学习·计算机视觉·数学建模
笨笨饿4 天前
30_泰勒级数
c语言·stm32·嵌入式硬件·线性代数·机器学习·自动化·概率论
计算机安禾4 天前
【数据结构与算法】第28篇:平衡二叉树(AVL树)
开发语言·数据结构·数据库·线性代数·算法·矩阵·visual studio
郝学胜-神的一滴5 天前
[简化版 GAMES 101] 计算机图形学 03:线性代数下
开发语言·c++·线性代数·图形渲染
AI科技星6 天前
全球AI信息场(信息网)基础理论与数学建模研究(乖乖数学)
开发语言·人工智能·线性代数·算法·机器学习·数学建模
⊱⋛赫宇⋚⊰6 天前
转专业数学
线性代数·机器学习·概率论