Skip to content

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.

Advanced ~12 min6 steps

What runs in CodeSplash

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

01

From resemblance to a map

Read

The 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.

02

How sure is each prediction?

Predict

Predict 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?

Where the measured values are most variableFar from every siteExactly at the sites
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.

03

Krige the Meuse floodplain

In the app
Ordinary krigingRecorded · Python and R agreeRecorded 2026-11-21 · 29 values compared · largest relative difference 1.3e-9
R

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

SettingValue
Nugget0.0616
Partial sill0.5898
Sill0.6514
Range parameter942.52
Practical range942.52

Leave-one-out predictions at the sites

xyObservedLeft-out predictionStandard errorStandardized error
181,072333,6116.9306.7550.43780.3987
181,025333,5587.0406.7540.43070.6623
181,165333,5376.4616.3000.43660.3706
181,298333,4845.5496.0470.4852−1.026
181,307333,3305.5955.5890.42850.0143
181,390333,2605.6385.4300.48900.4263
181,165333,3705.8465.8790.4300−0.0766
181,027333,3636.0066.4070.4265−0.9401
181,060333,2315.8495.8120.37400.0997
181,232333,1685.2095.3910.4054−0.4474
181,191333,1155.2425.3170.4045−0.1870
181,032333,0315.5255.5170.43940.0202
180,874333,3396.9996.6810.44630.7144
180,969333,2526.2236.2120.39590.0277
181,011333,1615.7875.8190.3977−0.0818
180,830333,2466.9396.5620.42940.8778
180,763333,1046.4076.4790.4400−0.1648
180,694332,9726.5676.3440.43320.5140
180,625332,8476.6006.4770.42270.2913
180,555332,7076.9586.6960.42780.6145
180,642332,7086.5126.3470.37510.4388
180,704332,7175.9966.0780.3759−0.2162
180,704332,6645.8386.1080.3899−0.6927
181,153332,9255.3845.2460.43010.3214
181,147332,8235.2985.2810.38210.0456
181,167332,7785.2685.2820.4041−0.0348
181,008332,7775.3335.3170.40310.0385
180,973332,6875.1935.3490.4155−0.3760
180,916332,7535.4815.3790.40570.2503
181,352332,9465.1935.3120.5516−0.2162
181,133332,5705.3385.3250.52750.0230
180,878332,4895.2885.4390.4044−0.3723
180,829332,4505.5215.4960.40360.0643
180,954332,3995.2575.3400.4153−0.1988
180,956332,3185.3615.3300.47030.0663
180,710332,3305.7715.5210.46140.5422
180,632332,4456.3445.9990.43870.7861
180,530332,5386.7256.6460.40090.1982
180,478332,5786.8096.9670.4107−0.3836
180,383332,4767.2826.7600.45641.144

First 40 of 50 rows.

Predictions on the grid

xyPredictionStandard error95% low95% highNearest site
178,605329,7146.4200.63905.1687.672210.77
178744.25329,7146.5390.53015.5007.578115.79
178883.50329,7146.4980.48695.5437.452141.78
179022.75329,7146.3900.37315.6597.12219.041
179,162329,7146.3090.42755.4717.14783
179301.25329,7146.3090.41535.4957.12356.250
179440.50329,7146.1210.47715.1867.05793.109
179579.75329,7145.9060.56904.7917.022163.73
179,719329,7145.8950.66314.5957.194282.20
179858.25329,7146.0170.73414.5787.456382.22
179997.50329,7146.1070.77964.5797.635501.33
180136.75329,7146.1440.80274.5707.717628.77
180,276329,7146.1600.80724.5787.742591.42
180415.25329,7146.1050.80004.5377.673520.97
180554.50329,7146.0010.79134.4517.552481.49
180693.75329,7145.9300.79004.3827.479480.66
180,833329,7145.9260.79884.3607.492518.66
180972.25329,7145.9690.81284.3767.562588.03
181111.50329,7146.0080.82484.3927.625679.20
181250.75329,7146.0410.83114.4127.670784.63
181,390329,7146.0590.83304.4277.692899.30
178,605329848.386.3800.60775.1897.571182.91
178744.25329848.386.4960.43835.6377.35549.386
178883.50329848.386.3320.45245.4457.219101.01
179022.75329848.386.0460.43765.1886.904115.39
179,162329848.385.8860.39265.1176.65649.611
179301.25329848.386.0510.38245.3026.80141.779
179440.50329848.385.8330.37805.0926.57341.623
179579.75329848.385.5890.47054.6676.51196.330
179,719329848.385.7050.60484.5196.890192.24
179858.25329848.385.9430.69604.5797.307321.58
179997.50329848.386.1510.74744.6867.616456.78
180136.75329848.386.2460.76964.7387.755504.82
180,276329848.386.2930.77044.7837.803489.80
180415.25329848.386.2230.75624.7417.705401.92
180554.50329848.386.0540.73974.6047.503349.23
180693.75329848.385.9200.73884.4727.368348.08
180,833329848.385.8680.75974.3797.357398.92
180972.25329848.385.9070.78924.3617.454485.70
181111.50329848.385.9710.81364.3777.566592.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
))
Python

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

