💻 Module: 08-SciPy-Engineering • Unabridged Executed Lesson
📑 Download Module Slides (PDF) 🐍 Download Notebook (.ipynb)

Lesson 20: SciPy Quadrature (quad) & Dynamic Engineering ODEs (solve_ivp)

The “Boring Stuff” Problem: Manual Time Stepping (\(dt\)) Bugs & Higher-Order Differential Equations

In textbooks, you spend weeks memorizing integrating factors and variation of parameters—only for real mechanical systems to add nonlinear radiation cooling (\(T^4\)), aerodynamic quadratic drag (\(V^2\)), or nonlinear shock absorber damping that NO pencil-and-paper formula can solve!

scipy.integrate handles both:

  1. quad(fn, a, b): Adaptive Gauss–Kronrod quadrature computing definite integrals like variable-specific-heat enthalpy \(\Delta h = \int_{T_1}^{T_2} c_p(T)\,dT\) (ME 200) to 1e-10 accuracy in one line.
  2. solve_ivp(rhs, (t0, tf), y0, dense_output=True): Adaptive Runge–Kutta (RK45 or stiff Radau/BDF) that automatically shrinks step sizes during violent transients and enlarges them during slow decay!

Turning ANY 2nd-Order Mechanical ODE Into solve_ivp State Space

Suppose you have Newton’s Second Law for a damped mass-spring suspension (Dynamics & Vibrations): \[m \ddot{x} + c \dot{x} + k x = F_0 \cos(\omega t)\] solve_ivp expects a 1st-order vector system \(\frac{d\mathbf{y}}{dt} = \mathbf{f}(t, \mathbf{y})\). Just define two states: y = [position_x, velocity_v]! Then:

Watch Out! solve_ivp Signature Traps!

  1. Function order MUST be rhs(t, y) (time t FIRST, state y SECOND—backwards from older odeint!).
  2. Even for a 1-equation thermal ODE (dT/dt = ...), initial condition MUST be a list y0 = [T0], and solution sol.y[0] is a 1D row!
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad, solve_ivp

# Example 1 (ME 200 Thermodynamics + HMT Quenching): Variable-cp Quadrature & Radiative Quench ODE
# Air NASA-style polynomial cp(T) [kJ/(kg*K)] integrated cleanly from 300 K to 1200 K
cp_air = lambda T: 0.994 + 1.67e-4*T - 7.22e-8*(T**2)  # Good ~300-1500 K estimate [kJ/(kg*K)]
dh_exact, err_est = quad(cp_air, 300.0, 1200.0)
dh_const = 1.005 * (1200.0 - 300.0)
print(f"Variable-cp Air Delta h (300 -> 1200 K) via quad : {dh_exact:.2f} kJ/kg (constant-cp err: {abs(dh_exact-dh_const):.1f} kJ/kg)")

# Nonlinear Combined Convection + Radiation Steel Sphere Cooling ODE (dT/dt)
rho_st, cp_st, D_sp = 7850.0, 480.0, 0.040  # 40 mm steel ball initially at 850 C
V_sp = np.pi * D_sp**3 / 6.0
A_sp = np.pi * D_sp**2
h_conv, eps, sigma = 45.0, 0.80, 5.670374419e-8
T_inf_K = 25.0 + 273.15

def cooling_rhs(t, y):
    T_K = y[0]
    q_loss = A_sp * (h_conv * (T_K - T_inf_K) + eps * sigma * (T_K**4 - T_inf_K**4))
    return [-q_loss / (rho_st * V_sp * cp_st)]

def conv_only_rhs(t, y):
    T_K = y[0]
    return [-(h_conv * A_sp * (T_K - T_inf_K)) / (rho_st * V_sp * cp_st)]

t_eval = np.linspace(0, 600, 121)
sol_rad = solve_ivp(cooling_rhs, (0, 600), [850.0 + 273.15], t_eval=t_eval)
sol_lin = solve_ivp(conv_only_rhs, (0, 600), [850.0 + 273.15], t_eval=t_eval)

print(f"Temp at t=120s -> Conv+Rad: {sol_rad.y[0][24]-273.15:.1f} C | Linear Conv-Only: {sol_lin.y[0][24]-273.15:.1f} C (Radiation cools faster at 850 C!)")
Variable-cp Air Delta h (300 -> 1200 K) via quad : 966.39 kJ/kg (constant-cp err: 61.9 kJ/kg)
Temp at t=120s -> Conv+Rad: 535.1 C | Linear Conv-Only: 690.4 C (Radiation cools faster at 850 C!)
# Example 2 (Dynamics & Vibrations): Resonance vs. Damped Transient Suspension ODE (solve_ivp)
m, k = 12.0, 4800.0        # Natural frequency omega_n = sqrt(4800/12) = 20.0 rad/s (3.18 Hz)
omega_n = np.sqrt(k / m)
c_under = 2.0 * 0.12 * m * omega_n   # Light damping zeta = 0.12
c_crit = 2.0 * 0.70 * m * omega_n    # Well-damped vehicle shock zeta = 0.70

def sdof_rhs(t, y, c_val):
    x, v = y
    F_step = 120.0 if t >= 0.05 else 0.0  # Road bump step input at t = 0.05 s
    return [v, (F_step - c_val * v - k * x) / m]

