import time
N_REPEATS = 3
PRED_SIZES = [500, 1000, 2000, 4000, 8000]
N_PRED_MAX = max(PRED_SIZES)
K = 16
RATE_BASE = 100000.0
df_lbc = pd.read_csv(DATA_DIR / "LBC_1998_2012_USA.csv")
gdf_cty = gpd.read_file(DATA_DIR / "US_COUNTY.shp")
df_pop = pd.read_csv(DATA_DIR / "usa_diabetes_data.csv")[["FIPS", "POP_Total"]]
df_lbc["FIPS"] = df_lbc["FIPS"].astype(int)
gdf_cty["FIPS"] = gdf_cty["FIPS"].astype(int)
df_pop["FIPS"] = df_pop["FIPS"].astype(int)
joined = gdf_cty.merge(df_lbc, on="FIPS", how="inner")
joined = joined.merge(df_pop, on="FIPS", how="inner")
joined = joined.dropna(subset=["LBC_MORTALITY_RATE", "POP_Total", "X", "Y", "Year"])
joined = joined[joined["POP_Total"] > 0].copy()
xy_train = joined[["X", "Y"]].to_numpy(dtype=float)
t_train = joined["Year"].to_numpy(dtype=float)
z_train = joined["LBC_MORTALITY_RATE"].to_numpy(dtype=float)
pop_train = joined["POP_Total"].to_numpy(dtype=float)
n_train = len(xy_train)
n_counties = joined["FIPS"].nunique()
n_years = joined["Year"].nunique()
xmin, ymin, xmax, ymax = gdf_cty.total_bounds
rng_sim = np.random.default_rng(42)
xy_pred_all = rng_sim.uniform([xmin, ymin], [xmax, ymax], size=(N_PRED_MAX, 2))
t_pred_all = rng_sim.uniform(1998.0, 2012.0, size=N_PRED_MAX)
# Hold ST model fixed (Atlantic-scale metric params); fitting is not timed.
st_model = vgm_st(
"metric",
joint=vgm(psill=124.60, model="exponential", range_=575681.0, nugget=79.61),
st_ani=53938.0,
)
print("USA county LBC mortality (k-NN ST Poisson kriging)")
print(f" counties : {n_counties:,} joined on FIPS "
f"(LBC_1998_2012_USA.csv + US_COUNTY.shp + usa_diabetes POP_Total)")
print(f" area-years : {n_train:,} ({n_counties} × {n_years} years)")
print(f" LBC rate : [{z_train.min():.1f}, {z_train.max():.1f}] per 100,000")
print(" ST model : metric Exp nugget=79.61 sill=124.60 range=575681 m stAni=53938 m/yr")
print(" CRS : NAD 1983 Albers (metres)")
print()
def _time_stpk(xy_pr, t_pr, use_gpu, repeats=N_REPEATS, warmup=True):
"""Median wall time of STPoissonKriging.fit + predict (k-NN)."""
def _run():
stpk = STPoissonKriging(st_model, rate_base=RATE_BASE, use_gpu=use_gpu).fit(
xy_train, t_train, z_train, pop_train,
)
return stpk.predict(xy_pr, t_pr, number_of_neighbors=K)
if warmup:
k_pr = min(40, len(xy_pr))
STPoissonKriging(st_model, rate_base=RATE_BASE, use_gpu=use_gpu).fit(
xy_train, t_train, z_train, pop_train,
).predict(xy_pred_all[:k_pr], t_pred_all[:k_pr], number_of_neighbors=K)
if use_gpu:
import cupy as cp
cp.cuda.Device(0).synchronize()
times = []
last = None
for _ in range(repeats):
t0 = time.perf_counter()
last = _run()
if use_gpu:
import cupy as cp
cp.cuda.Device(0).synchronize()
times.append(time.perf_counter() - t0)
return float(np.median(times)), last
print(f"GPU usable : {USE_GPU}")
print(f"Repeats : {N_REPEATS} (median wall time of fit+predict, k-NN)")
print(f"n_train : {n_train} (USA LBC county-years)")
print(f"n_pred : {PRED_SIZES} (random (x,y,t) in the US_COUNTY bbox × 1998-2012)")
print(f"neighbors : {K}; rate_base={RATE_BASE:.0f}")
print()
rows = []
for n_pred in PRED_SIZES:
xy_pr = xy_pred_all[:n_pred]
t_pr = t_pred_all[:n_pred]
cpu_t, pred_cpu = _time_stpk(xy_pr, t_pr, use_gpu=False)
row = {
"dataset": "USA LBC",
"n_train": n_train,
"n_pred": n_pred,
"CPU (s)": cpu_t,
"GPU (s)": np.nan,
"speedup": np.nan,
"match": "n/a",
}
if USE_GPU:
gpu_t, pred_gpu = _time_stpk(xy_pr, t_pr, use_gpu=True)
row["GPU (s)"] = gpu_t
row["speedup"] = cpu_t / gpu_t
row["match"] = bool(
np.allclose(pred_cpu[0], pred_gpu[0], rtol=1e-4, atol=1e-4)
and np.allclose(pred_cpu[1], pred_gpu[1], rtol=1e-4, atol=1e-4, equal_nan=True)
)
import cupy as cp
cp.get_default_memory_pool().free_all_blocks()
rows.append(row)
df_bench = pd.DataFrame(rows)
df_show = df_bench.copy()
df_show["CPU (ms)"] = (df_show["CPU (s)"] * 1000).round(1)
df_show["GPU (ms)"] = (df_show["GPU (s)"] * 1000).round(1)
df_show["speedup"] = df_show["speedup"].map(
lambda x: "n/a" if pd.isna(x) else f"{x:.2f}×"
)
print(df_show[["dataset", "n_train", "n_pred", "CPU (ms)", "GPU (ms)", "speedup", "match"]].to_string(index=False))
print()
fig, axes = plt.subplots(1, 2, figsize=(12, 4.2))
n_vals = df_bench["n_pred"].to_numpy()
cpu_ms = df_bench["CPU (s)"].to_numpy() * 1000
gpu_ms = df_bench["GPU (s)"].to_numpy() * 1000
labels = [str(int(n)) for n in n_vals]
x = np.arange(len(n_vals))
w = 0.36
axes[0].bar(x - w / 2, cpu_ms, w, label="CPU (NumPy)", color="steelblue")
if USE_GPU and np.isfinite(gpu_ms).all():
axes[0].bar(x + w / 2, gpu_ms, w, label="GPU (CuPy)", color="darkorange")
axes[0].set_xticks(x)
axes[0].set_xticklabels(labels, fontsize=9)
axes[0].set_xlabel(r"Number of prediction points $n_{\mathrm{pred}}$")
axes[0].set_ylabel("Median time (ms)")
axes[0].set_title("STPoissonKriging.predict (k-NN): CPU vs GPU")
axes[0].legend()
axes[0].set_yscale("log")
if USE_GPU:
axes[1].plot(n_vals, df_bench["speedup"], "o-", color="darkgreen", lw=2)
axes[1].axhline(1.0, color="grey", ls="--", lw=1)
axes[1].set_xlabel(r"Number of prediction points $n_{\mathrm{pred}}$")
axes[1].set_ylabel("Speedup (CPU time / GPU time)")
axes[1].set_title("GPU speedup vs prediction size")
axes[1].grid(True, alpha=0.3)
else:
axes[1].text(
0.5, 0.5,
"GPU not usable in this environment\nCPU-only timings shown",
ha="center", va="center", transform=axes[1].transAxes,
)
axes[1].set_axis_off()
plt.tight_layout()
plt.show()