Lesson 41 (Capstone 5): Activated Sludge Optimization & Leak-Free QSAR Aquatic Ecotoxicity ML

Courses Integrated: Biological Wastewater Engineering Β· LCA Track 2 (Module 4 USEtox Ecotoxicity) Β· Clean Cross-Validated Machine Learning
Companion Datasets: UCI_Water_Treatment_Plant_Daily.csv, UCI_QSAR_Aquatic_Toxicity.csv

Capstone Unification: Process Optimization + Chemical Hazard ML

In our final capstone, we unite two pillars of environmental engineering:

  1. Least-Cost Activated Sludge Design (scipy.optimize.minimize): Sizing reactor Volume \(V\) (\(\theta = V/Q\)) and Sludge Retention Time (SRT) simultaneously under EPA BOD effluent limits (\(S_{\text{eff}} \le 20\text{ mg/L}\)) and aeration blower electricity cost!
  2. Leak-Free 5-Fold Cross-Validated QSAR Toxicity ML (UCI_QSAR_Aquatic_Toxicity.csv): Predicting acute fathead minnow toxicity -log10(LC50 [mol/L]) across 546 real industrial chemicals using 8 molecular descriptors (TPSA, SAacc, H050, MLOGP, RDCHI, GATS1p, nN, C040)β€”comparing transparent Regularized Ridge Regression vs Distance-Weighted K-Nearest Neighbors (KNN, \(k=7\)) evaluated strictly inside out-of-sample CV folds!
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
import pandas as pd
from scipy.optimize import minimize
import matplotlib.pyplot as plt

# --- Part 1: Activated Sludge SRT & Aeration Cost Optimization ---
# Standard Metcalf & Eddy Steady-State CSTR ASM Relations:
# S_eff = Ks*(1 + kd*SRT) / (SRT*(mumax - kd) - 1)
# Sludge Mass M_x = Y * Q * (S0 - S_eff) * SRT / (1 + kd*SRT) -> Reactor Vol V = M_x / MLSS
Q_ww = 22000.0      # m^3/day
S0_bod = 240.0      # Influent soluble BOD [mg/L]
mumax, Ks, Y_bio, kd_bio = 3.2, 55.0, 0.55, 0.08
MLSS = 3200.0       # Target aeration tank mixed liquor [mg/L]

def wwtp_annual_cost_k(x):
    srt = float(x[0])
    s_eff = Ks * (1.0 + kd_bio * srt) / (srt * (mumax - kd_bio) - 1.0)
    mx_kg = (Y_bio * Q_ww * (S0_bod - s_eff) * srt * 1e-3) / (1.0 + kd_bio * srt)
    vol_m3 = (mx_kg * 1000.0) / MLSS
    # Larger SRT lowers effluent BOD, yet expands concrete tankage + endogenous aeration O2!
    o2_kg_d = Q_ww * (S0_bod - s_eff) * 1e-3 - 1.42 * (mx_kg / srt)
    capex_k = 0.08 * (0.45 * vol_m3)       # annualized tankage [$k]
    aeration_k = (o2_kg_d / 1.5 * 0.12 * 365.0) / 1000.0   # 1.5 kg O2/kWh blower
    sludge_disposal_k = ((mx_kg / srt) * 0.18 * 365.0) / 1000.0
    return capex_k + aeration_k + sludge_disposal_k

cons_ww = [
    {"type": "ineq", "fun": lambda x: 20.0 - Ks*(1+kd_bio*x[0])/(x[0]*(mumax-kd_bio)-1.0)},  # S_eff <= 20 mg/L
    {"type": "ineq", "fun": lambda x: x[0]*(mumax-kd_bio) - 1.0 - 0.5},                       # Washout safety margin!
]
res_ww = minimize(wwtp_annual_cost_k, x0=[8.0], bounds=[(2.5, 25.0)], constraints=cons_ww, method="SLSQP")
assert res_ww.success
srt_opt = float(res_ww.x[0])
s_eff_opt = Ks * (1.0 + kd_bio * srt_opt) / (srt_opt * (mumax - kd_bio) - 1.0)
print(f"Optimal Activated Sludge SRT* = {srt_opt:.2f} days -> Effluent BOD = {s_eff_opt:.2f} mg/L | Total Annual Cost = ${res_ww.fun:,.1f}k/yr")

# --- Part 2: 5-Fold Leak-Free Cross-Validation on 546 UCI QSAR Chemicals ---
qsar = pd.read_csv(data_file("UCI_QSAR_Aquatic_Toxicity.csv"))
X_q = qsar.drop(columns=["LC50_neglog_molL"]).values
y_q = qsar["LC50_neglog_molL"].values

rng = np.random.default_rng(123)
perm = rng.permutation(len(y_q))
folds = np.array_split(perm, 5)

oof_ridge = np.empty_like(y_q)
oof_knn = np.empty_like(y_q)

for val_idx in folds:
    tr_idx = np.setdiff1d(perm, val_idx)
    X_tr, y_tr = X_q[tr_idx], y_q[tr_idx]
    X_va = X_q[val_idx]

    # Standardize strictly inside fold!
    mu_f, sd_f = X_tr.mean(axis=0), np.where(X_tr.std(axis=0) > 1e-9, X_tr.std(axis=0), 1.0)
    Z_tr = (X_tr - mu_f) / sd_f
    Z_va = (X_va - mu_f) / sd_f

    # Model A: Ridge Linear QSAR
    Xb_tr = np.column_stack([np.ones(len(Z_tr)), Z_tr])
    Xb_va = np.column_stack([np.ones(len(Z_va)), Z_va])
    reg = np.eye(Xb_tr.shape[1]); reg[0, 0] = 0.0
    w_f = np.linalg.solve(Xb_tr.T @ Xb_tr + 10.0 * reg, Xb_tr.T @ y_tr)
    oof_ridge[val_idx] = Xb_va @ w_f

    # Model B: Distance-Weighted K=7 Nearest Neighbors in Standardized Chemical Space
    dists = np.sqrt(((Z_va[:, None, :] - Z_tr[None, :, :]) ** 2).sum(axis=2))
    nn_idx = np.argsort(dists, axis=1)[:, :7]
    nn_d = np.take_along_axis(dists, nn_idx, axis=1) + 1e-6
    wts = 1.0 / nn_d
    oof_knn[val_idx] = (wts * y_tr[nn_idx]).sum(axis=1) / wts.sum(axis=1)