SettingValue
Nugget0.0616
Partial sill0.5898
Sill0.6514
Range parameter942.52
Practical range942.52

Leave-one-out predictions at the sites

xyObservedLeft-out predictionStandard errorStandardized error
181,072333,6116.9306.7550.43780.3987
181,025333,5587.0406.7540.43070.6623
181,165333,5376.4616.3000.43660.3706
181,298333,4845.5496.0470.4852−1.026
181,307333,3305.5955.5890.42850.0143
181,390333,2605.6385.4300.48900.4263
181,165333,3705.8465.8790.4300−0.0766
181,027333,3636.0066.4070.4265−0.9401
181,060333,2315.8495.8120.37400.0997
181,232333,1685.2095.3910.4054−0.4474
181,191333,1155.2425.3170.4045−0.1870
181,032333,0315.5255.5170.43940.0202
180,874333,3396.9996.6810.44630.7144
180,969333,2526.2236.2120.39590.0277
181,011333,1615.7875.8190.3977−0.0818
180,830333,2466.9396.5620.42940.8778
180,763333,1046.4076.4790.4400−0.1648
180,694332,9726.5676.3440.43320.5140
180,625332,8476.6006.4770.42270.2913
180,555332,7076.9586.6960.42780.6145
180,642332,7086.5126.3470.37510.4388
180,704332,7175.9966.0780.3759−0.2162
180,704332,6645.8386.1080.3899−0.6927
181,153332,9255.3845.2460.43010.3214
181,147332,8235.2985.2810.38210.0456
181,167332,7785.2685.2820.4041−0.0348
181,008332,7775.3335.3170.40310.0385
180,973332,6875.1935.3490.4155−0.3760
180,916332,7535.4815.3790.40570.2503
181,352332,9465.1935.3120.5516−0.2162
181,133332,5705.3385.3250.52750.0230
180,878332,4895.2885.4390.4044−0.3723
180,829332,4505.5215.4960.40360.0643
180,954332,3995.2575.3400.4153−0.1988
180,956332,3185.3615.3300.47030.0663
180,710332,3305.7715.5210.46140.5422
180,632332,4456.3445.9990.43870.7861
180,530332,5386.7256.6460.40090.1982
180,478332,5786.8096.9670.4107−0.3836
180,383332,4767.2826.7600.45641.144

First 40 of 50 rows.

Predictions on the grid

