Lesson
36: Spatial Geostatistics — Inverse Distance Weighting
(IDW) & Experimental Semivariograms \(\gamma(h)\)
The “Boring Stuff” Problem: Turning 10 Monitoring Wells Into a Full Aquifer Contamination Map
Environmental monitoring budgets pay for 8 to 15 sampling wells across a watershed—NEVER 10,000! Geostatistics bridges sparse point assays to continuous spatial contours:
Inverse Distance Weighting (
IDW, \(p=2\)): \[\hat{Z}(x_0) = \frac{\sum_{i=1}^n Z_i / d_i^p}{\sum_{i=1}^n 1 / d_i^p}\] Exact Point Guard (d < 1e-9): When predicting right on top of Well \(i\),1 / d_i^pdivides by zero (inf/NaN)! Return \(Z_i\) verbatim whenever \(d_i < 10^{-9}\).Experimental Semivariogram \(\gamma(h)\): Measures how spatial correlation weakens with separation distance \(h\) (
Nuggetlab noise ->Sillplateau beyondRange): \[\gamma(h) = \frac{1}{2 N(h)} \sum_{(i,j)\in\text{bin}(h)} [Z(x_i) - Z(x_j)]^2\]
import numpy as np
import matplotlib.pyplot as plt
# Example 1: Aquifer Benzene/TCE Plume IDW Interpolation + Experimental Semivariogram
wells_xy = np.array([
[0.5, 2.0], [1.1, 2.3], [1.4, 1.5], [1.8, 2.8], [2.4, 2.1],
[2.9, 1.2], [3.3, 2.5], [3.8, 1.9], [4.2, 3.1], [4.6, 1.6],
[1.6, 3.6], [3.1, 3.5], [2.2, 0.8], [0.8, 0.9], [4.5, 2.8],
])
well_conc = np.array([18.0, 62.0, 95.0, 44.0, 72.0, 29.0, 38.0, 19.0, 11.0, 8.5, 22.0, 14.0, 25.0, 12.0, 9.0])
def idw_predict(grid_x, grid_y, pts_xy, vals, power=2.0):
gx_flat, gy_flat = grid_x.ravel()[:, None], grid_y.ravel()[:, None]
dists = np.sqrt((gx_flat - pts_xy[:, 0][None, :])**2 + (gy_flat - pts_xy[:, 1][None, :])**2)
zero_hit = dists < 1e-9
safe_d = np.where(zero_hit, 1.0, dists)
weights = 1.0 / (safe_d ** power)
z_hat = (weights @ vals) / weights.sum(axis=1)
# Restore exact measurements wherever zero_hit occurred
has_zero = zero_hit.any(axis=1)
if np.any(has_zero):
z_hat[has_zero] = vals[np.argmax(zero_hit[has_zero], axis=1)]
return z_hat.reshape(grid_x.shape)
gx = np.linspace(0.0, 5.0, 110)
gy = np.linspace(0.0, 4.2, 95)
GX, GY = np.meshgrid(gx, gy)
Z_idw = idw_predict(GX, GY, wells_xy, well_conc, power=2.0)
# Compute experimental isotropic semivariogram over 5 lag bins
dmat = np.sqrt((wells_xy[:, 0:1] - wells_xy[:, 0:1].T)**2 + (wells_xy[:, 1:2] - wells_xy[:, 1:2].T)**2)
sqdiff = 0.5 * (well_conc[:, None] - well_conc[None, :])**2
iu = np.triu_indices(len(well_conc), k=1)
pair_d, pair_g = dmat[iu], sqdiff[iu]
bins = np.linspace(0.4, 3.8, 7)
lag_centers, gamma_vals = [], []
for b0, b1 in zip(bins[:-1], bins[1:]):
mask = (pair_d >= b0) & (pair_d < b1)
if np.any(mask):
lag_centers.append(float(pair_d[mask].mean()))
gamma_vals.append(float(pair_g[mask].mean()))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 4.0))
cf = ax1.contourf(GX, GY, Z_idw, levels=16, cmap="YlOrRd")
plt.colorbar(cf, ax=ax1, label="TCE Plume Conc [ug/L]")
ax1.scatter(wells_xy[:, 0], wells_xy[:, 1], c="black", s=32, label="Monitoring Wells")
ax1.contour(GX, GY, Z_idw, levels=[5.0, 25.0, 50.0], colors=["#059669", "#0284c7", "#0f172a"], linewidths=1.3)
ax1.set_title("2D IDW (p=2) Aquifer Contaminant Plume Map"); ax1.set_xlabel("East [km]"); ax1.set_ylabel("North [km]"); ax1.legend()
ax2.plot(lag_centers, gamma_vals, "o-", color="#7c3aed", lw=2.2, markersize=7)
ax2.set_title("Empirical Isotropic Semivariogram gamma(h)"); ax2.set_xlabel("Lag Distance h [km]"); ax2.set_ylabel("Semivariance [(ug/L)^2]"); ax2.grid(True, alpha=0.3)
fig.tight_layout()
print("Lag h [km] -> Gamma [(ug/L)^2]:", [(round(h, 2), round(g, 1)) for h, g in zip(lag_centers, gamma_vals)])
Lag h [km] -> Gamma [(ug/L)^2]: [(0.78, 599.9), (1.27, 646.7), (1.85, 553.6), (2.32, 935.1), (2.96, 653.4), (3.46, 1104.5)]
Concept Check Questions
- Why did
idw_predictexplicitly protect againstdists < 1e-9? - Notice the semivariogram curve \(\gamma(h)\) rises at short lags (\(< 1.5\text{ km}\)) and levels off at longer distances: what do Range and Sill mean for planning new monitoring wells?
- What changes when you increase IDW exponent
powerfromp=1top=4?
Guided
Practice Problem 1: IDW Sensitivity (p=1 Smooth
vs. p=3 Local Pull)
Evaluate IDW arsenic/TCE prediction at candidate drinking-water well
location (2.0, 2.0) km across exponents
p = 1.0, 2.0, and 3.0, and check
whether ANY prediction falls near the 50 ug/L containment
target!
# Guided Practice 1 Starter
xq, yq = np.array([[2.0]]), np.array([[2.0]])
for p in [1.0, 2.0, 3.0]:
pred = idw_predict(xq, yq, wells_xy, well_conc, power=p)[0, 0]
print(f"IDW power p={p:.1f} at Well (2.0, 2.0) km -> Prediction = {pred:.2f} ug/L")IDW power p=1.0 at Well (2.0, 2.0) km -> Prediction = 43.94 ug/L
IDW power p=2.0 at Well (2.0, 2.0) km -> Prediction = 56.53 ug/L
IDW power p=3.0 at Well (2.0, 2.0) km -> Prediction = 65.35 ug/L