Appendix for the paper ‘Moving beyond spatial and random cross-validation in environmental modelling: a call for prediction-domain adaptive evaluation’

Published

Last Updated: April, 2026

1 Introduction

This appendix complements the paper “Moving beyond spatial and random cross-validation in environmental modelling: a call for prediction-domain adaptive evaluation” by detailing data, experimental design, diagnostics, and evaluation results used to compare map-accuracy estimation strategies under different scenarios. Using above‑ground biomass as the response and 28 environmental predictors, we contrast different sampling designs ranging from randomly distributed training points over weakly clustered and more clustered sampling designs to a design requiring extrapolation to a completely distinct area. We implement and visualize four accuracy-estimation strategies, design-based sampling, random cross-validation (CV), spatial CV, and prediction-domain adaptive CV, and analyze how each aligns with the actual prediction problem.

Specifically, the appendix:

  • Describes the study area, response, and predictors.
  • Defines the four sampling designs (random, weakly clustered, strongly clustered and extrapolation) and shows design-based splits and CV folds.
  • Quantifies how each CV induces train–test separation in geographic and predictor spaces, comparing training-to-training vs prediction-to-training distances.
  • Introduces the Area of Applicability (AOA) and examines distance distributions inside vs outside the AOA.
  • Details the modeling setup and the evaluation protocol: population (“true”) RMSE vs estimated RMSE, together with AOA coverage, repeated 100 times.
Key findings
  1. random CV is adequate for well-covered interpolation but optimistic elsewhere,
  2. spatial CV can be pessimistic for interpolation using random sample yet better for clustered/extrapolation,
  3. prediction-domain adaptive CV adapts across scenarios,
  4. design-based sampling of the prediction domain best captures true RMSE, and
  5. AOA coverage helps interpret when CV estimates are more or less transferable to the prediction domain.
Code
library(terra)
library(sf)
library(CAST)
library(ggplot2)
library(tidyterra)
library(dplyr)
library(tidyr)
library(purrr)
library(scales)
library(cowplot)
library(twosamples)
source("R/get_geodist.R")
source("R/get_featuredist.R")
source("R/generate_prob_sampling.R")
source("R/generate_folds.R")
source("R/sampling.R")
theme_set(theme_bw(base_size = 15))
CV_colours = c("#D55E00", "#0072B2", "#009E73")
interextra_colours = c("#6A0DAD", "#FFD700")
CV_order = c("random CV", "spatial CV", "prediction-domain adaptive CV")
dir.create("figures", showWarnings = FALSE)
Code
# helper to get legend from cowplot
get_legend_35 = function(plot) {
    # return all legend candidates
    legends = get_plot_component(plot, "guide-box", return_all = TRUE)
    # find non-zero legends
    nonzero = vapply(legends, \(x) !inherits(x, "zeroGrob"), TRUE)
    idx = which(nonzero)
    # return first non-zero legend if exists, and otherwise first element (which will be a zeroGrob)
    if (length(idx) > 0) {
        return(legends[[idx[1]]])
    } else {
        return(legends[[1]])
    }
}
Code
study_area = read_sf("data/study_area.gpkg")
samples = read_sf("data/sample_sf.gpkg") |>
  rename(geometry = geom) |> 
  mutate(design = factor(design, levels = c("random", "weakly clustered", "strongly clustered", "extrapolation")))
Code
r = rast(dir("data/raster_data/", pattern = "\\.tif$", full.names = TRUE))
study_area_west = read_sf("data/study_area_west_box.gpkg")
study_area_east = read_sf("data/study_area_east_box.gpkg")
study_area_box = read_sf("data/study_area_box.gpkg")
study_area = read_sf("data/study_area.gpkg")

r_west = crop(r, study_area_west)
r_east = crop(r, study_area_east)

study_areas_all = rbind(
  study_area_box |> mutate(design = "random"),
  study_area_box |> mutate(design = "weakly clustered"),
  study_area_box |> mutate(design = "strongly clustered"),
  study_area_east |> mutate(design = "extrapolation")
) |>
  mutate(design = factor(design, levels = c("random", "weakly clustered", "strongly clustered", "extrapolation")))

2 Material and methods

2.1 Input data and study area

The data used in this study is adapted from Wadoux et al. (2021), where it is described in detail.

The outcome variable is ABG1, representing above-ground biomass in megagrams per hectare. The extrapolation-scenario is created by sampling only in the western half of the study area, while the eastern half is entirely free of training samples (Figure 1). In this extrapolation scenario, the model is expected to predict values outside the locations of the available training data.

Code
agb_map = ggplot() +
  geom_spatraster(data = r$ABG1) +
  scale_fill_distiller(
    expression("AGB [Mg " ~ ha^-1 ~ "]"),
    palette = "YlGn",
    direction = 1,
    na.value = NA
  ) +
  geom_sf(
    data = study_area_east,
    fill = NA,
    colour = interextra_colours[[2]],
    linewidth = 1.25
  ) +
  geom_label(
    data = data.frame(),
    aes(label = "Extrapolation area", x = Inf, y = Inf), 
    size = 5,
    hjust = 1.5,
    vjust = 2.5,
    colour = interextra_colours[[2]]
  ) +
  theme(panel.grid = element_blank()) +
  xlab("") +
  ylab("")
agb_map

Figure 1: Map of above-ground biomass (AGB) in the study area. The interpolation area encompasses the whole available data, while the extrapolation area is the eastern half of the study area (outlined in gold).

28 predictors representing various variables, including climatic variables, elevation, soil properties and remote sensing data were used to predict the outcome variable (Figure 2).

Code
plot(r[[-1]], maxnl = Inf, nc = 4, axes = FALSE, mar = c(0, 0, 1, 5))

Figure 2: Predictor variables used in the study.
Code
rfiles = dir(pattern = "\\.(R|qmd|Rmd)$", recursive = TRUE, full.names = TRUE)
rfiles = rfiles[!grepl("data-raw/", rfiles)]
grateful::cite_packages(path = rfiles, output = "paragraph", out.dir = ".")