# Ensemble Blend (0.5 * Ridge + 0.5 * KNN)
oof_ens = 0.5 * oof_ridge + 0.5 * oof_knn
for name, pred in [("Ridge QSAR", oof_ridge), ("Distance-KNN (k=7)", oof_knn), ("Hybrid Ridge+KNN", oof_ens)]:
    rmse_cv = np.sqrt(np.mean((y_q - pred) ** 2))
    r2_cv = 1.0 - np.sum((y_q - pred)**2) / np.sum((y_q - y_q.mean())**2)
    # Binary high-hazard screening accuracy (-log10(LC50) > 5.0 -> LC50 < 10 uM)
    acc = np.mean((pred > 5.0) == (y_q > 5.0)) * 100.0
    print(f"5-Fold Out-of-Sample [{name:<18s}]: RMSE = {rmse_cv:.3f} | R^2 = {r2_cv:.3f} | High-Tox Screen Acc = {acc:.1f}%")

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.2, 3.8))
srts = np.linspace(2.2, 20.0, 90)
ax1.plot(srts, [wwtp_annual_cost_k([s]) for s in srts], color="#0284c7", lw=2.3, label="Total Cost (Tank + O2 + Sludge)")
ax1.plot(srt_opt, res_ww.fun, "ro", markersize=8, label=f"Optimum SRT* = {srt_opt:.2f} d")
ax1.set_title("Activated Sludge SRT Life-Cycle Cost Trade-Off"); ax1.set_xlabel("Sludge Retention Time SRT [days]"); ax1.set_ylabel("Total Cost [$k/yr]"); ax1.legend(); ax1.grid(True, alpha=0.3)

ax2.scatter(y_q, oof_ens, alpha=0.55, color="#7c3aed", s=24, edgecolors="white", linewidths=0.3)
ax2.plot([1, 9.5], [1, 9.5], "k--", lw=1.4, label="1:1 Exact Parity")
ax2.axvline(5.0, color="#dc2626", ls=":", lw=1.2); ax2.axhline(5.0, color="#dc2626", ls=":", lw=1.2)
ax2.set_title("5-Fold CV Aquatic Ecotoxicity Prediction (546 UCI Chemicals)"); ax2.set_xlabel("Measured -log10(LC50)"); ax2.set_ylabel("Predicted -log10(LC50)"); ax2.legend(); ax2.grid(True, alpha=0.3)
fig.tight_layout()
Activated Sludge Optimization & Leak-Free QSAR Aquatic Ecotoxicity ML Output Plot 1
Optimal Activated Sludge SRT* = 2.50 days -> Effluent BOD = 9.71 mg/L | Total Annual Cost = $269.5k/yr
5-Fold Out-of-Sample [Ridge QSAR        ]: RMSE = 1.221 | R^2 = 0.462 | High-Tox Screen Acc = 76.2%
5-Fold Out-of-Sample [Distance-KNN (k=7)]: RMSE = 1.156 | R^2 = 0.518 | High-Tox Screen Acc = 76.2%
5-Fold Out-of-Sample [Hybrid Ridge+KNN  ]: RMSE = 1.122 | R^2 = 0.546 | High-Tox Screen Acc = 77.3%

Concept Check Questions

  1. Explain physically why choosing too short an SRT risks microbial washout, while an excessively long SRT drives up aeration tank concrete volume and endogenous oxygen power demand.
  2. Notice our distance-weighted KNN + Ridge out-of-fold ensemble outperformed pure linear Ridge: why can nonlinear local neighbors capture aquatic chemical mode-of-action better than one global hyperplane?
  3. Why did we standardize molecular descriptors inside each of the 5 cross-validation iterations rather than once across all 546 chemicals beforehand?

Guided Practice Problem 1: Tighter EPA Nutrient/BOD Permit (S_eff <= 10.0 mg/L) Cost Impact

Re-solve the activated sludge SLSQP optimization tightening the discharge limit from 20.0 mg/L down to 10.0 mg/L (S_eff <= 10.0 mg/L), and report the new optimal SRT*, required aeration basin volume V_m3, and annual cost premium!

# Guided Practice 1 Starter
cons_tight = [
    {"type": "ineq", "fun": lambda x: 10.0 - Ks*(1+kd_bio*x[0])/(x[0]*(mumax-kd_bio)-1.0)},
    {"type": "ineq", "fun": lambda x: x[0]*(mumax-kd_bio) - 1.0 - 0.5},
]
res_t = minimize(wwtp_annual_cost_k, x0=[12.0], bounds=[(2.5, 30.0)], constraints=cons_tight, method="SLSQP")
assert res_t.success
srt_t = float(res_t.x[0])
print(f"Tighter Permit (<=10 mg/L): SRT*={srt_t:.2f} d | Cost=${res_t.fun:,.1f}k/yr (+${res_t.fun - res_ww.fun:.1f}k/yr)")
Tighter Permit (<=10 mg/L): SRT*=2.50 d | Cost=$269.5k/yr (+$0.0k/yr)