Lesson
21: SciPy Table Interpolation & Nonlinear Model Fitting
(CubicSpline & curve_fit)
The “Boring Stuff” Problem: Manual Linear Steam-Table Interpolation & Linearizing Log Plots
Every engineering student remembers the pain of doing 2-step linear
interpolation on saturated steam tables at \(T
= 137.4^\circ\text{C}\) when the appendix only prints \(135^\circ\text{C}\) and \(140^\circ\text{C}\). Worse, when reducing
Heat Transfer convection data (Pin Fin Heat Sink), standard
spreadsheets force you to take ugly logarithms of both axes just to run
a linear trendline.
scipy.interpolate +
scipy.optimize.curve_fit do both cleanly:
CubicSpline(x_tab, y_tab): Fits smooth piecewise cubic polynomials cleanly through exact table nodes—giving instant continuous lookup functionshf_func(137.4)across all thermodynamic tables (ME 200/ME 300).curve_fit(model_fn, x_data, y_data): Uses nonlinear least squares directly on raw un-transformed units (Nu = C * Re**m) and returns BOTH optimal fitted parameterspoptAND their statistical \(1\sigma\) confidence uncertainties (np.sqrt(np.diag(pcov)))!
Watch
Out! Extrapolation vs. Interpolation + Good Curve-Fit Guesses
(p0)
- Never Extrapolate Wildly Outside Your Table Domain:
CubicSplinebehaves like a rocket ship outside[x_min, x_max]because cubics blow up at edges. Restrict lookups inside[x_tab[0], x_tab[-1]]! - Always Provide Initial Parameter Guesses
p0=[...]for Nonlinear Exponentials: If a cooling model hasA + B * np.exp(-t / tau), defaultingtau = 1when truetau = 200stalls convergence—supply realistic physical guesses!
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
from scipy.interpolate import CubicSpline
from scipy.optimize import curve_fit
# Example 1 (ME 200 Automated Saturated Steam Table Evaluator): CubicSpline Lookup Tool
sat_p = next(p for p in [Path("datasets/ME200_Saturated_Water_Temp_Table.csv"), Path("../datasets/ME200_Saturated_Water_Temp_Table.csv")] if p.exists())
sat_df = pd.read_csv(sat_p)
sat_df.columns = [" ".join(c.strip().split()) for c in sat_df.columns]
T_tab = sat_df["Temp. (C)"].values
P_spline = CubicSpline(T_tab, sat_df["Press. (bar)"].values)
hf_spline = CubicSpline(T_tab, sat_df["Enthalpy (hf, kJ/kg)"].values)
hg_spline = CubicSpline(T_tab, sat_df["Enthalpy (hg, kJ/kg)"].values)
sg_spline = CubicSpline(T_tab, sat_df["Entropy (sg, kJ/kg/K)"].values)
# Query any fractional temperature instantaneously!
for T_q in [87.5, 137.4, 265.2]:
print(f"T = {T_q:5.1f} C -> P_sat = {float(P_spline(T_q)):7.4f} bar | hf = {float(hf_spline(T_q)):6.2f} | hg = {float(hg_spline(T_q)):6.1f} kJ/kg")T = 87.5 C -> P_sat = 0.6378 bar | hf = 366.52 | hg = 2655.4 kJ/kg
T = 137.4 C -> P_sat = 3.3572 bar | hf = 578.02 | hg = 2730.0 kJ/kg
T = 265.2 C -> P_sat = 51.0154 bar | hf = 1161.01 | hg = 2793.4 kJ/kg
# Example 2 (Heat & Mass Transfer Module 4): Fitting Empirical Nusselt Power Law directly to Pin-Fin Data!
fin_p = next(p for p in [Path("datasets/HMT_Pin_Fin_Heat_Sink_Data.csv"), Path("../datasets/HMT_Pin_Fin_Heat_Sink_Data.csv")] if p.exists())
fin_df = pd.read_csv(fin_p)
Re_exp = fin_df["Reynolds_Number_ReD"].values
Nu_exp = fin_df["Nusselt_Number_NuD"].values
def nusselt_power_law(Re, C, m):
return C * (Re ** m)
popt, pcov = curve_fit(nusselt_power_law, Re_exp, Nu_exp, p0=[0.6, 0.5])
C_fit, m_fit = popt
C_std, m_std = np.sqrt(np.diag(pcov))
Nu_pred = nusselt_power_law(Re_exp, C_fit, m_fit)
r2 = 1.0 - np.sum((Nu_exp - Nu_pred)**2) / np.sum((Nu_exp - np.mean(Nu_exp))**2)
print(f"\n=== Nonlinear Nusselt Power Law Fit: Nu = C * Re^m ===")
print(f"Fitted C = {C_fit:.5f} +/- {C_std:.5f} | Exponent m = {m_fit:.4f} +/- {m_std:.4f} | R^2 = {r2:.6f}")
fig, ax = plt.subplots(figsize=(6.8, 4.1))
Re_grid = np.linspace(Re_exp.min(), Re_exp.max(), 200)
ax.scatter(Re_exp, Nu_exp, color="#dc2626", s=55, zorder=5, label="Wind-Tunnel Pin-Fin Data")
ax.plot(Re_grid, nusselt_power_law(Re_grid, C_fit, m_fit), "-", color="#0284c7", lw=2.2,
label=f"SciPy Fit: $Nu = {C_fit:.3f}\\,Re^{{{m_fit:.3f}}}$ ($R^2={r2:.5f}$)")
ax.set_title("Empirical Pin-Fin Heat Transfer Correlation via `curve_fit`")
ax.set_xlabel("Reynolds Number $Re_D$"); ax.set_ylabel("Nusselt Number $Nu_D$")
ax.grid(True, alpha=0.3); ax.legend(); fig.tight_layout()
=== Nonlinear Nusselt Power Law Fit: Nu = C * Re^m ===
Fitted C = 0.47530 +/- 0.00628 | Exponent m = 0.5094 +/- 0.0018 | R^2 = 0.999922
Practice Questions (Concept Check)
- Why does
CubicSplineavoid sharp corner kinks when computing slopes (\(dP_{\text{sat}}/dT\) for Clausius–Clapeyron latent heat) compared to linearnp.interp? - How do you extract the \(1\sigma\)
standard error bars of fitted parameters from
popt, pcov = curve_fit(...)? - What is \(R^2\)
(
coefficient of determination), and what value indicates a near-exact physical model fit? - Why is fitting
Nu = C * Re^mdirectly with nonlinearcurve_fitoften statistically cleaner than fittingln(Nu) = ln(C) + m*ln(Re)by linear least squares?
Guided
Practice Problem 1 (Worked Self-Check): Clausius–Clapeyron Fit to Water
Vapor Pressure (Fluid Mechanics)
Load Temp_K and Water_Vapor_Pressure_kPa
from datasets/Fluids_Property_and_Viscosity_Table.csv, fit
the Antoine / exponential vapor pressure model \(P_v(T) = A \exp(-B / T)\) with
curve_fit(p0=[1e8, 5000.0]), print the implied enthalpy of
vaporization \(h_{fg} \approx B \cdot
R_{\text{water}}\) (\(R_{\text{water}}
= 0.4615\text{ kJ/(kg}\cdot\text{K)}\)), and check against true
water \(h_{fg} \approx 2400\text{
kJ/kg}\)!
Hint: Use T in Kelvin (already provided in col Temp_K!)
In Clausius–Clapeyron, \(\ln P_v = \text{const} - \frac{h_{fg}}{R_v T}\), so parameter \(B = h_{fg}/R_v\)!
# Worked Practice Problem 1 Solution: Vapor Pressure Fit & Latent Heat Recovery
fp = next(p for p in [Path("datasets/Fluids_Property_and_Viscosity_Table.csv"), Path("../datasets/Fluids_Property_and_Viscosity_Table.csv")] if p.exists())
fdf = pd.read_csv(fp)
T_k = fdf["Temp_K"].values
Pv_kpa = fdf["Water_Vapor_Pressure_kPa"].values
popt_vp, _ = curve_fit(lambda T, A, B: A * np.exp(-B / T), T_k, Pv_kpa, p0=[1e8, 5200.0], maxfev=5000)
R_vapor = 0.46152 # kJ/(kg*K)
h_fg_est = popt_vp[1] * R_vapor
print(f"Clausius-Clapeyron Fit: B = {popt_vp[1]:.1f} K -> Implied water h_fg = {h_fg_est:.1f} kJ/kg (mean 0-100 C table ~ 2380 kJ/kg)")Clausius-Clapeyron Fit: B = 5049.8 K -> Implied water h_fg = 2330.6 kJ/kg (mean 0-100 C table ~ 2380 kJ/kg)
End-of-Chapter Practice Problems (Try Yourself!)
- Inverted Steam Property Lookup
(
ME 200): BuildT_from_P_sat(P_bar)usingCubicSplineonP_bar->T_satfromME200_Saturated_Water_Temp_Table.csvand find water’s boiling point at Denver pressure0.835 barand boiler pressure45.0 bar! - Andrade Fluid Viscosity Fit
(
Fluid Mechanics): Fit \(\mu(T) = A \exp(B / T_K)\) toWater_Dynamic_Viscosity_Pa_sfromFluids_Property_and_Viscosity_Table.csvand evaluate RMSE in \(\text{mPa}\cdot\text{s}\). - Exponential Lumped Quench Constant Extraction
(
Heat Transfer): Fit \(T(t) = T_\infty + (T_0 - T_\infty)e^{-t/\tau}\) toT_Surface_xL_degCinHMT_Steel_Quenching_Transient_Data.csvto measure thermal time constant \(\tau\)!