xyPredictionStandard error95% low95% highNearest site
178,605329,7146.4200.63905.1687.672210.77
178744.25329,7146.5390.53015.5007.578115.79
178883.50329,7146.4980.48695.5437.452141.78
179022.75329,7146.3900.37315.6597.12219.041
179,162329,7146.3090.42755.4717.14783
179301.25329,7146.3090.41535.4957.12356.250
179440.50329,7146.1210.47715.1867.05793.109
179579.75329,7145.9060.56904.7917.022163.73
179,719329,7145.8950.66314.5957.194282.20
179858.25329,7146.0170.73414.5787.456382.22
179997.50329,7146.1070.77964.5797.635501.33
180136.75329,7146.1440.80274.5707.717628.77
180,276329,7146.1600.80724.5787.742591.42
180415.25329,7146.1050.80004.5377.673520.97
180554.50329,7146.0010.79134.4517.552481.49
180693.75329,7145.9300.79004.3827.479480.66
180,833329,7145.9260.79884.3607.492518.66
180972.25329,7145.9690.81284.3767.562588.03
181111.50329,7146.0080.82484.3927.625679.20
181250.75329,7146.0410.83114.4127.670784.63
181,390329,7146.0590.83304.4277.692899.30
178,605329848.386.3800.60775.1897.571182.91
178744.25329848.386.4960.43835.6377.35549.386
178883.50329848.386.3320.45245.4457.219101.01
179022.75329848.386.0460.43765.1886.904115.39
179,162329848.385.8860.39265.1176.65649.611
179301.25329848.386.0510.38245.3026.80141.779
179440.50329848.385.8330.37805.0926.57341.623
179579.75329848.385.5890.47054.6676.51196.330
179,719329848.385.7050.60484.5196.890192.24
179858.25329848.385.9430.69604.5797.307321.58
179997.50329848.386.1510.74744.6867.616456.78
180136.75329848.386.2460.76964.7387.755504.82
180,276329848.386.2930.77044.7837.803489.80
180415.25329848.386.2230.75624.7417.705401.92
180554.50329848.386.0540.73974.6047.503349.23
180693.75329848.385.9200.73884.4727.368348.08
180,833329848.385.8680.75974.3797.357398.92
180972.25329848.385.9070.78924.3617.454485.70
181111.50329848.385.9710.81364.3777.566592.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.

04

Does the map hold up?

Predict

Predict 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?

Close to 1Close to 0Above 5
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.

05

A trend, or a Gaussian process

Read

Zinc 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.

Universal krigingRecorded · Python and R agreeRecorded 2026-11-21 · 29 values compared
R

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

SettingValue
Nugget0.0620
Partial sill0.4987
Sill0.5607
Range parameter655.64
Practical range1966.93

Leave-one-out predictions at the sites

xyObservedLeft-out predictionStandard errorStandardized error
181,072333,6116.9306.7760.41340.3714
181,025333,5587.0406.7560.40530.6995
181,165333,5376.4616.2970.40860.4025
181,298333,4845.5496.0310.4483−1.076
181,307333,3305.5955.5860.40250.0205
181,390333,2605.6385.3460.45170.6463
181,165333,3705.8465.8840.4026−0.0940
181,027333,3636.0066.3800.3997−0.9358
181,060333,2315.8495.8200.35700.0820
181,232333,1685.2095.4140.3834−0.5323
181,191333,1155.2425.3630.3826−0.3161
181,032333,0315.5255.5490.4102−0.0567
180,874333,3396.9996.6890.41630.7455
180,969333,2526.2236.2090.37450.0373
181,011333,1615.7875.8420.3761−0.1457
180,830333,2466.9396.5980.40280.8477
180,763333,1046.4076.4830.4117−0.1856
180,694332,9726.5676.3690.40640.4862
180,625332,8476.6006.5310.39710.1744
180,555332,7076.9586.6840.40160.6835
180,642332,7086.5126.3430.35820.4699
180,704332,7175.9966.0980.3590−0.2827
180,704332,6645.8386.1140.3704−0.7456
181,153332,9255.3845.2900.40300.2346
181,147332,8235.2985.2870.36510.0304
181,167332,7785.2685.2590.38300.0236
181,008332,7775.3335.3250.38080.0197
180,973332,6875.1935.3820.3914−0.4837
180,916332,7535.4815.4180.38330.1636
181,352332,9465.1935.2040.4992−0.0230
181,133332,5705.3385.1300.48060.4328
180,878332,4895.2885.4700.3832−0.4744
180,829332,4505.5215.5140.38240.0194
180,954332,3995.2575.3240.3924−0.1704
180,956332,3185.3615.2050.43560.3588
180,710332,3305.7715.5710.42930.4659
180,632332,4456.3446.0150.41030.8009
180,530332,5386.7256.6240.38000.2661
180,478332,5786.8096.9310.3885−0.3132
180,383332,4767.2826.7390.42541.278

First 40 of 50 rows.

Predictions on the grid