We used R v. 4.5.3 (R Core Team 2026) and the following R packages: caret v. 7.0.1 (Kuhn and Max 2008), CAST v. 1.1.0 (Meyer et al. 2026), cowplot v. 1.2.0.9000 (Wilke 2025), FNN v. 1.1.4.1 (Beygelzimer et al. 2024), ggnewscale v. 0.5.2 (Campitelli 2025), ggpp v. 0.5.8.1 (Aphalo 2024), ggtext v. 0.1.2 (Wilke and Wiernik 2022), lwgeom v. 0.2.14 (Pebesma 2024), Polychrome v. 1.5.4 (Coombes et al. 2019), rmarkdown v. 2.31 (Xie, Allaire, and Grolemund 2018; Xie, Dervieux, and Riederer 2020; Allaire et al. 2026), scales v. 1.4.0 (Wickham, Pedersen, and Seidel 2025), sf v. 1.1.1 (Pebesma 2018; Pebesma and Bivand 2023), terra v. 1.9.11 (Hijmans, Brown, and Barbosa 2026), tidyterra v. 1.1.0 (Hernangómez 2023), tidyverse v. 2.0.0 (Wickham et al. 2019), twosamples v. 2.0.1 (Dowd 2023).

2.2 Training sampling designs

We consider four different training sampling designs: random, weakly clustered, strongly clustered and extrapolation. These different designs define a continuum ranging from interpolation towards extrapolation. Within random sampling, training points are distributed randomly across the study area, whereas in clustered sampling, training points are grouped into clusters with many unsampled areas in between (Figure 3).

Code
map_designs = ggplot() +
    geom_spatraster(data = r$ABG1) +
    scale_fill_distiller(
      name = expression("AGB [Mg " ~ ha^-1 ~ "]"),
      palette = "YlGn",
      direction = 1,
      na.value = NA
    ) +
    geom_sf(data = samples, aes(shape = ""), size = 0.6) +
    scale_shape_manual(name = "training points:", values = 1) + # 1 is the open circle
    geom_sf(
      data = study_areas_all,
      fill = NA,
      aes(colour = ""),
      linewidth = 1.25
    ) +
    scale_color_manual("prediction area:", values = interextra_colours[[2]]) +
    coord_sf(expand = FALSE) +
    scale_x_continuous(n.breaks = 4) +
    scale_y_continuous(n.breaks = 4) +
    theme_bw() +
    theme(
      strip.text = element_text(size = 15),
      plot.margin = unit(c(0, 0, 0, 0), "pt"),
      panel.grid = element_blank(),
      panel.border = element_blank(),
      legend.text = element_text(size = 13.5),
      legend.position = "bottom",
      legend.title.position = "left",
      legend.title = element_text(hjust = 0.5, size = 15)) +
  guides(
    colour = guide_legend(
      position = "bottom",
      direction = "vertical",
      override.aes = list(size = 6),
      order = 3
    ),
    fill = guide_colourbar(
      position = "bottom",
      theme = theme(
        legend.frame = element_rect(colour = "black"),
        legend.ticks = element_line(colour = "black"),
        legend.key.height = unit(5, "mm"),
        legend.key.width = unit(30, "mm")
      ),
      order = 1
    ),
    shape = guide_legend(override.aes = list(size = 4), order = 2)) +
    facet_wrap(~design, ncol = 2)

map_designs

ggsave(
  map_designs,
  filename = "figures/map_designs.pdf",
  width = 10,
  height = 7
)

Figure 3: Four different training sampling designs: random, weakly clustered, strongly clustered and extrapolation.

2.3 Strategies for map accuracy estimation

We tested four different strategies for map accuracy estimation:

  • Design-based sampling (independent probability sampling)
  • Random cross-validation (random CV)
  • Spatial cross-validation (using spatial clustering CV)
  • Prediction-domain adaptive cross-validation (using kNNDM CV)

The design-based sampling always covers the entire prediction area – which is the eastern part of the study area for the extrapolation design. In the design-based approach, we used 350 points for training (yellow) and 150 points for evaluation (red) to mimic a realistic scenario where 30% of the sampling effort is directed towards evaluation.

Figure 4 shows the different cross-validation folds for the three different CV strategies, as well as the design-based split. Each color indicates a different fold. In design-based sampling, yellow indicates test points, and black indicates training points.

Code
set.seed(10)

prob_sampling = lapply(unique(samples$design), generate_prob_sampling, samples = samples) |> 
  do.call(what = "rbind") |> 
  select(design, cv_name = name, geometry) |>
  mutate(
    value = ifelse(cv_name == "design-based", 1, 2),
    cv_name = ifelse(value == 2, "design-based", cv_name)
  )

folds = lapply(unique(samples$design), generate_folds, samples = samples) |>
  do.call(what = "rbind") |> 
  pivot_longer(c(randomCV, spatialCV, knndmCV)) |>
  select(design, cv_name = name, value, geometry) |>
  mutate(cv_name = case_when(
    cv_name == "randomCV" ~ "random CV",
    cv_name == "spatialCV" ~ "spatial CV",
    cv_name == "knndmCV" ~ "prediction-domain adaptive CV"
  ))

folds = folds |>
  mutate(
    cv_name = factor(
      cv_name,
      levels = c(
        "random CV",
        "spatial CV",
        "prediction-domain adaptive CV"
      )
    )
  ) |>
  st_as_sf()

folds = rbind(folds, prob_sampling)

point_cols = Polychrome::sky.colors(23)
names(point_cols) = 1:23

ggplot() +
  geom_sf(data = study_area, fill = "grey", colour = "grey") +
  geom_sf(data = study_areas_all, fill = NA, aes(colour = "prediction area"), linewidth = 1) +
  scale_colour_manual("prediction area", values = interextra_colours[[2]]) +
  ggnewscale::new_scale_colour() +
  geom_sf(data = folds, aes(color = as.factor(value)), size = 0.6) +
  scale_colour_manual(values = point_cols) +
  facet_grid(cv_name ~ design, labeller = ggplot2::labeller(
    .rows = ggplot2::label_wrap_gen(width = 20)
  )) +
  theme_bw(base_size = 12) +
  theme(
    panel.grid = element_blank(),
    axis.text.x = element_text(angle = 45, hjust = 1),
    legend.position = "None"
  )

