我正在编辑【python】代码,遇到了 【画图结果出错】
,请帮我检查并改正错误点。我的原始代码如下:
【import numpy as np
from scipy.optimize import newton
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
# ==========================
# CO₂物性参数设置
# ==========================
Tc = 304.13 # 临界温度 (K)
Pc = 7.38e6 # 临界压力 (Pa)
omega = 0.225 # 偏心因子
R = 8.314 # 气体常数 (J/(mol·K))
M = 44.01e-3 # 摩尔质量 (kg/mol)
# ==========================
# PR状态方程相关函数
# ==========================
def pr_parameters(T):
"""计算PR方程参数a和b"""
k = 0.37464 + 1.54226 * omega - 0.26992 * omega ** 2
alpha = (1 + k * (1 - np.sqrt(T / Tc))) ** 2
a = 0.45724 * (R ** 2 * Tc ** 2) / Pc * alpha
b = 0.07780 * R * Tc / Pc
return a, b
def pr_equation(Z, T, P):
"""定义PR方程的三次方形式"""
a, b = pr_parameters(T)
A = a * P / (R ** 2 * T ** 2)
B = b * P / (R * T)
return Z ** 3 - (1 - B) * Z ** 2 + (A - 3 * B ** 2 - 2 * B) * Z - (A * B - B ** 2 - B ** 3)
def calculate_density(T, P):
"""计算CO₂密度 (kg/m³)"""
try:
# 牛顿迭代法求解压缩因子
Z_initial_guess = 0.6 # 超临界流体典型初始值
Z = newton(pr_equation, Z_initial_guess, args=(T, P))
molar_volume = Z * R * T / P # 摩尔体积 (m³/mol)
return M / molar_volume
except:
return np.nan # 处理不收敛情况
# ==========================
# 敏感性分析参数设置
# ==========================
# 温度范围 (转换为开尔文)
T_min = 31 + 273.15 # 304.15 K
T_max = 100 + 273.15 # 373.15 K
P_min = 7e6 # 7 MPa (转换为Pa)
P_max = 30e6 # 30 MPa
# 网格参数
n_points = 50 # 网格密度
delta = 0.1 # 差分步长 (K/MPa)
# 生成计算网格
T_values = np.linspace(T_min, T_max, n_points)
P_values = np.linspace(P_min, P_max, n_points)
TT, PP = np.meshgrid(T_values, P_values)
# ==========================
# 主计算循环
# ==========================
d_rho_dT = np.zeros_like(TT)
d_rho_dP = np.zeros_like(TT)
rho_grid = np.zeros_like(TT)
print("开始计算密度场...")
for i in range(n_points):
for j in range(n_points):
T = TT[i, j]
P = PP[i, j]
# 计算基础密度
rho = calculate_density(T, P)
rho_grid[i, j] = rho
# 温度敏感性 (中心差分)
if T + delta <= T_max and T - delta >= T_min:
rho_Tp = calculate_density(T + delta, P)
rho_Tm = calculate_density(T - delta, P)
d_rho_dT[i, j] = (rho_Tp - rho_Tm) / (2 * delta)
# 压力敏感性 (中心差分)
if P + delta * 1e6 <= P_max and P - delta * 1e6 >= P_min:
rho_Pp = calculate_density(T, P + delta * 1e6)
rho_Pm = calculate_density(T, P - delta * 1e6)
d_rho_dP[i, j] = (rho_Pp - rho_Pm) / (2 * delta * 1e6)
print("计算完成,开始绘图...")
# ==========================
# 可视化设置
# ==========================
plt.rcParams.update({'font.size': 12, 'font.family': 'Arial'})
extent = [T_min - 273.15, T_max - 273.15, P_min / 1e6, P_max / 1e6]
# 温度敏感性热图
plt.figure(figsize=(12, 5))
plt.subplot(121)
cf = plt.contourf(TT - 273.15, PP / 1e6, np.abs(d_rho_dT), levels=50, cmap='viridis')
plt.colorbar(cf, label='|∂ρ/∂T| (kg/m³/K)')
plt.contour(TT - 273.15, PP / 1e6, np.abs(d_rho_dT), colors='k', linewidths=0.5, levels=10)
plt.scatter(Tc - 273.15, Pc / 1e6, c='red', marker='*', s=100, label='Critical Point')
plt.xlabel('Temperature (°C)')
plt.ylabel('Pressure (MPa)')
plt.title('Temperature Sensitivity')
plt.grid(alpha=0.3)
plt.legend()
# 压力敏感性热图
plt.subplot(122)
cf = plt.contourf(TT - 273.15, PP / 1e6, np.abs(d_rho_dP), levels=50, cmap='plasma')
plt.colorbar(cf, label='|∂ρ/∂P| (kg/m³/MPa)')
plt.contour(TT - 273.15, PP / 1e6, np.abs(d_rho_dP), colors='k', linewidths=0.5, levels=10)
plt.scatter(Tc - 273.15, Pc / 1e6, c='red', marker='*', s=100, label='Critical Point')
plt.xlabel('Temperature (°C)')
plt.ylabel('Pressure (MPa)')
plt.title('Pressure Sensitivity')
plt.grid(alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
# ==========================
# 高敏感区域识别
# ==========================
# 识别敏感性高于平均值的区域
threshold_T = 0.8 * np.nanmax(np.abs(d_rho_dT))
threshold_P = 0.8 * np.nanmax(np.abs(d_rho_dP))
high_sens_T = np.where(np.abs(d_rho_dT) > threshold_T)
high_sens_P = np.where(np.abs(d_rho_dP) > threshold_P)
print("\n高温度敏感性区域特征:")
print(f"- 温度范围: {np.min(TT[high_sens_T] - 273.15):.1f} ~ {np.max(TT[high_sens_T] - 273.15):.1f} °C")
print(f"- 压力范围: {np.min(PP[high_sens_T] / 1e6):.1f} ~ {np.max(PP[high_sens_T] / 1e6):.1f} MPa")
print("\n高压力敏感性区域特征:")
print(f"- 温度范围: {np.min(TT[high_sens_P]-273.15):.1f} ~ {np.max(TT[high_sens_P] - 273.15):.1f} °C")
print(f"- 压力范围: {np.min(PP[high_sens_P] / 1e6):.1f} ~ {np.max(PP[high_sens_P] / 1e6):.1f} MPa")
# ==========================
# 新增:折线图绘制函数
# ==========================
def plot_sensitivity_profiles():
# 设置固定参数
fixed_pressures = [7.38, 10, 15, 20] # MPa (临界压力和其他典型值)
fixed_temperatures = [35, 50, 60] # °C
# 创建画布
plt.figure(figsize=(15, 10))
# ===================================================================
# 子图1:固定压力时温度敏感性随温度变化
# ===================================================================
plt.subplot(2, 2, 1)
for P_fixed in fixed_pressures:
# 找到最接近的压力索引
P_idx = np.argmin(np.abs(P_values / 1e6 - P_fixed))
# 提取对应压力下的数据
T_profile = TT[:, P_idx] - 273.15 # 转换为°C
sens_profile = np.abs(d_rho_dT[:, P_idx])
# 过滤无效值
valid = ~np.isnan(sens_profile)
plt.plot(T_profile[valid], sens_profile[valid],
lw=2, marker='o', markersize=5,
label=f'P={P_fixed} MPa')
plt.xlabel('Temperature (°C)')
plt.ylabel('|∂ρ/∂T| (kg/m³/K)')
plt.title('Temperature Sensitivity at Fixed Pressures')
plt.grid(alpha=0.3)
plt.legend()
# ===================================================================
# 子图2:固定温度时压力敏感性随压力变化
# ===================================================================
plt.subplot(2, 2, 2)
for T_fixed in fixed_temperatures:
# 找到最接近的温度索引
T_idx = np.argmin(np.abs(T_values - (T_fixed + 273.15)))
# 提取对应温度下的数据
P_profile = PP[T_idx, :] / 1e6 # 转换为MPa
sens_profile = np.abs(d_rho_dP[T_idx, :])
# 过滤无效值
valid = ~np.isnan(sens_profile)
plt.plot(P_profile[valid], sens_profile[valid],
lw=2, marker='s', markersize=5,
label=f'T={T_fixed}°C')
plt.xlabel('Pressure (MPa)')
plt.ylabel('|∂ρ/∂P| (kg/m³/MPa)')
plt.title('Pressure Sensitivity at Fixed Temperatures')
plt.grid(alpha=0.3)
plt.legend()
# ===================================================================
# 子图3:固定压力时压力敏感性随温度变化(交叉分析)
# ===================================================================
plt.subplot(2, 2, 3)
for P_fixed in fixed_pressures:
P_idx = np.argmin(np.abs(P_values / 1e6 - P_fixed))
T_profile = TT[:, P_idx] - 273.15
sens_profile = np.abs(d_rho_dP[:, P_idx])
valid = ~np.isnan(sens_profile)
plt.semilogy(T_profile[valid], sens_profile[valid], # 对数坐标
lw=2, linestyle='--',
label=f'P={P_fixed} MPa')
plt.xlabel('Temperature (°C)')
plt.ylabel('|∂ρ/∂P| (kg/m³/MPa)')
plt.title('Pressure Sensitivity vs Temperature (log scale)')
plt.grid(alpha=0.3, which='both')
plt.legend()
# ===================================================================
# 子图4:固定温度时温度敏感性随压力变化(交叉分析)
# ===================================================================
plt.subplot(2, 2, 4)
for T_fixed in fixed_temperatures:
T_idx = np.argmin(np.abs(T_values - (T_fixed + 273.15)))
P_profile = PP[T_idx, :] / 1e6
sens_profile = np.abs(d_rho_dT[T_idx, :])
valid = ~np.isnan(sens_profile)
plt.semilogy(P_profile[valid], sens_profile[valid],
lw=2, linestyle='-.',
label=f'T={T_fixed}°C')
plt.xlabel('Pressure (MPa)')
plt.ylabel('|∂ρ/∂T| (kg/m³/K)')
plt.title('Temperature Sensitivity vs Pressure (log scale)')
plt.grid(alpha=0.3, which='both')
plt.legend()
plt.tight_layout()
plt.show()
# ==========================
# 执行绘图
# ==========================
print("\n生成折线图...")
plot_sensitivity_profiles()】
最新发布