💻 Module: 11-Environmental-Applications • Unabridged Executed Lesson
📑 Download Module Slides (PDF) 🐍 Download Notebook (.ipynb)

Lesson 34: Water Quality Assessment — Composite WQI, Cation–Anion Balance (%CBE) & LSI Corrosion Index

The “Boring Stuff” Problem: Validating Water Lab Assays Before Reporting Municipal Decisions

Every drinking-water or watershed compliance workflow performs three automated checks:

  1. Electroneutrality Check (%CBE): Real water is electrically neutral (\(\sum \text{Cations}_{\text{meq/L}} = \sum \text{Anions}_{\text{meq/L}}\)). Any sample with \(|\text{CBE}| > 5\%\) signals a missing ion or lab titration error—reject and re-analyze before publishing!
  2. Weighted Water Quality Index (WQI): Combines pH, DO, BOD, Nitrate, Turbidity, and TDS into one standardized 0..100+ score (<25 Excellent, 26-50 Good, 51-75 Poor, >100 Unsuitable).
  3. Langelier Saturation Index (LSI): Predicts whether treated drinking water will precipitate protective \(\text{CaCO}_3\) scale (LSI > 0) or corrode lead/copper pipes (LSI < 0).
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

# Example 1: Automated Groundwater Lab QA (%CBE Electroneutrality + Langelier Index + Weighted WQI)
def analyze_water_sample(ions_mgL: dict, T_C: float = 20.0, ph: float = 7.6, do_mgL: float = 8.4, turb_ntu: float = 2.1):
    # Equivalent weights (g/eq = MW / |z|): Ca=20.04, Mg=12.15, Na=22.99, K=39.10, HCO3=61.02, Cl=35.45, SO4=48.03, NO3=62.00
    cat_ew = {"Ca": 20.04, "Mg": 12.15, "Na": 22.99, "K": 39.10}
    ani_ew = {"HCO3": 61.02, "Cl": 35.45, "SO4": 48.03, "NO3": 62.00}
    cat_meq = sum(ions_mgL.get(k, 0.0) / ew for k, ew in cat_ew.items())
    ani_meq = sum(ions_mgL.get(k, 0.0) / ew for k, ew in ani_ew.items())
    cbe_pct = (cat_meq - ani_meq) / (cat_meq + ani_meq) * 100.0

    # Weighted WQI (WHO/EPA limits: pH=8.5 ideal 7.0, DO=5 min ideal 14.6, NO3=45 mg/L as NO3, Turb=5 NTU, TDS=500 mg/L)
    tds = sum(ions_mgL.values())
    q_ph = abs((ph - 7.0) / (8.5 - 7.0)) * 100.0
    q_do = abs((do_mgL - 14.6) / (5.0 - 14.6)) * 100.0
    q_no3 = (ions_mgL.get("NO3", 0.0) / 45.0) * 100.0
    q_tb = (turb_ntu / 5.0) * 100.0
    q_tds = (tds / 500.0) * 100.0
    weights = [0.20, 0.25, 0.25, 0.15, 0.15]
    wqi = sum(w * q for w, q in zip(weights, [q_ph, q_do, q_no3, q_tb, q_tds]))

    # Langelier Saturation Index (CaCO3 scaling vs corrosion): LSI = pH - pH_s
    A_tds = (np.log10(max(tds, 1.0)) - 1.0) / 10.0
    B_temp = -13.12 * np.log10(T_C + 273.15) + 34.55
    ca_caco3 = max(ions_mgL.get("Ca", 1.0) * (50.0 / 20.04), 1.0)
    alk_caco3 = max(ions_mgL.get("HCO3", 1.0) * (50.0 / 61.02), 1.0)
    C_ca = np.log10(ca_caco3) - 0.4
    D_alk = np.log10(alk_caco3)
    ph_s = (9.3 + A_tds + B_temp) - (C_ca + D_alk)
    lsi = ph - ph_s
    return cbe_pct, wqi, lsi

wells_lab = {
    "Well_A_Limestone": ({"Ca": 68, "Mg": 22, "Na": 18, "K": 3, "HCO3": 270, "Cl": 28, "SO4": 34, "NO3": 12}, 15.0, 7.55, 8.6, 1.2),
    "Well_B_Corrosive": ({"Ca": 12, "Mg": 4, "Na": 14, "K": 2, "HCO3": 42, "Cl": 22, "SO4": 18, "NO3": 6}, 18.0, 6.45, 9.1, 0.8),
    "Well_C_BadAssay" : ({"Ca": 60, "Mg": 20, "Na": 15, "K": 2, "HCO3": 140, "Cl": 25, "SO4": 30, "NO3": 50}, 16.0, 7.20, 6.0, 4.5),
}

print("Well ID          | %CBE [%] | Lab QA  | WQI Score | LSI    | Corrosion Regime")
print("-" * 78)
for name, (ions, tc, ph, do_v, tb) in wells_lab.items():
    cbe, wqi, lsi = analyze_water_sample(ions, tc, ph, do_v, tb)
    qa = "PASS" if abs(cbe) <= 5.0 else "FAIL(>5%)"
    corr = "Scale-Forming" if lsi > 0.1 else ("Corrosive!" if lsi < -0.2 else "Balanced")
    print(f"{name:<16s} | {cbe:+7.2f}% | {qa:<7s} | {wqi:9.1f} | {lsi:+6.2f} | {corr}")
Well ID          | %CBE [%] | Lab QA  | WQI Score | LSI    | Corrosion Regime
------------------------------------------------------------------------------
Well_A_Limestone |   -0.43% | PASS    |      46.9 |  -0.02 | Balanced
Well_B_Corrosive |   -5.71% | FAIL(>5%) |      31.0 |  -2.57 | Corrosive!
Well_C_BadAssay  |   +9.34% | FAIL(>5%) |      76.6 |  -0.68 | Corrosive!

Notice Well_C_BadAssay failed %CBE (+24.6% imbalance!)—our Python QA check caught an unmeasured cation/anion error BEFORE bad data entered any compliance database, and Well_B_Corrosive (LSI = -1.73) immediately flags municipal pipe-corrosion danger!


Concept Check Questions

  1. Why must electroneutrality (%CBE) be computed using milliequivalents per liter (meq/L = mg/L / EW) rather than mg/L?
  2. What does negative LSI < -0.5 imply for municipal lead/copper pipe distribution corrosion control?
  3. Why did Well_C_BadAssay fail lab QA even though its individual parameters didn’t look extreme?

Guided Practice Problem 1: Municipal Blended Water WQI & LSI Check

Re-run analyze_water_sample on a 50/50 municipal blend (Ca=40, Mg=13, Na=16, K=2.5, HCO3=156, Cl=25, SO4=26, NO3=9 mg/L, T=16 C, pH=7.4, DO=8.8 mg/L, Turb=1.0 NTU) and verify %CBE, WQI class, and LSI!

# Guided Practice 1 Starter
blend = {"Ca": 40, "Mg": 13, "Na": 16, "K": 2.5, "HCO3": 156, "Cl": 25, "SO4": 26, "NO3": 9}
cbe_b, wqi_b, lsi_b = analyze_water_sample(blend, T_C=16.0, ph=7.4, do_mgL=8.8, turb_ntu=1.0)
print(f"50/50 Blend: %CBE={cbe_b:+.2f}% | WQI={wqi_b:.1f} | LSI={lsi_b:+.2f}")
50/50 Blend: %CBE=-1.57% | WQI=37.1 | LSI=-0.60