Figure 4: Evaluation strategies for map accuracy estimation in the four different sampling designs of the training data. The different colors indicate the different cross-validation folds and the train/test split for design-based sampling.

3 Properties of the cross-validation strategies

3.1 Relationship between cross-validation and spatial distances

Figure 5 shows the distribution of spatial nearest-neighbor distances1 between training points (training-to-training) and between prediction cells and training points (prediction-to-training) for the four different sampling designs of the training data. The training-to-training and prediction-to-training distance distributions overlap largely for the random training sampling, whereas they are getting more dissimilar towards the extrapolation design. Lines on the figure indicate the distribution of spatial nearest-neighbor distances between evaluation and training points for the three different cross-validation strategies – i.e., the distance from the test points in the held-out fold to the nearest training point. Random cross-validation (random CV) captures the training-to-training distances very well, but does not capture the prediction-to-training distances, which is important for the clustered and extrapolation sampling designs. Spatial cross-validation (spatial CV) is more effective at capturing prediction-to-training distances for clustered training sampling and in the extrapolation scenario, but does not capture them for random training sampling. The prediction-domain adaptive cross-validation (prediction-domain adaptive CV) adapts to the prediction situation and captures both the training-to-training and prediction-to-training distances fairly well in all scenarios (although worse for the extrapolation case).

Code
# CV strategies
geodist_df = lapply(unique(samples$design), function(d) {
  samples |>
      filter(design == d) |>
      get_geodist() |>
      mutate(design = d)
}) |>
  do.call(what = "rbind") |> 
  mutate(
    CV = grepl("CV", what),
    design = factor(
      design,
      levels = c("random", "weakly clustered", "strongly clustered", "extrapolation")
    ),
    what = factor(
      what,
      levels = c("training-to-training", "prediction-to-training", CV_order)
    )
  )

geod_design_CV = geodist_df |> filter(CV == TRUE)
geod_design_sd = geodist_df |> filter(CV == FALSE)

gg_geod = ggplot() +
  geom_density(
    data = geod_design_sd,
    aes(x = dist, fill = what),
    alpha = 0.5,
    linewidth = 0.1
  ) +
  geom_density(
    data = geod_design_CV,
    aes(x = dist, colour = what),
    linewidth = 1.2,
    show.legend = FALSE
  ) +
  stat_density(
    data = geod_design_CV,
    aes(x = dist, colour = what),
    geom = "line",
    position = "identity"
  ) +
  scale_colour_manual("CV method:", values = CV_colours) +
  scale_fill_manual("spatial distance:", values = c("#f9ebea", "#f5b7b1")) +
  guides(
    colour = guide_legend(order = 2, override.aes = list(linewidth = 1.5)),
    fill = guide_legend(order = 1)
  ) +
  scale_x_log10(
    "distance (m)",
    labels = function(x) format(x, scientific = FALSE)#,
    # limits = c(1000, 50000)
  ) +
  coord_cartesian(clip = "off") +
  xlab("distance (m)") +
  facet_wrap(~ design, ncol = 2) +
  theme(
    legend.position = "bottom",
    legend.box = "vertical",
    legend.spacing.y = unit(2, "mm"),
    legend.title = element_text(size = 15),
    legend.text = element_text(size = 13.5),
    strip.text = element_text(size = 15),
    panel.grid = element_blank(),
    plot.margin = unit(c(5.5, 20, 5.5, 5.5), "pt")
  )

gg_geod
ggsave(gg_geod, filename = "figures/geodist_plot.pdf", width = 10, height = 7)

Figure 5: Areas representing the distribution of spatial distances between training points (training-to-training) and between prediction cells and training points (prediction-to-training) for the four different sampling designs of the training data. The lines indicate the distribution of spatial distances between test and training points for the three different cross-validation strategies.

3.2 Relationship between cross-validation and predictor-space distances

Figure 6 shows the distribution of nearest neighbor distances in the predictor space2 between training points (training-to-training) and between prediction cells and training points (prediction-to-training) for the four different sampling designs of the training data. All of the results are similar to the one based on spatial distances:

  1. The training-to-training and prediction-to-training distance distributions overlap largely for the random training sampling, while they are more dissimilar for the clustered training sampling and in the extrapolation scenario.
  2. Random cross-validation (random CV) captures the training-to-training distances very well, but does not capture the prediction-to-training distances, which is important for the clustered training sampling and in the extrapolation scenario.
  3. Spatial cross-validation (spatial CV) is better at capturing the prediction-to-training distances for the clustered training sampling and in the extrapolation scenario, but does not capture them for the random and weakly clustered training sampling.
  4. The prediction-domain adaptive cross-validation (prediction-domain adaptive CV) adapts to the prediction situation and captures both the training-to-training and prediction-to-training distances fairly well in all scenarios (although worse for the extrapolation scenario).
Code
variables = setdiff(names(r), c("ABG1"))

featuredist_df = lapply(unique(samples$design), function(d) {
  samples |>
        filter(design == d) |>
        get_featuredist(variables = variables) |>
        mutate(design = d)
}) |>
  do.call(what = "rbind") |> 
  mutate(
    CV = grepl("CV", what),
    design = factor(
      design,
      levels = c("random", "weakly clustered", "strongly clustered", "extrapolation")
    ),
    what = factor(
      what,
      levels = c("training-to-training", "prediction-to-training", CV_order)
    )
  )

featuredist_design_CV = featuredist_df |> filter(CV == TRUE)
featuredist_design_sd = featuredist_df |> filter(CV == FALSE)

