Skip to content

CSpatial · spatial.kriging

Kriging (ordinary, universal, Gaussian process)

What is the value between the sites, and how sure is each prediction?

Predicts a value measured at sites everywhere in between, on a grid over the map. Ordinary kriging weights nearby sites by a fitted semivariogram; universal kriging also follows a trend across the map; a Gaussian process fits the covariance to the sites directly. Every prediction comes with a standard error, and leave-one-out cross-validation shows how well both hold up.

Verified in Python and R Python and R agree to 6 decimals Also called kriging, ordinary kriging, universal kriging…

A real result

Example “Meuse ordinary spherical”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

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.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Meuse ordinary sphericalsp_meuse · x_coord: x · y: log_zinc · y_coord: y
  • Meuse universal exponentialsp_meuse · x_coord: x · y: log_zinc · y_coord: y
  • Meuse ordinary gaussian robustsp_meuse · x_coord: x · y: zinc · y_coord: y
  • Meuse gpsp_meuse · x_coord: x · y: log_zinc · y_coord: y
  • Nc lonlat gp matern32sp_nc_sids · x_coord: lon · y: rate · y_coord: lat
  • Nc lonlat ordinarysp_nc_sids · x_coord: lon · y: rate · y_coord: lat
  • Degenerate n3sp_meuse · x_coord: x · y: log_zinc · y_coord: y
  • Degenerate constantsp_meuse · x_coord: x · y: log_zinc · y_coord: y

In the guides

Where it sits in the decision guides

  • Continuous–continuous: Pearson / Spearman / Kendall · Statistics Guide · C — Test association
  • Probabilistic forecasting (Bayesian, deep ensembles) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Variablenumeric · 1 column
What you measured at each site, for example a soil concentration.
X or longitudenumeric · 1 column
Each site's horizontal position, in map units or degrees east.
Y or latitudenumeric · 1 column
Each site's vertical position, in map units or degrees north.

Choices you make

options

Coordinatesdefault planar

What the coordinates are.

  • Planar (meters, kilometers, grid units)(default) — Distances are straight lines in the coordinates' own units.
  • Longitude and latitude (degrees) — Projected to kilometers at the sites' mean latitude; suits a region, not a continent.
Methoddefault ordinary

How the predictions are formed.

  • Ordinary kriging(default) — A constant but unknown mean across the map; the semivariogram sets how much each site counts.
  • Universal kriging (trend in x and y) — The mean may rise or fall across the map; the semivariogram is fitted to what's left after that trend.
  • Gaussian process — Fits the covariance's scale, smoothness and noise to the sites by maximum likelihood instead of a semivariogram.
Semivariogram modeldefault spherical

The curve fitted to the empirical semivariogram by weighted least squares, as in the semivariogram method.

  • Spherical(default) — Rises almost in a straight line and levels off at a definite range.
  • Exponential — Levels off gradually; the practical range is three times the parameter.
  • Gaussian — Flat near zero, for very smooth surfaces; the practical range is √3 times the parameter.
Semivariogram estimatordefault matheron

How semivariance is estimated in each distance class before the curve is fitted.

  • Matheron (classical)(default) — Half the mean squared difference: the standard estimator, sensitive to outliers.
  • Cressie–Hawkins (robust) — Based on square roots of absolute differences; less affected by outliers.
Largest distancedefault —

Pairs further apart than this are left out of the semivariogram fit.

Distance classesdefault 15

Equal-width classes up to the largest distance; aim for at least 30 pairs in each.

Kerneldefault matern52

How quickly resemblance between sites fades with distance in the Gaussian process.

  • Matérn 5/2(default) — Smooth but not too smooth: a good default for measured surfaces.
  • Matérn 3/2 — Rougher surfaces that can change quickly between sites.
  • Radial basis (squared exponential) — Very smooth surfaces; can over-smooth sharp changes.

plots

Grid points on the longer sidedefault 40

