Код: Выделить всё
import numpy as np
from scipy.interpolate import RectBivariateSpline
import CoolProp.CoolProp as CP
import mygrad as mg
from mygrad import tensor
# Define the refrigerant
refrigerant = 'R134a'
# Constant temperature (e.g., 20°C)
T = 20 + 273.15 # Convert to Kelvin
# Get saturation pressures
P_sat = CP.PropsSI('P', 'T', T, 'Q', 0, refrigerant)
# Define a pressure range around the saturation pressure
P_min = P_sat * 0.5
P_max = P_sat * 1.5
P_values = np.linspace(P_min, P_max, 100)
# Define a temperature range around the constant temperature
T_min = T - 10
T_max = T + 10
T_values = np.linspace(T_min, T_max, 100)
# Generate enthalpy data
h_values = []
for P in P_values:
h_row = []
for T in T_values:
try:
h = CP.PropsSI('H', 'P', P, 'T', T, refrigerant)
h_row.append(h)
except:
h_row.append(np.nan)
h_values.append(h_row)
# Convert lists to arrays
h_values = np.array(h_values)
# Fit spline for enthalpy
h_spline = RectBivariateSpline(P_values, T_values, h_values)
# Function to interpolate enthalpy
def h_interp(P, T):
return tensor(h_spline.ev(P, T))
# Example function using the interpolated enthalpy with AD
def example_function(P):
h = h_interp(P, T)
result = h**2 # Example calculation
return result
# Define a pressure value for testing
P_test = tensor(P_sat, )
# Compute the example function and its gradient
result = example_function(P_test)
result.backward()
# Print the result and the gradient
print(f"Result: {result.item()}")
print(f"Gradient: {P_test.grad}")
Подробнее здесь: https://stackoverflow.com/questions/790 ... ariatespli