Lesson
29: SymPy Differentiation, Integration & Deriving
Critical River Oxygen Sag (\(t_c\))
The βBoring Stuffβ Problem: Grinding Out Product Rules & Exponentials by Hand
Look back at Lesson 19: we dropped the famous critical oxygen deficit time formula \[t_c = \frac{1}{k_r - k_d}\ln\left[\frac{k_r}{k_d}\left(1 - \frac{D_0(k_r - k_d)}{k_d L_0}\right)\right]\] into code. Where did that ugly formula come from? From differentiating \(D(t)\) with respect to \(t\), setting \(\frac{dD}{dt} = 0\), and solving for \(t\)!
With SymPy:
sp.diff(expr, t)differentiates ANY equation cleanly without chain-rule mistakes.sp.integrate(expr, (t, a, b))computes exact definite integrals (cumulative storm mass loads, total carbon emissions, dynamic LCA impulse response integralsLCA Track 2 Module 8!).
import sympy as sp
# Example 1: Derive Streeter-Phelps Critical Sag Time tc Symbolically From Scratch!
t, kd, kr, L0, D0 = sp.symbols("t kd kr L0 D0", positive=True)
D_expr = (kd * L0 / (kr - kd)) * (sp.exp(-kd * t) - sp.exp(-kr * t)) + D0 * sp.exp(-kr * t)
dD_dt = sp.diff(D_expr, t)
tc_sol = sp.simplify(sp.solve(sp.Eq(dD_dt, 0), t)[0])
print("=== Automated Derivation of Streeter-Phelps Critical Time tc ===")
print("dD/dt =", sp.factor(dD_dt))
print("Exact tc =", tc_sol)
# Verify numerically with Lesson 19 values (kd=0.25, kr=0.55, L0=26, D0=1.2)
vals = {kd: 0.25, kr: 0.55, L0: 26.0, D0: 1.2}
print(f"Numeric Check t_c = {float(tc_sol.subs(vals)):.4f} days -> D_c = {float(D_expr.subs({**vals, t: tc_sol.subs(vals)})):.4f} mg/L")=== Automated Derivation of Streeter-Phelps Critical Time tc ===
dD/dt = -(D0*kd*kr*exp(kd*t) - D0*kr**2*exp(kd*t) - L0*kd**2*exp(kr*t) + L0*kd*kr*exp(kd*t))*exp(-kd*t)*exp(-kr*t)/(kd - kr)
Exact tc = -log(kr*(D0*kd - D0*kr + L0*kd)/(L0*kd**2))/(kd - kr)
Numeric Check t_c = 2.4383 days -> D_c = 6.4242 mg/L
# Example 2 (LCA Track 2 Dynamic Climate Radiative Forcing + Pre-Calculus Integration): Cumulative AGWP Integral
# From LCA Track 2 Module 8: Impulse Response Function RF(t) for CO2 atmospheric decay:
# Compute exact 100-year Absolute Global Warming Potential integral: AGWP(100) = integral_0^100 (0.2173 + 0.224*exp(-t/394.4) + 0.2824*exp(-t/36.54) + 0.2763*exp(-t/4.304)) dt
tau = sp.symbols("t", nonnegative=True)
irf_co2 = 0.2173 + 0.2240 * sp.exp(-tau / 394.4) + 0.2824 * sp.exp(-tau / 36.54) + 0.2763 * sp.exp(-tau / 4.304)
agwp_20 = sp.integrate(irf_co2, (tau, 0, 20)).evalf()
agwp_100 = sp.integrate(irf_co2, (tau, 0, 100)).evalf()
print(f"IPCC Bern CO2 Impulse Integral: 20-yr = {agwp_20:.2f} yr | 100-yr = {agwp_100:.2f} yr (Matches IPCC AR5/AR6 baseline!)")IPCC Bern CO2 Impulse Integral: 20-yr = 14.24 yr | 100-yr = 52.36 yr (Matches IPCC AR5/AR6 baseline!)
Concept Check Questions
- Why is setting
positive=Truewhen declaringt, kd, kressential before callingsp.solve(sp.Eq(dD_dt, 0), t)? - Look at
sp.integrate(irf_co2, (tau, 0, 100)): how does this exact integral power LCA Track 2 Module 8 dynamic climate time-horizon comparisons? - Explain what
sp.integrate(Q_t * C_t, (t, 0, 24))computes physically during a 24-hour flood wave.
Guided Practice Problem 1: Symbolic Cumulative First-Order BOD Exerted Over Time
Integrate the rate of oxygen consumption \(\text{Rate}(t) = k_d L_0 e^{-k_d t}\) symbolically from \(t = 0\) to \(t = T\) to prove exact \(\text{BOD}_T = L_0(1 - e^{-k_d T})\), and check the classic 5-day ratio \(\text{BOD}_5 / L_0\) at \(k_d = 0.23\text{ day}^{-1}\)!
# Guided Practice 1 Starter
T_sym = sp.symbols("T", positive=True)
bod_T = sp.simplify(sp.integrate(kd * L0 * sp.exp(-kd * t), (t, 0, T_sym)))
print("Exact SymPy Formula BOD(T) =", bod_T)
print(f"BOD5 / Ultimate BODL @ kd=0.23/d : {float((bod_T/L0).subs({kd: 0.23, T_sym: 5})):.4f}")Exact SymPy Formula BOD(T) = L0 - L0*exp(-T*kd)
BOD5 / Ultimate BODL @ kd=0.23/d : 0.6834