xyPredictionStandard error95% low95% highNearest site
178,605329,7146.7130.58775.5627.865210.77
178768.82329,7146.6060.47975.6657.546109.36
178932.65329,7146.4300.43315.5817.27993.308
179096.47329,7146.2870.40185.5007.07574.920
179260.29329,7146.2920.35035.6056.97815.294
179424.12329,7146.0390.43925.1786.90095.316
179587.94329,7145.7500.52284.7256.775170.53
179751.76329,7145.6250.60644.4366.813302.96
179915.59329,7145.6050.66344.3056.905429.80
180079.41329,7145.5920.69784.2256.960575.63
180243.24329,7145.5330.71854.1246.941611.43
180407.06329,7145.4070.73453.9686.847524.36
180570.88329,7145.2210.75553.7406.702479.30
180734.71329,7144.9900.79153.4396.542488.03
180898.53329,7144.7350.84323.0826.387548.00
181062.35329,7144.4740.90292.7046.244645.06
181226.18329,7144.2190.96392.3306.109765.24
181,390329,7143.9771.0231.9715.982899.30
178,605329876.386.6420.55255.5597.724188.99
178768.82329876.386.4870.41605.6727.30357.023
178932.65329876.386.1500.43445.2987.001156.40
179096.47329876.385.8020.37215.0736.53240.868
179260.29329876.385.8770.38425.1246.63076.970
179424.12329876.385.7670.37405.0346.50072.450
179587.94329876.385.4650.42424.6346.29774.079
179751.76329876.385.5510.55054.4726.630211.56
179915.59329876.385.6960.61684.4876.905371.08
180079.41329876.385.8000.64654.5327.067481.97
180243.24329876.385.7990.65754.5107.088485.47
180407.06329876.385.6810.65984.3886.974383.06
180570.88329876.385.4750.66734.1676.783318.61
180734.71329876.385.2080.70573.8256.591331.60
180898.53329876.384.9130.77403.3966.430414.84
181062.35329876.384.6200.84912.9566.284536.56
181226.18329876.384.3440.92022.5416.148676.29
181,390329876.384.0880.98542.1576.020824.94
178,605330038.756.4930.55605.4037.582282.39
178768.82330038.756.2070.49315.2407.173217.43
178932.65330038.755.8240.43554.9716.678106.53
179096.47330038.755.4600.38844.6986.22179.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
))
Python

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

SettingValue
Nugget0.0620
Partial sill0.4987
Sill0.5607
Range parameter655.64
Practical range1966.93

Leave-one-out predictions at the sites

xyObservedLeft-out predictionStandard errorStandardized error
181,072333,6116.9306.7760.41340.3714
181,025333,5587.0406.7560.40530.6995
181,165333,5376.4616.2970.40860.4025
181,298333,4845.5496.0310.4483−1.076
181,307333,3305.5955.5860.40250.0205
181,390333,2605.6385.3460.45170.6463
181,165333,3705.8465.8840.4026−0.0940
181,027333,3636.0066.3800.3997−0.9358
181,060333,2315.8495.8200.35700.0820
181,232333,1685.2095.4140.3834−0.5323
181,191333,1155.2425.3630.3826−0.3161
181,032333,0315.5255.5490.4102−0.0567
180,874333,3396.9996.6890.41630.7455
180,969333,2526.2236.2090.37450.0373
181,011333,1615.7875.8420.3761−0.1457
180,830333,2466.9396.5980.40280.8477
180,763333,1046.4076.4830.4117−0.1856
180,694332,9726.5676.3690.40640.4862
180,625332,8476.6006.5310.39710.1744
180,555332,7076.9586.6840.40160.6835
180,642332,7086.5126.3430.35820.4699
180,704332,7175.9966.0980.3590−0.2827
180,704332,6645.8386.1140.3704−0.7456
181,153332,9255.3845.2900.40300.2346
181,147332,8235.2985.2870.36510.0304
181,167332,7785.2685.2590.38300.0236
181,008332,7775.3335.3250.38080.0197
180,973332,6875.1935.3820.3914−0.4837
180,916332,7535.4815.4180.38330.1636
181,352332,9465.1935.2040.4992−0.0230
181,133332,5705.3385.1300.48060.4328
180,878332,4895.2885.4700.3832−0.4744
180,829332,4505.5215.5140.38240.0194
180,954332,3995.2575.3240.3924−0.1704
180,956332,3185.3615.2050.43560.3588
180,710332,3305.7715.5710.42930.4659
180,632332,4456.3446.0150.41030.8009
180,530332,5386.7256.6240.38000.2661
180,478332,5786.8096.9310.3885−0.3132
180,383332,4767.2826.7390.42541.278