gg_fspace = ggplot() +
  geom_density(
    data = featuredist_design_sd,
    aes(x = dist, fill = what),
    alpha = 0.5,
    linewidth = 0.1
  ) +
  geom_density(
    data = featuredist_design_CV,
    aes(x = dist, colour = what),
    linewidth = 1.2,
    show.legend = FALSE
  ) +
  stat_density(
    data = featuredist_design_CV,
    aes(x = dist, colour = what),
    geom = "line",
    position = "identity"
  ) +
  # geom_vline(data=featuredist_design_CV,aes(xintercept = aoa_threshold, colour=what), show_guide=FALSE) +
  scale_colour_manual("CV method:", values = CV_colours) +
  scale_fill_manual("predictor-space distance:", values = c("grey", "grey40")) + #c("#f9ebea", "#f5b7b1")) +
  guides(
    colour = guide_legend(order = 2, override.aes = list(linewidth = 1.5)),
    fill = guide_legend(order = 1)
  ) +
  scale_x_log10(
    "distance (predictor space)",
    labels = function(x) format(x, scientific = FALSE)#,
    # limits = c(0.1, 20)
  ) +
  facet_wrap( ~ design) +
  theme(
    legend.position = "bottom",
    legend.box = "vertical",
    legend.spacing.y = unit(2, "mm"),
    legend.title = element_text(size = 15),
    legend.text = element_text(size = 13.5),
    strip.text = element_text(size = 15),
    panel.grid = element_blank()
  )
gg_fspace
ggsave(
  gg_fspace,
  filename = "figures/featuredist_plot.pdf",
  width = 10,
  height = 7
)

Figure 6: Areas representing the distribution of predictor-space distances between training points (training-to-training) and between prediction cells and training points (prediction-to-training) for the four different sampling designs of the training data. The lines indicate the distribution of predictor-space distances between test and training points for the three different cross-validation strategies.

3.3 Area of applicability

Figure 7 shows the distribution of predictor-space distances between prediction cells and training points (prediction-to-training) for all prediction cells (gray filled areas) and only for the prediction cells that are inside the area of applicability (AOA) (pink filled areas with black line colour) as defined by the AOA threshold. The AOA masks prediction raster cells that are too dissimilar from the training data by excluding prediction locations that have longer predictor-space distances to their nearest training point than the longest distances found during cross-validation. Hence, the AOA defines the area where the cross-validation error estimate is expected to be reliable. Applying the AOA had little effect with random distributed and weakly clustered training points, but resulted in a better match of prediction-to-training distances and cross-validation distances in the clustered and extrapolation scenarios by masking prediction cells that are too far away from the training points. Furthermore, the cut-off threshold is much smaller for random CV than for spatial and prediction-domain adaptive CV, which means that a larger fraction of prediction cells needs to be masked for the random CV to yield reliable estimates of map accuracy.

Code
# filter pred_to_samples given a sampling design + task
filter_to_aoa = function(fdf, pred_to_samples, design, prediction_task) {
  aoa_t = fdf |>
    filter(design == design) |>
    pull(aoa_threshold) |>
    unique()

  pred_to_samples |>
    filter(
      design == design,
      dist < aoa_t
    )
}

# main function
to_aoa = function(cv_method) {
  fdf = featuredist_design_CV |>
    filter(what == cv_method)

  map_dfr(
    unique(samples$design),
    ~ filter_to_aoa(fdf, pred_to_samples, .x, .y)
  )
}

# driver code
fdf = featuredist_design_CV
pdf = featuredist_design_sd

pred_to_samples = pdf |>
  filter(what == "prediction-to-training") |>
  rename(what2 = what)

pred_to_samples_aoa = map_dfr(
  c("random CV", "spatial CV", "prediction-domain adaptive CV"),
  to_aoa
)
gg_aoa = ggplot() +
  geom_density(
    data = pred_to_samples,
    aes(x = dist, fill = "all samples"),
    alpha = 0.25,
    linewidth = 0.4,
    color = "grey40"
  ) +
  geom_density(
    data = pred_to_samples_aoa,
    aes(x = dist, fill = "inside AOA only"),
    alpha = 0.2,
    linewidth = 0.4,
    color = "black"
  ) +
  scale_fill_manual(
    "prediction-to-training:", 
    values = c("all samples" = "grey40", "inside AOA only" = "#f5b7b1")
  ) +
  stat_density(
    data = fdf,
    aes(x = dist, color = what),
    linewidth = 1,
    geom = "line",
    position = "identity"
  ) +
  scale_colour_manual("CV method: ", values = CV_colours) +
  geom_vline(
    data = fdf,
    aes(xintercept = aoa_threshold, linetype = "AOA threshold"),
    colour = "black"
  ) +
  scale_linetype_manual(
    name = NULL,
    values = c("AOA threshold" = "dashed")
  ) +
  scale_x_log10(
    "distance (predictor space)",
    labels = function(x) format(x, scientific = FALSE)#,
    # limits = c(0.1, 20)
  ) +
  facet_grid(
    design ~ what
  ) +
  guides(
    fill = guide_legend(order = 1),
    colour = guide_legend(order = 3),
    linetype = guide_legend(order = 2)
  ) +
  theme_bw(base_size = 12) +
  theme(
    legend.position = "bottom",
    legend.box = "vertical",
    legend.spacing.y = unit(2, "mm"),
    legend.title = element_text(size = 11),
    legend.text = element_text(size = 10),
    strip.text = element_text(size = 11),
    panel.grid = element_blank(),
    aspect.ratio = 0.85,
    plot.title = ggtext::element_textbox_simple(
      size = 12,
      halign = 0.5,
      padding = margin(2, 5.5, 2, 5.5),
      margin = margin(0, 0, 0, 0),
      fill = "grey85",
      box.colour = "black",
      linewidth = 0.2,
      linetype = 1
    )
  )
gg_aoa
ggsave(
  gg_aoa,
  filename = "figures/featuredist_aoa_plot.pdf",
  width = 8,
  height = 10
)

Figure 7: Distribution of predictor-space distances between prediction cells and training points (prediction-to-training) for the four different sampling designs of the training data. The gray-filled areas indicate all of the distances, while the pink-filled areas indicate the distances that are inside the area of applicability (AOA) as defined by the AOA threshold (black dashed vertical line). The lines indicate the distribution of predictor-space distances between test and training points for the three different cross-validation strategies.

3.4 Summary

The Figure 8 summarises the findings presented above. It gives an overview of the different sampling designs (first row), and then shows the continuum from random sampling towards an extrapolation design in the second row. Here, the Wasserstein statistic was used to calculate the difference between training-to-training and prediction-to-training distance distributions. The Wasserstein statistic increases as we follow the gradient towards extrapolation, quantitatively supporting our visual assessment above. The third row shows the spatial nearest-neighbour distance distributions between cross-validation folds, while the last row shows those distances in the predictor space.