Prediction points along the longer side of the sites' bounding box; the shorter side gets a proportional number.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Enough pairs per distance

    Distance classes with fewer than 30 pairs make the fitted semivariogram noisy (kriging only).

  • Standard errors match the errors

    Leave-one-out errors divided by their standard errors should have a mean square near 1; far below means the errors are overstated, far above understated.

  • Same pattern everywhere on the mapNot checked from data: state why it holds

    Ordinary kriging and the Gaussian process assume one mean and one covariance across the map; universal kriging allows a straight-line trend.

  • Same pattern in every directionNot checked from data: state why it holds

    Distances ignore direction; patterns along rivers or wind are not isotropic.

  • Predictions near the sitesNot checked from data: state why it holds

    Far from every site a prediction falls back to the mean with a large standard error; read the grid's distance to the nearest site.

What it reports

n
How many independent units the analysis used; it sets precision and power.
method
Predicts a value between sites as a weighted mean of nearby sites, weights set by the semivariogram, with a standard error.
nugget
The semivariance at distance zero, from measurement error and variation closer than your closest pair of sites.
psill
The level where a semivariogram flattens out, close to the data's total variance.
sill
The level where a semivariogram flattens out, close to the data's total variance.
range
The distance past which sites stop resembling each other. Samples further apart than this carry nearly independent information.
effective_range
The distance past which sites stop resembling each other. Samples further apart than this carry nearly independent information.
cutoff
Half the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other.
n_lags
How many independent units the analysis used; it sets precision and power.
min_pairs
Half the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other.
trend_x
Kriging when the mean rises or falls across the map: a trend in the coordinates plus a semivariogram of what's left.
trend_y
Kriging when the mean rises or falls across the map: a trend in the coordinates plus a semivariogram of what's left.
gp_lengthscale
How far apart two rows can be, in standardized feature units, before the function's values stop being similar.
gp_signal_sd
How far the Gaussian process function typically moves from its mean, reported on the target's scale.
gp_noise_sd
Spread of the rows around the fitted smooth function, on the target's scale; part of every predictive SD.
gp_log_marginal_likelihood
How probable the training targets are under the kernel, with the function averaged out; kernel settings maximize it.
cv_me
Each site predicted from all the others; the errors show how well the map would predict a new site.
cv_rmse
Each site predicted from all the others; the errors show how well the map would predict a new site.
cv_msse
The average of (left-out error ÷ its predicted SD)²: near 1 when the standard errors are honest.
cv_r2
Each site predicted from all the others; the errors show how well the map would predict a new site.
n_cv
Each site predicted from all the others; the errors show how well the map would predict a new site.
grid_nx
Evenly spaced points over the sites' bounding box where values are predicted, for the map and the table.
grid_ny
Evenly spaced points over the sites' bounding box where values are predicted, for the map and the table.
pred_min
Evenly spaced points over the sites' bounding box where values are predicted, for the map and the table.
pred_max
Evenly spaced points over the sites' bounding box where values are predicted, for the map and the table.
sd_min
How uncertain a kriged prediction is: small near sites, large far from them; it depends on where sites are, not their values.
sd_max
How uncertain a kriged prediction is: small near sites, large far from them; it depends on where sites are, not their values.
sd_mean
How uncertain a kriged prediction is: small near sites, large far from them; it depends on where sites are, not their values.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Kriging systems are solved by LAPACK in both engines (scipy.linalg.solve ↔ base solve); the semivariogram fit is spatial.variogram's twin (range profiled, then golden-section search), so the engines agree to about 1e-10 relative.
  • Gaussian process: the learn.gp twins (the same projected BFGS from the same start), on coordinates centered and divided by one common scale. A left-out error close to zero is a difference of two near-equal numbers, so its standardized value can differ by a few 1e-8 between engines (abs 1e-7).
Python

The exact script CodeSplash ran for example “Meuse ordinary spherical” · 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,
})
R

The exact script CodeSplash ran for example “Meuse ordinary spherical” · 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
))

Sources

  • Matheron, G. (1963). Principles of geostatistics. Economic Geology, 58, 1246–1266.
  • Cressie, N. (1993). Statistics for Spatial Data (rev. ed.). Wiley. §3.2–3.4.
  • Dubrule, O. (1983). Cross validation of kriging in a unique neighborhood. Mathematical Geology, 15, 687–699.
  • Pebesma, E. J. (2004). Multivariable geostatistics in S: the gstat package. Computers & Geosciences, 30, 683–691.
  • Rasmussen, C. E., & Williams, C. K. I. (2006). Gaussian Processes for Machine Learning. MIT Press. §5.4.2.

From the CodeSplash method registry · spatial.kriging v1.0.0.