Lesson
25: SciPy Optimization (brentq,
root, minimize) โ Treatment Costs & Carbon
Concrete
The โBoring Stuffโ Problem: Manual Trial-and-Error Sizing Across Pipe Loops & Reactor Costs
Hand-coded bisection works great for 1 equation, yet real environmental design involves balancing capital vs.ย pumping power costs, meeting strict EPA strength/effluent constraints, and finding exact system-pump intersections.
scipy.optimize handles all of this cleanly:
brentq(f, a, b): Fast, guaranteed root finder whenf(a)andf(b)change sign (exact sewer pipe friction, aeration balance, critical sag time).minimize(obj, x0, bounds=..., constraints=...)(SLSQP): Minimizes treatment cost or embodied \(\text{CO}_2\) subject to compliance inequality constraints (fun(x) >= 0).
Watch Out! Always
Verify assert res.success
An unconstrained or poorly scaled optimizer can stop early and leave
unusable numbers inside res.x. Scale physical units close
to \(O(1)\) and assert
res.success every single time!
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 brentq, minimize
import matplotlib.pyplot as plt
# Example 1 (Wastewater Pump Hydraulics from Fluid Mechanics CSV + Cost): Least-Cost Treatment Force Main Sizing
# Trade-off: larger pipe diameter D_m cuts pumping electricity, yet raises trenching & pipe capital cost!
Q_m3s = 0.14 # Peak municipal lift station flow [m^3/s]
L_pipe = 2400.0 # Force main length [m]
f_darcy = 0.019 # Moody friction factor
eta_p = 0.76 # Pump wire-to-water efficiency
elec_rate = 0.14 # $/kWh
hours_yr = 8760.0
crf = 0.0802 # Capital Recovery Factor (20 yr @ 5%)
def total_annual_cost(D_arr):
D = float(D_arr[0])
# Capital cost: $520 * D^1.55 per meter annualized by CRF
capex_ann = crf * (520.0 * (D ** 1.55) * L_pipe)
V = Q_m3s / (np.pi * D**2 / 4.0)
hf = f_darcy * (L_pipe / D) * (V**2 / (2.0 * 9.80665))
pump_kw = (998.0 * 9.80665 * Q_m3s * (22.0 + hf) / eta_p) / 1000.0
opex_ann = pump_kw * hours_yr * elec_rate
return capex_ann + opex_ann
# Velocity must stay >= 0.75 m/s (scour solids) and <= 2.5 m/s (limit surge/erosion)
cons = [
{"type": "ineq", "fun": lambda x: (Q_m3s / (np.pi * x[0]**2 / 4.0)) - 0.75},
{"type": "ineq", "fun": lambda x: 2.50 - (Q_m3s / (np.pi * x[0]**2 / 4.0))},
]
res = minimize(total_annual_cost, x0=[0.35], bounds=[(0.15, 0.90)], constraints=cons, method="SLSQP")
assert res.success, res.message
D_opt = float(res.x[0])
V_opt = Q_m3s / (np.pi * D_opt**2 / 4.0)
D_sweep = np.linspace(0.24, 0.55, 80)
costs = [total_annual_cost([d]) / 1000.0 for d in D_sweep]
fig, ax = plt.subplots(figsize=(7.4, 3.8))
ax.plot(D_sweep * 1000, costs, color="#0284c7", lw=2.3, label="Total Annualized Cost (CapEx + Pumping)")
ax.plot(D_opt * 1000, res.fun / 1000.0, "ro", markersize=8, label=f"SLSQP Optimum D* = {D_opt*1000:.1f} mm (${res.fun/1000:.1f}k/yr)")
ax.set_title("Least-Cost Wastewater Force Main Diameter Optimization")
ax.set_xlabel("Pipe Diameter D [mm]"); ax.set_ylabel("Total Annualized Cost [$k / yr]")
ax.grid(True, alpha=0.3); ax.legend(); fig.tight_layout()
print(f"Optimal Force Main D* = {D_opt*1000:.1f} mm | Velocity = {V_opt:.2f} m/s | Cost = ${res.fun:,.0f}/yr")
Optimal Force Main D* = 350.0 mm | Velocity = 1.46 m/s | Cost = $99,407/yr
# Example 2 (Exact Hydraulic Pumping Match via brentq on Fluids_Pump_and_Pipe_Network.csv)
p_dat = np.genfromtxt(data_file("Fluids_Pump_and_Pipe_Network.csv"), delimiter=",", skip_header=1, usecols=(0, 3, 4))
q_pts, h_sys_pts, h_pump_pts = p_dat.T
# Fit smooth quadratic curves and solve exact intersection H_pump(Q) - H_sys(Q) = 0 with brentq!
coef_p = np.polyfit(q_pts, h_pump_pts, 2)
coef_s = np.polyfit(q_pts, h_sys_pts, 2)
Q_match = brentq(lambda q: np.polyval(coef_p, q) - np.polyval(coef_s, q), q_pts[0], q_pts[-1])
print(f"Exact Pump-System Operating Point via brentq: Q* = {Q_match:.2f} L/s | Head = {np.polyval(coef_p, Q_match):.2f} m")Exact Pump-System Operating Point via brentq: Q* = 70.05 L/s | Head = 42.92 m
Concept Check Questions
- Why did
SLSQPuse{"type": "ineq", "fun": lambda x: V(x) - 0.75}and2.50 - V(x)? Remember SciPy treats EVERY"ineq"constraint asfun(x) >= 0! - Explain the two opposing costs balanced at optimal pipe diameter \(D^*\).
- What preconditions must
[a, b]satisfy before callingbrentq(f, a, b)?
Guided
Practice Problem 1: Least-Cost Activated Sludge HRT Split
(V_1 + V_2 Minimum Capital)
A plug-flow bioreactor followed by a polish basin has first-order
substrate removal \(S_{\text{out}} =
\frac{S_0}{(1 + k\theta_1)(1 + k\theta_2)}\) with \(k = 1.8\text{ day}^{-1}\), influent \(S_0 = 260\text{ mg/L}\), and effluent cap
\(S_{\text{out}} \le 12.0\text{
mg/L}\). Use scipy.optimize.minimize to minimize
total residence time \(\theta_1 +
\theta_2\) subject to \(S_{\text{out}}
\le 12.0\text{ mg/L}\) (theta >= 0.05). Verify
that equal sizing \(\theta_1^* =
\theta_2^*\) minimizes total reactor volume!
# Guided Practice 1 Starter
k_bio, S0, S_lim = 1.8, 260.0, 12.0
res_bio = minimize(
lambda t: t[0] + t[1],
x0=[1.5, 3.0],
bounds=[(0.05, 10.0), (0.05, 10.0)],
constraints=[{"type": "ineq", "fun": lambda t: S_lim - S0 / ((1 + k_bio*t[0]) * (1 + k_bio*t[1]))}],
method="SLSQP",
)
assert res_bio.success
print(f"Optimal Basin Splits: theta1 = {res_bio.x[0]:.3f} d, theta2 = {res_bio.x[1]:.3f} d | Total HRT = {res_bio.fun*24:.1f} h")Optimal Basin Splits: theta1 = 2.030 d, theta2 = 2.030 d | Total HRT = 97.5 h