import time
N_REPEATS = 3
N_SIM = 8000
N_PRED = 500
N_HERMITE_T = 8
TRAIN_SIZES = [500, 1000, 2000, 4000, 6000]
rng_sim = np.random.default_rng(42)
pad = 0.15
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_all = rng_sim.uniform([xmin, ymin], [xmax, ymax], size=(N_SIM, 2))
xy_pred_t = rng_sim.uniform([xmin, ymin], [xmax, ymax], size=(N_PRED, 2))
df_cond = pd.DataFrame({"x": coords[:, 0], "y": coords[:, 1], "log_cd": np.log(z)})
log_cd_var = float(np.var(np.log(z)))
vario_sgs = [0, 0.05 * log_cd_var, 1.2, 1.2, log_cd_var, "exponential"]
print(f"Simulating {N_SIM:,} Jura-like Cd locations with sgsim")
print(f" conditioning : {len(z)} samples from data/jura_data.csv")
print(f" vario : azimuth=0, nugget={0.05 * log_cd_var:.3f}, range=1.2 km, exponential, log(Cd)")
t0 = time.perf_counter()
sims = sgsim(
xy_all, df_cond, "x", "y", "log_cd",
num_points=12, vario=vario_sgs, radius=2.5,
kriging_type="ordinary", nsim=1, itrans=False, seed=42, quiet=True,
)
sgsim_s = time.perf_counter() - t0
cd_sim = np.exp(np.asarray(sims[0], dtype=float))
print(f" sgsim wall : {sgsim_s:.1f} s (not included in DisjunctiveKriging times)")
print(f" simulated Cd : [{cd_sim.min():.2f}, {cd_sim.max():.2f}] mg/kg "
f"(Jura observed [{z.min():.2f}, {z.max():.2f}])")
print()
def _time_dk(xy_train, z_train, xy_pred, use_gpu, repeats=N_REPEATS, warmup=True):
"""Median wall time of DisjunctiveKriging.fit + predict(return_variance=True)."""
kw = dict(
model="spherical", n_hermite=N_HERMITE_T, tails="linear",
use_gpu=use_gpu, variogram_kwargs={"n_lags": 12, "estimator": "matheron"},
)
if warmup:
k_tr = min(40, len(xy_train))
k_pr = min(40, len(xy_pred))
DisjunctiveKriging(**kw).fit(xy_train[:k_tr], z_train[:k_tr]).predict(
xy_pred[:k_pr], return_variance=True
)
if use_gpu:
import cupy as cp
cp.cuda.Device(0).synchronize()
times = []
last = None
for _ in range(repeats):
t0 = time.perf_counter()
dk_m = DisjunctiveKriging(**kw).fit(xy_train, z_train)
last = dk_m.predict(xy_pred, return_variance=True)
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 DK fit + predict)")
print(f"n_hermite : {N_HERMITE_T} (timing only; mapping in §6 uses N=20)")
print(f"n_pred : {N_PRED} locations drawn in the Jura bbox")
print(f"n_train : {TRAIN_SIZES} (prefixes of the {N_SIM:,} sgsim locations)")
print()
rows = []
for n in TRAIN_SIZES:
xy_tr, z_tr = xy_all[:n], cd_sim[:n]
cpu_t, pred_cpu = _time_dk(xy_tr, z_tr, xy_pred_t, use_gpu=False)
row = {
"dataset": "Jura (sgsim)",
"n_train": n,
"n_pred": N_PRED,
"CPU (s)": cpu_t,
"GPU (s)": np.nan,
"speedup": np.nan,
"match": "—",
}
if USE_GPU:
gpu_t, pred_gpu = _time_dk(xy_tr, z_tr, xy_pred_t, use_gpu=True)
row["GPU (s)"] = gpu_t
row["speedup"] = cpu_t / gpu_t
z_c, se_c = pred_cpu
z_g, se_g = pred_gpu
row["match"] = bool(
np.allclose(z_c, z_g, rtol=1e-4, atol=1e-4, equal_nan=True)
and np.allclose(se_c, se_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: "—" 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_train"].to_numpy()
cpu_ms = df_bench["CPU (s)"].to_numpy() * 1000
gpu_ms = df_bench["GPU (s)"].to_numpy() * 1000
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([str(int(n)) for n in n_vals], fontsize=9)
axes[0].set_xlabel(r"Number of training points $n_{\mathrm{train}}$")
axes[0].set_ylabel("Median time (ms)")
axes[0].set_title("DisjunctiveKriging.fit + predict — 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 training points $n_{\mathrm{train}}$")
axes[1].set_ylabel("Speedup (CPU time / GPU time)")
axes[1].set_title("GPU speedup vs training 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()