Lesson 33: Environmental Time Series — DatetimeIndex, EPA 24h/8h Rolling Attainment & Water Years (YS-OCT)

The “Boring Stuff” Problem: Row-Count Rolling Windows That Silently Average Across Missing Days

Suppose an hourly ozone or \(\text{PM}_{2.5}\) sensor loses power for 4 days, then comes back online.

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

# Example 1: True Time-Based 24-h Rolling EPA PM2.5 Compliance on 5-Year Beijing Hourly Archive
bj = pd.read_csv(data_file("UCI_Beijing_PM25_Meteorology.csv"))
bj["Datetime"] = pd.to_datetime(bj[["year", "month", "day", "hour"]])
bj = bj.set_index("Datetime").sort_index()

# Time-window 24-hour rolling average requiring >= 18 valid hours (75% EPA completeness!)
bj["PM25_24h"] = bj["pm2.5"].rolling("24h", min_periods=18).mean()
monthly_pm = bj["pm2.5"].groupby(bj.index.to_period("M")).mean()
water_year = bj.index.year + (bj.index.month >= 10).astype(int)
annual_wy = bj["pm2.5"].groupby(water_year).mean()

daily_24h_peaks = bj["PM25_24h"].resample("D").max().dropna()
pct_us_naaqs_exceed = (daily_24h_peaks > 35.0).mean() * 100.0
pct_who_severe = (daily_24h_peaks > 150.0).mean() * 100.0

print("=== 5-Year Time-Series EPA Rolling 24-h PM2.5 Attainment Audit (Beijing) ===")
print(f"Valid 24-h Attainment Days : {len(daily_24h_peaks):,} days")
print(f"Days > 35 ug/m^3 (US EPA)  : {pct_us_naaqs_exceed:.1f}% | Severe > 150 ug/m^3 : {pct_who_severe:.1f}%")
print("\nWater-Year Mean PM2.5 (Oct 1 - Sep 30 Hydrological Grouping):")
for yr, val in annual_wy.items():
    print(f"  WY {yr}: {val:5.1f} ug/m^3")

# Plot 2013 severe winter haze episode cleanly with raw hourly vs smooth 24-h EPA rolling mean
win13 = bj.loc["2013-01-01":"2013-02-15"]
fig, ax = plt.subplots(figsize=(8.2, 3.8))
ax.plot(win13.index, win13["pm2.5"], color="#94a3b8", lw=0.8, alpha=0.85, label="Raw Hourly PM2.5")
ax.plot(win13.index, win13["PM25_24h"], color="#dc2626", lw=2.0, label="24-h Time Rolling Avg (min_periods=18)")
ax.axhline(35.0, color="#059669", ls="--", lw=1.4, label="US EPA 24-h Limit (35 ug/m^3)")
ax.set_title("Jan-Feb 2013 Beijing Winter Haze Episode (Hourly vs 24-h EPA Rolling Window)")
ax.set_ylabel("PM2.5 [ug/m^3]"); ax.grid(True, alpha=0.3); ax.legend(fontsize=8.5); fig.tight_layout()
Environmental Time Series — DatetimeIndex, EPA 24h/8h Rolling Attainment & Water Years (YS-OCT) Output Plot 1
=== 5-Year Time-Series EPA Rolling 24-h PM2.5 Attainment Audit (Beijing) ===
Valid 24-h Attainment Days : 1,761 days
Days > 35 ug/m^3 (US EPA)  : 91.1% | Severe > 150 ug/m^3 : 31.3%

Water-Year Mean PM2.5 (Oct 1 - Sep 30 Hydrological Grouping):
  WY 2010:  99.2 ug/m^3
  WY 2011:  98.6 ug/m^3
  WY 2012:  96.3 ug/m^3
  WY 2013: 101.3 ug/m^3
  WY 2014:  95.4 ug/m^3
  WY 2015: 108.3 ug/m^3
# Example 2: Diurnal Traffic Fingerprint (Weekday vs Weekend NO2 & Benzene in UCI Italy Air Quality)
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["Hour"] = aq["Datetime"].dt.hour
aq["DayType"] = np.where(aq["Datetime"].dt.dayofweek >= 5, "Weekend", "Weekday")
diurnal = aq.groupby(["DayType", "Hour"])[["CO(GT)", "C6H6(GT)", "NO2(GT)"]].mean()
wk_peak = int(diurnal.loc["Weekday", "C6H6(GT)"].idxmax())
print(f"\nItaly Weekday Commute Peak Benzene Hour = {wk_peak:02d}:00 ({diurnal.loc[('Weekday', wk_peak), 'C6H6(GT)']:.1f} ug/m^3) vs Weekend same hour ({diurnal.loc[('Weekend', wk_peak), 'C6H6(GT)']:.1f} ug/m^3)")
Italy Weekday Commute Peak Benzene Hour = 19:00 (20.4 ug/m^3) vs Weekend same hour (11.3 ug/m^3)

Concept Check Questions

  1. Explain the bug in df["pm2.5"].rolling(24).mean() if 10 hourly rows are missing from the CSV vs. df["pm2.5"].rolling("24h", min_periods=18).mean().
  2. What calendar boundary does resample("YS-OCT") represent in US hydrological engineering (USGS Water Year)?
  3. Why does checking weekday vs. weekend hourly pollutant cycles help air-quality engineers distinguish mobile commuter tailpipe traffic from stationary industrial smokestacks?

Guided Practice Problem 1: Flow-Weighted Mean Nutrient Load & Monthly Resampling Check

Synthesize 365 daily stream records (2025-01-01..2025-12-31) where spring flood storms elevate both flow \(Q\) and nitrate concentration (C_NO3), aggregate to monthly sums using .groupby(hyd.index.to_period("M")).sum(), and verify monthly Flow-Weighted Mean Concentration (Sum(Load)/Sum(Vol)) vs. naive monthly arithmetic mean!

# Guided Practice 1 Starter
rng = np.random.default_rng(7)
dates = pd.date_range("2025-01-01", periods=365, freq="D")
q_d = 12.0 + 35.0 * np.exp(-0.5 * ((np.arange(365) - 105) / 22.0) ** 2) + rng.exponential(2.0, 365)
c_d = 2.0 + 0.14 * q_d + rng.normal(0, 0.3, 365)
hyd = pd.DataFrame({"Q_m3s": q_d, "NO3_mgL": c_d, "Vol_m3": q_d * 86400.0, "Load_kg": q_d * 86400.0 * c_d * 1e-3}, index=dates)
mo = hyd.groupby(hyd.index.to_period("M")).sum()
mo["FWMC_mgL"] = mo["Load_kg"] * 1000.0 / mo["Vol_m3"]
print(f"Annual Arithmetic Mean = {hyd['NO3_mgL'].mean():.2f} mg/L vs Annual True FWMC = {hyd['Load_kg'].sum()*1e3/hyd['Vol_m3'].sum():.2f} mg/L")
print("Top 3 Spring Export Months (kg NO3-N):", mo["Load_kg"].nlargest(3).round(0).to_dict())
Annual Arithmetic Mean = 4.68 mg/L vs Annual True FWMC = 5.46 mg/L
Top 3 Spring Export Months (kg NO3-N): {Period('2025-04', 'M'): 1019674.0, Period('2025-05', 'M'): 497212.0, Period('2025-03', 'M'): 461645.0}