First 40 of 50 rows.

Predictions on the grid

xyPredictionStandard error95% low95% highNearest site
178,605329,7146.7130.58775.5627.865210.77
178768.82329,7146.6060.47975.6657.546109.36
178932.65329,7146.4300.43315.5817.27993.308
179096.47329,7146.2870.40185.5007.07574.920
179260.29329,7146.2920.35035.6056.97815.294
179424.12329,7146.0390.43925.1786.90095.316
179587.94329,7145.7500.52284.7256.775170.53
179751.76329,7145.6250.60644.4366.813302.96
179915.59329,7145.6050.66344.3056.905429.80
180079.41329,7145.5920.69784.2256.960575.63
180243.24329,7145.5330.71854.1246.941611.43
180407.06329,7145.4070.73453.9686.847524.36
180570.88329,7145.2210.75553.7406.702479.30
180734.71329,7144.9900.79153.4396.542488.03
180898.53329,7144.7350.84323.0826.387548.00
181062.35329,7144.4740.90292.7046.244645.06
181226.18329,7144.2190.96392.3306.109765.24
181,390329,7143.9771.0231.9715.982899.30
178,605329876.386.6420.55255.5597.724188.99
178768.82329876.386.4870.41605.6727.30357.023
178932.65329876.386.1500.43445.2987.001156.40
179096.47329876.385.8020.37215.0736.53240.868
179260.29329876.385.8770.38425.1246.63076.970
179424.12329876.385.7670.37405.0346.50072.450
179587.94329876.385.4650.42424.6346.29774.079
179751.76329876.385.5510.55054.4726.630211.56
179915.59329876.385.6960.61684.4876.905371.08
180079.41329876.385.8000.64654.5327.067481.97
180243.24329876.385.7990.65754.5107.088485.47
180407.06329876.385.6810.65984.3886.974383.06
180570.88329876.385.4750.66734.1676.783318.61
180734.71329876.385.2080.70573.8256.591331.60
180898.53329876.384.9130.77403.3966.430414.84
181062.35329876.384.6200.84912.9566.284536.56
181226.18329876.384.3440.92022.5416.148676.29
181,390329876.384.0880.98542.1576.020824.94
178,605330038.756.4930.55605.4037.582282.39
178768.82330038.756.2070.49315.2407.173217.43
178932.65330038.755.8240.43554.9716.678106.53
179096.47330038.755.4600.38844.6986.22179.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:

Gaussian processRecorded · Python and R agreeRecorded 2026-11-21 · 29 values compared · largest relative difference 1.0e-8
R

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

SettingValue
Lengthscale (map units)575.91
Signal SD1.078
Noise SD0.3225
Log marginal likelihood−149.49

Leave-one-out predictions at the sites

