Map the values between the sites
Kriging turns a fitted semivariogram into predictions everywhere on a map, with a standard error for each, and leave-one-out shows whether both hold up.
What runs in CodeSplash
- Kriging (ordinary, universal, Gaussian process) Verified in Python and R
You will be able to
- Say how ordinary kriging weights nearby sites, and what its standard error depends on
- Choose between ordinary kriging, universal kriging and a Gaussian process
- Read leave-one-out RMSE and the mean squared standardized error
Read first
From resemblance to a map
ReadThe semivariogram said how far resemblance reaches. Ordinary krigingOrdinary krigingPredicts a value between sites as a weighted mean of nearby sites, weights set by the semivariogram, with a standard error. uses it to predict a value anywhere: a weighted mean of the sites, with weights chosen so the prediction is unbiased and its error as small as possible.
Close sites get large weights and far ones small. Sites that sit together share their weight, because they carry overlapping information.
How sure is each prediction?
PredictPredict first
Kriging gives a standard errorKriging standard errorHow uncertain a kriged prediction is: small near sites, large far from them; it depends on where sites are, not their values. for every point on the grid. Where do you expect it to be largest?
Reveal
Far from every site. The kriging standard error depends on where the sites are and on the semivariogram, not on the values measured. At a site it is zero, and kriging returns the measured value.
Krige the Meuse floodplain
In the appLOO RMSE = 0.396, R² = 0.70, MSSE = 0.80, n = 155
- LOO RMSE
- 0.3965
- LOO R²
- 0.6964
- Mean squared standardized error
- 0.8027
Assumptions
- Enough pairs per distance — The smallest distance class has 52 pairs, enough to be stable.
- Standard errors match the errors — Left-out sites' squared errors are 0.80 times their predicted variances on average (near 1: the standard errors are about right).
Semivariogram model
| Setting | Value |
|---|---|
| Nugget | 0.0616 |
| Partial sill | 0.5898 |
| Sill | 0.6514 |
| Range parameter | 942.52 |
| Practical range | 942.52 |
Leave-one-out predictions at the sites
| x | y | Observed | Left-out prediction | Standard error | Standardized error |
|---|---|---|---|---|---|
| 181,072 | 333,611 | 6.930 | 6.755 | 0.4378 | 0.3987 |
| 181,025 | 333,558 | 7.040 | 6.754 | 0.4307 | 0.6623 |
| 181,165 | 333,537 | 6.461 | 6.300 | 0.4366 | 0.3706 |
| 181,298 | 333,484 | 5.549 | 6.047 | 0.4852 | −1.026 |
| 181,307 | 333,330 | 5.595 | 5.589 | 0.4285 | 0.0143 |
| 181,390 | 333,260 | 5.638 | 5.430 | 0.4890 | 0.4263 |
| 181,165 | 333,370 | 5.846 | 5.879 | 0.4300 | −0.0766 |
| 181,027 | 333,363 | 6.006 | 6.407 | 0.4265 | −0.9401 |
| 181,060 | 333,231 | 5.849 | 5.812 | 0.3740 | 0.0997 |
| 181,232 | 333,168 | 5.209 | 5.391 | 0.4054 | −0.4474 |
| 181,191 | 333,115 | 5.242 | 5.317 | 0.4045 | −0.1870 |
| 181,032 | 333,031 | 5.525 | 5.517 | 0.4394 | 0.0202 |
| 180,874 | 333,339 | 6.999 | 6.681 | 0.4463 | 0.7144 |
| 180,969 | 333,252 | 6.223 | 6.212 | 0.3959 | 0.0277 |
| 181,011 | 333,161 | 5.787 | 5.819 | 0.3977 | −0.0818 |
| 180,830 | 333,246 | 6.939 | 6.562 | 0.4294 | 0.8778 |
| 180,763 | 333,104 | 6.407 | 6.479 | 0.4400 | −0.1648 |
| 180,694 | 332,972 | 6.567 | 6.344 | 0.4332 | 0.5140 |
| 180,625 | 332,847 | 6.600 | 6.477 | 0.4227 | 0.2913 |
| 180,555 | 332,707 | 6.958 | 6.696 | 0.4278 | 0.6145 |
| 180,642 | 332,708 | 6.512 | 6.347 | 0.3751 | 0.4388 |
| 180,704 | 332,717 | 5.996 | 6.078 | 0.3759 | −0.2162 |
| 180,704 | 332,664 | 5.838 | 6.108 | 0.3899 | −0.6927 |
| 181,153 | 332,925 | 5.384 | 5.246 | 0.4301 | 0.3214 |
| 181,147 | 332,823 | 5.298 | 5.281 | 0.3821 | 0.0456 |
| 181,167 | 332,778 | 5.268 | 5.282 | 0.4041 | −0.0348 |
| 181,008 | 332,777 | 5.333 | 5.317 | 0.4031 | 0.0385 |
| 180,973 | 332,687 | 5.193 | 5.349 | 0.4155 | −0.3760 |
| 180,916 | 332,753 | 5.481 | 5.379 | 0.4057 | 0.2503 |
| 181,352 | 332,946 | 5.193 | 5.312 | 0.5516 | −0.2162 |
| 181,133 | 332,570 | 5.338 | 5.325 | 0.5275 | 0.0230 |
| 180,878 | 332,489 | 5.288 | 5.439 | 0.4044 | −0.3723 |
| 180,829 | 332,450 | 5.521 | 5.496 | 0.4036 | 0.0643 |
| 180,954 | 332,399 | 5.257 | 5.340 | 0.4153 | −0.1988 |
| 180,956 | 332,318 | 5.361 | 5.330 | 0.4703 | 0.0663 |
| 180,710 | 332,330 | 5.771 | 5.521 | 0.4614 | 0.5422 |
| 180,632 | 332,445 | 6.344 | 5.999 | 0.4387 | 0.7861 |
| 180,530 | 332,538 | 6.725 | 6.646 | 0.4009 | 0.1982 |
| 180,478 | 332,578 | 6.809 | 6.967 | 0.4107 | −0.3836 |
| 180,383 | 332,476 | 7.282 | 6.760 | 0.4564 | 1.144 |
First 40 of 50 rows.
Predictions on the grid
| x | y | Prediction | Standard error | 95% low | 95% high | Nearest site |
|---|---|---|---|---|---|---|
| 178,605 | 329,714 | 6.420 | 0.6390 | 5.168 | 7.672 | 210.77 |
| 178744.25 | 329,714 | 6.539 | 0.5301 | 5.500 | 7.578 | 115.79 |
| 178883.50 | 329,714 | 6.498 | 0.4869 | 5.543 | 7.452 | 141.78 |
| 179022.75 | 329,714 | 6.390 | 0.3731 | 5.659 | 7.122 | 19.041 |
| 179,162 | 329,714 | 6.309 | 0.4275 | 5.471 | 7.147 | 83 |
| 179301.25 | 329,714 | 6.309 | 0.4153 | 5.495 | 7.123 | 56.250 |
| 179440.50 | 329,714 | 6.121 | 0.4771 | 5.186 | 7.057 | 93.109 |
| 179579.75 | 329,714 | 5.906 | 0.5690 | 4.791 | 7.022 | 163.73 |
| 179,719 | 329,714 | 5.895 | 0.6631 | 4.595 | 7.194 | 282.20 |
| 179858.25 | 329,714 | 6.017 | 0.7341 | 4.578 | 7.456 | 382.22 |
| 179997.50 | 329,714 | 6.107 | 0.7796 | 4.579 | 7.635 | 501.33 |
| 180136.75 | 329,714 | 6.144 | 0.8027 | 4.570 | 7.717 | 628.77 |
| 180,276 | 329,714 | 6.160 | 0.8072 | 4.578 | 7.742 | 591.42 |
| 180415.25 | 329,714 | 6.105 | 0.8000 | 4.537 | 7.673 | 520.97 |
| 180554.50 | 329,714 | 6.001 | 0.7913 | 4.451 | 7.552 | 481.49 |
| 180693.75 | 329,714 | 5.930 | 0.7900 | 4.382 | 7.479 | 480.66 |
| 180,833 | 329,714 | 5.926 | 0.7988 | 4.360 | 7.492 | 518.66 |
| 180972.25 | 329,714 | 5.969 | 0.8128 | 4.376 | 7.562 | 588.03 |
| 181111.50 | 329,714 | 6.008 | 0.8248 | 4.392 | 7.625 | 679.20 |
| 181250.75 | 329,714 | 6.041 | 0.8311 | 4.412 | 7.670 | 784.63 |
| 181,390 | 329,714 | 6.059 | 0.8330 | 4.427 | 7.692 | 899.30 |
| 178,605 | 329848.38 | 6.380 | 0.6077 | 5.189 | 7.571 | 182.91 |
| 178744.25 | 329848.38 | 6.496 | 0.4383 | 5.637 | 7.355 | 49.386 |
| 178883.50 | 329848.38 | 6.332 | 0.4524 | 5.445 | 7.219 | 101.01 |
| 179022.75 | 329848.38 | 6.046 | 0.4376 | 5.188 | 6.904 | 115.39 |
| 179,162 | 329848.38 | 5.886 | 0.3926 | 5.117 | 6.656 | 49.611 |
| 179301.25 | 329848.38 | 6.051 | 0.3824 | 5.302 | 6.801 | 41.779 |
| 179440.50 | 329848.38 | 5.833 | 0.3780 | 5.092 | 6.573 | 41.623 |
| 179579.75 | 329848.38 | 5.589 | 0.4705 | 4.667 | 6.511 | 96.330 |
| 179,719 | 329848.38 | 5.705 | 0.6048 | 4.519 | 6.890 | 192.24 |
| 179858.25 | 329848.38 | 5.943 | 0.6960 | 4.579 | 7.307 | 321.58 |
| 179997.50 | 329848.38 | 6.151 | 0.7474 | 4.686 | 7.616 | 456.78 |
| 180136.75 | 329848.38 | 6.246 | 0.7696 | 4.738 | 7.755 | 504.82 |
| 180,276 | 329848.38 | 6.293 | 0.7704 | 4.783 | 7.803 | 489.80 |
| 180415.25 | 329848.38 | 6.223 | 0.7562 | 4.741 | 7.705 | 401.92 |
| 180554.50 | 329848.38 | 6.054 | 0.7397 | 4.604 | 7.503 | 349.23 |
| 180693.75 | 329848.38 | 5.920 | 0.7388 | 4.472 | 7.368 | 348.08 |
| 180,833 | 329848.38 | 5.868 | 0.7597 | 4.379 | 7.357 | 398.92 |
| 180972.25 | 329848.38 | 5.907 | 0.7892 | 4.361 | 7.454 | 485.70 |
| 181111.50 | 329848.38 | 5.971 | 0.8136 | 4.377 | 7.566 | 592.83 |
First 40 of 50 rows.
- Grid: 21 × 30 points over the sites' bounding box; 95% intervals are the prediction ± 1.96 standard errors.
- A spherical semivariogram (nugget 0.06159, partial sill 0.5898, range parameter 942.5) fitted by weighted least squares to 15 distance classes.
The exact R script · R R version 4.5.1 (2025-06-13)
# Kriging (ordinary, universal, Gaussian process)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.kriging 1.0.0 · spec 2ba884d026c7cdd6
# Dataset: sp_meuse (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# Classic equivalent: gstat::krige(z ~ 1, sites, grid, model = fit.variogram(variogram(z ~ 1, sites), vgm("Sph")))
# and gstat::krige.cv().
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sp_meuse.parquet", col_select = c("log_zinc", "x", "y")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("log_zinc", "x", "y")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("log_zinc", "x", "y")) # infinite values stop the run (registry/errors.yaml)
# %% Fit
# Ordinary or universal kriging from spatial.variogram's fitted semivariogram (Matheron 1963; Cressie 1993), or a
# Gaussian process on the coordinates; predictions on a grid over the sites and Dubrule's (1983) leave-one-out.
Y <- "log_zinc"
XC <- "x"
YC <- "y"
coordinates <- "planar" # planar | lonlat
method <- "ordinary" # ordinary | universal | gp
model <- "spherical" # spherical | exponential | gaussian
estimator <- "matheron" # matheron | cressie
cutoff <- 1500
n_lags <- as.integer(15)
kernel <- "matern52" # matern52 | matern32 | rbf
n_grid <- as.integer(30)
x0 <- as.numeric(df[[XC]])
y0 <- as.numeric(df[[YC]])
pr <- cs_spp_project(x0, y0, coordinates)
px <- pr$x
py <- pr$y
z <- as.numeric(df[[Y]])
n <- length(z)
cs_krige_check_sites(px, py, z, list(y = Y, x = XC, y_coord = YC))
res <- cs_krige(px, py, z, method, model, estimator, cutoff, n_lags, kernel, n_grid)
ks <- cs_krige_scales(x0, y0, coordinates)
gx <- res$qx / ks[1] # grid points in the coordinates' own units
gy <- res$qy / ks[2]
pred <- res$pred
sd <- res$sd
rows <- if (!is.null(res$cv_rows)) res$cv_rows + 1L else seq_len(n)
cv <- cs_krige_cv_summary(z[rows], res$cv_err, res$cv_sd)
fit <- res$fit
gp <- res$gp
# %% Assumptions
assumptions <- list()
if (!is.null(fit)) {
min_pairs <- as.integer(min(res$emp$pairs))
assumptions[[1]] <- list(key = "pairs", label = "Enough pairs per distance", status = if (min_pairs >= 30) "pass" else "warn",
detail = paste0(sprintf("The smallest distance class has %d pairs", min_pairs),
if (min_pairs >= 30) ", enough to be stable." else "; classes under 30 pairs make the fitted semivariogram noisy. Use fewer classes or a larger distance."))
} else {
min_pairs <- NA_integer_
assumptions[[1]] <- list(key = "pairs", label = "Enough pairs per distance", status = "info",
detail = "The Gaussian process fits the covariance to the sites directly, without distance classes.")
}
msse <- cv$cv_msse
ok <- !is.nan(msse) && msse >= 0.5 && msse <= 2
assumptions[[2]] <- list(key = "calibration", label = "Standard errors match the errors", status = if (ok) "pass" else "warn",
detail = paste0(sprintf("Left-out sites' squared errors are %.2f times their predicted variances on average", msse),
if (ok) " (near 1: the standard errors are about right)." else if (msse < 0.5) "; the standard errors overstate the errors." else "; the standard errors understate the errors. Try another model or method."))
# %% Result
label <- c(ordinary = "Ordinary kriging", universal = "Universal kriging", gp = "Gaussian process")[[method]]
lower <- pred - 1.959963984540054 * sd
upper <- pred + 1.959963984540054 * sd
values <- list(n = n, method = method, cv_me = cv$cv_me, cv_rmse = cv$cv_rmse, cv_msse = cv$cv_msse, cv_r2 = cv$cv_r2,
n_cv = length(rows), grid_nx = length(res$gx), grid_ny = length(res$gy), pred_min = min(pred), pred_max = max(pred),
sd_min = min(sd), sd_max = max(sd), sd_mean = mean(sd), min_pairs = min_pairs,
missing_share = if (n_input > 0) n_dropped / n_input else 0)
if (!is.null(fit)) {
for (key in c("nugget", "psill", "sill", "range", "effective_range")) values[[key]] <- fit[[key]]
values$cutoff <- res$emp$cutoff
values$n_lags <- length(res$emp$h)
}
if (!is.null(res$trend)) { # slopes per map unit (km for degrees)
span <- max(max(px) - min(px), max(py) - min(py))
values$trend_x <- res$trend[2] / span
values$trend_y <- res$trend[3] / span
}
if (!is.null(gp)) {
values$gp_lengthscale <- gp$lengthscale
values$gp_signal_sd <- gp$signal_sd
values$gp_noise_sd <- gp$noise_sd
values$gp_log_marginal_likelihood <- gp$lml
}
for (key in c("nugget", "psill", "sill", "range", "effective_range", "cutoff", "n_lags", "trend_x", "trend_y", "gp_lengthscale", "gp_signal_sd", "gp_noise_sd", "gp_log_marginal_likelihood")) {
if (is.null(values[[key]])) values[[key]] <- NA_real_ # only some methods produce these
}
summary <- sprintf("%s of %s from %d sites predicts values from %.3g to %.3g over a %d × %d grid. Left out one at a time, the sites are predicted with an RMSE of %.3g (R² %.2f).",
label, Y, n, min(pred), max(pred), length(res$gx), length(res$gy), cv$cv_rmse, cv$cv_r2)
grid_cols <- list(list(key = "x", label = XC, type = "number"), list(key = "y", label = YC, type = "number"), list(key = "prediction", label = "Prediction", type = "number"),
list(key = "se", label = "Standard error", type = "number"), list(key = "lower", label = "95% low", type = "number"), list(key = "upper", label = "95% high", type = "number"),
list(key = "nearest", label = "Nearest site", type = "number"))
grid_rows <- lapply(seq_along(pred), function(k) list(x = gx[k], y = gy[k], prediction = pred[k], se = sd[k], lower = lower[k], upper = upper[k], nearest = res$nearest[k]))
loo_pred <- z[rows] - res$cv_err
cv_cols <- list(list(key = "x", label = XC, type = "number"), list(key = "y", label = YC, type = "number"), list(key = "observed", label = "Observed", type = "number"),
list(key = "predicted", label = "Left-out prediction", type = "number"), list(key = "se", label = "Standard error", type = "number"), list(key = "z", label = "Standardized error", type = "number"))
cv_rows <- lapply(seq_along(rows), function(k) {
i <- rows[k]
list(x = x0[i], y = y0[i], observed = z[i], predicted = loo_pred[k], se = res$cv_sd[k], z = if (res$cv_sd[k] > 0) res$cv_err[k] / res$cv_sd[k] else NA_real_)
})
model_rows <- if (!is.null(fit)) {
list(list(setting = "Nugget", value = fit$nugget), list(setting = "Partial sill", value = fit$psill), list(setting = "Sill", value = fit$sill),
list(setting = "Range parameter", value = fit$range), list(setting = "Practical range", value = fit$effective_range))
} else {
list(list(setting = "Lengthscale (map units)", value = gp$lengthscale), list(setting = "Signal SD", value = gp$signal_sd),
list(setting = "Noise SD", value = gp$noise_sd), list(setting = "Log marginal likelihood", value = gp$lml))
}
tables <- list(
list(key = "model", title = if (!is.null(fit)) "Semivariogram model" else "Gaussian process settings",
columns = list(list(key = "setting", label = "Setting", type = "string"), list(key = "value", label = "Value", type = "number")), rows = model_rows),
list(key = "cv", title = "Leave-one-out predictions at the sites", columns = cv_cols, rows = cv_rows),
list(key = "grid", title = "Predictions on the grid", columns = grid_cols, rows = grid_rows)
)
kind <- c(rep("grid", length(pred)), rep("point", n))
xs <- c(gx, x0)
ys <- c(gy, y0)
charts <- list(
cs_chart("prediction", "contour-grid", sprintf("Predicted %s", Y),
list(x = cs_col(XC, xs), y = cs_col(YC, ys), z = cs_col(sprintf("Predicted %s", Y), c(pred, z)),
kind = cs_col("kind", kind, "categorical", c("grid", "point")))),
cs_chart("se", "contour-grid", "Standard error of the prediction",
list(x = cs_col(XC, xs), y = cs_col(YC, ys), z = cs_col("Standard error", c(sd, rep(NA_real_, n)), "numeric"),
kind = cs_col("kind", kind, "categorical", c("grid", "point")))),
cs_chart("loo", "pred-actual", "Left-out predictions at the sites",
list(actual = cs_col(sprintf("Observed %s", Y), z[rows]), predicted = cs_col("Left-out prediction", loo_pred)))
)
if (!is.null(fit)) {
emp <- res$emp
charts[[length(charts) + 1L]] <- cs_chart("variogram", "variogram", sprintf("Semivariogram used for kriging%s", if (method == "universal") " (trend removed)" else ""),
list(h = cs_col("Distance", emp$h), gamma = cs_col("Semivariance", emp$gamma), pairs = cs_col("Pairs", emp$pairs),
fitted = cs_col("Fitted", res$fitted)), controls = list(variance = stats::var(z)))
}
statistics <- list(list(key = "cv_rmse", label = "LOO RMSE", value = cv$cv_rmse), list(key = "cv_r2", label = "LOO R²", value = cv$cv_r2),
list(key = "cv_msse", label = "Mean squared standardized error", value = cv$cv_msse))
notes <- list(sprintf("Grid: %d × %d points over the sites' bounding box; 95%% intervals are the prediction ± 1.96 standard errors.", length(res$gx), length(res$gy)))
if (!is.null(fit)) {
notes[[2]] <- paste0(sprintf("A %s semivariogram (nugget %.4g, partial sill %.4g, range parameter %.4g) fitted by weighted least squares to %d distance classes",
model, fit$nugget, fit$psill, fit$range, length(res$emp$h)),
if (method == "universal") " of the residuals from a trend in the coordinates." else ".")
} else {
notes[[2]] <- sprintf("Gaussian process with a %s kernel fitted to %d sites by maximum likelihood (lengthscale %.4g map units).", kernel, as.integer(gp$n_fit), gp$lengthscale)
}
if (coordinates == "lonlat") {
notes[[length(notes) + 1L]] <- "Longitude and latitude were projected to kilometers at the sites' mean latitude; distances, ranges and trends are in kilometers."
}
cs_publish(list(
method = "spatial.kriging",
methodVersion = "1.0.0",
title = label,
engine = cs_engine_info("stats"),
n = n,
summary = summary,
apa = sprintf("LOO RMSE = %.3g, R² = %.2f, MSSE = %.2f, n = %d", cv$cv_rmse, cv$cv_r2, cv$cv_msse, n),
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
values = values,
charts = charts
))
LOO RMSE = 0.396, R² = 0.70, MSSE = 0.80, n = 155
- LOO RMSE
- 0.3965
- LOO R²
- 0.6964
- Mean squared standardized error
- 0.8027
Assumptions
- Enough pairs per distance — The smallest distance class has 52 pairs, enough to be stable.
- Standard errors match the errors — Left-out sites' squared errors are 0.80 times their predicted variances on average (near 1: the standard errors are about right).
Semivariogram model
| Setting | Value |
|---|---|
| Nugget | 0.0616 |
| Partial sill | 0.5898 |
| Sill | 0.6514 |
| Range parameter | 942.52 |
| Practical range | 942.52 |
Leave-one-out predictions at the sites
| x | y | Observed | Left-out prediction | Standard error | Standardized error |
|---|---|---|---|---|---|
| 181,072 | 333,611 | 6.930 | 6.755 | 0.4378 | 0.3987 |
| 181,025 | 333,558 | 7.040 | 6.754 | 0.4307 | 0.6623 |
| 181,165 | 333,537 | 6.461 | 6.300 | 0.4366 | 0.3706 |
| 181,298 | 333,484 | 5.549 | 6.047 | 0.4852 | −1.026 |
| 181,307 | 333,330 | 5.595 | 5.589 | 0.4285 | 0.0143 |
| 181,390 | 333,260 | 5.638 | 5.430 | 0.4890 | 0.4263 |
| 181,165 | 333,370 | 5.846 | 5.879 | 0.4300 | −0.0766 |
| 181,027 | 333,363 | 6.006 | 6.407 | 0.4265 | −0.9401 |
| 181,060 | 333,231 | 5.849 | 5.812 | 0.3740 | 0.0997 |
| 181,232 | 333,168 | 5.209 | 5.391 | 0.4054 | −0.4474 |
| 181,191 | 333,115 | 5.242 | 5.317 | 0.4045 | −0.1870 |
| 181,032 | 333,031 | 5.525 | 5.517 | 0.4394 | 0.0202 |
| 180,874 | 333,339 | 6.999 | 6.681 | 0.4463 | 0.7144 |
| 180,969 | 333,252 | 6.223 | 6.212 | 0.3959 | 0.0277 |
| 181,011 | 333,161 | 5.787 | 5.819 | 0.3977 | −0.0818 |
| 180,830 | 333,246 | 6.939 | 6.562 | 0.4294 | 0.8778 |
| 180,763 | 333,104 | 6.407 | 6.479 | 0.4400 | −0.1648 |
| 180,694 | 332,972 | 6.567 | 6.344 | 0.4332 | 0.5140 |
| 180,625 | 332,847 | 6.600 | 6.477 | 0.4227 | 0.2913 |
| 180,555 | 332,707 | 6.958 | 6.696 | 0.4278 | 0.6145 |
| 180,642 | 332,708 | 6.512 | 6.347 | 0.3751 | 0.4388 |
| 180,704 | 332,717 | 5.996 | 6.078 | 0.3759 | −0.2162 |
| 180,704 | 332,664 | 5.838 | 6.108 | 0.3899 | −0.6927 |
| 181,153 | 332,925 | 5.384 | 5.246 | 0.4301 | 0.3214 |
| 181,147 | 332,823 | 5.298 | 5.281 | 0.3821 | 0.0456 |
| 181,167 | 332,778 | 5.268 | 5.282 | 0.4041 | −0.0348 |
| 181,008 | 332,777 | 5.333 | 5.317 | 0.4031 | 0.0385 |
| 180,973 | 332,687 | 5.193 | 5.349 | 0.4155 | −0.3760 |
| 180,916 | 332,753 | 5.481 | 5.379 | 0.4057 | 0.2503 |
| 181,352 | 332,946 | 5.193 | 5.312 | 0.5516 | −0.2162 |
| 181,133 | 332,570 | 5.338 | 5.325 | 0.5275 | 0.0230 |
| 180,878 | 332,489 | 5.288 | 5.439 | 0.4044 | −0.3723 |
| 180,829 | 332,450 | 5.521 | 5.496 | 0.4036 | 0.0643 |
| 180,954 | 332,399 | 5.257 | 5.340 | 0.4153 | −0.1988 |
| 180,956 | 332,318 | 5.361 | 5.330 | 0.4703 | 0.0663 |
| 180,710 | 332,330 | 5.771 | 5.521 | 0.4614 | 0.5422 |
| 180,632 | 332,445 | 6.344 | 5.999 | 0.4387 | 0.7861 |
| 180,530 | 332,538 | 6.725 | 6.646 | 0.4009 | 0.1982 |
| 180,478 | 332,578 | 6.809 | 6.967 | 0.4107 | −0.3836 |
| 180,383 | 332,476 | 7.282 | 6.760 | 0.4564 | 1.144 |
First 40 of 50 rows.
Predictions on the grid
| x | y | Prediction | Standard error | 95% low | 95% high | Nearest site |
|---|---|---|---|---|---|---|
| 178,605 | 329,714 | 6.420 | 0.6390 | 5.168 | 7.672 | 210.77 |
| 178744.25 | 329,714 | 6.539 | 0.5301 | 5.500 | 7.578 | 115.79 |
| 178883.50 | 329,714 | 6.498 | 0.4869 | 5.543 | 7.452 | 141.78 |
| 179022.75 | 329,714 | 6.390 | 0.3731 | 5.659 | 7.122 | 19.041 |
| 179,162 | 329,714 | 6.309 | 0.4275 | 5.471 | 7.147 | 83 |
| 179301.25 | 329,714 | 6.309 | 0.4153 | 5.495 | 7.123 | 56.250 |
| 179440.50 | 329,714 | 6.121 | 0.4771 | 5.186 | 7.057 | 93.109 |
| 179579.75 | 329,714 | 5.906 | 0.5690 | 4.791 | 7.022 | 163.73 |
| 179,719 | 329,714 | 5.895 | 0.6631 | 4.595 | 7.194 | 282.20 |
| 179858.25 | 329,714 | 6.017 | 0.7341 | 4.578 | 7.456 | 382.22 |
| 179997.50 | 329,714 | 6.107 | 0.7796 | 4.579 | 7.635 | 501.33 |
| 180136.75 | 329,714 | 6.144 | 0.8027 | 4.570 | 7.717 | 628.77 |
| 180,276 | 329,714 | 6.160 | 0.8072 | 4.578 | 7.742 | 591.42 |
| 180415.25 | 329,714 | 6.105 | 0.8000 | 4.537 | 7.673 | 520.97 |
| 180554.50 | 329,714 | 6.001 | 0.7913 | 4.451 | 7.552 | 481.49 |
| 180693.75 | 329,714 | 5.930 | 0.7900 | 4.382 | 7.479 | 480.66 |
| 180,833 | 329,714 | 5.926 | 0.7988 | 4.360 | 7.492 | 518.66 |
| 180972.25 | 329,714 | 5.969 | 0.8128 | 4.376 | 7.562 | 588.03 |
| 181111.50 | 329,714 | 6.008 | 0.8248 | 4.392 | 7.625 | 679.20 |
| 181250.75 | 329,714 | 6.041 | 0.8311 | 4.412 | 7.670 | 784.63 |
| 181,390 | 329,714 | 6.059 | 0.8330 | 4.427 | 7.692 | 899.30 |
| 178,605 | 329848.38 | 6.380 | 0.6077 | 5.189 | 7.571 | 182.91 |
| 178744.25 | 329848.38 | 6.496 | 0.4383 | 5.637 | 7.355 | 49.386 |
| 178883.50 | 329848.38 | 6.332 | 0.4524 | 5.445 | 7.219 | 101.01 |
| 179022.75 | 329848.38 | 6.046 | 0.4376 | 5.188 | 6.904 | 115.39 |
| 179,162 | 329848.38 | 5.886 | 0.3926 | 5.117 | 6.656 | 49.611 |
| 179301.25 | 329848.38 | 6.051 | 0.3824 | 5.302 | 6.801 | 41.779 |
| 179440.50 | 329848.38 | 5.833 | 0.3780 | 5.092 | 6.573 | 41.623 |
| 179579.75 | 329848.38 | 5.589 | 0.4705 | 4.667 | 6.511 | 96.330 |
| 179,719 | 329848.38 | 5.705 | 0.6048 | 4.519 | 6.890 | 192.24 |
| 179858.25 | 329848.38 | 5.943 | 0.6960 | 4.579 | 7.307 | 321.58 |
| 179997.50 | 329848.38 | 6.151 | 0.7474 | 4.686 | 7.616 | 456.78 |
| 180136.75 | 329848.38 | 6.246 | 0.7696 | 4.738 | 7.755 | 504.82 |
| 180,276 | 329848.38 | 6.293 | 0.7704 | 4.783 | 7.803 | 489.80 |
| 180415.25 | 329848.38 | 6.223 | 0.7562 | 4.741 | 7.705 | 401.92 |
| 180554.50 | 329848.38 | 6.054 | 0.7397 | 4.604 | 7.503 | 349.23 |
| 180693.75 | 329848.38 | 5.920 | 0.7388 | 4.472 | 7.368 | 348.08 |
| 180,833 | 329848.38 | 5.868 | 0.7597 | 4.379 | 7.357 | 398.92 |
| 180972.25 | 329848.38 | 5.907 | 0.7892 | 4.361 | 7.454 | 485.70 |
| 181111.50 | 329848.38 | 5.971 | 0.8136 | 4.377 | 7.566 | 592.83 |
First 40 of 50 rows.
- Grid: 21 × 30 points over the sites' bounding box; 95% intervals are the prediction ± 1.96 standard errors.
- A spherical semivariogram (nugget 0.06159, partial sill 0.5898, range parameter 942.5) fitted by weighted least squares to 15 distance classes.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kriging (ordinary, universal, Gaussian process)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.kriging 1.0.0 · spec 2ba884d026c7cdd6
# Dataset: sp_meuse (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import kriging as kr
from codesplash.stats import spatial_points as spp
# Classic equivalent: gstat::krige(z ~ 1, sites, grid, model = fit.variogram(variogram(z ~ 1, sites), vgm("Sph")))
# and gstat::krige.cv(); in Python pykrige.ok.OrdinaryKriging(x, y, z, variogram_model="spherical").
# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_meuse.parquet", columns=["log_zinc", "x", "y"])
n_input = len(df)
df = df.dropna(subset=["log_zinc", "x", "y"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["log_zinc", "x", "y"]) # infinite values stop the run (registry/errors.yaml)
# %% Fit
# Ordinary or universal kriging from spatial.variogram's fitted semivariogram (Matheron 1963; Cressie 1993), or a
# Gaussian process on the coordinates; predictions on a grid over the sites and Dubrule's (1983) leave-one-out.
Y = "log_zinc"
XC = "x"
YC = "y"
coordinates = "planar" # planar | lonlat
method = "ordinary" # ordinary | universal | gp
model = "spherical" # spherical | exponential | gaussian
estimator = "matheron" # matheron | cressie
cutoff = 1500
n_lags = int(15)
kernel = "matern52" # matern52 | matern32 | rbf
n_grid = int(30)
x0 = df[XC].to_numpy(dtype=float)
y0 = df[YC].to_numpy(dtype=float)
px, py = spp.project(x0, y0, coordinates)
z = df[Y].to_numpy(dtype=float)
n = z.size
kr.check_sites(px, py, z, {"y": Y, "x": XC, "y_coord": YC})
res = kr.krige(px, py, z, method, model, estimator, cutoff, n_lags, kernel, n_grid)
kx, ky = kr.scales(x0, y0, coordinates)
gx, gy = res["qx"] / kx, res["qy"] / ky # grid points in the coordinates' own units
pred, sd = res["pred"], res["sd"]
rows = res["cv_rows"] if "cv_rows" in res else np.arange(n)
cv = kr.cv_summary(z[rows], res["cv_err"], res["cv_sd"])
fit = res.get("fit")
gp = res.get("gp")
# %% Assumptions
assumptions = []
if fit is not None:
min_pairs = int(np.min(res["emp"]["pairs"]))
assumptions.append({"key": "pairs", "label": "Enough pairs per distance", "status": "pass" if min_pairs >= 30 else "warn",
"detail": f"The smallest distance class has {min_pairs} pairs" + (", enough to be stable." if min_pairs >= 30 else "; classes under 30 pairs make the fitted semivariogram noisy. Use fewer classes or a larger distance.")})
else:
min_pairs = None
assumptions.append({"key": "pairs", "label": "Enough pairs per distance", "status": "info",
"detail": "The Gaussian process fits the covariance to the sites directly, without distance classes."})
msse = cv["cv_msse"]
ok = msse == msse and 0.5 <= msse <= 2.0
assumptions.append({"key": "calibration", "label": "Standard errors match the errors", "status": "pass" if ok else "warn",
"detail": f"Left-out sites' squared errors are {msse:.2f} times their predicted variances on average"
+ (" (near 1: the standard errors are about right)." if ok else ("; the standard errors overstate the errors." if msse < 0.5 else "; the standard errors understate the errors. Try another model or method."))})
# %% Result
label = {"ordinary": "Ordinary kriging", "universal": "Universal kriging", "gp": "Gaussian process"}[method]
lower, upper = pred - 1.959963984540054 * sd, pred + 1.959963984540054 * sd
values = {"n": n, "method": method, "cv_me": cv["cv_me"], "cv_rmse": cv["cv_rmse"], "cv_msse": cv["cv_msse"], "cv_r2": cv["cv_r2"],
"n_cv": int(rows.size), "grid_nx": int(res["gx"].size), "grid_ny": int(res["gy"].size), "pred_min": float(np.min(pred)),
"pred_max": float(np.max(pred)), "sd_min": float(np.min(sd)), "sd_max": float(np.max(sd)), "sd_mean": float(np.mean(sd)),
"min_pairs": min_pairs, "missing_share": n_dropped / n_input if n_input else 0.0}
if fit is not None:
values.update({key: fit[key] for key in ("nugget", "psill", "sill", "range", "effective_range")})
values.update({"cutoff": res["emp"]["cutoff"], "n_lags": int(res["emp"]["h"].size)})
if "trend" in res: # slopes per map unit (km for degrees)
span = max(float(np.max(px) - np.min(px)), float(np.max(py) - np.min(py)))
values.update({"trend_x": float(res["trend"][1]) / span, "trend_y": float(res["trend"][2]) / span})
if gp is not None:
values.update({"gp_lengthscale": gp["lengthscale"], "gp_signal_sd": gp["signal_sd"], "gp_noise_sd": gp["noise_sd"], "gp_log_marginal_likelihood": gp["lml"]})
for key in ("nugget", "psill", "sill", "range", "effective_range", "cutoff", "n_lags", "trend_x", "trend_y", "gp_lengthscale", "gp_signal_sd", "gp_noise_sd", "gp_log_marginal_likelihood"):
values.setdefault(key, None) # only some methods produce these
summary = (f"{label} of {Y} from {n} sites predicts values from {np.min(pred):.3g} to {np.max(pred):.3g} over a {res['gx'].size} × {res['gy'].size} grid. "
f"Left out one at a time, the sites are predicted with an RMSE of {cv['cv_rmse']:.3g} (R² {cv['cv_r2']:.2f}).")
grid_cols = [{"key": "x", "label": XC, "type": "number"}, {"key": "y", "label": YC, "type": "number"}, {"key": "prediction", "label": "Prediction", "type": "number"},
{"key": "se", "label": "Standard error", "type": "number"}, {"key": "lower", "label": "95% low", "type": "number"}, {"key": "upper", "label": "95% high", "type": "number"},
{"key": "nearest", "label": "Nearest site", "type": "number"}]
grid_rows = [{"x": float(gx[k]), "y": float(gy[k]), "prediction": float(pred[k]), "se": float(sd[k]), "lower": float(lower[k]), "upper": float(upper[k]),
"nearest": float(res["nearest"][k])} for k in range(pred.size)]
loo_pred = z[rows] - res["cv_err"]
cv_cols = [{"key": "x", "label": XC, "type": "number"}, {"key": "y", "label": YC, "type": "number"}, {"key": "observed", "label": "Observed", "type": "number"},
{"key": "predicted", "label": "Left-out prediction", "type": "number"}, {"key": "se", "label": "Standard error", "type": "number"}, {"key": "z", "label": "Standardized error", "type": "number"}]
cv_rows = [{"x": float(x0[i]), "y": float(y0[i]), "observed": float(z[i]), "predicted": float(loo_pred[k]), "se": float(res["cv_sd"][k]),
"z": float(res["cv_err"][k] / res["cv_sd"][k]) if res["cv_sd"][k] > 0 else None} for k, i in enumerate(rows.tolist())]
if fit is not None:
model_rows = [{"setting": "Nugget", "value": fit["nugget"]}, {"setting": "Partial sill", "value": fit["psill"]}, {"setting": "Sill", "value": fit["sill"]},
{"setting": "Range parameter", "value": fit["range"]}, {"setting": "Practical range", "value": fit["effective_range"]}]
else:
model_rows = [{"setting": "Lengthscale (map units)", "value": gp["lengthscale"]}, {"setting": "Signal SD", "value": gp["signal_sd"]},
{"setting": "Noise SD", "value": gp["noise_sd"]}, {"setting": "Log marginal likelihood", "value": gp["lml"]}]
tables = [
{"key": "model", "title": "Semivariogram model" if fit is not None else "Gaussian process settings",
"columns": [{"key": "setting", "label": "Setting", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": model_rows},
{"key": "cv", "title": "Leave-one-out predictions at the sites", "columns": cv_cols, "rows": cv_rows},
{"key": "grid", "title": "Predictions on the grid", "columns": grid_cols, "rows": grid_rows},
]
kind = ["grid"] * pred.size + ["point"] * n
xs = np.concatenate([gx, x0])
ys = np.concatenate([gy, y0])
charts = [
cs.chart("prediction", "contour-grid", f"Predicted {Y}",
{"x": cs.col(XC, xs), "y": cs.col(YC, ys), "z": cs.col(f"Predicted {Y}", np.concatenate([pred, z])),
"kind": cs.col("kind", kind, "categorical", ["grid", "point"])}),
cs.chart("se", "contour-grid", "Standard error of the prediction",
{"x": cs.col(XC, xs), "y": cs.col(YC, ys), "z": cs.col("Standard error", list(sd.tolist()) + [None] * n, "numeric"),
"kind": cs.col("kind", kind, "categorical", ["grid", "point"])}),
cs.chart("loo", "pred-actual", "Left-out predictions at the sites",
{"actual": cs.col(f"Observed {Y}", z[rows]), "predicted": cs.col("Left-out prediction", loo_pred)}),
]
if fit is not None:
emp = res["emp"]
charts.append(cs.chart("variogram", "variogram", f"Semivariogram used for kriging{' (trend removed)' if method == 'universal' else ''}",
{"h": cs.col("Distance", emp["h"]), "gamma": cs.col("Semivariance", emp["gamma"]), "pairs": cs.col("Pairs", emp["pairs"]),
"fitted": cs.col("Fitted", res["fitted"])}, controls={"variance": float(np.var(z, ddof=1))}))
statistics = [{"key": "cv_rmse", "label": "LOO RMSE", "value": cv["cv_rmse"]}, {"key": "cv_r2", "label": "LOO R²", "value": cv["cv_r2"]},
{"key": "cv_msse", "label": "Mean squared standardized error", "value": cv["cv_msse"]}]
notes = [f"Grid: {res['gx'].size} × {res['gy'].size} points over the sites' bounding box; 95% intervals are the prediction ± 1.96 standard errors."]
if fit is not None:
notes.append(f"A {model} semivariogram (nugget {fit['nugget']:.4g}, partial sill {fit['psill']:.4g}, range parameter {fit['range']:.4g}) fitted by weighted least squares to {int(res['emp']['h'].size)} distance classes"
+ (" of the residuals from a trend in the coordinates." if method == "universal" else "."))
else:
notes.append(f"Gaussian process with a {kernel} kernel fitted to {gp['n_fit']} sites by maximum likelihood (lengthscale {gp['lengthscale']:.4g} map units).")
if coordinates == "lonlat":
notes.append("Longitude and latitude were projected to kilometers at the sites' mean latitude; distances, ranges and trends are in kilometers.")
cs.publish({
"method": "spatial.kriging",
"methodVersion": "1.0.0",
"title": label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"LOO RMSE = {cv['cv_rmse']:.3g}, R² = {cv['cv_r2']:.2f}, MSSE = {cv['cv_msse']:.2f}, n = {n}",
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"values": values,
"charts": charts,
})
Shortened for the Academy: 4 chart(s) dropped to stay under 100 KB; a table cut from 155 to 50 rows; a table cut from 630 to 50 rows; 4 chart(s) dropped to stay under 100 KB; a table cut from 155 to 50 rows; a table cut from 630 to 50 rows.
Log zinc in the Meuse floodplain is predicted from 4.83 to 7.46 over the grid. The standard-error map is lowest where the sites are dense.
Does the map hold up?
PredictPredict first
Kriging cross-validationKriging cross-validationEach site predicted from all the others; the errors show how well the map would predict a new site. predicts each site from all the others. If the standard errors are honest, what should the average of (error ÷ standard error)² be?
Reveal
Close to 1. Here the mean squared standardized errorMean squared standardized errorThe average of (left-out error ÷ its predicted SD)²: near 1 when the standard errors are honest. is 0.80, and the left-out RMSE is 0.396. Far below 1, the map overstates its uncertainty; far above, it is overconfident.
A trend, or a Gaussian process
ReadZinc falls with distance from the river, so the mean is not the same everywhere. Universal krigingUniversal krigingKriging when the mean rises or falls across the map: a trend in the coordinates plus a semivariogram of what's left. adds a trend in the coordinates and fits the semivariogram to what is left.
LOO RMSE = 0.389, R² = 0.71, MSSE = 0.88, n = 155
- LOO RMSE
- 0.3891
- LOO R²
- 0.7075
- Mean squared standardized error
- 0.8771
Assumptions
- Enough pairs per distance — The smallest distance class has 52 pairs, enough to be stable.
- Standard errors match the errors — Left-out sites' squared errors are 0.88 times their predicted variances on average (near 1: the standard errors are about right).
Semivariogram model
| Setting | Value |
|---|---|
| Nugget | 0.0620 |
| Partial sill | 0.4987 |
| Sill | 0.5607 |
| Range parameter | 655.64 |
| Practical range | 1966.93 |
Leave-one-out predictions at the sites
| x | y | Observed | Left-out prediction | Standard error | Standardized error |
|---|---|---|---|---|---|
| 181,072 | 333,611 | 6.930 | 6.776 | 0.4134 | 0.3714 |
| 181,025 | 333,558 | 7.040 | 6.756 | 0.4053 | 0.6995 |
| 181,165 | 333,537 | 6.461 | 6.297 | 0.4086 | 0.4025 |
| 181,298 | 333,484 | 5.549 | 6.031 | 0.4483 | −1.076 |
| 181,307 | 333,330 | 5.595 | 5.586 | 0.4025 | 0.0205 |
| 181,390 | 333,260 | 5.638 | 5.346 | 0.4517 | 0.6463 |
| 181,165 | 333,370 | 5.846 | 5.884 | 0.4026 | −0.0940 |
| 181,027 | 333,363 | 6.006 | 6.380 | 0.3997 | −0.9358 |
| 181,060 | 333,231 | 5.849 | 5.820 | 0.3570 | 0.0820 |
| 181,232 | 333,168 | 5.209 | 5.414 | 0.3834 | −0.5323 |
| 181,191 | 333,115 | 5.242 | 5.363 | 0.3826 | −0.3161 |
| 181,032 | 333,031 | 5.525 | 5.549 | 0.4102 | −0.0567 |
| 180,874 | 333,339 | 6.999 | 6.689 | 0.4163 | 0.7455 |
| 180,969 | 333,252 | 6.223 | 6.209 | 0.3745 | 0.0373 |
| 181,011 | 333,161 | 5.787 | 5.842 | 0.3761 | −0.1457 |
| 180,830 | 333,246 | 6.939 | 6.598 | 0.4028 | 0.8477 |
| 180,763 | 333,104 | 6.407 | 6.483 | 0.4117 | −0.1856 |
| 180,694 | 332,972 | 6.567 | 6.369 | 0.4064 | 0.4862 |
| 180,625 | 332,847 | 6.600 | 6.531 | 0.3971 | 0.1744 |
| 180,555 | 332,707 | 6.958 | 6.684 | 0.4016 | 0.6835 |
| 180,642 | 332,708 | 6.512 | 6.343 | 0.3582 | 0.4699 |
| 180,704 | 332,717 | 5.996 | 6.098 | 0.3590 | −0.2827 |
| 180,704 | 332,664 | 5.838 | 6.114 | 0.3704 | −0.7456 |
| 181,153 | 332,925 | 5.384 | 5.290 | 0.4030 | 0.2346 |
| 181,147 | 332,823 | 5.298 | 5.287 | 0.3651 | 0.0304 |
| 181,167 | 332,778 | 5.268 | 5.259 | 0.3830 | 0.0236 |
| 181,008 | 332,777 | 5.333 | 5.325 | 0.3808 | 0.0197 |
| 180,973 | 332,687 | 5.193 | 5.382 | 0.3914 | −0.4837 |
| 180,916 | 332,753 | 5.481 | 5.418 | 0.3833 | 0.1636 |
| 181,352 | 332,946 | 5.193 | 5.204 | 0.4992 | −0.0230 |
| 181,133 | 332,570 | 5.338 | 5.130 | 0.4806 | 0.4328 |
| 180,878 | 332,489 | 5.288 | 5.470 | 0.3832 | −0.4744 |
| 180,829 | 332,450 | 5.521 | 5.514 | 0.3824 | 0.0194 |
| 180,954 | 332,399 | 5.257 | 5.324 | 0.3924 | −0.1704 |
| 180,956 | 332,318 | 5.361 | 5.205 | 0.4356 | 0.3588 |
| 180,710 | 332,330 | 5.771 | 5.571 | 0.4293 | 0.4659 |
| 180,632 | 332,445 | 6.344 | 6.015 | 0.4103 | 0.8009 |
| 180,530 | 332,538 | 6.725 | 6.624 | 0.3800 | 0.2661 |
| 180,478 | 332,578 | 6.809 | 6.931 | 0.3885 | −0.3132 |
| 180,383 | 332,476 | 7.282 | 6.739 | 0.4254 | 1.278 |
First 40 of 50 rows.
Predictions on the grid
| x | y | Prediction | Standard error | 95% low | 95% high | Nearest site |
|---|---|---|---|---|---|---|
| 178,605 | 329,714 | 6.713 | 0.5877 | 5.562 | 7.865 | 210.77 |
| 178768.82 | 329,714 | 6.606 | 0.4797 | 5.665 | 7.546 | 109.36 |
| 178932.65 | 329,714 | 6.430 | 0.4331 | 5.581 | 7.279 | 93.308 |
| 179096.47 | 329,714 | 6.287 | 0.4018 | 5.500 | 7.075 | 74.920 |
| 179260.29 | 329,714 | 6.292 | 0.3503 | 5.605 | 6.978 | 15.294 |
| 179424.12 | 329,714 | 6.039 | 0.4392 | 5.178 | 6.900 | 95.316 |
| 179587.94 | 329,714 | 5.750 | 0.5228 | 4.725 | 6.775 | 170.53 |
| 179751.76 | 329,714 | 5.625 | 0.6064 | 4.436 | 6.813 | 302.96 |
| 179915.59 | 329,714 | 5.605 | 0.6634 | 4.305 | 6.905 | 429.80 |
| 180079.41 | 329,714 | 5.592 | 0.6978 | 4.225 | 6.960 | 575.63 |
| 180243.24 | 329,714 | 5.533 | 0.7185 | 4.124 | 6.941 | 611.43 |
| 180407.06 | 329,714 | 5.407 | 0.7345 | 3.968 | 6.847 | 524.36 |
| 180570.88 | 329,714 | 5.221 | 0.7555 | 3.740 | 6.702 | 479.30 |
| 180734.71 | 329,714 | 4.990 | 0.7915 | 3.439 | 6.542 | 488.03 |
| 180898.53 | 329,714 | 4.735 | 0.8432 | 3.082 | 6.387 | 548.00 |
| 181062.35 | 329,714 | 4.474 | 0.9029 | 2.704 | 6.244 | 645.06 |
| 181226.18 | 329,714 | 4.219 | 0.9639 | 2.330 | 6.109 | 765.24 |
| 181,390 | 329,714 | 3.977 | 1.023 | 1.971 | 5.982 | 899.30 |
| 178,605 | 329876.38 | 6.642 | 0.5525 | 5.559 | 7.724 | 188.99 |
| 178768.82 | 329876.38 | 6.487 | 0.4160 | 5.672 | 7.303 | 57.023 |
| 178932.65 | 329876.38 | 6.150 | 0.4344 | 5.298 | 7.001 | 156.40 |
| 179096.47 | 329876.38 | 5.802 | 0.3721 | 5.073 | 6.532 | 40.868 |
| 179260.29 | 329876.38 | 5.877 | 0.3842 | 5.124 | 6.630 | 76.970 |
| 179424.12 | 329876.38 | 5.767 | 0.3740 | 5.034 | 6.500 | 72.450 |
| 179587.94 | 329876.38 | 5.465 | 0.4242 | 4.634 | 6.297 | 74.079 |
| 179751.76 | 329876.38 | 5.551 | 0.5505 | 4.472 | 6.630 | 211.56 |
| 179915.59 | 329876.38 | 5.696 | 0.6168 | 4.487 | 6.905 | 371.08 |
| 180079.41 | 329876.38 | 5.800 | 0.6465 | 4.532 | 7.067 | 481.97 |
| 180243.24 | 329876.38 | 5.799 | 0.6575 | 4.510 | 7.088 | 485.47 |
| 180407.06 | 329876.38 | 5.681 | 0.6598 | 4.388 | 6.974 | 383.06 |
| 180570.88 | 329876.38 | 5.475 | 0.6673 | 4.167 | 6.783 | 318.61 |
| 180734.71 | 329876.38 | 5.208 | 0.7057 | 3.825 | 6.591 | 331.60 |
| 180898.53 | 329876.38 | 4.913 | 0.7740 | 3.396 | 6.430 | 414.84 |
| 181062.35 | 329876.38 | 4.620 | 0.8491 | 2.956 | 6.284 | 536.56 |
| 181226.18 | 329876.38 | 4.344 | 0.9202 | 2.541 | 6.148 | 676.29 |
| 181,390 | 329876.38 | 4.088 | 0.9854 | 2.157 | 6.020 | 824.94 |
| 178,605 | 330038.75 | 6.493 | 0.5560 | 5.403 | 7.582 | 282.39 |
| 178768.82 | 330038.75 | 6.207 | 0.4931 | 5.240 | 7.173 | 217.43 |
| 178932.65 | 330038.75 | 5.824 | 0.4355 | 4.971 | 6.678 | 106.53 |
| 179096.47 | 330038.75 | 5.460 | 0.3884 | 4.698 | 6.221 | 79.303 |
First 40 of 50 rows.
- Grid: 18 × 25 points over the sites' bounding box; 95% intervals are the prediction ± 1.96 standard errors.
- A exponential semivariogram (nugget 0.06196, partial sill 0.4987, range parameter 655.6) fitted by weighted least squares to 15 distance classes of the residuals from a trend in the coordinates.
The exact R script · R R version 4.5.1 (2025-06-13)
# Kriging (ordinary, universal, Gaussian process)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.kriging 1.0.0 · spec c38a531afe194bdf
# Dataset: sp_meuse (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# Classic equivalent: gstat::krige(z ~ 1, sites, grid, model = fit.variogram(variogram(z ~ 1, sites), vgm("Sph")))
# and gstat::krige.cv().
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sp_meuse.parquet", col_select = c("log_zinc", "x", "y")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("log_zinc", "x", "y")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("log_zinc", "x", "y")) # infinite values stop the run (registry/errors.yaml)
# %% Fit
# Ordinary or universal kriging from spatial.variogram's fitted semivariogram (Matheron 1963; Cressie 1993), or a
# Gaussian process on the coordinates; predictions on a grid over the sites and Dubrule's (1983) leave-one-out.
Y <- "log_zinc"
XC <- "x"
YC <- "y"
coordinates <- "planar" # planar | lonlat
method <- "universal" # ordinary | universal | gp
model <- "exponential" # spherical | exponential | gaussian
estimator <- "matheron" # matheron | cressie
cutoff <- 1500
n_lags <- as.integer(15)
kernel <- "matern52" # matern52 | matern32 | rbf
n_grid <- as.integer(25)
x0 <- as.numeric(df[[XC]])
y0 <- as.numeric(df[[YC]])
pr <- cs_spp_project(x0, y0, coordinates)
px <- pr$x
py <- pr$y
z <- as.numeric(df[[Y]])
n <- length(z)
cs_krige_check_sites(px, py, z, list(y = Y, x = XC, y_coord = YC))
res <- cs_krige(px, py, z, method, model, estimator, cutoff, n_lags, kernel, n_grid)
ks <- cs_krige_scales(x0, y0, coordinates)
gx <- res$qx / ks[1] # grid points in the coordinates' own units
gy <- res$qy / ks[2]
pred <- res$pred
sd <- res$sd
rows <- if (!is.null(res$cv_rows)) res$cv_rows + 1L else seq_len(n)
cv <- cs_krige_cv_summary(z[rows], res$cv_err, res$cv_sd)
fit <- res$fit
gp <- res$gp
# %% Assumptions
assumptions <- list()
if (!is.null(fit)) {
min_pairs <- as.integer(min(res$emp$pairs))
assumptions[[1]] <- list(key = "pairs", label = "Enough pairs per distance", status = if (min_pairs >= 30) "pass" else "warn",
detail = paste0(sprintf("The smallest distance class has %d pairs", min_pairs),
if (min_pairs >= 30) ", enough to be stable." else "; classes under 30 pairs make the fitted semivariogram noisy. Use fewer classes or a larger distance."))
} else {
min_pairs <- NA_integer_
assumptions[[1]] <- list(key = "pairs", label = "Enough pairs per distance", status = "info",
detail = "The Gaussian process fits the covariance to the sites directly, without distance classes.")
}
msse <- cv$cv_msse
ok <- !is.nan(msse) && msse >= 0.5 && msse <= 2
assumptions[[2]] <- list(key = "calibration", label = "Standard errors match the errors", status = if (ok) "pass" else "warn",
detail = paste0(sprintf("Left-out sites' squared errors are %.2f times their predicted variances on average", msse),
if (ok) " (near 1: the standard errors are about right)." else if (msse < 0.5) "; the standard errors overstate the errors." else "; the standard errors understate the errors. Try another model or method."))
# %% Result
label <- c(ordinary = "Ordinary kriging", universal = "Universal kriging", gp = "Gaussian process")[[method]]
lower <- pred - 1.959963984540054 * sd
upper <- pred + 1.959963984540054 * sd
values <- list(n = n, method = method, cv_me = cv$cv_me, cv_rmse = cv$cv_rmse, cv_msse = cv$cv_msse, cv_r2 = cv$cv_r2,
n_cv = length(rows), grid_nx = length(res$gx), grid_ny = length(res$gy), pred_min = min(pred), pred_max = max(pred),
sd_min = min(sd), sd_max = max(sd), sd_mean = mean(sd), min_pairs = min_pairs,
missing_share = if (n_input > 0) n_dropped / n_input else 0)
if (!is.null(fit)) {
for (key in c("nugget", "psill", "sill", "range", "effective_range")) values[[key]] <- fit[[key]]
values$cutoff <- res$emp$cutoff
values$n_lags <- length(res$emp$h)
}
if (!is.null(res$trend)) { # slopes per map unit (km for degrees)
span <- max(max(px) - min(px), max(py) - min(py))
values$trend_x <- res$trend[2] / span
values$trend_y <- res$trend[3] / span
}
if (!is.null(gp)) {
values$gp_lengthscale <- gp$lengthscale
values$gp_signal_sd <- gp$signal_sd
values$gp_noise_sd <- gp$noise_sd
values$gp_log_marginal_likelihood <- gp$lml
}
for (key in c("nugget", "psill", "sill", "range", "effective_range", "cutoff", "n_lags", "trend_x", "trend_y", "gp_lengthscale", "gp_signal_sd", "gp_noise_sd", "gp_log_marginal_likelihood")) {
if (is.null(values[[key]])) values[[key]] <- NA_real_ # only some methods produce these
}
summary <- sprintf("%s of %s from %d sites predicts values from %.3g to %.3g over a %d × %d grid. Left out one at a time, the sites are predicted with an RMSE of %.3g (R² %.2f).",
label, Y, n, min(pred), max(pred), length(res$gx), length(res$gy), cv$cv_rmse, cv$cv_r2)
grid_cols <- list(list(key = "x", label = XC, type = "number"), list(key = "y", label = YC, type = "number"), list(key = "prediction", label = "Prediction", type = "number"),
list(key = "se", label = "Standard error", type = "number"), list(key = "lower", label = "95% low", type = "number"), list(key = "upper", label = "95% high", type = "number"),
list(key = "nearest", label = "Nearest site", type = "number"))
grid_rows <- lapply(seq_along(pred), function(k) list(x = gx[k], y = gy[k], prediction = pred[k], se = sd[k], lower = lower[k], upper = upper[k], nearest = res$nearest[k]))
loo_pred <- z[rows] - res$cv_err
cv_cols <- list(list(key = "x", label = XC, type = "number"), list(key = "y", label = YC, type = "number"), list(key = "observed", label = "Observed", type = "number"),
list(key = "predicted", label = "Left-out prediction", type = "number"), list(key = "se", label = "Standard error", type = "number"), list(key = "z", label = "Standardized error", type = "number"))
cv_rows <- lapply(seq_along(rows), function(k) {
i <- rows[k]
list(x = x0[i], y = y0[i], observed = z[i], predicted = loo_pred[k], se = res$cv_sd[k], z = if (res$cv_sd[k] > 0) res$cv_err[k] / res$cv_sd[k] else NA_real_)
})
model_rows <- if (!is.null(fit)) {
list(list(setting = "Nugget", value = fit$nugget), list(setting = "Partial sill", value = fit$psill), list(setting = "Sill", value = fit$sill),
list(setting = "Range parameter", value = fit$range), list(setting = "Practical range", value = fit$effective_range))
} else {
list(list(setting = "Lengthscale (map units)", value = gp$lengthscale), list(setting = "Signal SD", value = gp$signal_sd),
list(setting = "Noise SD", value = gp$noise_sd), list(setting = "Log marginal likelihood", value = gp$lml))
}
tables <- list(
list(key = "model", title = if (!is.null(fit)) "Semivariogram model" else "Gaussian process settings",
columns = list(list(key = "setting", label = "Setting", type = "string"), list(key = "value", label = "Value", type = "number")), rows = model_rows),
list(key = "cv", title = "Leave-one-out predictions at the sites", columns = cv_cols, rows = cv_rows),
list(key = "grid", title = "Predictions on the grid", columns = grid_cols, rows = grid_rows)
)
kind <- c(rep("grid", length(pred)), rep("point", n))
xs <- c(gx, x0)
ys <- c(gy, y0)
charts <- list(
cs_chart("prediction", "contour-grid", sprintf("Predicted %s", Y),
list(x = cs_col(XC, xs), y = cs_col(YC, ys), z = cs_col(sprintf("Predicted %s", Y), c(pred, z)),
kind = cs_col("kind", kind, "categorical", c("grid", "point")))),
cs_chart("se", "contour-grid", "Standard error of the prediction",
list(x = cs_col(XC, xs), y = cs_col(YC, ys), z = cs_col("Standard error", c(sd, rep(NA_real_, n)), "numeric"),
kind = cs_col("kind", kind, "categorical", c("grid", "point")))),
cs_chart("loo", "pred-actual", "Left-out predictions at the sites",
list(actual = cs_col(sprintf("Observed %s", Y), z[rows]), predicted = cs_col("Left-out prediction", loo_pred)))
)
if (!is.null(fit)) {
emp <- res$emp
charts[[length(charts) + 1L]] <- cs_chart("variogram", "variogram", sprintf("Semivariogram used for kriging%s", if (method == "universal") " (trend removed)" else ""),
list(h = cs_col("Distance", emp$h), gamma = cs_col("Semivariance", emp$gamma), pairs = cs_col("Pairs", emp$pairs),
fitted = cs_col("Fitted", res$fitted)), controls = list(variance = stats::var(z)))
}
statistics <- list(list(key = "cv_rmse", label = "LOO RMSE", value = cv$cv_rmse), list(key = "cv_r2", label = "LOO R²", value = cv$cv_r2),
list(key = "cv_msse", label = "Mean squared standardized error", value = cv$cv_msse))
notes <- list(sprintf("Grid: %d × %d points over the sites' bounding box; 95%% intervals are the prediction ± 1.96 standard errors.", length(res$gx), length(res$gy)))
if (!is.null(fit)) {
notes[[2]] <- paste0(sprintf("A %s semivariogram (nugget %.4g, partial sill %.4g, range parameter %.4g) fitted by weighted least squares to %d distance classes",
model, fit$nugget, fit$psill, fit$range, length(res$emp$h)),
if (method == "universal") " of the residuals from a trend in the coordinates." else ".")
} else {
notes[[2]] <- sprintf("Gaussian process with a %s kernel fitted to %d sites by maximum likelihood (lengthscale %.4g map units).", kernel, as.integer(gp$n_fit), gp$lengthscale)
}
if (coordinates == "lonlat") {
notes[[length(notes) + 1L]] <- "Longitude and latitude were projected to kilometers at the sites' mean latitude; distances, ranges and trends are in kilometers."
}
cs_publish(list(
method = "spatial.kriging",
methodVersion = "1.0.0",
title = label,
engine = cs_engine_info("stats"),
n = n,
summary = summary,
apa = sprintf("LOO RMSE = %.3g, R² = %.2f, MSSE = %.2f, n = %d", cv$cv_rmse, cv$cv_r2, cv$cv_msse, n),
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
values = values,
charts = charts
))
LOO RMSE = 0.389, R² = 0.71, MSSE = 0.88, n = 155
- LOO RMSE
- 0.3891
- LOO R²
- 0.7075
- Mean squared standardized error
- 0.8771
Assumptions
- Enough pairs per distance — The smallest distance class has 52 pairs, enough to be stable.
- Standard errors match the errors — Left-out sites' squared errors are 0.88 times their predicted variances on average (near 1: the standard errors are about right).
Semivariogram model
| Setting | Value |
|---|---|
| Nugget | 0.0620 |
| Partial sill | 0.4987 |
| Sill | 0.5607 |
| Range parameter | 655.64 |
| Practical range | 1966.93 |
Leave-one-out predictions at the sites
| x | y | Observed | Left-out prediction | Standard error | Standardized error |
|---|---|---|---|---|---|
| 181,072 | 333,611 | 6.930 | 6.776 | 0.4134 | 0.3714 |
| 181,025 | 333,558 | 7.040 | 6.756 | 0.4053 | 0.6995 |
| 181,165 | 333,537 | 6.461 | 6.297 | 0.4086 | 0.4025 |
| 181,298 | 333,484 | 5.549 | 6.031 | 0.4483 | −1.076 |
| 181,307 | 333,330 | 5.595 | 5.586 | 0.4025 | 0.0205 |
| 181,390 | 333,260 | 5.638 | 5.346 | 0.4517 | 0.6463 |
| 181,165 | 333,370 | 5.846 | 5.884 | 0.4026 | −0.0940 |
| 181,027 | 333,363 | 6.006 | 6.380 | 0.3997 | −0.9358 |
| 181,060 | 333,231 | 5.849 | 5.820 | 0.3570 | 0.0820 |
| 181,232 | 333,168 | 5.209 | 5.414 | 0.3834 | −0.5323 |
| 181,191 | 333,115 | 5.242 | 5.363 | 0.3826 | −0.3161 |
| 181,032 | 333,031 | 5.525 | 5.549 | 0.4102 | −0.0567 |
| 180,874 | 333,339 | 6.999 | 6.689 | 0.4163 | 0.7455 |
| 180,969 | 333,252 | 6.223 | 6.209 | 0.3745 | 0.0373 |
| 181,011 | 333,161 | 5.787 | 5.842 | 0.3761 | −0.1457 |
| 180,830 | 333,246 | 6.939 | 6.598 | 0.4028 | 0.8477 |
| 180,763 | 333,104 | 6.407 | 6.483 | 0.4117 | −0.1856 |
| 180,694 | 332,972 | 6.567 | 6.369 | 0.4064 | 0.4862 |
| 180,625 | 332,847 | 6.600 | 6.531 | 0.3971 | 0.1744 |
| 180,555 | 332,707 | 6.958 | 6.684 | 0.4016 | 0.6835 |
| 180,642 | 332,708 | 6.512 | 6.343 | 0.3582 | 0.4699 |
| 180,704 | 332,717 | 5.996 | 6.098 | 0.3590 | −0.2827 |
| 180,704 | 332,664 | 5.838 | 6.114 | 0.3704 | −0.7456 |
| 181,153 | 332,925 | 5.384 | 5.290 | 0.4030 | 0.2346 |
| 181,147 | 332,823 | 5.298 | 5.287 | 0.3651 | 0.0304 |
| 181,167 | 332,778 | 5.268 | 5.259 | 0.3830 | 0.0236 |
| 181,008 | 332,777 | 5.333 | 5.325 | 0.3808 | 0.0197 |
| 180,973 | 332,687 | 5.193 | 5.382 | 0.3914 | −0.4837 |
| 180,916 | 332,753 | 5.481 | 5.418 | 0.3833 | 0.1636 |
| 181,352 | 332,946 | 5.193 | 5.204 | 0.4992 | −0.0230 |
| 181,133 | 332,570 | 5.338 | 5.130 | 0.4806 | 0.4328 |
| 180,878 | 332,489 | 5.288 | 5.470 | 0.3832 | −0.4744 |
| 180,829 | 332,450 | 5.521 | 5.514 | 0.3824 | 0.0194 |
| 180,954 | 332,399 | 5.257 | 5.324 | 0.3924 | −0.1704 |
| 180,956 | 332,318 | 5.361 | 5.205 | 0.4356 | 0.3588 |
| 180,710 | 332,330 | 5.771 | 5.571 | 0.4293 | 0.4659 |
| 180,632 | 332,445 | 6.344 | 6.015 | 0.4103 | 0.8009 |
| 180,530 | 332,538 | 6.725 | 6.624 | 0.3800 | 0.2661 |
| 180,478 | 332,578 | 6.809 | 6.931 | 0.3885 | −0.3132 |
| 180,383 | 332,476 | 7.282 | 6.739 | 0.4254 | 1.278 |
First 40 of 50 rows.
Predictions on the grid
| x | y | Prediction | Standard error | 95% low | 95% high | Nearest site |
|---|---|---|---|---|---|---|
| 178,605 | 329,714 | 6.713 | 0.5877 | 5.562 | 7.865 | 210.77 |
| 178768.82 | 329,714 | 6.606 | 0.4797 | 5.665 | 7.546 | 109.36 |
| 178932.65 | 329,714 | 6.430 | 0.4331 | 5.581 | 7.279 | 93.308 |
| 179096.47 | 329,714 | 6.287 | 0.4018 | 5.500 | 7.075 | 74.920 |
| 179260.29 | 329,714 | 6.292 | 0.3503 | 5.605 | 6.978 | 15.294 |
| 179424.12 | 329,714 | 6.039 | 0.4392 | 5.178 | 6.900 | 95.316 |
| 179587.94 | 329,714 | 5.750 | 0.5228 | 4.725 | 6.775 | 170.53 |
| 179751.76 | 329,714 | 5.625 | 0.6064 | 4.436 | 6.813 | 302.96 |
| 179915.59 | 329,714 | 5.605 | 0.6634 | 4.305 | 6.905 | 429.80 |
| 180079.41 | 329,714 | 5.592 | 0.6978 | 4.225 | 6.960 | 575.63 |
| 180243.24 | 329,714 | 5.533 | 0.7185 | 4.124 | 6.941 | 611.43 |
| 180407.06 | 329,714 | 5.407 | 0.7345 | 3.968 | 6.847 | 524.36 |
| 180570.88 | 329,714 | 5.221 | 0.7555 | 3.740 | 6.702 | 479.30 |
| 180734.71 | 329,714 | 4.990 | 0.7915 | 3.439 | 6.542 | 488.03 |
| 180898.53 | 329,714 | 4.735 | 0.8432 | 3.082 | 6.387 | 548.00 |
| 181062.35 | 329,714 | 4.474 | 0.9029 | 2.704 | 6.244 | 645.06 |
| 181226.18 | 329,714 | 4.219 | 0.9639 | 2.330 | 6.109 | 765.24 |
| 181,390 | 329,714 | 3.977 | 1.023 | 1.971 | 5.982 | 899.30 |
| 178,605 | 329876.38 | 6.642 | 0.5525 | 5.559 | 7.724 | 188.99 |
| 178768.82 | 329876.38 | 6.487 | 0.4160 | 5.672 | 7.303 | 57.023 |
| 178932.65 | 329876.38 | 6.150 | 0.4344 | 5.298 | 7.001 | 156.40 |
| 179096.47 | 329876.38 | 5.802 | 0.3721 | 5.073 | 6.532 | 40.868 |
| 179260.29 | 329876.38 | 5.877 | 0.3842 | 5.124 | 6.630 | 76.970 |
| 179424.12 | 329876.38 | 5.767 | 0.3740 | 5.034 | 6.500 | 72.450 |
| 179587.94 | 329876.38 | 5.465 | 0.4242 | 4.634 | 6.297 | 74.079 |
| 179751.76 | 329876.38 | 5.551 | 0.5505 | 4.472 | 6.630 | 211.56 |
| 179915.59 | 329876.38 | 5.696 | 0.6168 | 4.487 | 6.905 | 371.08 |
| 180079.41 | 329876.38 | 5.800 | 0.6465 | 4.532 | 7.067 | 481.97 |
| 180243.24 | 329876.38 | 5.799 | 0.6575 | 4.510 | 7.088 | 485.47 |
| 180407.06 | 329876.38 | 5.681 | 0.6598 | 4.388 | 6.974 | 383.06 |
| 180570.88 | 329876.38 | 5.475 | 0.6673 | 4.167 | 6.783 | 318.61 |
| 180734.71 | 329876.38 | 5.208 | 0.7057 | 3.825 | 6.591 | 331.60 |
| 180898.53 | 329876.38 | 4.913 | 0.7740 | 3.396 | 6.430 | 414.84 |
| 181062.35 | 329876.38 | 4.620 | 0.8491 | 2.956 | 6.284 | 536.56 |
| 181226.18 | 329876.38 | 4.344 | 0.9202 | 2.541 | 6.148 | 676.29 |
| 181,390 | 329876.38 | 4.088 | 0.9854 | 2.157 | 6.020 | 824.94 |
| 178,605 | 330038.75 | 6.493 | 0.5560 | 5.403 | 7.582 | 282.39 |
| 178768.82 | 330038.75 | 6.207 | 0.4931 | 5.240 | 7.173 | 217.43 |
| 178932.65 | 330038.75 | 5.824 | 0.4355 | 4.971 | 6.678 | 106.53 |
| 179096.47 | 330038.75 | 5.460 | 0.3884 | 4.698 | 6.221 | 79.303 |
First 40 of 50 rows.
- Grid: 18 × 25 points over the sites' bounding box; 95% intervals are the prediction ± 1.96 standard errors.
- A exponential semivariogram (nugget 0.06196, partial sill 0.4987, range parameter 655.6) fitted by weighted least squares to 15 distance classes of the residuals from a trend in the coordinates.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kriging (ordinary, universal, Gaussian process)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.kriging 1.0.0 · spec c38a531afe194bdf
# Dataset: sp_meuse (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import kriging as kr
from codesplash.stats import spatial_points as spp
# Classic equivalent: gstat::krige(z ~ 1, sites, grid, model = fit.variogram(variogram(z ~ 1, sites), vgm("Sph")))
# and gstat::krige.cv(); in Python pykrige.ok.OrdinaryKriging(x, y, z, variogram_model="spherical").
# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_meuse.parquet", columns=["log_zinc", "x", "y"])
n_input = len(df)
df = df.dropna(subset=["log_zinc", "x", "y"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["log_zinc", "x", "y"]) # infinite values stop the run (registry/errors.yaml)
# %% Fit
# Ordinary or universal kriging from spatial.variogram's fitted semivariogram (Matheron 1963; Cressie 1993), or a
# Gaussian process on the coordinates; predictions on a grid over the sites and Dubrule's (1983) leave-one-out.
Y = "log_zinc"
XC = "x"
YC = "y"
coordinates = "planar" # planar | lonlat
method = "universal" # ordinary | universal | gp
model = "exponential" # spherical | exponential | gaussian
estimator = "matheron" # matheron | cressie
cutoff = 1500
n_lags = int(15)
kernel = "matern52" # matern52 | matern32 | rbf
n_grid = int(25)
x0 = df[XC].to_numpy(dtype=float)
y0 = df[YC].to_numpy(dtype=float)
px, py = spp.project(x0, y0, coordinates)
z = df[Y].to_numpy(dtype=float)
n = z.size
kr.check_sites(px, py, z, {"y": Y, "x": XC, "y_coord": YC})
res = kr.krige(px, py, z, method, model, estimator, cutoff, n_lags, kernel, n_grid)
kx, ky = kr.scales(x0, y0, coordinates)
gx, gy = res["qx"] / kx, res["qy"] / ky # grid points in the coordinates' own units
pred, sd = res["pred"], res["sd"]
rows = res["cv_rows"] if "cv_rows" in res else np.arange(n)
cv = kr.cv_summary(z[rows], res["cv_err"], res["cv_sd"])
fit = res.get("fit")
gp = res.get("gp")
# %% Assumptions
assumptions = []
if fit is not None:
min_pairs = int(np.min(res["emp"]["pairs"]))
assumptions.append({"key": "pairs", "label": "Enough pairs per distance", "status": "pass" if min_pairs >= 30 else "warn",
"detail": f"The smallest distance class has {min_pairs} pairs" + (", enough to be stable." if min_pairs >= 30 else "; classes under 30 pairs make the fitted semivariogram noisy. Use fewer classes or a larger distance.")})
else:
min_pairs = None
assumptions.append({"key": "pairs", "label": "Enough pairs per distance", "status": "info",
"detail": "The Gaussian process fits the covariance to the sites directly, without distance classes."})
msse = cv["cv_msse"]
ok = msse == msse and 0.5 <= msse <= 2.0
assumptions.append({"key": "calibration", "label": "Standard errors match the errors", "status": "pass" if ok else "warn",
"detail": f"Left-out sites' squared errors are {msse:.2f} times their predicted variances on average"
+ (" (near 1: the standard errors are about right)." if ok else ("; the standard errors overstate the errors." if msse < 0.5 else "; the standard errors understate the errors. Try another model or method."))})
# %% Result
label = {"ordinary": "Ordinary kriging", "universal": "Universal kriging", "gp": "Gaussian process"}[method]
lower, upper = pred - 1.959963984540054 * sd, pred + 1.959963984540054 * sd
values = {"n": n, "method": method, "cv_me": cv["cv_me"], "cv_rmse": cv["cv_rmse"], "cv_msse": cv["cv_msse"], "cv_r2": cv["cv_r2"],
"n_cv": int(rows.size), "grid_nx": int(res["gx"].size), "grid_ny": int(res["gy"].size), "pred_min": float(np.min(pred)),
"pred_max": float(np.max(pred)), "sd_min": float(np.min(sd)), "sd_max": float(np.max(sd)), "sd_mean": float(np.mean(sd)),
"min_pairs": min_pairs, "missing_share": n_dropped / n_input if n_input else 0.0}
if fit is not None:
values.update({key: fit[key] for key in ("nugget", "psill", "sill", "range", "effective_range")})
values.update({"cutoff": res["emp"]["cutoff"], "n_lags": int(res["emp"]["h"].size)})
if "trend" in res: # slopes per map unit (km for degrees)
span = max(float(np.max(px) - np.min(px)), float(np.max(py) - np.min(py)))
values.update({"trend_x": float(res["trend"][1]) / span, "trend_y": float(res["trend"][2]) / span})
if gp is not None:
values.update({"gp_lengthscale": gp["lengthscale"], "gp_signal_sd": gp["signal_sd"], "gp_noise_sd": gp["noise_sd"], "gp_log_marginal_likelihood": gp["lml"]})
for key in ("nugget", "psill", "sill", "range", "effective_range", "cutoff", "n_lags", "trend_x", "trend_y", "gp_lengthscale", "gp_signal_sd", "gp_noise_sd", "gp_log_marginal_likelihood"):
values.setdefault(key, None) # only some methods produce these
summary = (f"{label} of {Y} from {n} sites predicts values from {np.min(pred):.3g} to {np.max(pred):.3g} over a {res['gx'].size} × {res['gy'].size} grid. "
f"Left out one at a time, the sites are predicted with an RMSE of {cv['cv_rmse']:.3g} (R² {cv['cv_r2']:.2f}).")
grid_cols = [{"key": "x", "label": XC, "type": "number"}, {"key": "y", "label": YC, "type": "number"}, {"key": "prediction", "label": "Prediction", "type": "number"},
{"key": "se", "label": "Standard error", "type": "number"}, {"key": "lower", "label": "95% low", "type": "number"}, {"key": "upper", "label": "95% high", "type": "number"},
{"key": "nearest", "label": "Nearest site", "type": "number"}]
grid_rows = [{"x": float(gx[k]), "y": float(gy[k]), "prediction": float(pred[k]), "se": float(sd[k]), "lower": float(lower[k]), "upper": float(upper[k]),
"nearest": float(res["nearest"][k])} for k in range(pred.size)]
loo_pred = z[rows] - res["cv_err"]
cv_cols = [{"key": "x", "label": XC, "type": "number"}, {"key": "y", "label": YC, "type": "number"}, {"key": "observed", "label": "Observed", "type": "number"},
{"key": "predicted", "label": "Left-out prediction", "type": "number"}, {"key": "se", "label": "Standard error", "type": "number"}, {"key": "z", "label": "Standardized error", "type": "number"}]
cv_rows = [{"x": float(x0[i]), "y": float(y0[i]), "observed": float(z[i]), "predicted": float(loo_pred[k]), "se": float(res["cv_sd"][k]),
"z": float(res["cv_err"][k] / res["cv_sd"][k]) if res["cv_sd"][k] > 0 else None} for k, i in enumerate(rows.tolist())]
if fit is not None:
model_rows = [{"setting": "Nugget", "value": fit["nugget"]}, {"setting": "Partial sill", "value": fit["psill"]}, {"setting": "Sill", "value": fit["sill"]},
{"setting": "Range parameter", "value": fit["range"]}, {"setting": "Practical range", "value": fit["effective_range"]}]
else:
model_rows = [{"setting": "Lengthscale (map units)", "value": gp["lengthscale"]}, {"setting": "Signal SD", "value": gp["signal_sd"]},
{"setting": "Noise SD", "value": gp["noise_sd"]}, {"setting": "Log marginal likelihood", "value": gp["lml"]}]
tables = [
{"key": "model", "title": "Semivariogram model" if fit is not None else "Gaussian process settings",
"columns": [{"key": "setting", "label": "Setting", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": model_rows},
{"key": "cv", "title": "Leave-one-out predictions at the sites", "columns": cv_cols, "rows": cv_rows},
{"key": "grid", "title": "Predictions on the grid", "columns": grid_cols, "rows": grid_rows},
]
kind = ["grid"] * pred.size + ["point"] * n
xs = np.concatenate([gx, x0])
ys = np.concatenate([gy, y0])
charts = [
cs.chart("prediction", "contour-grid", f"Predicted {Y}",
{"x": cs.col(XC, xs), "y": cs.col(YC, ys), "z": cs.col(f"Predicted {Y}", np.concatenate([pred, z])),
"kind": cs.col("kind", kind, "categorical", ["grid", "point"])}),
cs.chart("se", "contour-grid", "Standard error of the prediction",
{"x": cs.col(XC, xs), "y": cs.col(YC, ys), "z": cs.col("Standard error", list(sd.tolist()) + [None] * n, "numeric"),
"kind": cs.col("kind", kind, "categorical", ["grid", "point"])}),
cs.chart("loo", "pred-actual", "Left-out predictions at the sites",
{"actual": cs.col(f"Observed {Y}", z[rows]), "predicted": cs.col("Left-out prediction", loo_pred)}),
]
if fit is not None:
emp = res["emp"]
charts.append(cs.chart("variogram", "variogram", f"Semivariogram used for kriging{' (trend removed)' if method == 'universal' else ''}",
{"h": cs.col("Distance", emp["h"]), "gamma": cs.col("Semivariance", emp["gamma"]), "pairs": cs.col("Pairs", emp["pairs"]),
"fitted": cs.col("Fitted", res["fitted"])}, controls={"variance": float(np.var(z, ddof=1))}))
statistics = [{"key": "cv_rmse", "label": "LOO RMSE", "value": cv["cv_rmse"]}, {"key": "cv_r2", "label": "LOO R²", "value": cv["cv_r2"]},
{"key": "cv_msse", "label": "Mean squared standardized error", "value": cv["cv_msse"]}]
notes = [f"Grid: {res['gx'].size} × {res['gy'].size} points over the sites' bounding box; 95% intervals are the prediction ± 1.96 standard errors."]
if fit is not None:
notes.append(f"A {model} semivariogram (nugget {fit['nugget']:.4g}, partial sill {fit['psill']:.4g}, range parameter {fit['range']:.4g}) fitted by weighted least squares to {int(res['emp']['h'].size)} distance classes"
+ (" of the residuals from a trend in the coordinates." if method == "universal" else "."))
else:
notes.append(f"Gaussian process with a {kernel} kernel fitted to {gp['n_fit']} sites by maximum likelihood (lengthscale {gp['lengthscale']:.4g} map units).")
if coordinates == "lonlat":
notes.append("Longitude and latitude were projected to kilometers at the sites' mean latitude; distances, ranges and trends are in kilometers.")
cs.publish({
"method": "spatial.kriging",
"methodVersion": "1.0.0",
"title": label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"LOO RMSE = {cv['cv_rmse']:.3g}, R² = {cv['cv_r2']:.2f}, MSSE = {cv['cv_msse']:.2f}, n = {n}",
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"values": values,
"charts": charts,
})
Shortened for the Academy: 4 chart(s) dropped to stay under 100 KB; a table cut from 155 to 50 rows; a table cut from 450 to 50 rows; 4 chart(s) dropped to stay under 100 KB; a table cut from 155 to 50 rows; a table cut from 450 to 50 rows.
Its left-out RMSE is 0.389. A Gaussian process skips the semivariogram and fits the covariance's scale, smoothness and noise by maximum likelihood:
LOO RMSE = 0.387, R² = 0.71, MSSE = 1.01, n = 155
- LOO RMSE
- 0.3867
- LOO R²
- 0.7112
- Mean squared standardized error
- 1.007
Assumptions
- Enough pairs per distance — The Gaussian process fits the covariance to the sites directly, without distance classes.
- Standard errors match the errors — Left-out sites' squared errors are 1.01 times their predicted variances on average (near 1: the standard errors are about right).
Gaussian process settings
| Setting | Value |
|---|---|
| Lengthscale (map units) | 575.91 |
| Signal SD | 1.078 |
| Noise SD | 0.3225 |
| Log marginal likelihood | −149.49 |
Leave-one-out predictions at the sites
| x | y | Observed | Left-out prediction | Standard error | Standardized error |
|---|---|---|---|---|---|
| 181,072 | 333,611 | 6.930 | 6.751 | 0.4132 | 0.4317 |
| 181,025 | 333,558 | 7.040 | 6.789 | 0.3933 | 0.6374 |
| 181,165 | 333,537 | 6.461 | 6.303 | 0.3761 | 0.4206 |
| 181,298 | 333,484 | 5.549 | 6.049 | 0.4153 | −1.204 |
| 181,307 | 333,330 | 5.595 | 5.529 | 0.3721 | 0.1753 |
| 181,390 | 333,260 | 5.638 | 5.261 | 0.4254 | 0.8874 |
| 181,165 | 333,370 | 5.846 | 5.905 | 0.3605 | −0.1617 |
| 181,027 | 333,363 | 6.006 | 6.404 | 0.3604 | −1.103 |
| 181,060 | 333,231 | 5.849 | 5.828 | 0.3501 | 0.0613 |
| 181,232 | 333,168 | 5.209 | 5.401 | 0.3614 | −0.5300 |
| 181,191 | 333,115 | 5.242 | 5.362 | 0.3600 | −0.3352 |
| 181,032 | 333,031 | 5.525 | 5.482 | 0.3630 | 0.1189 |
| 180,874 | 333,339 | 6.999 | 6.730 | 0.3881 | 0.6938 |
| 180,969 | 333,252 | 6.223 | 6.200 | 0.3515 | 0.0638 |
| 181,011 | 333,161 | 5.787 | 5.810 | 0.3523 | −0.0651 |
| 180,830 | 333,246 | 6.939 | 6.594 | 0.3759 | 0.9170 |
| 180,763 | 333,104 | 6.407 | 6.521 | 0.3780 | −0.3027 |
| 180,694 | 332,972 | 6.567 | 6.406 | 0.3763 | 0.4281 |
| 180,625 | 332,847 | 6.600 | 6.565 | 0.3708 | 0.0954 |
| 180,555 | 332,707 | 6.958 | 6.721 | 0.3688 | 0.6430 |
| 180,642 | 332,708 | 6.512 | 6.361 | 0.3527 | 0.4280 |
| 180,704 | 332,717 | 5.996 | 6.137 | 0.3545 | −0.3969 |
| 180,704 | 332,664 | 5.838 | 6.130 | 0.3574 | −0.8181 |
| 181,153 | 332,925 | 5.384 | 5.219 | 0.3630 | 0.4563 |
| 181,147 | 332,823 | 5.298 | 5.229 | 0.3622 | 0.1902 |
| 181,167 | 332,778 | 5.268 | 5.239 | 0.3725 | 0.0770 |
| 181,008 | 332,777 | 5.333 | 5.296 | 0.3565 | 0.1025 |
| 180,973 | 332,687 | 5.193 | 5.351 | 0.3623 | −0.4373 |
| 180,916 | 332,753 | 5.481 | 5.418 | 0.3604 | 0.1750 |
| 181,352 | 332,946 | 5.193 | 5.323 | 0.4631 | −0.2799 |
| 181,133 | 332,570 | 5.338 | 5.238 | 0.4351 | 0.2283 |
| 180,878 | 332,489 | 5.288 | 5.483 | 0.3641 | −0.5338 |
| 180,829 | 332,450 | 5.521 | 5.509 | 0.3632 | 0.0339 |
| 180,954 | 332,399 | 5.257 | 5.336 | 0.3761 | −0.2096 |
| 180,956 | 332,318 | 5.361 | 5.190 | 0.4266 | 0.4011 |
| 180,710 | 332,330 | 5.771 | 5.427 | 0.3802 | 0.9057 |
| 180,632 | 332,445 | 6.344 | 5.946 | 0.3657 | 1.087 |
| 180,530 | 332,538 | 6.725 | 6.612 | 0.3596 | 0.3154 |
| 180,478 | 332,578 | 6.809 | 6.955 | 0.3709 | −0.3949 |
| 180,383 | 332,476 | 7.282 | 6.896 | 0.3778 | 1.023 |
First 40 of 50 rows.
Predictions on the grid
| x | y | Prediction | Standard error | 95% low | 95% high | Nearest site |
|---|---|---|---|---|---|---|
| 178,605 | 329,714 | 6.700 | 0.6123 | 5.500 | 7.900 | 210.77 |
| 178819.23 | 329,714 | 6.623 | 0.4497 | 5.742 | 7.505 | 113.00 |
| 179033.46 | 329,714 | 6.421 | 0.3981 | 5.641 | 7.201 | 21.225 |
| 179247.69 | 329,714 | 6.310 | 0.3889 | 5.548 | 7.072 | 2.692 |
| 179461.92 | 329,714 | 6.137 | 0.4390 | 5.276 | 6.997 | 94.527 |
| 179676.15 | 329,714 | 5.985 | 0.5981 | 4.813 | 7.157 | 249.16 |
| 179890.38 | 329,714 | 6.091 | 0.7848 | 4.553 | 7.629 | 408.58 |
| 180104.62 | 329,714 | 6.265 | 0.8945 | 4.512 | 8.018 | 598.89 |
| 180318.85 | 329,714 | 6.267 | 0.9227 | 4.458 | 8.075 | 567.04 |
| 180533.08 | 329,714 | 6.093 | 0.9098 | 4.310 | 7.876 | 485.18 |
| 180747.31 | 329,714 | 5.896 | 0.9191 | 4.094 | 7.697 | 490.97 |
| 180961.54 | 329,714 | 5.781 | 0.9760 | 3.868 | 7.694 | 581.80 |
| 181175.77 | 329,714 | 5.751 | 1.042 | 3.709 | 7.793 | 726.45 |
| 181,390 | 329,714 | 5.768 | 1.087 | 3.638 | 7.898 | 899.30 |
| 178,605 | 329919.11 | 6.464 | 0.5563 | 5.373 | 7.554 | 205.40 |
| 178819.23 | 329919.11 | 6.224 | 0.4168 | 5.407 | 7.041 | 102.63 |
| 179033.46 | 329919.11 | 5.855 | 0.3797 | 5.111 | 6.600 | 105.63 |
| 179247.69 | 329919.11 | 5.665 | 0.3637 | 4.953 | 6.378 | 101.92 |
| 179461.92 | 329919.11 | 5.525 | 0.3663 | 4.807 | 6.243 | 90.521 |
| 179676.15 | 329919.11 | 5.586 | 0.4807 | 4.644 | 6.528 | 127.87 |
| 179890.38 | 329919.11 | 6.047 | 0.6688 | 4.736 | 7.358 | 341.03 |
| 180104.62 | 329919.11 | 6.482 | 0.7631 | 4.986 | 7.978 | 436.37 |
| 180318.85 | 329919.11 | 6.503 | 0.7640 | 5.005 | 8.000 | 410.30 |
| 180533.08 | 329919.11 | 6.188 | 0.7110 | 4.795 | 7.582 | 286.72 |
| 180747.31 | 329919.11 | 5.868 | 0.7269 | 4.443 | 7.293 | 296.41 |
| 180961.54 | 329919.11 | 5.711 | 0.8603 | 4.025 | 7.397 | 430.46 |
| 181175.77 | 329919.11 | 5.686 | 0.9905 | 3.745 | 7.628 | 611.99 |
| 181,390 | 329919.11 | 5.721 | 1.067 | 3.629 | 7.813 | 809.66 |
| 178,605 | 330124.21 | 6.211 | 0.5280 | 5.176 | 7.245 | 281.79 |
| 178819.23 | 330124.21 | 5.926 | 0.4226 | 5.098 | 6.755 | 194.94 |
| 179033.46 | 330124.21 | 5.586 | 0.3713 | 4.858 | 6.314 | 42.352 |
| 179247.69 | 330124.21 | 5.276 | 0.3581 | 4.574 | 5.978 | 76.443 |
| 179461.92 | 330124.21 | 5.103 | 0.3676 | 4.383 | 5.824 | 52.545 |
| 179676.15 | 330124.21 | 5.356 | 0.4452 | 4.484 | 6.229 | 176.84 |
| 179890.38 | 330124.21 | 6.108 | 0.5631 | 5.005 | 7.212 | 346.79 |
| 180104.62 | 330124.21 | 6.776 | 0.5829 | 5.633 | 7.918 | 233.44 |
| 180318.85 | 330124.21 | 6.757 | 0.5515 | 5.676 | 7.838 | 241.80 |
| 180533.08 | 330124.21 | 6.254 | 0.4784 | 5.317 | 7.192 | 114.67 |
| 180747.31 | 330124.21 | 5.814 | 0.5347 | 4.766 | 6.862 | 137.12 |
| 180961.54 | 330124.21 | 5.631 | 0.7713 | 4.120 | 7.143 | 340.95 |
First 40 of 50 rows.
- Grid: 14 × 20 points over the sites' bounding box; 95% intervals are the prediction ± 1.96 standard errors.
- Gaussian process with a matern52 kernel fitted to 155 sites by maximum likelihood (lengthscale 575.9 map units).
The exact R script · R R version 4.5.1 (2025-06-13)
# Kriging (ordinary, universal, Gaussian process)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.kriging 1.0.0 · spec 66b6fb15a28818d4
# Dataset: sp_meuse (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# Classic equivalent: gstat::krige(z ~ 1, sites, grid, model = fit.variogram(variogram(z ~ 1, sites), vgm("Sph")))
# and gstat::krige.cv().
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sp_meuse.parquet", col_select = c("log_zinc", "x", "y")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("log_zinc", "x", "y")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("log_zinc", "x", "y")) # infinite values stop the run (registry/errors.yaml)
# %% Fit
# Ordinary or universal kriging from spatial.variogram's fitted semivariogram (Matheron 1963; Cressie 1993), or a
# Gaussian process on the coordinates; predictions on a grid over the sites and Dubrule's (1983) leave-one-out.
Y <- "log_zinc"
XC <- "x"
YC <- "y"
coordinates <- "planar" # planar | lonlat
method <- "gp" # ordinary | universal | gp
model <- "spherical" # spherical | exponential | gaussian
estimator <- "matheron" # matheron | cressie
cutoff <- NULL
n_lags <- as.integer(15)
kernel <- "matern52" # matern52 | matern32 | rbf
n_grid <- as.integer(20)
x0 <- as.numeric(df[[XC]])
y0 <- as.numeric(df[[YC]])
pr <- cs_spp_project(x0, y0, coordinates)
px <- pr$x
py <- pr$y
z <- as.numeric(df[[Y]])
n <- length(z)
cs_krige_check_sites(px, py, z, list(y = Y, x = XC, y_coord = YC))
res <- cs_krige(px, py, z, method, model, estimator, cutoff, n_lags, kernel, n_grid)
ks <- cs_krige_scales(x0, y0, coordinates)
gx <- res$qx / ks[1] # grid points in the coordinates' own units
gy <- res$qy / ks[2]
pred <- res$pred
sd <- res$sd
rows <- if (!is.null(res$cv_rows)) res$cv_rows + 1L else seq_len(n)
cv <- cs_krige_cv_summary(z[rows], res$cv_err, res$cv_sd)
fit <- res$fit
gp <- res$gp
# %% Assumptions
assumptions <- list()
if (!is.null(fit)) {
min_pairs <- as.integer(min(res$emp$pairs))
assumptions[[1]] <- list(key = "pairs", label = "Enough pairs per distance", status = if (min_pairs >= 30) "pass" else "warn",
detail = paste0(sprintf("The smallest distance class has %d pairs", min_pairs),
if (min_pairs >= 30) ", enough to be stable." else "; classes under 30 pairs make the fitted semivariogram noisy. Use fewer classes or a larger distance."))
} else {
min_pairs <- NA_integer_
assumptions[[1]] <- list(key = "pairs", label = "Enough pairs per distance", status = "info",
detail = "The Gaussian process fits the covariance to the sites directly, without distance classes.")
}
msse <- cv$cv_msse
ok <- !is.nan(msse) && msse >= 0.5 && msse <= 2
assumptions[[2]] <- list(key = "calibration", label = "Standard errors match the errors", status = if (ok) "pass" else "warn",
detail = paste0(sprintf("Left-out sites' squared errors are %.2f times their predicted variances on average", msse),
if (ok) " (near 1: the standard errors are about right)." else if (msse < 0.5) "; the standard errors overstate the errors." else "; the standard errors understate the errors. Try another model or method."))
# %% Result
label <- c(ordinary = "Ordinary kriging", universal = "Universal kriging", gp = "Gaussian process")[[method]]
lower <- pred - 1.959963984540054 * sd
upper <- pred + 1.959963984540054 * sd
values <- list(n = n, method = method, cv_me = cv$cv_me, cv_rmse = cv$cv_rmse, cv_msse = cv$cv_msse, cv_r2 = cv$cv_r2,
n_cv = length(rows), grid_nx = length(res$gx), grid_ny = length(res$gy), pred_min = min(pred), pred_max = max(pred),
sd_min = min(sd), sd_max = max(sd), sd_mean = mean(sd), min_pairs = min_pairs,
missing_share = if (n_input > 0) n_dropped / n_input else 0)
if (!is.null(fit)) {
for (key in c("nugget", "psill", "sill", "range", "effective_range")) values[[key]] <- fit[[key]]
values$cutoff <- res$emp$cutoff
values$n_lags <- length(res$emp$h)
}
if (!is.null(res$trend)) { # slopes per map unit (km for degrees)
span <- max(max(px) - min(px), max(py) - min(py))
values$trend_x <- res$trend[2] / span
values$trend_y <- res$trend[3] / span
}
if (!is.null(gp)) {
values$gp_lengthscale <- gp$lengthscale
values$gp_signal_sd <- gp$signal_sd
values$gp_noise_sd <- gp$noise_sd
values$gp_log_marginal_likelihood <- gp$lml
}
for (key in c("nugget", "psill", "sill", "range", "effective_range", "cutoff", "n_lags", "trend_x", "trend_y", "gp_lengthscale", "gp_signal_sd", "gp_noise_sd", "gp_log_marginal_likelihood")) {
if (is.null(values[[key]])) values[[key]] <- NA_real_ # only some methods produce these
}
summary <- sprintf("%s of %s from %d sites predicts values from %.3g to %.3g over a %d × %d grid. Left out one at a time, the sites are predicted with an RMSE of %.3g (R² %.2f).",
label, Y, n, min(pred), max(pred), length(res$gx), length(res$gy), cv$cv_rmse, cv$cv_r2)
grid_cols <- list(list(key = "x", label = XC, type = "number"), list(key = "y", label = YC, type = "number"), list(key = "prediction", label = "Prediction", type = "number"),
list(key = "se", label = "Standard error", type = "number"), list(key = "lower", label = "95% low", type = "number"), list(key = "upper", label = "95% high", type = "number"),
list(key = "nearest", label = "Nearest site", type = "number"))
grid_rows <- lapply(seq_along(pred), function(k) list(x = gx[k], y = gy[k], prediction = pred[k], se = sd[k], lower = lower[k], upper = upper[k], nearest = res$nearest[k]))
loo_pred <- z[rows] - res$cv_err
cv_cols <- list(list(key = "x", label = XC, type = "number"), list(key = "y", label = YC, type = "number"), list(key = "observed", label = "Observed", type = "number"),
list(key = "predicted", label = "Left-out prediction", type = "number"), list(key = "se", label = "Standard error", type = "number"), list(key = "z", label = "Standardized error", type = "number"))
cv_rows <- lapply(seq_along(rows), function(k) {
i <- rows[k]
list(x = x0[i], y = y0[i], observed = z[i], predicted = loo_pred[k], se = res$cv_sd[k], z = if (res$cv_sd[k] > 0) res$cv_err[k] / res$cv_sd[k] else NA_real_)
})
model_rows <- if (!is.null(fit)) {
list(list(setting = "Nugget", value = fit$nugget), list(setting = "Partial sill", value = fit$psill), list(setting = "Sill", value = fit$sill),
list(setting = "Range parameter", value = fit$range), list(setting = "Practical range", value = fit$effective_range))
} else {
list(list(setting = "Lengthscale (map units)", value = gp$lengthscale), list(setting = "Signal SD", value = gp$signal_sd),
list(setting = "Noise SD", value = gp$noise_sd), list(setting = "Log marginal likelihood", value = gp$lml))
}
tables <- list(
list(key = "model", title = if (!is.null(fit)) "Semivariogram model" else "Gaussian process settings",
columns = list(list(key = "setting", label = "Setting", type = "string"), list(key = "value", label = "Value", type = "number")), rows = model_rows),
list(key = "cv", title = "Leave-one-out predictions at the sites", columns = cv_cols, rows = cv_rows),
list(key = "grid", title = "Predictions on the grid", columns = grid_cols, rows = grid_rows)
)
kind <- c(rep("grid", length(pred)), rep("point", n))
xs <- c(gx, x0)
ys <- c(gy, y0)
charts <- list(
cs_chart("prediction", "contour-grid", sprintf("Predicted %s", Y),
list(x = cs_col(XC, xs), y = cs_col(YC, ys), z = cs_col(sprintf("Predicted %s", Y), c(pred, z)),
kind = cs_col("kind", kind, "categorical", c("grid", "point")))),
cs_chart("se", "contour-grid", "Standard error of the prediction",
list(x = cs_col(XC, xs), y = cs_col(YC, ys), z = cs_col("Standard error", c(sd, rep(NA_real_, n)), "numeric"),
kind = cs_col("kind", kind, "categorical", c("grid", "point")))),
cs_chart("loo", "pred-actual", "Left-out predictions at the sites",
list(actual = cs_col(sprintf("Observed %s", Y), z[rows]), predicted = cs_col("Left-out prediction", loo_pred)))
)
if (!is.null(fit)) {
emp <- res$emp
charts[[length(charts) + 1L]] <- cs_chart("variogram", "variogram", sprintf("Semivariogram used for kriging%s", if (method == "universal") " (trend removed)" else ""),
list(h = cs_col("Distance", emp$h), gamma = cs_col("Semivariance", emp$gamma), pairs = cs_col("Pairs", emp$pairs),
fitted = cs_col("Fitted", res$fitted)), controls = list(variance = stats::var(z)))
}
statistics <- list(list(key = "cv_rmse", label = "LOO RMSE", value = cv$cv_rmse), list(key = "cv_r2", label = "LOO R²", value = cv$cv_r2),
list(key = "cv_msse", label = "Mean squared standardized error", value = cv$cv_msse))
notes <- list(sprintf("Grid: %d × %d points over the sites' bounding box; 95%% intervals are the prediction ± 1.96 standard errors.", length(res$gx), length(res$gy)))
if (!is.null(fit)) {
notes[[2]] <- paste0(sprintf("A %s semivariogram (nugget %.4g, partial sill %.4g, range parameter %.4g) fitted by weighted least squares to %d distance classes",
model, fit$nugget, fit$psill, fit$range, length(res$emp$h)),
if (method == "universal") " of the residuals from a trend in the coordinates." else ".")
} else {
notes[[2]] <- sprintf("Gaussian process with a %s kernel fitted to %d sites by maximum likelihood (lengthscale %.4g map units).", kernel, as.integer(gp$n_fit), gp$lengthscale)
}
if (coordinates == "lonlat") {
notes[[length(notes) + 1L]] <- "Longitude and latitude were projected to kilometers at the sites' mean latitude; distances, ranges and trends are in kilometers."
}
cs_publish(list(
method = "spatial.kriging",
methodVersion = "1.0.0",
title = label,
engine = cs_engine_info("stats"),
n = n,
summary = summary,
apa = sprintf("LOO RMSE = %.3g, R² = %.2f, MSSE = %.2f, n = %d", cv$cv_rmse, cv$cv_r2, cv$cv_msse, n),
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
values = values,
charts = charts
))
LOO RMSE = 0.387, R² = 0.71, MSSE = 1.01, n = 155
- LOO RMSE
- 0.3867
- LOO R²
- 0.7112
- Mean squared standardized error
- 1.007
Assumptions
- Enough pairs per distance — The Gaussian process fits the covariance to the sites directly, without distance classes.
- Standard errors match the errors — Left-out sites' squared errors are 1.01 times their predicted variances on average (near 1: the standard errors are about right).
Gaussian process settings
| Setting | Value |
|---|---|
| Lengthscale (map units) | 575.91 |
| Signal SD | 1.078 |
| Noise SD | 0.3225 |
| Log marginal likelihood | −149.49 |
Leave-one-out predictions at the sites
| x | y | Observed | Left-out prediction | Standard error | Standardized error |
|---|---|---|---|---|---|
| 181,072 | 333,611 | 6.930 | 6.751 | 0.4132 | 0.4317 |
| 181,025 | 333,558 | 7.040 | 6.789 | 0.3933 | 0.6374 |
| 181,165 | 333,537 | 6.461 | 6.303 | 0.3761 | 0.4206 |
| 181,298 | 333,484 | 5.549 | 6.049 | 0.4153 | −1.204 |
| 181,307 | 333,330 | 5.595 | 5.529 | 0.3721 | 0.1753 |
| 181,390 | 333,260 | 5.638 | 5.261 | 0.4254 | 0.8874 |
| 181,165 | 333,370 | 5.846 | 5.905 | 0.3605 | −0.1617 |
| 181,027 | 333,363 | 6.006 | 6.404 | 0.3604 | −1.103 |
| 181,060 | 333,231 | 5.849 | 5.828 | 0.3501 | 0.0613 |
| 181,232 | 333,168 | 5.209 | 5.401 | 0.3614 | −0.5300 |
| 181,191 | 333,115 | 5.242 | 5.362 | 0.3600 | −0.3352 |
| 181,032 | 333,031 | 5.525 | 5.482 | 0.3630 | 0.1189 |
| 180,874 | 333,339 | 6.999 | 6.730 | 0.3881 | 0.6938 |
| 180,969 | 333,252 | 6.223 | 6.200 | 0.3515 | 0.0638 |
| 181,011 | 333,161 | 5.787 | 5.810 | 0.3523 | −0.0651 |
| 180,830 | 333,246 | 6.939 | 6.594 | 0.3759 | 0.9170 |
| 180,763 | 333,104 | 6.407 | 6.521 | 0.3780 | −0.3027 |
| 180,694 | 332,972 | 6.567 | 6.406 | 0.3763 | 0.4281 |
| 180,625 | 332,847 | 6.600 | 6.565 | 0.3708 | 0.0954 |
| 180,555 | 332,707 | 6.958 | 6.721 | 0.3688 | 0.6430 |
| 180,642 | 332,708 | 6.512 | 6.361 | 0.3527 | 0.4280 |
| 180,704 | 332,717 | 5.996 | 6.137 | 0.3545 | −0.3969 |
| 180,704 | 332,664 | 5.838 | 6.130 | 0.3574 | −0.8181 |
| 181,153 | 332,925 | 5.384 | 5.219 | 0.3630 | 0.4563 |
| 181,147 | 332,823 | 5.298 | 5.229 | 0.3622 | 0.1902 |
| 181,167 | 332,778 | 5.268 | 5.239 | 0.3725 | 0.0770 |
| 181,008 | 332,777 | 5.333 | 5.296 | 0.3565 | 0.1025 |
| 180,973 | 332,687 | 5.193 | 5.351 | 0.3623 | −0.4373 |
| 180,916 | 332,753 | 5.481 | 5.418 | 0.3604 | 0.1750 |
| 181,352 | 332,946 | 5.193 | 5.323 | 0.4631 | −0.2799 |
| 181,133 | 332,570 | 5.338 | 5.238 | 0.4351 | 0.2283 |
| 180,878 | 332,489 | 5.288 | 5.483 | 0.3641 | −0.5338 |
| 180,829 | 332,450 | 5.521 | 5.509 | 0.3632 | 0.0339 |
| 180,954 | 332,399 | 5.257 | 5.336 | 0.3761 | −0.2096 |
| 180,956 | 332,318 | 5.361 | 5.190 | 0.4266 | 0.4011 |
| 180,710 | 332,330 | 5.771 | 5.427 | 0.3802 | 0.9057 |
| 180,632 | 332,445 | 6.344 | 5.946 | 0.3657 | 1.087 |
| 180,530 | 332,538 | 6.725 | 6.612 | 0.3596 | 0.3154 |
| 180,478 | 332,578 | 6.809 | 6.955 | 0.3709 | −0.3949 |
| 180,383 | 332,476 | 7.282 | 6.896 | 0.3778 | 1.023 |
First 40 of 50 rows.
Predictions on the grid
| x | y | Prediction | Standard error | 95% low | 95% high | Nearest site |
|---|---|---|---|---|---|---|
| 178,605 | 329,714 | 6.700 | 0.6123 | 5.500 | 7.900 | 210.77 |
| 178819.23 | 329,714 | 6.623 | 0.4497 | 5.742 | 7.505 | 113.00 |
| 179033.46 | 329,714 | 6.421 | 0.3981 | 5.641 | 7.201 | 21.225 |
| 179247.69 | 329,714 | 6.310 | 0.3889 | 5.548 | 7.072 | 2.692 |
| 179461.92 | 329,714 | 6.137 | 0.4390 | 5.276 | 6.997 | 94.527 |
| 179676.15 | 329,714 | 5.985 | 0.5981 | 4.813 | 7.157 | 249.16 |
| 179890.38 | 329,714 | 6.091 | 0.7848 | 4.553 | 7.629 | 408.58 |
| 180104.62 | 329,714 | 6.265 | 0.8945 | 4.512 | 8.018 | 598.89 |
| 180318.85 | 329,714 | 6.267 | 0.9227 | 4.458 | 8.075 | 567.04 |
| 180533.08 | 329,714 | 6.093 | 0.9098 | 4.310 | 7.876 | 485.18 |
| 180747.31 | 329,714 | 5.896 | 0.9191 | 4.094 | 7.697 | 490.97 |
| 180961.54 | 329,714 | 5.781 | 0.9760 | 3.868 | 7.694 | 581.80 |
| 181175.77 | 329,714 | 5.751 | 1.042 | 3.709 | 7.793 | 726.45 |
| 181,390 | 329,714 | 5.768 | 1.087 | 3.638 | 7.898 | 899.30 |
| 178,605 | 329919.11 | 6.464 | 0.5563 | 5.373 | 7.554 | 205.40 |
| 178819.23 | 329919.11 | 6.224 | 0.4168 | 5.407 | 7.041 | 102.63 |
| 179033.46 | 329919.11 | 5.855 | 0.3797 | 5.111 | 6.600 | 105.63 |
| 179247.69 | 329919.11 | 5.665 | 0.3637 | 4.953 | 6.378 | 101.92 |
| 179461.92 | 329919.11 | 5.525 | 0.3663 | 4.807 | 6.243 | 90.521 |
| 179676.15 | 329919.11 | 5.586 | 0.4807 | 4.644 | 6.528 | 127.87 |
| 179890.38 | 329919.11 | 6.047 | 0.6688 | 4.736 | 7.358 | 341.03 |
| 180104.62 | 329919.11 | 6.482 | 0.7631 | 4.986 | 7.978 | 436.37 |
| 180318.85 | 329919.11 | 6.503 | 0.7640 | 5.005 | 8.000 | 410.30 |
| 180533.08 | 329919.11 | 6.188 | 0.7110 | 4.795 | 7.582 | 286.72 |
| 180747.31 | 329919.11 | 5.868 | 0.7269 | 4.443 | 7.293 | 296.41 |
| 180961.54 | 329919.11 | 5.711 | 0.8603 | 4.025 | 7.397 | 430.46 |
| 181175.77 | 329919.11 | 5.686 | 0.9905 | 3.745 | 7.628 | 611.99 |
| 181,390 | 329919.11 | 5.721 | 1.067 | 3.629 | 7.813 | 809.66 |
| 178,605 | 330124.21 | 6.211 | 0.5280 | 5.176 | 7.245 | 281.79 |
| 178819.23 | 330124.21 | 5.926 | 0.4226 | 5.098 | 6.755 | 194.94 |
| 179033.46 | 330124.21 | 5.586 | 0.3713 | 4.858 | 6.314 | 42.352 |
| 179247.69 | 330124.21 | 5.276 | 0.3581 | 4.574 | 5.978 | 76.443 |
| 179461.92 | 330124.21 | 5.103 | 0.3676 | 4.383 | 5.824 | 52.545 |
| 179676.15 | 330124.21 | 5.356 | 0.4452 | 4.484 | 6.229 | 176.84 |
| 179890.38 | 330124.21 | 6.108 | 0.5631 | 5.005 | 7.212 | 346.79 |
| 180104.62 | 330124.21 | 6.776 | 0.5829 | 5.633 | 7.918 | 233.44 |
| 180318.85 | 330124.21 | 6.757 | 0.5515 | 5.676 | 7.838 | 241.80 |
| 180533.08 | 330124.21 | 6.254 | 0.4784 | 5.317 | 7.192 | 114.67 |
| 180747.31 | 330124.21 | 5.814 | 0.5347 | 4.766 | 6.862 | 137.12 |
| 180961.54 | 330124.21 | 5.631 | 0.7713 | 4.120 | 7.143 | 340.95 |
First 40 of 50 rows.
- Grid: 14 × 20 points over the sites' bounding box; 95% intervals are the prediction ± 1.96 standard errors.
- Gaussian process with a matern52 kernel fitted to 155 sites by maximum likelihood (lengthscale 575.9 map units).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kriging (ordinary, universal, Gaussian process)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.kriging 1.0.0 · spec 66b6fb15a28818d4
# Dataset: sp_meuse (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import kriging as kr
from codesplash.stats import spatial_points as spp
# Classic equivalent: gstat::krige(z ~ 1, sites, grid, model = fit.variogram(variogram(z ~ 1, sites), vgm("Sph")))
# and gstat::krige.cv(); in Python pykrige.ok.OrdinaryKriging(x, y, z, variogram_model="spherical").
# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_meuse.parquet", columns=["log_zinc", "x", "y"])
n_input = len(df)
df = df.dropna(subset=["log_zinc", "x", "y"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["log_zinc", "x", "y"]) # infinite values stop the run (registry/errors.yaml)
# %% Fit
# Ordinary or universal kriging from spatial.variogram's fitted semivariogram (Matheron 1963; Cressie 1993), or a
# Gaussian process on the coordinates; predictions on a grid over the sites and Dubrule's (1983) leave-one-out.
Y = "log_zinc"
XC = "x"
YC = "y"
coordinates = "planar" # planar | lonlat
method = "gp" # ordinary | universal | gp
model = "spherical" # spherical | exponential | gaussian
estimator = "matheron" # matheron | cressie
cutoff = None
n_lags = int(15)
kernel = "matern52" # matern52 | matern32 | rbf
n_grid = int(20)
x0 = df[XC].to_numpy(dtype=float)
y0 = df[YC].to_numpy(dtype=float)
px, py = spp.project(x0, y0, coordinates)
z = df[Y].to_numpy(dtype=float)
n = z.size
kr.check_sites(px, py, z, {"y": Y, "x": XC, "y_coord": YC})
res = kr.krige(px, py, z, method, model, estimator, cutoff, n_lags, kernel, n_grid)
kx, ky = kr.scales(x0, y0, coordinates)
gx, gy = res["qx"] / kx, res["qy"] / ky # grid points in the coordinates' own units
pred, sd = res["pred"], res["sd"]
rows = res["cv_rows"] if "cv_rows" in res else np.arange(n)
cv = kr.cv_summary(z[rows], res["cv_err"], res["cv_sd"])
fit = res.get("fit")
gp = res.get("gp")
# %% Assumptions
assumptions = []
if fit is not None:
min_pairs = int(np.min(res["emp"]["pairs"]))
assumptions.append({"key": "pairs", "label": "Enough pairs per distance", "status": "pass" if min_pairs >= 30 else "warn",
"detail": f"The smallest distance class has {min_pairs} pairs" + (", enough to be stable." if min_pairs >= 30 else "; classes under 30 pairs make the fitted semivariogram noisy. Use fewer classes or a larger distance.")})
else:
min_pairs = None
assumptions.append({"key": "pairs", "label": "Enough pairs per distance", "status": "info",
"detail": "The Gaussian process fits the covariance to the sites directly, without distance classes."})
msse = cv["cv_msse"]
ok = msse == msse and 0.5 <= msse <= 2.0
assumptions.append({"key": "calibration", "label": "Standard errors match the errors", "status": "pass" if ok else "warn",
"detail": f"Left-out sites' squared errors are {msse:.2f} times their predicted variances on average"
+ (" (near 1: the standard errors are about right)." if ok else ("; the standard errors overstate the errors." if msse < 0.5 else "; the standard errors understate the errors. Try another model or method."))})
# %% Result
label = {"ordinary": "Ordinary kriging", "universal": "Universal kriging", "gp": "Gaussian process"}[method]
lower, upper = pred - 1.959963984540054 * sd, pred + 1.959963984540054 * sd
values = {"n": n, "method": method, "cv_me": cv["cv_me"], "cv_rmse": cv["cv_rmse"], "cv_msse": cv["cv_msse"], "cv_r2": cv["cv_r2"],
"n_cv": int(rows.size), "grid_nx": int(res["gx"].size), "grid_ny": int(res["gy"].size), "pred_min": float(np.min(pred)),
"pred_max": float(np.max(pred)), "sd_min": float(np.min(sd)), "sd_max": float(np.max(sd)), "sd_mean": float(np.mean(sd)),
"min_pairs": min_pairs, "missing_share": n_dropped / n_input if n_input else 0.0}
if fit is not None:
values.update({key: fit[key] for key in ("nugget", "psill", "sill", "range", "effective_range")})
values.update({"cutoff": res["emp"]["cutoff"], "n_lags": int(res["emp"]["h"].size)})
if "trend" in res: # slopes per map unit (km for degrees)
span = max(float(np.max(px) - np.min(px)), float(np.max(py) - np.min(py)))
values.update({"trend_x": float(res["trend"][1]) / span, "trend_y": float(res["trend"][2]) / span})
if gp is not None:
values.update({"gp_lengthscale": gp["lengthscale"], "gp_signal_sd": gp["signal_sd"], "gp_noise_sd": gp["noise_sd"], "gp_log_marginal_likelihood": gp["lml"]})
for key in ("nugget", "psill", "sill", "range", "effective_range", "cutoff", "n_lags", "trend_x", "trend_y", "gp_lengthscale", "gp_signal_sd", "gp_noise_sd", "gp_log_marginal_likelihood"):
values.setdefault(key, None) # only some methods produce these
summary = (f"{label} of {Y} from {n} sites predicts values from {np.min(pred):.3g} to {np.max(pred):.3g} over a {res['gx'].size} × {res['gy'].size} grid. "
f"Left out one at a time, the sites are predicted with an RMSE of {cv['cv_rmse']:.3g} (R² {cv['cv_r2']:.2f}).")
grid_cols = [{"key": "x", "label": XC, "type": "number"}, {"key": "y", "label": YC, "type": "number"}, {"key": "prediction", "label": "Prediction", "type": "number"},
{"key": "se", "label": "Standard error", "type": "number"}, {"key": "lower", "label": "95% low", "type": "number"}, {"key": "upper", "label": "95% high", "type": "number"},
{"key": "nearest", "label": "Nearest site", "type": "number"}]
grid_rows = [{"x": float(gx[k]), "y": float(gy[k]), "prediction": float(pred[k]), "se": float(sd[k]), "lower": float(lower[k]), "upper": float(upper[k]),
"nearest": float(res["nearest"][k])} for k in range(pred.size)]
loo_pred = z[rows] - res["cv_err"]
cv_cols = [{"key": "x", "label": XC, "type": "number"}, {"key": "y", "label": YC, "type": "number"}, {"key": "observed", "label": "Observed", "type": "number"},
{"key": "predicted", "label": "Left-out prediction", "type": "number"}, {"key": "se", "label": "Standard error", "type": "number"}, {"key": "z", "label": "Standardized error", "type": "number"}]
cv_rows = [{"x": float(x0[i]), "y": float(y0[i]), "observed": float(z[i]), "predicted": float(loo_pred[k]), "se": float(res["cv_sd"][k]),
"z": float(res["cv_err"][k] / res["cv_sd"][k]) if res["cv_sd"][k] > 0 else None} for k, i in enumerate(rows.tolist())]
if fit is not None:
model_rows = [{"setting": "Nugget", "value": fit["nugget"]}, {"setting": "Partial sill", "value": fit["psill"]}, {"setting": "Sill", "value": fit["sill"]},
{"setting": "Range parameter", "value": fit["range"]}, {"setting": "Practical range", "value": fit["effective_range"]}]
else:
model_rows = [{"setting": "Lengthscale (map units)", "value": gp["lengthscale"]}, {"setting": "Signal SD", "value": gp["signal_sd"]},
{"setting": "Noise SD", "value": gp["noise_sd"]}, {"setting": "Log marginal likelihood", "value": gp["lml"]}]
tables = [
{"key": "model", "title": "Semivariogram model" if fit is not None else "Gaussian process settings",
"columns": [{"key": "setting", "label": "Setting", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": model_rows},
{"key": "cv", "title": "Leave-one-out predictions at the sites", "columns": cv_cols, "rows": cv_rows},
{"key": "grid", "title": "Predictions on the grid", "columns": grid_cols, "rows": grid_rows},
]
kind = ["grid"] * pred.size + ["point"] * n
xs = np.concatenate([gx, x0])
ys = np.concatenate([gy, y0])
charts = [
cs.chart("prediction", "contour-grid", f"Predicted {Y}",
{"x": cs.col(XC, xs), "y": cs.col(YC, ys), "z": cs.col(f"Predicted {Y}", np.concatenate([pred, z])),
"kind": cs.col("kind", kind, "categorical", ["grid", "point"])}),
cs.chart("se", "contour-grid", "Standard error of the prediction",
{"x": cs.col(XC, xs), "y": cs.col(YC, ys), "z": cs.col("Standard error", list(sd.tolist()) + [None] * n, "numeric"),
"kind": cs.col("kind", kind, "categorical", ["grid", "point"])}),
cs.chart("loo", "pred-actual", "Left-out predictions at the sites",
{"actual": cs.col(f"Observed {Y}", z[rows]), "predicted": cs.col("Left-out prediction", loo_pred)}),
]
if fit is not None:
emp = res["emp"]
charts.append(cs.chart("variogram", "variogram", f"Semivariogram used for kriging{' (trend removed)' if method == 'universal' else ''}",
{"h": cs.col("Distance", emp["h"]), "gamma": cs.col("Semivariance", emp["gamma"]), "pairs": cs.col("Pairs", emp["pairs"]),
"fitted": cs.col("Fitted", res["fitted"])}, controls={"variance": float(np.var(z, ddof=1))}))
statistics = [{"key": "cv_rmse", "label": "LOO RMSE", "value": cv["cv_rmse"]}, {"key": "cv_r2", "label": "LOO R²", "value": cv["cv_r2"]},
{"key": "cv_msse", "label": "Mean squared standardized error", "value": cv["cv_msse"]}]
notes = [f"Grid: {res['gx'].size} × {res['gy'].size} points over the sites' bounding box; 95% intervals are the prediction ± 1.96 standard errors."]
if fit is not None:
notes.append(f"A {model} semivariogram (nugget {fit['nugget']:.4g}, partial sill {fit['psill']:.4g}, range parameter {fit['range']:.4g}) fitted by weighted least squares to {int(res['emp']['h'].size)} distance classes"
+ (" of the residuals from a trend in the coordinates." if method == "universal" else "."))
else:
notes.append(f"Gaussian process with a {kernel} kernel fitted to {gp['n_fit']} sites by maximum likelihood (lengthscale {gp['lengthscale']:.4g} map units).")
if coordinates == "lonlat":
notes.append("Longitude and latitude were projected to kilometers at the sites' mean latitude; distances, ranges and trends are in kilometers.")
cs.publish({
"method": "spatial.kriging",
"methodVersion": "1.0.0",
"title": label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"LOO RMSE = {cv['cv_rmse']:.3g}, R² = {cv['cv_r2']:.2f}, MSSE = {cv['cv_msse']:.2f}, n = {n}",
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"values": values,
"charts": charts,
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; a table cut from 155 to 50 rows; a table cut from 280 to 50 rows; 3 chart(s) dropped to stay under 100 KB; a table cut from 155 to 50 rows; a table cut from 280 to 50 rows.
It reaches a left-out RMSE of 0.387, with a lengthscale of 575.912 meters.
Check your understanding
CheckpointCheck yourself
A grid cell lies far beyond the range from every site. What does ordinary kriging predict there?
Show the answer
Answer: b
Past the range, no site resembles the cell more than any other, so the weights even out and the prediction falls back toward the mean; the kriging variance approaches the sill.
Check yourself
The semivariogram keeps rising and never levels off. Which method fits best?
Show the answer
Answer: b
A semivariogram that keeps rising usually means a trend. Universal kriging models it, and fits the semivariogram to the residuals.
Check yourself
Why is the kriging standard error zero at a measured site?
Show the answer
Answer: a
At a site the best linear unbiased prediction is the measurement itself, with all the weight on that site.