Code
set.seed(2025-10-21)

# Sample prediction points
n_ppoints = 1000
ppoints_inter = terra::spatSample(r, n_ppoints, method = "regular", as.points = TRUE, values = FALSE, na.rm = TRUE) |>
  st_as_sf() |>
  mutate(type = "interpolation") |> 
  st_set_crs(st_crs(samples))

ppoints_transfer = terra::spatSample(r_east, n_ppoints, method = "regular", as.points = TRUE, values = FALSE, na.rm = TRUE) |>
  st_as_sf() |>
  mutate(type = "extrapolation") |> 
  st_set_crs(st_crs(samples))

ppoints = list(inter = ppoints_inter, extra = ppoints_transfer)

# Calculate geodistance
all_dists = lapply(unique(samples$design), function(d) {
  s = samples |> 
    filter(design == d)
  s_extr = terra::extract(r, s, bind = TRUE, ID = FALSE) |> 
    st_as_sf() |> 
    tidyr::drop_na() |> 
    st_transform(st_crs(s))

  if(d == "extrapolation") {
    p = ppoints[["extra"]]
  } else {
    p = ppoints[["inter"]]
  }

  geodist = get_geodist(s, p)
  featuredist = get_featuredist(s_extr, variables = setdiff(names(r), c("ABG1")), predpoints = p)

  geodist$dist_type = "geo"

  all_dists_d = rbind(geodist, featuredist |> select(!aoa_threshold)) |> mutate(design = d)

  return(all_dists_d)

}) |> 
  bind_rows() |> 
  mutate(what = factor(what, levels = c("training-to-training", "prediction-to-training", CV_order)))
[1] "warning: k is higher than number of unique locations. k is set to 8"
Code
## Plots ------

# 1) Maps of sampling designs
samples_map_list = lapply(unique(samples$design), function(d) {

  ggplot() +
    geom_spatraster(data = r$ABG1) +
    scale_fill_distiller(
      name = expression("AGB [Mg " ~ ha^-1 ~ "]"),
      palette = "YlGn",
      direction = 1,
      na.value = NA
    ) +
    geom_sf(data = samples |> filter(design == d), aes(shape = ""), size = 0.6) +
    scale_shape_manual(name = "training points:", values = 1) + 
    geom_sf(
      data = study_areas_all |> filter(design == d),
      fill = NA,
      aes(colour = ""),
      linewidth = 1.25
    ) +
    scale_color_manual("prediction area:", values = interextra_colours[[2]]) +
    coord_sf(expand = FALSE) +
    scale_x_continuous(n.breaks = 4) +
    scale_y_continuous(n.breaks = 4) +
    ggtitle(d) +
    theme_bw() +
    theme(
      panel.grid = element_blank(),
      panel.border = element_blank(),
      legend.position = "bottom",
      legend.title.position = "left",
      legend.title = element_text(hjust = 0.5),
      plot.title = ggtext::element_textbox_simple(
        size = 12, halign=0.5,
        padding = margin(5.5, 5.5, 5.5, 5.5),
        margin = margin(0, 0, 0, 0),
        fill = "grey85", box.colour = "black", linewidth = 0.2, linetype = 1
      )) +
  guides(
    fill = guide_colourbar(
      position = "bottom",
      theme = theme(
        legend.frame = element_rect(colour = "black"),
        legend.ticks = element_line(colour = "black"),
        legend.key.height = unit(5, "mm"),
        legend.key.width = unit(30, "mm"),
        legend.title.position = "top"
      ),
      order = 1
    ),
    shape = guide_legend(override.aes = list(size = 4), order = 2)
  ) 
})

map_legend = get_legend_35(samples_map_list[[1]] + theme(legend.position = "bottom"))
map_plot_clean = lapply(samples_map_list, function(p) {
  p + theme(legend.position = "none", axis.title = element_blank())
})

# Calculate ranges for each of the following rows
xlims_geodistances = quantile(
  all_dists |> filter(dist_type == "geo") |> mutate(dist = dist/1000) |> pull(dist),
  probs = c(0.01, 0.99),
  na.rm = TRUE
)

xlims_featuredistances = quantile(
  all_dists |> filter(dist_type == "feature") |> pull(dist),
  probs = c(0.01, 0.99),
  na.rm = TRUE
)

# 2) Density plots of geographic training-training and prediction-training distances
geodist_plot_list = lapply(unique(samples$design), function(d) {

  dists = all_dists |> 
    filter(dist_type == "geo", what %in% c("training-to-training", "prediction-to-training"),
    design == d) |> 
      mutate(dist = dist / 1000)

  ## Wasserstein statistic (difference between NND distributions)
  Gij = dists |> filter(what == "prediction-to-training") |> pull(dist)
  Gj  = dists |> filter(what == "training-to-training") |> pull(dist)
  W_stat = data.frame("W" = wass_stat(Gj, Gij))
  
  ylims = c(0, 2)

  ggplot(dists, aes(x = dist, group = what, fill = what)) +

    geom_density(
      aes(x = dist, fill = what),
      alpha = 0.5,
      linewidth = 0.1, 
      adjust = 1.5
    ) +
    scale_fill_manual("spatial distance:", values = c("#f9ebea", "#f5b7b1")) + #c("#f9ebea", "#f5b7b1")) +
    ggpp::geom_text_npc(
      data = W_stat,
      aes(npcx = 0.05, npcy = 0.95, label = paste0("W = ", scales::comma(round(W)))),
      fontface = "bold",
      size = 4
    ) +

   scale_y_continuous(limits = ylims) +
      
    scale_x_log10(
      "distance (km)",
      labels = function(x) format(x, scientific = FALSE),
      breaks = c(1, 10, 100),
      limits = xlims_geodistances
    ) +
    theme_bw() +
    theme(
      legend.position = "bottom",
      legend.box = "vertical",
      legend.spacing.y = unit(2, "mm"),
      legend.title.position = "top",
      legend.title = element_text(size = 12),
      legend.text = element_text(size = 11),
      legend.direction = "vertical",
      panel.grid = element_blank(),
      plot.margin = unit(c(0, 0, 0, 0), "pt"),
      legend.justification = c(1,0)
    )
})

