Lesson
27: Curve Fitting (curve_fit) & Interpolation —
Adsorption Isotherms & Solar Models
The
“Boring Stuff” Problem: Manually Straightening Curved Lab Plots With
1/q vs 1/C
For decades, textbooks taught students to linearize Langmuir adsorption (\(\frac{1}{q_e}\) vs \(\frac{1}{C_e}\)): Lineweaver-Burk double-reciprocal linearization severely distorts experimental lab error at small concentrations!
Modern computational engineers fit the true nonlinear model
directly using
scipy.optimize.curve_fit(model_fn, xdata, ydata, p0=...):
- Langmuir Isotherm (GAC Micropollutant Removal): \(q_e = \frac{q_{\max} K_L C_e}{1 + K_L C_e}\)
- Freundlich Isotherm: \(q_e = K_F C_e^{1/n}\)
- Plus
np.interp/CubicSplinefor interpolating thermophysical tables (Fluids_Water_Properties_Table.csv) at exact field temperatures!
from pathlib import Path
def data_file(name):
"""Locate a dataset file whether running from SRC_DIR, module folder, HOMEWORK, or EXAMS."""
for p in [
Path("datasets") / name,
Path("../datasets") / name,
Path("../../datasets") / name,
]:
if p.exists():
return p
raise FileNotFoundError(f"Missing dataset {name} in datasets/")
import numpy as np
from scipy.optimize import curve_fit
from scipy.interpolate import CubicSpline
import matplotlib.pyplot as plt
# Example 1: Nonlinear GAC Activated Carbon PFAS/Atrazine Adsorption Isotherm Comparison
Ce_obs = np.array([1.2, 3.5, 8.0, 16.0, 32.0, 60.0, 100.0]) # Equilibrium liquid Conc [ug/L]
qe_obs = np.array([4.1, 9.8, 17.2, 24.5, 31.8, 36.2, 38.9]) # Adsorbed on GAC [mg/g]
def langmuir(C, qmax, KL):
return (qmax * KL * C) / (1.0 + KL * C)
def freundlich(C, KF, inv_n):
return KF * (C ** inv_n)
popt_L, _ = curve_fit(langmuir, Ce_obs, qe_obs, p0=[45.0, 0.08], bounds=(0, np.inf))
popt_F, _ = curve_fit(freundlich, Ce_obs, qe_obs, p0=[4.0, 0.5], bounds=(0, np.inf))
r2 = lambda y, yhat: 1.0 - np.sum((y - yhat)**2) / np.sum((y - y.mean())**2)
r2_L = r2(qe_obs, langmuir(Ce_obs, *popt_L))
r2_F = r2(qe_obs, freundlich(Ce_obs, *popt_F))
C_fine = np.linspace(0.5, 105.0, 200)
fig, ax = plt.subplots(figsize=(7.5, 4.0))
ax.plot(Ce_obs, qe_obs, "ko", markersize=7, label="Bench Jar-Test Measurements")
ax.plot(C_fine, langmuir(C_fine, *popt_L), color="#0284c7", lw=2.3, label=f"Langmuir (qmax={popt_L[0]:.1f} mg/g, R^2={r2_L:.4f})")
ax.plot(C_fine, freundlich(C_fine, *popt_F), color="#d97706", ls="--", lw=2.0, label=f"Freundlich (KF={popt_F[0]:.2f}, R^2={r2_F:.4f})")
ax.set_title("Nonlinear Activated Carbon Isotherm Fitting via scipy.optimize.curve_fit")
ax.set_xlabel("Equilibrium Liquid Concentration C_e [ug/L]"); ax.set_ylabel("Adsorbed Capacity q_e [mg/g]")
ax.grid(True, alpha=0.3); ax.legend(fontsize=8.5); fig.tight_layout()
print(f"Langmuir Fit : qmax = {popt_L[0]:.2f} mg/g, KL = {popt_L[1]:.4f} L/ug (R^2 = {r2_L:.4f})")
print(f"Freundlich Fit: KF = {popt_F[0]:.2f}, 1/n = {popt_F[1]:.3f} (R^2 = {r2_F:.4f})")
Langmuir Fit : qmax = 43.66 mg/g, KL = 0.0817 L/ug (R^2 = 0.9999)
Freundlich Fit: KF = 7.88, 1/n = 0.365 (R^2 = 0.9424)
# Example 2 (Fluid Mechanics Course Table Interpolation): CubicSpline Water Viscosity mu(T)
wt_tbl = np.loadtxt(data_file("Fluids_Water_Properties_Table.csv"), delimiter=",", skiprows=1)
T_pts, mu_pts, pv_pts = wt_tbl[:, 0], wt_tbl[:, 3], wt_tbl[:, 6]
cs_mu = CubicSpline(T_pts, mu_pts)
cs_pv = CubicSpline(T_pts, pv_pts)
for tc in [12.5, 17.8, 26.4]:
print(f"Water @ T={tc:4.1f} C -> Spline Viscosity = {cs_mu(tc):.4e} Pa*s | Vapor Press = {cs_pv(tc):.3f} kPa")Water @ T=12.5 C -> Spline Viscosity = 1.2173e-03 Pa*s | Vapor Press = 1.449 kPa
Water @ T=17.8 C -> Spline Viscosity = 1.0581e-03 Pa*s | Vapor Press = 2.038 kPa
Water @ T=26.4 C -> Spline Viscosity = 8.6309e-04 Pa*s | Vapor Press = 3.443 kPa
Concept Check Questions
- Why is nonlinear
curve_fitstrictly more accurate statistically than plotting1/qevs1/Ceand running linear regression? - What does
bounds=(0, np.inf)enforce insidecurve_fit? - When should you use
CubicSplinevs. straight linearnp.interpon smooth fluid-property tables?
Guided Practice Problem 1: Fit Monod Half-Velocity Curve to Wastewater Respirometry Lab Data
Substrate concentration
S = [5, 12, 25, 60, 120, 250] mg/L yields specific growth
rates mu = [0.42, 0.88, 1.45, 2.38, 2.95, 3.42] 1/day. Fit
the nonlinear Monod equation \(\mu(S) = \frac{\mu_{\max} S}{K_s + S}\)
using curve_fit, reporting \(\mu_{\max}\), \(K_s\), and \(R^2\)!
# Guided Practice 1 Starter
S_d = np.array([5., 12., 25., 60., 120., 250.])
mu_d = np.array([0.42, 0.88, 1.45, 2.38, 2.95, 3.42])
popt_m, _ = curve_fit(lambda S, mumax, Ks: mumax * S / (Ks + S), S_d, mu_d, p0=[4.0, 35.0], bounds=(0, np.inf))
r2_m = 1.0 - np.sum((mu_d - popt_m[0]*S_d/(popt_m[1]+S_d))**2) / np.sum((mu_d - mu_d.mean())**2)
print(f"Monod Fit: mu_max = {popt_m[0]:.3f} 1/d | Ks = {popt_m[1]:.2f} mg/L | R^2 = {r2_m:.4f}")Monod Fit: mu_max = 4.012 1/d | Ks = 42.77 mg/L | R^2 = 0.9997