import time
N_REPEATS = 3
PRED_SIZES = [500, 1000, 2000, 4000, 8000]
rng_sim = np.random.default_rng(7)
nx_h, ny_h = 16, 16
n_holes = nx_h * ny_h
gx, gy = np.meshgrid(np.linspace(8.0, 92.0, nx_h), np.linspace(8.0, 92.0, ny_h))
hole_x = np.clip(gx.ravel() + rng_sim.uniform(-2.0, 2.0, n_holes), 5.0, 95.0)
hole_y = np.clip(gy.ravel() + rng_sim.uniform(-2.0, 2.0, n_holes), 5.0, 95.0)
depths = np.arange(1.0, 40.0, 1.8)
dz = float(np.diff(depths).mean())
hole_id, Xb, Yb, Zb = [], [], [], []
for i in range(n_holes):
for d in depths:
hole_id.append(i)
Xb.append(hole_x[i]); Yb.append(hole_y[i]); Zb.append(d)
Xb, Yb, Zb = np.asarray(Xb), np.asarray(Yb), np.asarray(Zb)
n_train = len(Xb)
# 2-D spherical GP on collars (Cholesky of 256 x 256)
P2 = np.column_stack([hole_x, hole_y])
dxy = np.sqrt(((P2[:, None, :] - P2[None, :, :]) ** 2).sum(-1))
hr = dxy / 25.0
C2 = np.where(hr < 1.0, 1.0 * (1.0 - 1.5 * hr + 0.5 * hr ** 3), 0.0)
np.fill_diagonal(C2, 1.05)
L2 = np.linalg.cholesky(C2 + 1e-8 * np.eye(n_holes))
collar = L2 @ rng_sim.standard_normal(n_holes)
rho = float(np.exp(-3.0 * dz / 8.0))
resid = np.empty(n_train)
j = 0
for i in range(n_holes):
e = collar[i]
for _ in depths:
e = rho * e + np.sqrt(max(1.0 - rho ** 2, 0.0)) * rng_sim.standard_normal()
resid[j] = e
j += 1
grade = (
2.0
+ 8.0 * np.exp(-((Xb - 50) ** 2 + (Yb - 50) ** 2) / (2 * 25.0 ** 2))
* np.exp(-(Zb - 18) ** 2 / (2 * 9.0 ** 2))
+ resid
)
bh_big = pd.DataFrame({"X": Xb, "Y": Yb, "Z": Zb, "Grade": grade})
VARIOGRAM_BENCH = {
"nugget": 0.05,
"structures": [{"type": "spherical", "sill": 1.0, "range": 25.0,
"range2": 25.0, "range3": 8.0}],
}
pts_all = np.column_stack([
rng_sim.uniform(5.0, 95.0, max(PRED_SIZES)),
rng_sim.uniform(5.0, 95.0, max(PRED_SIZES)),
rng_sim.uniform(1.0, 39.0, max(PRED_SIZES)),
])
print(f"Simulated borehole campaign: {n_train:,} assays from {n_holes} holes "
f"({nx_h}×{ny_h} collars × {len(depths)} intervals)")
print(f" vertical AR(1) ρ = {rho:.3f} (Δz = {dz:.2f} m, a_v = 8 m)")
print(f" Grade range : [{grade.min():.2f}, {grade.max():.2f}]")
print()
def _time_kt3d(data, points, use_gpu, repeats=N_REPEATS, warmup=True):
kw = dict(
x="X", y="Y", z="Z", value="Grade", points=points,
variogram=VARIOGRAM_BENCH, ktype="ordinary",
search_radius=25.0, search_radius3=10.0, ndmin=2, ndmax=12,
use_gpu=use_gpu,
)
if warmup:
k = min(40, len(points))
kt3d(data, **{**kw, "points": points[: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 = kt3d(data, **kw)
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 kt3d ordinary point kriging)")
print(f"n_train : {n_train} (simulated borehole grade)")
print(f"n_pred : {PRED_SIZES}")
print("ktype : ordinary ndmax=12 noct=0 (batched SK/OK path)")
print()
rows = []
for n_pred in PRED_SIZES:
pts = pts_all[:n_pred]
cpu_t, pred_cpu = _time_kt3d(bh_big, pts, use_gpu=False)
row = {
"dataset": "Borehole (sim)",
"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_kt3d(bh_big, pts, use_gpu=True)
row["GPU (s)"] = gpu_t
row["speedup"] = cpu_t / gpu_t
z_c, v_c = pred_cpu["estimate"].to_numpy(), pred_cpu["variance"].to_numpy()
z_g, v_g = pred_gpu["estimate"].to_numpy(), pred_gpu["variance"].to_numpy()
row["match"] = bool(
np.allclose(z_c, z_g, rtol=1e-4, atol=1e-4, equal_nan=True)
and np.allclose(v_c, v_g, 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))
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("kt3d ordinary point kriging: 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()