xyObservedLeft-out predictionStandard errorStandardized error
181,072333,6116.9306.7510.41320.4317
181,025333,5587.0406.7890.39330.6374
181,165333,5376.4616.3030.37610.4206
181,298333,4845.5496.0490.4153−1.204
181,307333,3305.5955.5290.37210.1753
181,390333,2605.6385.2610.42540.8874
181,165333,3705.8465.9050.3605−0.1617
181,027333,3636.0066.4040.3604−1.103
181,060333,2315.8495.8280.35010.0613
181,232333,1685.2095.4010.3614−0.5300
181,191333,1155.2425.3620.3600−0.3352
181,032333,0315.5255.4820.36300.1189
180,874333,3396.9996.7300.38810.6938
180,969333,2526.2236.2000.35150.0638
181,011333,1615.7875.8100.3523−0.0651
180,830333,2466.9396.5940.37590.9170
180,763333,1046.4076.5210.3780−0.3027
180,694332,9726.5676.4060.37630.4281
180,625332,8476.6006.5650.37080.0954
180,555332,7076.9586.7210.36880.6430
180,642332,7086.5126.3610.35270.4280
180,704332,7175.9966.1370.3545−0.3969
180,704332,6645.8386.1300.3574−0.8181
181,153332,9255.3845.2190.36300.4563
181,147332,8235.2985.2290.36220.1902
181,167332,7785.2685.2390.37250.0770
181,008332,7775.3335.2960.35650.1025
180,973332,6875.1935.3510.3623−0.4373
180,916332,7535.4815.4180.36040.1750
181,352332,9465.1935.3230.4631−0.2799
181,133332,5705.3385.2380.43510.2283
180,878332,4895.2885.4830.3641−0.5338
180,829332,4505.5215.5090.36320.0339
180,954332,3995.2575.3360.3761−0.2096
180,956332,3185.3615.1900.42660.4011
180,710332,3305.7715.4270.38020.9057
180,632332,4456.3445.9460.36571.087
180,530332,5386.7256.6120.35960.3154
180,478332,5786.8096.9550.3709−0.3949
180,383332,4767.2826.8960.37781.023

First 40 of 50 rows.

Predictions on the grid

xyPredictionStandard error95% low95% highNearest site
178,605329,7146.7000.61235.5007.900210.77
178819.23329,7146.6230.44975.7427.505113.00
179033.46329,7146.4210.39815.6417.20121.225
179247.69329,7146.3100.38895.5487.0722.692
179461.92329,7146.1370.43905.2766.99794.527
179676.15329,7145.9850.59814.8137.157249.16
179890.38329,7146.0910.78484.5537.629408.58
180104.62329,7146.2650.89454.5128.018598.89
180318.85329,7146.2670.92274.4588.075567.04
180533.08329,7146.0930.90984.3107.876485.18
180747.31329,7145.8960.91914.0947.697490.97
180961.54329,7145.7810.97603.8687.694581.80
181175.77329,7145.7511.0423.7097.793726.45
181,390329,7145.7681.0873.6387.898899.30
178,605329919.116.4640.55635.3737.554205.40
178819.23329919.116.2240.41685.4077.041102.63
179033.46329919.115.8550.37975.1116.600105.63
179247.69329919.115.6650.36374.9536.378101.92
179461.92329919.115.5250.36634.8076.24390.521
179676.15329919.115.5860.48074.6446.528127.87
179890.38329919.116.0470.66884.7367.358341.03
180104.62329919.116.4820.76314.9867.978436.37
180318.85329919.116.5030.76405.0058.000410.30
180533.08329919.116.1880.71104.7957.582286.72
180747.31329919.115.8680.72694.4437.293296.41
180961.54329919.115.7110.86034.0257.397430.46
181175.77329919.115.6860.99053.7457.628611.99
181,390329919.115.7211.0673.6297.813809.66
178,605330124.216.2110.52805.1767.245281.79
178819.23330124.215.9260.42265.0986.755194.94
179033.46330124.215.5860.37134.8586.31442.352
179247.69330124.215.2760.35814.5745.97876.443
179461.92330124.215.1030.36764.3835.82452.545
179676.15330124.215.3560.44524.4846.229176.84
179890.38330124.216.1080.56315.0057.212346.79
180104.62330124.216.7760.58295.6337.918233.44
180318.85330124.216.7570.55155.6767.838241.80
180533.08330124.216.2540.47845.3177.192114.67
180747.31330124.215.8140.53474.7666.862137.12
180961.54330124.215.6310.77134.1207.143340.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
))
Python

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

SettingValue
Lengthscale (map units)575.91
Signal SD1.078
Noise SD0.3225
Log marginal likelihood−149.49

Leave-one-out predictions at the sites

