Lesson
24: SymPy Systems, Measurement Uncertainty Jacobians &
lambdify Speedups
The “Boring Stuff” Problem: Symbolic Math Is Exact—Until You Run It 10,000 Times
Calling expr.subs(x, val).evalf() inside a
for loop of 10,000 crank angles or
5,000 fluid grid points is painfully slow
(taking seconds instead of milliseconds) because SymPy re-parses the
symbolic tree at every single point!
sp.lambdify((args...), expr, modules="numpy")
compiles any symbolic derivative, kinematic equation, or CFD analytical
formula directly into a blazingly fast vectorized NumPy Python
function! You get BOTH worlds:
- Exact calculus derivatives with zero algebra typos
(
sp.diff,Matrix.jacobian), AND - Microsecond array evaluation across thousands of points
(
func(theta_array))!
Also in Mechanical Engineering Labs
(ME Instrumentation & Fluid Lab), sensor propagation of
uncertainty requires partial derivatives \(\frac{\partial f}{\partial x_i}\): \[u_f = \sqrt{\sum_{i=1}^n \left(\frac{\partial
f}{\partial x_i} u_{x_i}\right)^2}\] With
sp.Matrix([f]).jacobian([x1, x2, ...]),
SymPy computes every sensitivity derivative automatically!
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
# Example 1 (Calculus I Week 7 + Dynamics): Exact Slider-Crank Kinematics via diff + lambdify!
theta, r_crank, l_rod, omega = sp.symbols("theta r_crank l_rod omega", positive=True)
# Piston displacement x_p from TDC: x_p(theta) = r*cos(theta) + sqrt(l^2 - (r*sin(theta))^2)
x_p_sym = r_crank * sp.cos(theta) + sp.sqrt(l_rod**2 - (r_crank * sp.sin(theta))**2)
# Velocity v = dx/dtheta * omega ; Acceleration a = dv/dtheta * omega (chain rule at constant omega!)
v_sym = sp.diff(x_p_sym, theta) * omega
a_sym = sp.diff(v_sym, theta) * omega
# Compile into vectorized NumPy functions cleanly with lambdify!
params = {r_crank: 0.045, l_rod: 0.160, omega: 3000.0 * 2.0 * np.pi / 60.0} # 45mm crank, 160mm rod, 3000 RPM
v_fn = sp.lambdify(theta, v_sym.subs(params), modules="numpy")
a_fn = sp.lambdify(theta, a_sym.subs(params), modules="numpy")
deg = np.linspace(0, 360, 361)
rad = np.radians(deg)
v_ms = v_fn(rad)
a_g = a_fn(rad) / 9.81 # Acceleration in g's!
print(f"Peak Piston Speed @ 3000 RPM : {np.max(np.abs(v_ms)):.2f} m/s")
print(f"Peak Piston TDC Accel : {a_g[0]:,.0f} g's (Critical Inertial Conrod Load!)")
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7.2, 4.8), sharex=True)
ax1.plot(deg, v_ms, color="#0284c7", lw=2)
ax1.set_ylabel("Piston Speed $v$ [m/s]"); ax1.set_title("IC Engine Slider-Crank Exact Kinematics (3000 RPM via SymPy `lambdify`)"); ax1.grid(True, alpha=0.3)
ax2.plot(deg, a_g, color="#dc2626", lw=2)
ax2.set_xlabel("Crank Angle $\\theta$ [deg]"); ax2.set_ylabel("Acceleration [g]"); ax2.grid(True, alpha=0.3)
fig.tight_layout()
Peak Piston Speed @ 3000 RPM : 14.69 m/s
Peak Piston TDC Accel : -580 g's (Critical Inertial Conrod Load!)
# Example 2 (Engineering Uncertainty Propagation via SymPy Jacobian): Pitot-Static Airspeed Lab Uncertainty
dP, rho, u_dP, u_rho = sp.symbols("Delta_P rho u_dP u_rho", positive=True)
V_pitot = sp.sqrt(2 * dP / rho)
# Compute symbolic sensitivity matrix [dV/d(Delta_P), dV/d(rho)] automatically!
J = sp.Matrix([V_pitot]).jacobian([dP, rho])
u_V_sym = sp.sqrt((J[0, 0] * u_dP)**2 + (J[0, 1] * u_rho)**2)
rel_u_V = sp.simplify(u_V_sym / V_pitot)
print("=== Symbolic Experimental Uncertainty Propagation ===")
print("Sensitivities dV/dP, dV/drho :", J[0, 0], " | ", J[0, 1])
print("Clean Relative Uncertainty u_V/V =", rel_u_V)
# Plug in real wind-tunnel readings: Delta_P = 420 +/- 5 Pa, rho = 1.20 +/- 0.015 kg/m^3
subs_lab = {dP: 420.0, u_dP: 5.0, rho: 1.20, u_rho: 0.015}
print(f"Measured Airspeed V = {float(V_pitot.subs(subs_lab)):.2f} +/- {float(u_V_sym.subs(subs_lab)):.3f} m/s ({float(rel_u_V.subs(subs_lab))*100:.2f}% uncertainty)")=== Symbolic Experimental Uncertainty Propagation ===
Sensitivities dV/dP, dV/drho : sqrt(2)/(2*sqrt(Delta_P)*sqrt(rho)) | -sqrt(2)*sqrt(Delta_P)/(2*rho**(3/2))
Clean Relative Uncertainty u_V/V = sqrt(Delta_P**2*u_rho**2 + rho**2*u_dP**2)/(2*Delta_P*rho)
Measured Airspeed V = 26.46 +/- 0.228 m/s (0.86% uncertainty)
Look at rel_u_V that SymPy discovered automatically:
\(\frac{u_V}{V} = \frac{1}{2}\sqrt{(u_{\Delta
P}/\Delta P)^2 + (u_\rho/\rho)^2}\)!
Practice Questions (Concept Check)
- Why is
sp.lambdify(x, expr, "numpy")orders of magnitude faster on 1,000 points than loopingexpr.subs(x, xi).evalf()? - Look at
v_sym = sp.diff(x_p_sym, theta) * omega: why did we multiply byomega(\(d\theta/dt\)) after differentiating with respect totheta? - How does
sp.Matrix([f1, f2]).jacobian([x, y])help both experimental uncertainty analysis AND Newton–Raphson nonlinear solvers? - What does
modules="numpy"telllambdifyto substitute forsp.sin,sp.cos, andsp.sqrt?
Guided
Practice Problem 1 (Worked Self-Check): Compressible Choked Nozzle
Critical Pressure & lambdify Sweep
(Fluids Mod 7)
Define symbolic isentropic stagnation pressure ratio \(P/P_0 = \left(1 + \frac{\gamma-1}{2}
Ma^2\right)^{-\frac{\gamma}{\gamma-1}}\), evaluate critical sonic
ratio \(P^*/P_0\) at \(Ma = 1\) symbolically for \(\gamma = 7/5\), take the sensitivity \(d(P/P_0)/dMa\), and lambdify
both over \(Ma \in [0, 3]\)!
Hint: Use sp.Rational(7, 5) so SymPy keeps exact fractions before .evalf()
At \(\gamma = 1.4, Ma = 1\), \(P^*/P_0 = (5/6)^{7/2} \approx 0.52828\)!
# Worked Practice Problem 1 Solution: Compressible Pressure Ratio & lambdify Sweep
Ma, gamma = sp.symbols("Ma gamma", positive=True)
P_P0 = (1 + ((gamma - 1) / 2) * Ma**2) ** (-gamma / (gamma - 1))
P_star_exact = P_P0.subs({Ma: 1, gamma: sp.Rational(7, 5)})
print(f"Exact Sonic Ratio P*/P0 = {P_star_exact} = {float(P_star_exact.evalf()):.5f}")
dP_dMa = sp.simplify(sp.diff(P_P0, Ma))
f_P = sp.lambdify(Ma, P_P0.subs(gamma, 1.4), "numpy")
ma_vals = np.array([0.3, 0.8, 1.0, 1.5, 2.5])
print("Fast lambdify P/P0 across Ma =", ma_vals, "->", np.round(f_P(ma_vals), 4))Exact Sonic Ratio P*/P0 = 125*sqrt(30)/1296 = 0.52828
Fast lambdify P/P0 across Ma = [0.3 0.8 1. 1.5 2.5] -> [0.9395 0.656 0.5283 0.2724 0.0585]
End-of-Chapter Practice Problems (Try Yourself!)
- Thermodynamic Entropy Uncertainty
(
ME 200): Propagate sensor error in Ideal Gas entropy change \(\Delta s = c_p \ln(T_2/T_1) - R\ln(P_2/P_1)\) when thermocouples have \(\pm 1.5\text{ K}\) and pressure transducers have \(\pm 2.0\text{ kPa}\) uncertainty using SymPy’sjacobian. - Rankine–Reynolds Sensitivity
lambdify: Derive \(\frac{\partial h_f}{\partial D}\) and \(\frac{\partial h_f}{\partial Q}\) for Darcy head loss \(h_f = \frac{8 f L Q^2}{\pi^2 g D^5}\),lambdify, and verify why doubling flow increases head loss \(4\times\) while halving diameter increases head loss \(32\times\)! - Coupled Nonlinear System
sp.solve: Find intersection coordinates of pump head \(H = H_0 - a Q^2\) and system curve \(H = H_s + b Q^2\) symbolically inSymPy.