import time
N_REPEATS = 3
N_TRAIN = 8000
PRED_SIZES = [500, 1000, 2000, 4000, 8000]
N_PRED_MAX = max(PRED_SIZES)
N_NEIGHBORS = 30
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_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_cd": np.log(cd),
})
log_cd_var = float(np.var(np.log(cd)))
vario_sgs = [0, 0.05 * log_cd_var, 1.2, 1.2, log_cd_var, "exponential"]
print(f"Simulating {N_TRAIN:,} Jura-like Cd locations with sgsim")
print(f" conditioning : {len(cd)} samples from data/jura_data.csv")
print(f" vario : azimuth=0, nugget={vario_sgs[1]:.3f}, range=1.2 km, exponential, log(Cd)")
t_sim0 = time.perf_counter()
sims = sgsim(
xy_train_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,
)
cd_sim = np.exp(np.asarray(sims[0], dtype=float))
print(f" sgsim wall : {time.perf_counter() - t_sim0:.1f} s (not included in FactorialKriging times)")
print(f" simulated Cd : [{cd_sim.min():.2f}, {cd_sim.max():.2f}] mg/kg"
f" (Jura observed [{cd.min():.2f}, {cd.max():.2f}])")
print()
def _extract_workload(fk, xy_pred):
z_tot, var = fk.extract(xy_pred, factor="total", return_variance=True)
z1 = fk.extract(xy_pred, factor=1)
z2 = fk.extract(xy_pred, factor=2)
return z_tot, var, z1, z2
def _time_fk(xy_train, z_train, xy_pred, use_gpu, repeats=N_REPEATS, warmup=True):
"""Median wall time of FactorialKriging.fit + extract (k-NN, search_radius=None)."""
kw = dict(
nugget=nugget,
structures=structures,
max_neighbors=N_NEIGHBORS,
search_radius=None,
use_gpu=use_gpu,
)
if warmup:
k_tr = min(40, len(xy_train))
k_pr = min(40, len(xy_pred))
fk_w = FactorialKriging(**kw)
fk_w.fit(xy_train[:k_tr], z_train[:k_tr])
_extract_workload(fk_w, xy_pred[:k_pr])
if use_gpu:
import cupy as cp
cp.cuda.Device(0).synchronize()
times = []
last = None
for _ in range(repeats):
t0 = time.perf_counter()
fk = FactorialKriging(**kw)
fk.fit(xy_train, z_train)
last = _extract_workload(fk, xy_pred)
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 FactorialKriging fit + extract, k-NN)")
print(f"n_train : {N_TRAIN} (sgsim Jura-like Cd)")
print(f"n_pred : {PRED_SIZES} (random locations in the Jura bbox)")
print(f"neighbors : max_neighbors={N_NEIGHBORS}; nested model from §7 (359 Jura samples)")
print()
rows = []
for n_pred in PRED_SIZES:
xy_pr = xy_pred_all[:n_pred]
cpu_t, pred_cpu = _time_fk(xy_train_all, cd_sim, xy_pr, use_gpu=False)
row = {
"dataset": "Jura (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_fk(xy_train_all, cd_sim, xy_pr, use_gpu=True)
row["GPU (s)"] = gpu_t
row["speedup"] = cpu_t / gpu_t
match = True
for a, b in zip(pred_cpu, pred_gpu):
match = match and bool(np.allclose(a, b, rtol=1e-4, atol=1e-4, equal_nan=True))
row["match"] = match
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("FactorialKriging.extract: 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()