xyObservedLeft-out predictionStandard errorStandardized error
181,072333,6116.9306.7510.41320.4317
181,025333,5587.0406.7890.39330.6374
181,165333,5376.4616.3030.37610.4206
181,298333,4845.5496.0490.4153−1.204
181,307333,3305.5955.5290.37210.1753
181,390333,2605.6385.2610.42540.8874
181,165333,3705.8465.9050.3605−0.1617
181,027333,3636.0066.4040.3604−1.103
181,060333,2315.8495.8280.35010.0613
181,232333,1685.2095.4010.3614−0.5300
181,191333,1155.2425.3620.3600−0.3352
181,032333,0315.5255.4820.36300.1189
180,874333,3396.9996.7300.38810.6938
180,969333,2526.2236.2000.35150.0638
181,011333,1615.7875.8100.3523−0.0651
180,830333,2466.9396.5940.37590.9170
180,763333,1046.4076.5210.3780−0.3027
180,694332,9726.5676.4060.37630.4281
180,625332,8476.6006.5650.37080.0954
180,555332,7076.9586.7210.36880.6430
180,642332,7086.5126.3610.35270.4280
180,704332,7175.9966.1370.3545−0.3969
180,704332,6645.8386.1300.3574−0.8181
181,153332,9255.3845.2190.36300.4563
181,147332,8235.2985.2290.36220.1902
181,167332,7785.2685.2390.37250.0770
181,008332,7775.3335.2960.35650.1025
180,973332,6875.1935.3510.3623−0.4373
180,916332,7535.4815.4180.36040.1750
181,352332,9465.1935.3230.4631−0.2799
181,133332,5705.3385.2380.43510.2283
180,878332,4895.2885.4830.3641−0.5338
180,829332,4505.5215.5090.36320.0339
180,954332,3995.2575.3360.3761−0.2096
180,956332,3185.3615.1900.42660.4011
180,710332,3305.7715.4270.38020.9057
180,632332,4456.3445.9460.36571.087
180,530332,5386.7256.6120.35960.3154
180,478332,5786.8096.9550.3709−0.3949
180,383332,4767.2826.8960.37781.023

First 40 of 50 rows.

Predictions on the grid

xyPredictionStandard error95% low95% highNearest site
178,605329,7146.7000.61235.5007.900210.77
178819.23329,7146.6230.44975.7427.505113.00
179033.46329,7146.4210.39815.6417.20121.225
179247.69329,7146.3100.38895.5487.0722.692
179461.92329,7146.1370.43905.2766.99794.527
179676.15329,7145.9850.59814.8137.157249.16
179890.38329,7146.0910.78484.5537.629408.58
180104.62329,7146.2650.89454.5128.018598.89
180318.85329,7146.2670.92274.4588.075567.04
180533.08329,7146.0930.90984.3107.876485.18
180747.31329,7145.8960.91914.0947.697490.97
180961.54329,7145.7810.97603.8687.694581.80
181175.77329,7145.7511.0423.7097.793726.45
181,390329,7145.7681.0873.6387.898899.30
178,605329919.116.4640.55635.3737.554205.40
178819.23329919.116.2240.41685.4077.041102.63
179033.46329919.115.8550.37975.1116.600105.63
179247.69329919.115.6650.36374.9536.378101.92
179461.92329919.115.5250.36634.8076.24390.521
179676.15329919.115.5860.48074.6446.528127.87
179890.38329919.116.0470.66884.7367.358341.03
180104.62329919.116.4820.76314.9867.978436.37
180318.85329919.116.5030.76405.0058.000410.30
180533.08329919.116.1880.71104.7957.582286.72
180747.31329919.115.8680.72694.4437.293296.41
180961.54329919.115.7110.86034.0257.397430.46
181175.77329919.115.6860.99053.7457.628611.99
181,390329919.115.7211.0673.6297.813809.66
178,605330124.216.2110.52805.1767.245281.79
178819.23330124.215.9260.42265.0986.755194.94
179033.46330124.215.5860.37134.8586.31442.352
179247.69330124.215.2760.35814.5745.97876.443
179461.92330124.215.1030.36764.3835.82452.545
179676.15330124.215.3560.44524.4846.229176.84
179890.38330124.216.1080.56315.0057.212346.79
180104.62330124.216.7760.58295.6337.918233.44
180318.85330124.216.7570.55155.6767.838241.80
180533.08330124.216.2540.47845.3177.192114.67
180747.31330124.215.8140.53474.7666.862137.12
180961.54330124.215.6310.77134.1207.143340.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.

06

Check your understanding

Checkpoint

Check 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.