geodist_legend = get_legend_35(geodist_plot_list[[1]] + theme(legend.position = "bottom"))
geodist_plot_clean = lapply(geodist_plot_list, function(p) {
  p + theme(legend.position = "none", axis.title = element_blank())
})


# 3) Density plots of geographic CV distances
geodist_CV_plot_list = lapply(unique(samples$design), function(d) {

  dists = all_dists |> 
    filter(dist_type == "geo", !(what %in% c("training-to-training", "prediction-to-training")), design == d) |> 
    mutate(dist = dist/1000)
  
  xlims = range(dists$dist, na.rm = TRUE)
  ylims = c(0, 3)

  ggplot(dists, aes(x = dist, group = what, fill = what)) +

    geom_density(
      aes(x = dist, colour = what),
      fill = "transparent",
      linewidth = 1.2,
      show.legend = FALSE
    ) +
    stat_density(
      aes(x = dist, colour = what),
      geom = "line",
      position = "identity"
    ) +
    scale_colour_manual("CV method:", values = CV_colours) +
    scale_y_continuous(limits = ylims) +
    scale_x_log10(
      "distance (km)",
      labels = function(x) format(x, scientific = FALSE),
      breaks = c(1, 10, 100),
      limits = xlims_geodistances
    ) +
    guides(
      colour = guide_legend(order = 2, override.aes = list(linewidth = 1.5)),
      fill = guide_legend(order = 1)
    ) +
    theme_bw() +
    theme(
      legend.position = "bottom",
      legend.box = "vertical",
      legend.spacing.y = unit(2, "mm"),
      legend.title.position = "top",
      legend.title = element_text(size = 12),
      legend.text = element_text(size = 11),
      legend.direction = "vertical",
      panel.grid = element_blank(),
      plot.margin = unit(c(0, 0, 0, 0), "pt"),
      legend.justification = c(1,0)
    )
})

geodist_CV_legend = get_legend_35(geodist_CV_plot_list[[1]] + theme(legend.position = "bottom"))
geodist_CV_plot_clean = lapply(geodist_CV_plot_list, function(p) {
  p + theme(legend.position = "none", axis.title = element_blank())
})

# 4) Feature space dissimilarities
featuredist_plot_list = lapply(unique(samples$design), function(d) {

  dists = all_dists |> 
    filter(dist_type == "feature", design == d)
  
  xlims = range(dists$dist, na.rm = TRUE)
  ylims = c(0, 3.6)

  featuredist_sd = dists |> filter(what %in% c("training-to-training", "prediction-to-training"))
  featuredist_CV = dists |> filter(!(what %in% c("training-to-training", "prediction-to-training")))

  ggplot() +
    geom_density(
      data = featuredist_sd,
      aes(x = dist, fill = what),
      alpha = 0.5,
      linewidth = 0.1
    ) +
    geom_density(
      data = featuredist_CV,
      aes(x = dist, colour = what),
      linewidth = 1.2,
      show.legend = FALSE
    ) +
    stat_density(
      data = featuredist_CV,
      aes(x = dist, colour = what),
      geom = "line",
      position = "identity"
    ) +
    scale_colour_manual("CV method:", values = CV_colours) +
    scale_fill_manual("predictor-space distance:", values = c("grey", "grey40")) + 
    guides(
      colour = guide_legend(order = 2, override.aes = list(linewidth = 1.5)),
      fill = guide_legend(order = 1)
    ) +
    scale_y_continuous(limits = ylims) +
    scale_x_log10(
      "distance (predictor space)",
      labels = function(x) format(x, scientific = FALSE),
      limits = xlims_featuredistances,
      expand = c(0, 0)
    ) +

    theme_bw() +
    theme(
      legend.position = "bottom",
      legend.box = "vertical",
      legend.spacing.y = unit(2, "mm"),
      legend.title.position = "top",
      legend.title = element_text(size = 12),
      legend.text = element_text(size = 11),
      legend.direction = "vertical",
      panel.grid = element_blank(),
      plot.margin = unit(c(0, 0, 0, 0), "pt")
    )
})

featuredist_legend = get_legend_35(featuredist_plot_list[[1]] + theme(legend.position = "bottom"))
featuredist_plot_clean = lapply(featuredist_plot_list, function(p) {
  p + theme(legend.position = "none", axis.title = element_blank())
})


## Combine density plots and maps
map_cols = lapply(seq_along(map_plot_clean), function(i) {
  map_plot2 = map_plot_clean[[i]] + theme(plot.margin = unit(c(0, 5, 0, 0), "pt"), axis.text = element_text(size = 10))
  geodist_plot2 = geodist_plot_clean[[i]] + theme(plot.margin = unit(c(0, 5, 0, 0), "pt"), axis.text = element_text(size = 10))
  geodist_CV_plot2 = geodist_CV_plot_clean[[i]] + theme(plot.margin = unit(c(0, 5, 0, 0), "pt"), axis.text = element_text(size = 10))
  featuredist_plot2 = featuredist_plot_clean[[i]] + theme(plot.margin = unit(c(0, 5, 0, 0), "pt"), axis.text = element_text(size = 10))

  # Add extra vertical spacing (heights control1
  plot_grid(
    map_plot2,
    NULL,
    geodist_plot2,
    NULL,
    geodist_CV_plot2,
    NULL,
    featuredist_plot2,
    NULL,
    ncol = 1,
    align = "v",
    rel_heights = c(1.2,0,1,0.2,1,0.2,1,0.2)
  )
})

# Combine columns side-by-side
dist_maps_all = plot_grid(
  plotlist = map_cols,
  nrow = 1,
  align = "hv",
  rel_widths = rep(1, length(map_cols))
)