t_span = (0.0, 1.5)
t_out = np.linspace(0.0, 1.5, 400)
s1 = solve_ivp(lambda t, y: sdof_rhs(t, y, c_under), t_span, [0.0, 0.0], t_eval=t_out, max_step=0.005)
s2 = solve_ivp(lambda t, y: sdof_rhs(t, y, c_crit), t_span, [0.0, 0.0], t_eval=t_out, max_step=0.005)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 4.0))
ax1.plot(s1.t, s1.y[0]*1000, "-", color="#dc2626", lw=2, label="Underdamped ($\\zeta=0.12$)")
ax1.plot(s2.t, s2.y[0]*1000, "--", color="#0284c7", lw=2, label="Tuned Damper ($\\zeta=0.70$)")
ax1.axhline(120.0/k*1000, color="#059669", ls=":", label="Static Defl $F/k=25$ mm")
ax1.set_title("SDOF Step Response (`solve_ivp`)")
ax1.set_xlabel("Time [s]"); ax1.set_ylabel("Displacement $x$ [mm]"); ax1.grid(True, alpha=0.3); ax1.legend(fontsize=8)

ax2.plot(s1.y[0]*1000, s1.y[1]*1000, "-", color="#dc2626", lw=1.6, label="Underdamped Spiral")
ax2.plot(s2.y[0]*1000, s2.y[1]*1000, "--", color="#0284c7", lw=1.8, label="Fast Convergence")
ax2.set_title("State-Space Phase Portrait ($v$ vs. $x$)")
ax2.set_xlabel("Position $x$ [mm]"); ax2.set_ylabel("Velocity $\\dot{x}$ [mm/s]"); ax2.grid(True, alpha=0.3); ax2.legend(fontsize=8)
fig.tight_layout()
`SciPy` Quadrature (`quad`) & Dynamic Engineering ODEs (`solve_ivp`) Output Plot 1

Practice Questions (Concept Check)

  1. Notice we passed max_step=0.005 in Example 2 when F_step switched instantaneously at t = 0.05 s. Why is limiting max_step important around sudden step/pulse loads?
  2. What do the two returned numbers from quad(f, a, b) represent (val, err = quad(...))?
  3. Why must a 3rd-order Blasius boundary-layer ODE \(f''' + \frac{1}{2} f f'' = 0\) be written as a 3-element state vector [f, f', f''] for solve_ivp?
  4. Look at sol.y shape: for 2 states and 400 t_eval steps, what is sol.y.shape?

Guided Practice Problem 1 (Worked Self-Check): Unsteady Fluid Tank Draining with solve_ivp & Event Detection

Solve the exact Torricelli tank draining ODE from Lesson 06 (\(\frac{dh}{dt} = -C_d (d_o/D_t)^2 \sqrt{2gh}\), \(h_0 = 2.0\text{ m}\), \(D_t = 1.2\text{ m}, d_o = 0.04\text{ m}, C_d = 0.61\)) using solve_ivp with an events= trigger that stops integration automatically the instant depth hits \(h = 0.20\text{ m}\)!

Hint: Set hit_target.terminal = True and hit_target.direction = -1

events=[lambda t, y: y[0] - 0.20] locates the exact root crossing y[0] == 0.20 inside sol.t_events[0][0]!

# Worked Practice Problem 1 Solution: Exact Event-Triggered Tank Draining (solve_ivp)
coeff = 0.61 * ((0.040 / 1.20) ** 2) * np.sqrt(2.0 * 9.81)
def drain_ode(t, y): return [-coeff * np.sqrt(max(y[0], 0.0))]
def hit_20cm(t, y): return y[0] - 0.20
hit_20cm.terminal = True
hit_20cm.direction = -1

sol_drain = solve_ivp(drain_ode, (0.0, 5000.0), [2.00], events=hit_20cm, rtol=1e-9, atol=1e-11)
t_event = sol_drain.t_events[0][0]
t_exact = (2.0 * (np.sqrt(2.0) - np.sqrt(0.20))) / coeff
print(f"solve_ivp Event Stop Time : {t_event:.6f} s | Exact Analytical: {t_exact:.6f} s (err {abs(t_event-t_exact):.2e} s!)")
solve_ivp Event Stop Time : 644.198379 s | Exact Analytical: 644.198379 s (err 7.50e-08 s!)

End-of-Chapter Practice Problems (Try Yourself!)

  1. Solar Thermal Daily Tank Heating ODE (Solar Thermal): Solve \(M c_p \frac{dT_s}{dt} = \dot{Q}_{\text{col}}(t) - U_{\text{tank}} A_s (T_s - T_{\text{room}})\) from \(t = 8\text{ h}\) to \(16\text{ h}\) with sinusoidal collector input \(\dot{Q}_{\text{col}}(t) = 3200\sin(\pi(t-8)/8)\text{ W}\).
  2. Piston-Cylinder Isothermal vs Polytropic Work (quad): Evaluate \(W = \int_{0.05}^{0.25} P(V)\,dV\) numerically with quad and inspect quad error tolerance.
  3. Rocket Sled Velocity Integration (Calculus I Week 12): Integrate thrust minus aerodynamic drag (\(m \frac{dv}{dt} = T_{\text{thrust}} - \frac{1}{2}\rho C_d A v^2\)) from \(v(0) = 0\) over \(t \in [0, 10]\text{ s}\) to find terminal speed!

🎬 Concept & Engineering Animation

🎬 Solve IVP Phase Portrait