读取文件求多项式偏导数+绘图+Fortran格式处理

发布于 3 天前  11 次阅读


Please refresh the page if equations are not rendered correctly.
---------------------------------------------------------------

读取含有多项式的文件求取多项式的偏导数程序

import sympy as sp

# 定义符号变量
x, y = sp.symbols('x y')

# 读取文件内容
file_path = r'D:\pythonProject\Kringing\krig_export\expr_iso.txt'
with open(file_path, 'r',encoding='UTF-8') as file:
    polynomial_str = file.read()

# 将字符串转换为 sympy 表达式
polynomial_expr = sp.sympify(polynomial_str)

# 对多项式进行对 x 求导
derivative_expr = sp.diff(polynomial_expr, x)
# 对多项式进行对y 求导
derivative_expr_y = sp.diff(polynomial_expr,y)

# 输出原多项式和求导后的结果
print(f"原多项式: {polynomial_expr}")
print(f"对 x 求导后的结果: {derivative_expr}")
print(f"对y求导后的结果:{derivative_expr_y}")

# 将求导后的多项式写入新文件
output_file_path = r'D:\pythonProject\Kringing\krig_export\derivative_expr_x.txt'
with open(output_file_path, 'w',encoding='UTF-8') as file:
    file.write(f"{derivative_expr}")

output_file_path = r'D:\pythonProject\Kringing\krig_export\derivative_expr_y.txt'
with open(output_file_path,'w',encoding='UTF-8') as file:
    file.write(f"{derivative_expr_y}")


读取偏导数的文件并绘制三维图像

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from krigingFuncs import expr_io
import sympy as sym

# 读取文件
polynomials = expr_io("D:\pythonProject\Kringing\expr_iso_dadt-Ver1.txt")

# 定义符号变量
x, y = sym.symbols('x y')


def parse_polynomial(polynomial_str):
    try:
        # 将字符串解析为sympy表达式
        polynomial_expr = sym.sympify(polynomial_str)
        return polynomial_expr
    except Exception as e:
        raise ValueError(f"Error parsing polynomial: {e}")


def evaluate_polynomial(polynomial_expr):
    try:
        # 使用lambdify将SymPy表达式转换为NumPy函数
        func = sym.lambdify((x, y), polynomial_expr, 'numpy')
        return func
    except Exception as e:
        raise ValueError(f"Error evaluating polynomial: {e}")


def process_and_plot(csv_file, polynomial_expr, output_csv):
    # 定义x和y的范围
    # 从CSV文件读取数据并指定列名,只读取列数可自己选
    # df = pd.read_csv(csv_file, header=None, usecols=[0], names=['x'])
    # x = df['x'].values / 360
    #y = (df['y'].values - 55) / 15
    # xx = np.linspace(0, 21600, 100)
    # yy = np.linspace(328.15, 343.15, 100)
    x_vals = np.linspace(0, 1, 100)
    y_vals = np.linspace(0, 1, 100)
    X, Y = np.meshgrid(x_vals, y_vals)

    # 使用lambdify后的函数计算z值
    func = evaluate_polynomial(polynomial_expr)
    Z = func(X, Y)

    # 创建新的DataFrame存储结果
    result_df = pd.DataFrame({'x': X.flatten(), 'y': Y.flatten(), 'z': Z.flatten()})

    # 保存结果到CSV文件
    result_df.to_csv(output_csv, index=False)

    # 绘制三维图像
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(X, Y, Z, cmap='viridis')

    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    ax.set_title('Polynomial Evaluation')

    plt.show()


# 示例使用
input_file = 'D:\\pythonProject\\Kringing\\krig_export\\expr_iso_dadt.txt'
output_csv = 'D:\\pythonProject\\Kringing\\krig_export\\results.csv'
polynomial_str = expr_io(input_file)
polynomial_expr = parse_polynomial(polynomial_str)
print(f"Polynomial: {polynomial_expr}")

# 处理数据并绘制图像
process_and_plot(input_file,polynomial_expr, output_csv)

快捷化将多项式输出为可以复制到Fortran中

def reformat_txt_file(input_file, output_file):
    # 读取原始文件内容,指定编码为 UTF-8
    with open(input_file, 'r', encoding='utf-8') as file:
        data = file.read().strip()

    # 在数据的开头添加 "Dalpha_Dt=",可改
    data = "Dalpha_Dt=" + data

    # 将数据按每行的列数分块,每行不超过100个字符
    columns_per_line = 100
    chunks = [data[i:i + columns_per_line] for i in range(0, len(data), columns_per_line)]

    # 格式化每一行,确保从第七列开始,并添加延续符号
    formatted_lines = []
    for i, chunk in enumerate(chunks):
        if i == 0:
            # 第一行直接添加,不需要延续符号
            formatted_lines.append(f"{chunk}")
        else:
            # 从第二行开始,每行从第七列开始,在第六列添加延续符号
            formatted_lines.append(f"     &{chunk} ")

    # 将格式化后的内容写入新文件,指定编码为 UTF-8
    with open(output_file, 'w', encoding='utf-8') as file:
        for line in formatted_lines:
            file.write(line.rstrip() + '\n')  # 移除行末的多余空格

# 示例使用
input_file = r'D:\pythonProject\Kringing\krig_export\derivative_expr_y.txt'
output_file = 'output-da-dt_y.txt'
reformat_txt_file(input_file, output_file)

Everything not saved will be lost.
最后更新于 2024-07-11