Lesson
19: SciPy Root-Finding & Constrained Engineering
Optimization
The โBoring Stuffโ Problem: Trial-and-Error Guessing in Piping & Vessel Design
In Lesson 06 we hand-coded our own while bisection loop.
That works for a quick 1-variable check, but professional engineering
requires solving multi-loop piping systems, finding
exact critical pipe diameters, and designing
minimum-weight pressure vessels subject to ASME stress
and volume limits.
scipy.optimize gives you battle-tested
industrial numerical solvers written in compiled C/Fortran:
brentq(f, a, b): Fast, guaranteed root-finding for any 1D implicit equation wheref(a)andf(b)have opposite signs (combines bisection safety with inverse-quadratic speed!).root(F, x0): Solves coupled nonlinear systems of \(N\) equations in \(N\) unknowns simultaneously (multi-branch pipe networks, chemical equilibrium, nonlinear trusses!).minimize(cost_fn, x0, bounds=..., constraints=...): Finds optimal dimensions \((r^*, t^*, L^*)\) minimizing mass or lifetime cost while obeying inequality constraints (stress <= Sy / FOS).
Watch Out! Two
Golden Rules for scipy.optimize
- Always Check
res.successBefore Trustingres.x! An unconstrained optimizer can fail to converge and still populate.xwith garbage. Writeassert res.success, res.message! - Scale Optimization Variables Close to Order ~1: If
radius \(r \sim 0.5\text{ m}\) and
pressure is \(2\times 10^6\text{ Pa}\),
scale stress constraints in MPa (or dimensionless
FOS - 1.5 >= 0) so numerical step sizes behave cleanly!
import math
import numpy as np
from scipy.optimize import brentq, root, minimize
# Example 1 (Fluid Mechanics Module 5): Exact Pump-System Intersection (brentq) + 2-Branch Parallel Network (root)
# Pump curve: H_pump(Q) = 42 - 0.018 * Q_Ls^2 [m]
# System curve: H_sys(Q) = 16 + 0.029 * Q_Ls^2 [m] (Static lift 16 m + Darcy pipe losses)
H_pump = lambda Q_ls: 42.0 - 0.018 * (Q_ls ** 2)
H_sys = lambda Q_ls: 16.0 + 0.029 * (Q_ls ** 2)
Q_star = brentq(lambda q: H_pump(q) - H_sys(q), 0.1, 60.0)
print(f"=== Pump-System Operating Point via brentq ===")
print(f"Matched Flow Q* = {Q_star:.4f} L/s | Operating Head H* = {H_pump(Q_star):.3f} m")
# Coupled 2-Branch Parallel Pipe Solver via scipy.optimize.root:
# Total flow Q1 + Q2 = 120 L/s = 0.120 m^3/s; Equal head loss h_f1(Q1) = h_f2(Q2)
def colebrook(Re, eps_D):
if Re < 2300: return 64.0 / max(Re, 1.0)
return brentq(lambda f: 1/math.sqrt(f) + 2*math.log10(eps_D/3.7 + 2.51/(Re*math.sqrt(f))), 1e-4, 0.2)
def branch_hf(Q, L, D, eps=4.5e-5, K=2.0, nu=1.004e-6):
V = Q / (math.pi * D**2 / 4.0)
f = colebrook(abs(V) * D / nu, eps / D)
return (f * L / D + K) * (V * abs(V)) / (2.0 * 9.81)
def parallel_residual(vars_q):
Q1, Q2 = vars_q
return [
(Q1 + Q2) - 0.120,
branch_hf(Q1, L=120.0, D=0.15) - branch_hf(Q2, L=200.0, D=0.20),
]
sol_net = root(parallel_residual, [0.06, 0.06])
assert sol_net.success, sol_net.message
q1, q2 = sol_net.x
print(f"\nParallel Pipe Split: Q1 = {q1*1000:.2f} L/s (D=150mm), Q2 = {q2*1000:.2f} L/s (D=200mm)")
print(f"Matched Branch Head Loss = {branch_hf(q1, 120.0, 0.15):.3f} m")=== Pump-System Operating Point via brentq ===
Matched Flow Q* = 23.5200 L/s | Operating Head H* = 32.043 m
Parallel Pipe Split: Q1 = 45.27 L/s (D=150mm), Q2 = 74.73 L/s (D=200mm)
Matched Branch Head Loss = 5.113 m
# Example 2 (Machine Design & Solids): Minimum-Weight ASME Cylindrical Pressure Vessel via SLSQP
# Design variables: x = [R_m (inner radius), L_m (cylinder length), t_mm (wall thickness)]
# Must hold V >= 1.20 m^3 at P = 2.4 MPa with AISI 4140 (Sy = 415 MPa, FOS >= 2.0, rho = 7850 kg/m^3)
P_mpa = 2.4
sigma_allow_mpa = 415.0 / 2.0
rho_steel = 7850.0
V_min = 1.20
def vessel_mass_kg(x):
R, L, t_mm = x
t = t_mm / 1000.0
# Cylindrical shell + two hemispherical end caps
vol_steel = 2.0 * math.pi * R * L * t + 4.0 * math.pi * (R ** 2) * t
return rho_steel * vol_steel
cons = [
{"type": "ineq", "fun": lambda x: (math.pi * x[0]**2 * x[1] + (4/3)*math.pi*x[0]**3) - V_min},
{"type": "ineq", "fun": lambda x: sigma_allow_mpa - (P_mpa * x[0] / (x[2]/1000.0))}, # Hoop stress check
{"type": "ineq", "fun": lambda x: (x[0] / (x[2]/1000.0)) - 10.0}, # Thin-wall check r/t >= 10
]
bounds = [(0.25, 1.2), (0.5, 4.0), (4.0, 50.0)]
res_v = minimize(vessel_mass_kg, x0=[0.45, 1.5, 12.0], method="SLSQP", bounds=bounds, constraints=cons)
assert res_v.success, res_v.message
R_opt, L_opt, t_opt = res_v.x
print("=== SLSQP Optimal Pressure Vessel Geometry ===")
print(f"Optimal R = {R_opt*1000:.1f} mm, L = {L_opt:.3f} m, Wall Thickness t = {t_opt:.2f} mm")
print(f"Minimum Steel Mass = {res_v.fun:.2f} kg | Hoop Stress = {P_mpa * R_opt / (t_opt/1000):.1f} MPa (limit {sigma_allow_mpa:.1f} MPa)")=== SLSQP Optimal Pressure Vessel Geometry ===
Optimal R = 345.8 mm, L = 2.733 m, Wall Thickness t = 4.00 mm
Minimum Steel Mass = 233.64 kg | Hoop Stress = 207.5 MPa (limit 207.5 MPa)
Practice Questions (Concept Check)
- What mathematical condition MUST hold on
[a, b]before callingbrentq(f, a, b)? What error does SciPy raise iff(a)andf(b)have the same sign? - Notice
consinSLSQPused{"type": "ineq", "fun": ...}. Does SciPy treat inequality constraints asfun(x) >= 0orfun(x) <= 0? - Why did we pass
t_mmin millimeters insideminimizeinstead oft_m(\(0.005\text{ m}\))? - How does
scipy.optimize.rootsolve nonlinear systems compared tonp.linalg.solve?
Guided
Practice Problem 1 (Worked Self-Check): Critical Pipe Insulation
Thickness Optimization (Heat Transfer)
A steam pipe of outer radius \(r_1 =
25\text{ mm}\) (\(T_1 =
180^\circ\text{C}\)) is wrapped in fiberglass insulation (\(k = 0.042\text{ W/(m}\cdot\text{K)}\))
exposed to \(20^\circ\text{C}\) air
with \(h = 12\text{
W/(m}^2\cdot\text{K)}\). The heat loss per meter of pipe is:
\[q'(r_2) = \frac{2\pi (T_1 -
T_\infty)}{\frac{\ln(r_2/r_1)}{k} + \frac{1}{h r_2}}\] Use
minimize_scalar (from scipy.optimize) over
\(r_2 \in [0.025, 0.15]\text{ m}\) to
find where radial insulation resistance minimizes or maximizes
\(q'\) โ Wait: compare
r_cr = k / h (3.5 mm < 25 mm)
to see why heat loss drops monotonically with added fiberglass here,
vs.ย a small D = 4 mm electrical wire (\(r_1 = 2\text{ mm} < r_{\text{cr}}\))
where insulation initially increases heat loss! Check the
maximum peak \(q'\) for \(r_1 = 2\text{ mm}\) (maximize
= minimize(-q'))!
Hint: Negate q_prime inside minimize_scalar to find a maximum!
Since r_cr = k / h = 0.042 / 12 = 3.5 mm, wrapping a
2 mm radius wire increases cooling until \(r_2\) hits 3.5 mm!
# Worked Practice Problem 1 Solution: Critical Radius of Insulation via minimize_scalar
from scipy.optimize import minimize_scalar
k_ins, h_air, r1_wire = 0.042, 12.0, 0.002 # 2 mm radius copper wire!
def heat_loss_per_m(r2):
R_cond = np.log(r2 / r1_wire) / (2 * np.pi * k_ins)
R_conv = 1.0 / (2 * np.pi * r2 * h_air)
return (100.0 - 20.0) / (R_cond + R_conv)
# Maximize q'(r2) by minimizing -q'(r2)
res_crit = minimize_scalar(lambda r: -heat_loss_per_m(r), bounds=(r1_wire, 0.020), method="bounded")
print(f"Numerical Critical Radius r_cr = {res_crit.x * 1000:.3f} mm | Analytical k/h = {(k_ins/h_air)*1000:.3f} mm")
print(f"Peak Wire Heat Dissipation = {-res_crit.fun:.2f} W/m (vs bare wire {heat_loss_per_m(r1_wire):.2f} W/m)")Numerical Critical Radius r_cr = 3.500 mm | Analytical k/h = 3.500 mm
Peak Wire Heat Dissipation = 13.54 W/m (vs bare wire 12.06 W/m)
End-of-Chapter Practice Problems (Try Yourself!)
- Moody Friction Solver Cross-Check
(
Fluids): Usingbrentq, verify EVERY turbulent row (\(Re_D \ge 4000\)) indatasets/Fluids_Moody_Friction_Dataset.csv(f_EpsD_0p0005_Colebrook) to \(< 10^{-5}\) tolerance! - Supersonic Nozzle AreaโMach Inversion
(
Fluid Mechanics Module 7): Given exit-to-throat area ratio \(A/A^* = 2.40\) and \(\gamma = 1.4\), usebrentqon both subsonic bracket[0.05, 0.999]and supersonic bracket[1.001, 5.0]to find BOTH isentropic Mach solutions of \(\frac{A}{A^*} = \frac{1}{Ma}\left[\frac{2}{\gamma+1}\left(1 + \frac{\gamma-1}{2}Ma^2\right)\right]^{\frac{\gamma+1}{2(\gamma-1)}}\). - Optimum Pin-Fin Array Spacing
(
Heat Transfer): Maximize total fin-bank heat transfer with respect to fin spacing subject to pressure-drop constraints usingSLSQP.