Lesson 24: Automated Sensor QA/QC Pipelines β€” Gap Filling, Anomaly Detection & Audit Figures

The β€œBoring Stuff” Problem: Turning Raw Field Files Into Verified Engineering Inputs

Before any ODE solver, water quality model, or ML forecaster ever touches monitoring data, an environmental engineer runs a 4-step automated QA/QC pipeline:

  1. Range & Physical Bounds Check: Reject physically impossible readings (e.g., RH > 100%, pH < 0, pH > 14, negative concentrations).
  2. Completeness Threshold Gate (>= 75%): EPA air/water design rules reject daily or 8-hour windows missing more than 25% of observations.
  3. Short-Gap Interpolation vs.Β Long-Gap Masking: Interpolate isolated 1–2 step dropouts (limit=2), NEVER blindly interpolate across a 3-day power outage!
  4. Statistical Spike Audit: Flag extreme excursions via Modified Z-score / Interquartile Range (IQR) so true spills are separated from electrical noise!
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
import matplotlib.pyplot as plt

# Real QA/QC Workflow on First 14 Days (336 Hours) of UCI_Air_Quality_Italy_Hourly.csv
aq = pd.read_csv(
    data_file("UCI_Air_Quality_Italy_Hourly.csv"),
    sep=";", decimal=",", na_values=[-200, -200.0, "-200", "-200,0"],
).dropna(axis=1, how="all")

aq["Datetime"] = pd.to_datetime(aq["Date"] + " " + aq["Time"], format="%d/%m/%Y %H.%M.%S")
aq = aq.set_index("Datetime").sort_index()

# Take 14-day March 2004 window cleanly
win = aq.loc["2004-03-11":"2004-03-24", ["CO(GT)", "C6H6(GT)", "NO2(GT)", "T"]].copy()
raw_missing = int(win["CO(GT)"].isna().sum())

# Step 1: Safe short-gap linear interpolation (max 2 consecutive missing hours ONLY!)
win["CO_clean"] = win["CO(GT)"].interpolate(method="time", limit=2, limit_area="inside")
post_missing = int(win["CO_clean"].isna().sum())

# Step 2: IQR Outlier & Commute Rush-Hour Audit
q25, q75 = win["CO_clean"].quantile([0.25, 0.75])
iqr = q75 - q25
upper_fence = q75 + 1.5 * iqr
peaks = win[win["CO_clean"] > upper_fence]

print("=== Automated 14-Day Roadside CO QA/QC Audit ===")
print(f"Total Hours          : {len(win)} | Raw -200 Dropouts : {raw_missing}")
print(f"After Limit-2 Interp : Still Missing = {post_missing} | High Rush-Hour Outliers (> {upper_fence:.2f} mg/m^3): {len(peaks)}")

fig, ax = plt.subplots(figsize=(8.0, 3.8))
ax.plot(win.index, win["CO_clean"], color="#0284c7", lw=1.6, label="QA/QC CO(GT) [mg/m^3] (limit=2 interp)")
ax.scatter(peaks.index, peaks["CO_clean"], color="#dc2626", s=28, zorder=5, label=f"Rush-Hour Peaks > {upper_fence:.2f} mg/m^3")
ax.axhline(10.0, color="#059669", ls="--", lw=1.5, label="WHO/EPA 8-h CO Guideline (~10 mg/m^3)")
ax.set_title("14-Day Roadside CO QA/QC Pipeline (Real UCI Italy Air Quality Archive)")
ax.set_ylabel("Carbon Monoxide CO [mg/m^3]")
ax.grid(True, alpha=0.3)
ax.legend(fontsize=8.5)
fig.tight_layout()
Automated Sensor QA/QC Pipelines β€” Gap Filling, Anomaly Detection & Audit Figures Output Plot 1
=== Automated 14-Day Roadside CO QA/QC Audit ===
Total Hours          : 336 | Raw -200 Dropouts : 16
After Limit-2 Interp : Still Missing = 0 | High Rush-Hour Outliers (> 5.96 mg/m^3): 12

Concept Check Questions

  1. Why is limit=2 critical inside .interpolate(method="time", limit=2)? What happens over a 48-hour calibration outage if you omit limit?
  2. Why did we parse aq["Date"] + " " + aq["Time"] with explicit format "%d/%m/%Y %H.%M.%S" (day/month/year)?
  3. What does limit_area="inside" prevent if the first or last hours of the archive are NaN?

Guided Practice Problem 1: Water Treatment Plant Conductivity & TSS Outlier Audit

Load UCI_Water_Treatment_Plant_Daily.csv (na_values=["?"]), extract suspended solids influent SS_E_mgL and effluent SS_S_mgL, compute IQR outlier threshold \(Q_3 + 1.5\cdot\text{IQR}\) on effluent SS_S_mgL, and print how many days experienced clarifier solids washout above the IQR upper fence or \(> 30\text{ mg/L}\).

# Guided Practice 1 Starter
wt = pd.read_csv(data_file("UCI_Water_Treatment_Plant_Daily.csv"), na_values=["?"])
ss_eff = wt["SS_S_mgL"].dropna()
q1, q3 = ss_eff.quantile([0.25, 0.75])
fence = q3 + 1.5 * (q3 - q1)
print(f"Effluent SS (n={len(ss_eff)}): Median={ss_eff.median():.1f} mg/L | IQR Fence={fence:.1f} | Washout (>30 mg/L): {(ss_eff > 30).sum()} days")
Effluent SS (n=522): Median=19.0 mg/L | IQR Fence=39.0 | Washout (>30 mg/L): 71 days