import time
from geolattice.geostatistics import sgsim
N_REPEATS = 3
N_TRAIN = 8000
PRED_SIZES = [500, 1000, 2000, 4000, 8000]
N_PRED_MAX = max(PRED_SIZES)
rng_sim = np.random.default_rng(42)
pad = 50.0
xmin, xmax = float(coords[:, 0].min()) - pad, float(coords[:, 0].max()) + pad
ymin, ymax = float(coords[:, 1].min()) - pad, float(coords[:, 1].max()) + pad
xy_train_all = rng_sim.uniform([xmin, ymin], [xmax, ymax], size=(N_TRAIN, 2))
xy_pred_all = rng_sim.uniform([xmin, ymin], [xmax, ymax], size=(N_PRED_MAX, 2))
df_cond = pd.DataFrame({
"x": coords[:, 0],
"y": coords[:, 1],
"log_zinc": np.log(zinc),
})
vario_sgs = [0, 0.05, 900.0, 900.0, float(np.var(np.log(zinc))), "exponential"]
print(f"Simulating {N_TRAIN:,} Meuse-like zinc locations with sgsim")
print(f" conditioning : {len(zinc)} samples from data/meuse.csv")
print(f" vario : azimuth=0, nugget=0.05, range=900 m, exponential, log(zinc) space")
t_sim0 = time.perf_counter()
sims = sgsim(
xy_train_all, df_cond, "x", "y", "log_zinc",
num_points=12, vario=vario_sgs, radius=2000,
kriging_type="ordinary", nsim=1, itrans=False, seed=42, quiet=True,
)
z_train_all = np.exp(np.asarray(sims[0], dtype=float))
print(f" sgsim wall : {time.perf_counter() - t_sim0:.1f} s (not included in IK times)")
print(f" simulated Zn : [{z_train_all.min():.0f}, {z_train_all.max():.0f}] ppm"
f" (Meuse observed [{zinc.min():.0f}, {zinc.max():.0f}])")
thresholds_sim = [float(t) for t in np.quantile(z_train_all, [0.25, 0.50, 0.75])]
variogram_params_sim = {t: (0.02, 0.20, 900.0) for t in thresholds_sim}
print(f" cutoffs : {[round(t, 1) for t in thresholds_sim]} ppm (quartiles)")
print()
def _time_ik(xy_train, z_train, xy_pred, use_gpu, repeats=N_REPEATS, warmup=True):
"""Median wall time of IndicatorKriging.fit + predict (k-NN, search_radius=None)."""
if warmup:
k_tr = min(40, len(xy_train))
k_pr = min(40, len(xy_pred))
IndicatorKriging(
cov_model="spherical", max_neighbors=12, search_radius=None, use_gpu=use_gpu,
).fit(xy_train[:k_tr], z_train[:k_tr]).predict(
xy_pred[:k_pr], thresholds_sim, variogram_params_sim
)
if use_gpu:
import cupy as cp
cp.cuda.Device(0).synchronize()
times = []
last = None
for _ in range(repeats):
t0 = time.perf_counter()
ik_m = IndicatorKriging(
cov_model="spherical", max_neighbors=12, search_radius=None, use_gpu=use_gpu,
)
ik_m.fit(xy_train, z_train)
last = ik_m.predict(xy_pred, thresholds_sim, variogram_params_sim)
if use_gpu:
import cupy as cp
cp.cuda.Device(0).synchronize()
times.append(time.perf_counter() - t0)
return float(np.median(times)), last
def _probs_match(a, b):
return all(
np.allclose(a[t], b[t], rtol=1e-4, atol=1e-4, equal_nan=True)
for t in thresholds_sim
)
print(f"GPU usable : {USE_GPU}")
print(f"Repeats : {N_REPEATS} (median wall time of IK fit + predict, k-NN)")
print(f"n_train : {N_TRAIN} (sgsim Meuse-like zinc)")
print(f"n_pred : {PRED_SIZES} (random locations in the Meuse bbox)")
print(f"thresholds : {len(thresholds_sim)} quartile cutoffs; max_neighbors=12")
print()
rows = []
for n_pred in PRED_SIZES:
xy_pr = xy_pred_all[:n_pred]
cpu_t, pred_cpu = _time_ik(xy_train_all, z_train_all, xy_pr, use_gpu=False)
row = {
"dataset": "Meuse (sgsim)",
"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_ik(xy_train_all, z_train_all, xy_pr, use_gpu=True)
row["GPU (s)"] = gpu_t
row["speedup"] = cpu_t / gpu_t
row["match"] = bool(_probs_match(pred_cpu, pred_gpu))
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))
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("Number of prediction points $n_{\\mathrm{pred}}$")
axes[0].set_ylabel("Median time (ms)")
axes[0].set_title("IndicatorKriging.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("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()