# ---- Add horizontal labels between rows ----
dist_maps_all_labeled = ggdraw() +
  draw_plot(dist_maps_all) +
  coord_cartesian(clip = "off") +
  # xlabs
  draw_label("distance (km)", x = 0.5, y = 0.525, size = 12) +
  draw_label("distance (km)", x = 0.5, y = 0.275, size = 12) +
  draw_label("distance (predictor space)", x = 0.5, y = 0.04, size = 12, vjust = 2) +
  # ylabs
  draw_label("Density", x = 0, vjust = -2, y = 0.39, angle = 90, size = 12) +
  # right-side row labels
  draw_label("A", x = 1.01, y = 0.93, size = 11, fontface = "bold") +
  draw_label("B", x = 1.01, y = 0.73, size = 11, fontface = "bold") +
  draw_label("C", x = 1.01, y = 0.48, size = 11, fontface = "bold") +
  draw_label("D", x = 1.01, y = 0.23, size = 11, fontface = "bold") 

legend_map_col = plot_grid(map_legend[[2]], NULL, map_legend[[3]], ncol = 1, align = "v", axis = "l", rel_heights = c(1,-0.5,1))
legend = plot_grid(map_legend[[1]], legend_map_col, geodist_legend[[1]], featuredist_legend[[1]], geodist_CV_legend[[1]], nrow = 1, align = "h", axis = "t")

dist_map_final = plot_grid(NULL, dist_maps_all_labeled, NULL, legend, ncol = 1, rel_heights = c(-0.05, 1, -0.05, 0.1))

ggsave("figures/pre_hoc.pdf", dist_map_final, height = 10, width = 12)

dist_map_final

Figure 8: The upper row shows sampling designs ranging from randomly distributed training points (left) over clustered training points towards a setting where transfer to a new region is required. The second row shows areas representing the distribution of spatial distances between training points (training-to-training) and between prediction cells and training samples (prediction-to-training) for the four different sampling designs of the training data. The difference between the two density distributions is measured by the Wasserstein statistic (bold W in the figure). The third row shows spatial distances between test and training points for the three different cross-validation strategies. The last row shows those distances in the predictor space.

4 Map accuracy estimation results

4.1 Modeling and validation setup

We used random forest models to predict above-ground biomass from the 28 predictor variables. All of the models were built using the default settings of the ranger::ranger() function.

To obtain the Population reference (full-domain) RMSE, we used models built on the full training sample (for our sampling designs and prediction scenarios, see Figure 3) and compared predictions for the interpolation or extrapolation area against the true values using RMSE.

Then, for each training sample, several approaches to estimate map accuracy were tested (Figure 4):

  1. Design-based sampling (independent probability sampling): the models are built on the training sample (350 points) and evaluated on the test points (150 points) covering the prediction area.
  2. Random cross-validation (random CV): 10 random folds are created, and a model is built on 9 of them and evaluated on the remaining one. This is repeated 10 times.
  3. Spatial cross-validation (spatial CV): K spatial folds are created using hierarchical clustering of the distance matrix of sampling locations. The clustering height is defined by the autocorrelation range of the response, in this case, 150 km. Then, a model is built on K-1 of them and evaluated on the remaining one. This is repeated K times.
  4. Prediction-domain adaptive cross-validation (prediction-domain adaptive CV): 10 k-fold nearest-neighbour distance matching (kNNDM) folds are created, and a model is built on 9 of them and evaluated on the remaining one. This is repeated 10 times.

For each approach, we calculated the estimated RMSE and compared it to the Population RMSE. Additionally, for each approach we computed the area of applicability (AOA) and the Population RMSE inside the AOA.

Finally, we calculated the percentage of the prediction area that is inside the AOA as defined by the AOA threshold.

The above process was repeated 100 times for each combination of prediction scenario and training data sampling design.

4.2 Difference between estimated and true RMSE

Figure 9 shows the difference between the estimated and true RMSE for each evaluation strategy and sampling design. It shows both, the difference between the estimated RMSE and the Population RMSE, and the difference between the RMSE and the Population RMSE inside the AOA. Values close to zero indicate agreement with the Population reference, positive values indicate larger RMSE than Population, and negative values indicate smaller RMSE than Population.

Code
validation_names = c(
  "design-based",
  "random CV",
  "spatial CV",
  "prediction-domain adaptive CV"
)

CV_colours = c(
  "design-based" = "#333333",            # grey for design-based
  "random CV" = "#D55E00",
  "spatial CV" = "#0072B2",
  "prediction-domain adaptive CV" = "#009E73"
)

sim_res = readRDS("data/all_models_stats.rds")

stats_500_pop = sim_res |>
  filter(type == "Population") |>
  select(sample, id, rmse_population = RMSE)

stats_500_rmse_diff = sim_res |>
  left_join(stats_500_pop, by = c("sample", "id")) |>
  filter(type != "Population") |>
  mutate(
    type = case_when(
      type == "Design-based proportional" ~ "design-based",
      type == "Random K-fold CV" ~ "random CV",
      type == "Spatial K-fold CV" ~ "spatial CV",
      type == "kNNDM K-fold CV" ~ "prediction-domain adaptive CV"
    ),
    type = factor(type, levels = validation_names)
  ) |>
  transmute(
    sample,
    id,
    type,
    est = RMSE_est - rmse_population,
    est_aoa = ifelse(type != "design-based", RMSE_est - RMSE_raster_aoa, NA)
  ) |>
  pivot_longer(
    cols = c(est, est_aoa),
    names_to = "metric",
    values_to = "rmse_diff"
  ) |>
  mutate(
    metric = factor(metric, levels = c("est", "est_aoa"), labels = c("whole area", "inside AoA"))
  )

gg_rmse_diff = ggplot(
  stats_500_rmse_diff,
  aes(x = type, y = rmse_diff, color = metric, fill = type)
) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_boxplot(size = 0.55, width = 0.5, position = position_dodge(0.65, preserve = "single"), outliers = FALSE) +
  scale_color_manual(values = c("whole area" = "black", "inside AoA" = "grey")) +
  scale_fill_manual(values = CV_colours) +
  theme_bw(base_size = 16) +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1),
    panel.grid = element_blank(),
    axis.title.x = element_blank(),
    legend.title = element_blank(),
    legend.position = "inside",
    legend.position.inside = c(0.15, 0.15)
  ) +
  guides(fill = "none") +
  labs(y = "estimated RMSE - true RMSE") +
  facet_wrap(~sample, nrow = 1)

gg_rmse_diff
ggsave("figures/post_hoc_rmse_diff.pdf", gg_rmse_diff, width = 12, height = 8)

