Lesson
28: SymPy Symbolic Algebra & Aqueous Carbonate
Chemistry Speciation
The “Boring Stuff” Problem: Re-Deriving Messy Equilibrium Fractions Every Exam
In environmental water chemistry, deriving carbonate distribution fractions \(\alpha_0(\text{H}^+), \alpha_1(\text{H}^+), \alpha_2(\text{H}^+)\) cleanly without dropping a \(K_1 K_2\) term takes pages of algebra.
SymPy treats H, K1, K2 as
exact algebraic math symbols instead of floating-point
numbers:
sp.solve(eq, unknown)rearranges exact symbolic formulas cleanly!sp.lambdify((pH), alpha_1, "numpy")converts any derived symbolic expression directly into a lightning-fast NumPy function for plotting!
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
# Example 1: Exact Symbolic Carbonate Distribution Fractions (Benjamin Water Chemistry)
H, K1, K2 = sp.symbols("H K1 K2", positive=True)
denom = H**2 + K1 * H + K1 * K2
alpha0 = sp.simplify(H**2 / denom) # H2CO3* (dissolved CO2)
alpha1 = sp.simplify(K1 * H / denom) # HCO3- (bicarbonate)
alpha2 = sp.simplify(K1 * K2 / denom) # CO3^2- (carbonate)
print("=== Exact SymPy Symbolic Speciation Identities ===")
print("alpha_0 + alpha_1 + alpha_2 =", sp.simplify(alpha0 + alpha1 + alpha2))
print("Exact intersection pH where alpha0 == alpha1:", sp.solve(sp.Eq(alpha0, alpha1), H))
# Compile into vectorized NumPy evaluators via sp.lambdify!
K1_num, K2_num = 10**-6.35, 10**-10.33
f_a0 = sp.lambdify(H, alpha0.subs({K1: K1_num, K2: K2_num}), "numpy")
f_a1 = sp.lambdify(H, alpha1.subs({K1: K1_num, K2: K2_num}), "numpy")
f_a2 = sp.lambdify(H, alpha2.subs({K1: K1_num, K2: K2_num}), "numpy")
ph_grid = np.linspace(3.0, 12.5, 200)
H_grid = 10.0 ** (-ph_grid)
fig, ax = plt.subplots(figsize=(7.5, 3.8))
ax.plot(ph_grid, f_a0(H_grid), lw=2.3, color="#dc2626", label=r"$\alpha_0$: $\mathrm{H_2CO_3^*}$")
ax.plot(ph_grid, f_a1(H_grid), lw=2.3, color="#0284c7", label=r"$\alpha_1$: $\mathrm{HCO_3^-}$")
ax.plot(ph_grid, f_a2(H_grid), lw=2.3, color="#059669", label=r"$\alpha_2$: $\mathrm{CO_3^{2-}}$")
ax.axvline(6.35, color="#64748b", ls=":", lw=1.2)
ax.axvline(10.33, color="#64748b", ls=":", lw=1.2)
ax.set_title("Exact Carbonate Speciation Diagram (Derived via SymPy + Lambdify)")
ax.set_xlabel("pH [-]"); ax.set_ylabel("Molar Fraction [-]")
ax.grid(True, alpha=0.3); ax.legend(); fig.tight_layout()
print(f"At river pH = 7.80 -> a0={f_a0(10**-7.8):.3f}, a1={f_a1(10**-7.8):.3f}, a2={f_a2(10**-7.8):.4f}")
=== Exact SymPy Symbolic Speciation Identities ===
alpha_0 + alpha_1 + alpha_2 = 1
Exact intersection pH where alpha0 == alpha1: [K1]
At river pH = 7.80 -> a0=0.034, a1=0.963, a2=0.0028
Concept Check Questions
- Why did we write
H, K1, K2 = sp.symbols("H K1 K2", positive=True)instead of leaving assumptions unset? - Look at
sp.simplify(alpha0 + alpha1 + alpha2)outputting1: what conservation principle does that prove symbolically? - What does
sp.lambdify(H, expr, "numpy")do so we never have to rewrite long SymPy equations by hand for plotting?
Guided
Practice Problem 1: Symbolic Ammonium–Ammonia (NH4+ /
NH3) Toxic Unionized Speciation
In aquaculture and EPA NPDES ammonia permits, unionized \(\text{NH}_3\) is highly toxic to fish while
ammonium \(\text{NH}_4^+\) is far safer
(Ka = 10^-9.25 at 25 C). Derive \(\alpha_{\text{NH}_3} = \frac{K_a}{H +
K_a}\) symbolically in SymPy, find the exact
symbolic \(\text{pH}\) where \(50\%\) is \(\text{NH}_3\), and evaluate the toxic
fraction at \(\text{pH } 7.0\)
vs. \(\text{pH } 8.5\)!
# Guided Practice 1 Starter
Ka = sp.symbols("Ka", positive=True)
alpha_nh3 = Ka / (H + Ka)
print("50% equilibrium H+ =", sp.solve(sp.Eq(alpha_nh3, sp.Rational(1, 2)), H))
for ph in [7.0, 8.0, 8.5]:
frac = float(alpha_nh3.subs({H: 10**-ph, Ka: 10**-9.25}))
print(f"pH = {ph:.1f} -> Toxic Unionized NH3 Fraction = {frac:.2%}")50% equilibrium H+ = [Ka]
pH = 7.0 -> Toxic Unionized NH3 Fraction = 0.56%
pH = 8.0 -> Toxic Unionized NH3 Fraction = 5.32%
pH = 8.5 -> Toxic Unionized NH3 Fraction = 15.10%