import time
N_REPEATS = 3
N_TRAIN = 8000
PRED_SIZES = [500, 1000, 2000, 4000, 8000]
N_PRED_MAX = max(PRED_SIZES)
HARD_FRAC = 0.20
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,
)
log_cd_sim = np.asarray(sims[0], dtype=float)
cd_sim = np.exp(log_cd_sim)
print(f" sgsim wall : {time.perf_counter() - t_sim0:.1f} s (not included in SoftKriging times)")
print(f" simulated Cd : [{cd_sim.min():.2f}, {cd_sim.max():.2f}] mg/kg"
f" (Jura observed [{cd.min():.2f}, {cd.max():.2f}])")
rho = float(np.corrcoef(np.log(cd), np.log(zn))[0, 1])
z_cd = (log_cd_sim - log_cd_sim.mean()) / log_cd_sim.std()
eps = rng_sim.normal(size=N_TRAIN)
z_zn = rho * z_cd + np.sqrt(max(1.0 - rho ** 2, 0.0)) * eps
zn_sim = np.exp(np.log(zn).mean() + np.log(zn).std() * z_zn)
print(f" corr(log Cd, log Zn) simulated = {np.corrcoef(np.log(cd_sim), np.log(zn_sim))[0, 1]:.3f}"
f" (Jura {rho:.3f})")
ind_all = indicator_transform(cd_sim, THRESHOLD, exceed=True)
pos = np.where(ind_all == 1)[0]
neg = np.where(ind_all == 0)[0]
rng_split = np.random.default_rng(42)
rng_split.shuffle(pos)
rng_split.shuffle(neg)
n_h_pos = max(1, int(round(HARD_FRAC * len(pos))))
n_h_neg = max(1, int(round(HARD_FRAC * len(neg))))
hard_idx_s = np.concatenate([pos[:n_h_pos], neg[:n_h_neg]])
soft_idx_s = np.concatenate([pos[n_h_pos:], neg[n_h_neg:]])
xy_hard_s = xy_train_all[hard_idx_s]
ind_hard_s = ind_all[hard_idx_s]
zn_hard_s = zn_sim[hard_idx_s]
xy_soft_s = xy_train_all[soft_idx_s]
zn_soft_s = zn_sim[soft_idx_s]
soft_model_s, soft_prob_hard_s = fit_soft_probability_model(
zn_hard_s, ind_hard_s, proxy_values_pred=zn_hard_s,
)
soft_prob_soft_s = soft_model_s.predict_proba(zn_soft_s.reshape(-1, 1))[:, 1]
B_s, corr_if, n_pairs_s = markov_bayes_calibrate(
xy_hard_s, ind_hard_s, xy_hard_s, soft_prob_hard_s,
)
print(f" n_hard / n_soft : {len(hard_idx_s)} / {len(soft_idx_s)}")
print(f" exceedance rate : {ind_all.mean():.3f} (Jura {indicator_all.mean():.3f})")
print(f" Markov-Bayes B : {B_s:.3f} (corr(I,F)={corr_if:.3f}, n_pairs={n_pairs_s})")
NUGGET_T, SILL_T, RANGE_T = 0.05, 0.20, 1.2
print()
def _time_sk(xy_h, ind_h, xy_s, f_s, B_val, xy_pred, use_gpu, repeats=N_REPEATS, warmup=True):
"""Median wall time of SoftKriging.fit + predict (k-NN, search_radius=None)."""
kw = dict(
cov_model="exponential",
max_neighbors_hard=12,
max_neighbors_soft=12,
search_radius=None,
use_gpu=use_gpu,
)
if warmup:
k_h = min(40, len(xy_h))
k_s = min(40, len(xy_s))
k_pr = min(40, len(xy_pred))
SoftKriging(**kw).fit(
xy_h[:k_h], ind_h[:k_h], xy_s[:k_s], f_s[:k_s], B=B_val,
).predict(xy_pred[:k_pr], sill=SILL_T, range_=RANGE_T, nugget=NUGGET_T, 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()
sk = SoftKriging(**kw)
sk.fit(xy_h, ind_h, xy_s, f_s, B=B_val)
last = sk.predict(xy_pred, sill=SILL_T, range_=RANGE_T, nugget=NUGGET_T, 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 SoftKriging fit + predict, k-NN)")
print(f"n_hard : {len(hard_idx_s)} n_soft: {len(soft_idx_s)} (sgsim Jura-like Cd + Zn)")
print(f"n_pred : {PRED_SIZES} (random locations in the Jura bbox)")
print(f"neighbors : hard=12, soft=12; exponential nugget={NUGGET_T}, sill={SILL_T}, range={RANGE_T} km")
print()
rows = []
for n_pred in PRED_SIZES:
xy_pr = xy_pred_all[:n_pred]
cpu_t, pred_cpu = _time_sk(
xy_hard_s, ind_hard_s, xy_soft_s, soft_prob_soft_s, B_s, xy_pr, use_gpu=False,
)
row = {
"dataset": "Jura (sgsim)",
"n_hard": len(hard_idx_s),
"n_soft": len(soft_idx_s),
"n_pred": n_pred,
"CPU (s)": cpu_t,
"GPU (s)": np.nan,
"speedup": np.nan,
"match": "—",
}
if USE_GPU:
gpu_t, pred_gpu = _time_sk(
xy_hard_s, ind_hard_s, xy_soft_s, soft_prob_soft_s, B_s, xy_pr, use_gpu=True,
)
row["GPU (s)"] = gpu_t
row["speedup"] = cpu_t / gpu_t
p_c, v_cpu = pred_cpu
p_g, v_gpu = pred_gpu
row["match"] = bool(
np.allclose(p_c, p_g, rtol=1e-4, atol=1e-4, equal_nan=True)
and np.allclose(v_cpu, v_gpu, 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_hard", "n_soft", "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(r"Number of prediction points $n_{\mathrm{pred}}$")
axes[0].set_ylabel("Median time (ms)")
axes[0].set_title("SoftKriging.predict (k-NN Markov–Bayes) — 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()