Figure 9: Differences from the Population RMSE under four different sampling designs. For each evaluation strategy, boxplots show the difference in estimated RMSE. For the cross-validation methods, the difference from the Population RMSE masked to the AOA is shown additionally. The dashed line marks perfect agreement with the Population RMSE.

4.3 Area of applicability coverage

Figure 10 summarizes the percentage of the prediction domain that falls inside the area of applicability (AOA) for each evaluation strategy and sampling design. Higher values indicate that a larger fraction of the prediction domain is considered well supported by the training data under that evaluation setup.

Code
stats_500_aoa = sim_res |>
  filter(type != "Population") |>
  mutate(
    type = case_when(
      type == "Design-based proportional" ~ "design-based",
      type == "Random K-fold CV" ~ "random CV",
      type == "Spatial K-fold CV" ~ "spatial CV",
      type == "kNNDM K-fold CV" ~ "prediction-domain adaptive CV"
    ),
    type = factor(type, levels = validation_names)
  ) |> 
    filter(type != "design-based")


ggplot(stats_500_aoa, aes(x = type, y = AoA_pct, fill = type)) +
  geom_boxplot(outliers = FALSE) +
  scale_fill_manual(values = CV_colours) +
  scale_y_continuous("cells inside AoA (%)", limits = c(0,100)) +
  facet_wrap(~sample, nrow = 1) +
  theme_bw(base_size = 16) +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1),
    panel.grid = element_blank(),
    axis.title.x = element_blank(),
    legend.title = element_blank(),
    legend.position = "inside",
    legend.position.inside = c(0.15, 0.15)
  ) +
  guides(fill = "none")

Figure 10: Area of applicability coverage under four different sampling designs.

References

Allaire, JJ, Yihui Xie, Christophe Dervieux, Jonathan McPherson, Javier Luraschi, Kevin Ushey, Aron Atkins, et al. 2026. rmarkdown: Dynamic Documents for r. https://github.com/rstudio/rmarkdown.
Aphalo, Pedro J. 2024. ggpp: Grammar Extensions to “ggplot2”. https://doi.org/10.32614/CRAN.package.ggpp.
Beygelzimer, Alina, Sham Kakadet, John Langford, Sunil Arya, David Mount, and Shengqiao Li. 2024. FNN: Fast Nearest Neighbor Search Algorithms and Applications. https://doi.org/10.32614/CRAN.package.FNN.
Campitelli, Elio. 2025. ggnewscale: Multiple Fill and Colour Scales in “ggplot2”. https://doi.org/10.32614/CRAN.package.ggnewscale.
Coombes, Kevin R., Guy Brock, Zachary B. Abrams, and Lynne V. Abruzzo. 2019. “Polychrome: Creating and Assessing Qualitative Palettes with Many Colors.” Journal of Statistical Software, Code Snippets 90 (1): 1–23. https://doi.org/10.18637/jss.v090.c01.
Dowd, Connor. 2023. twosamples: Fast Permutation Based Two Sample Tests. https://doi.org/10.32614/CRAN.package.twosamples.
Hernangómez, Diego. 2023. “Using the tidyverse with terra Objects: The tidyterra Package.” Journal of Open Source Software 8 (91): 5751. https://doi.org/10.21105/joss.05751.
Hijmans, Robert J., Andrew Brown, and Márcia Barbosa. 2026. terra: Spatial Data Analysis. https://doi.org/10.32614/CRAN.package.terra.
Kuhn, and Max. 2008. “Building Predictive Models in r Using the Caret Package.” Journal of Statistical Software 28 (5): 1–26. https://doi.org/10.18637/jss.v028.i05.
Meyer, Hanna, Carles Milà, Marvin Ludwig, Jan Linnenbrink, and Fabian Schumacher. 2026. CAST: “caret” Applications for Spatial-Temporal Models. https://github.com/HannaMeyer/CAST.
Pebesma, Edzer. 2018. “Simple Features for R: Standardized Support for Spatial Vector Data.” The R Journal 10 (1): 439–46. https://doi.org/10.32614/RJ-2018-009.
———. 2024. lwgeom: Bindings to Selected “liblwgeom” Functions for Simple Features. https://doi.org/10.32614/CRAN.package.lwgeom.
Pebesma, Edzer, and Roger Bivand. 2023. Spatial Data Science: With applications in R. Chapman and Hall/CRC. https://doi.org/10.1201/9780429459016.
R Core Team. 2026. R: A Language and Environment for Statistical Computing. Vienna, Austria: R Foundation for Statistical Computing. https://www.R-project.org/.
Wadoux, Alexandre M. J.-C., Gerard B. M. Heuvelink, Sytze de Bruin, and Dick J. Brus. 2021. “Spatial Cross-Validation Is Not the Right Way to Evaluate Map Accuracy.” Ecological Modelling 457: 109692. https://doi.org/https://doi.org/10.1016/j.ecolmodel.2021.109692.
Wickham, Hadley, Mara Averick, Jennifer Bryan, Winston Chang, Lucy D’Agostino McGowan, Romain François, Garrett Grolemund, et al. 2019. “Welcome to the tidyverse.” Journal of Open Source Software 4 (43): 1686. https://doi.org/10.21105/joss.01686.
Wickham, Hadley, Thomas Lin Pedersen, and Dana Seidel. 2025. scales: Scale Functions for Visualization. https://doi.org/10.32614/CRAN.package.scales.
Wilke, Claus O. 2025. cowplot: Streamlined Plot Theme and Plot Annotations for “ggplot2”. https://github.com/wilkelab/cowplot.
Wilke, Claus O., and Brenton M. Wiernik. 2022. ggtext: Improved Text Rendering Support for “ggplot2”. https://doi.org/10.32614/CRAN.package.ggtext.
Xie, Yihui, J. J. Allaire, and Garrett Grolemund. 2018. R Markdown: The Definitive Guide. Boca Raton, Florida: Chapman; Hall/CRC. https://yihui.org/rmarkdown/.
Xie, Yihui, Christophe Dervieux, and Emily Riederer. 2020. R Markdown Cookbook. Boca Raton, Florida: Chapman; Hall/CRC. https://yihui.org/rmarkdown-cookbook.