## ----setup, include=FALSE-----------------------------------------------------
# gstat estimates the autocorrelation range that sizes the blocks, and ggplot2
# draws the folds and the curves. Both are Suggests, so every chunk is gated
# on them and R CMD build succeeds without either.
# `eval` gates chunks only: knitr does not apply it to inline `r ...` code,
# which runs regardless. An inline reference to something a chunk defines
# has to guard itself, as in `r if (runs) x else NA`, and so does a fig.alt
# built from the output, or the article fails to build where a package is
# missing.
has_gstat  <- requireNamespace("gstat",   quietly = TRUE)
has_ggplot <- requireNamespace("ggplot2", quietly = TRUE)
runs <- has_gstat && has_ggplot

# A reading written inline as code, "matched" in backticks. Inline code cannot
# hold a backtick, so the helper writes it as \x60.
as_code <- function(x) sprintf("\x60\"%s\"\x60", x)

knitr::opts_chunk$set(
  echo      = TRUE,
  message   = FALSE,
  warning   = FALSE,
  fig.align = "center",
  out.width = "100%",
  eval      = runs
)

## ----missing-deps, echo=FALSE, eval=!runs, results='asis'---------------------
# cat("*`gstat` or `ggplot2` is not installed, so the code below is shown but",
#     "not run. Install them with `install.packages(c(\"gstat\", \"ggplot2\"))`",
#     "and rebuild.*\n")

## ----learner------------------------------------------------------------------
library(sf)
library(spatialkit)

knn_fit <- function(train_sf, response_var = "z", k = 5L) {
  new_spatial_fit(
    subclass       = "knnsurf_fit",
    engine         = list(xy = st_coordinates(train_sf),
                          y = st_drop_geometry(train_sf)[[response_var]],
                          k = k),
    formula        = as.formula(paste(response_var, "~ 1")),
    response_var   = response_var,
    predictor_vars = character(0),
    data_sf        = train_sf
  )
}

predict.knnsurf_fit <- function(object, newdata = NULL, ...) {
  e  <- object$engine
  xy <- if (is.null(newdata)) e$xy else st_coordinates(newdata)
  vapply(seq_len(nrow(xy)), function(i) {
    d <- sqrt((e$xy[, 1] - xy[i, 1])^2 + (e$xy[, 2] - xy[i, 2])^2)
    mean(e$y[order(d)[seq_len(min(e$k, length(d)))]])
  }, numeric(1))
}
registerS3method("predict", "knnsurf_fit", predict.knnsurf_fit)

knn_fn <- function(train_sf, ...) knn_fit(train_sf, "z", k = 5L)

## ----fixture------------------------------------------------------------------
set.seed(7)
n  <- 400
xy <- data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000))
D  <- as.matrix(dist(xy))
xy$z <- as.numeric(t(chol(exp(-D / 60) + diag(1e-8, n))) %*% rnorm(n)) +
        rnorm(n, sd = 0.3)
pts  <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)

## ----the-gap------------------------------------------------------------------
fr <- make_folds(pts, k = 5, method = "random_kfold", seed = 1)
fb <- make_folds(pts, k = 5, method = "block_kfold", block_size = 200, seed = 1)
c(width = fb$params$block_width, height = fb$params$block_height)

cv_random  <- cv_spatial(pts, "z", character(0), fit_fn = knn_fn, folds = fr)
cv_blocked <- cv_spatial(pts, "z", character(0), fit_fn = knn_fn, folds = fb)

c(random  = cv_random$overall$RMSE,
  blocked = cv_blocked$overall$RMSE,
  ratio   = cv_blocked$overall$RMSE / cv_random$overall$RMSE)

## ----separation---------------------------------------------------------------
map_pts <- st_make_grid(pts, n = c(30, 30), what = "centers")

reading <- function(folds, data = pts) {
  sep <- fold_separation(folds, data, prediction_points = map_pts)
  attr(sep, "target")$reading
}
c(random = reading(fr), blocked = reading(fb))

## ----separation-print---------------------------------------------------------
sep_blocked <- fold_separation(fb, pts, prediction_points = map_pts)
sep_blocked

## ----clustered----------------------------------------------------------------
set.seed(2)
centres <- pts[sample(nrow(pts), 6), ]
cl <- pts[lengths(st_is_within_distance(pts, centres, dist = 120)) > 0, ]
nrow(cl)

fr_cl <- make_folds(cl, k = 5, method = "random_kfold", seed = 1)
fk_cl <- make_folds(cl, k = 5, method = "knndm", prediction_points = map_pts,
                    seed = 1)
c(random = reading(fr_cl, cl), knndm = reading(fk_cl, cl))

cv_random_cl <- cv_spatial(cl, "z", character(0), fit_fn = knn_fn,
                           folds = fr_cl)
cv_knndm_cl  <- cv_spatial(cl, "z", character(0), fit_fn = knn_fn,
                           folds = fk_cl)
c(random = cv_random_cl$overall$RMSE, knndm = cv_knndm_cl$overall$RMSE)

## ----clustered-text, include=FALSE--------------------------------------------
sep_cl <- attr(fold_separation(fr_cl, cl, prediction_points = map_pts),
               "target")

## ----alt-folds, include=FALSE-------------------------------------------------
per_fold <- range(lengths(fb$params$fold_blocks))
alt_folds <- sprintf(paste(
  "A square study area divided into a %d by %d grid of blocks, with the points",
  "coloured by fold and the axes in metres of EPSG:32632. Every block belongs",
  "to one fold, and each fold is %d to %d blocks spread over the square."),
  fb$params$grid_nx, fb$params$grid_ny, per_fold[1], per_fold[2])

## ----plot-folds, fig.height=4.5, fig.alt=if (runs) alt_folds else NULL--------
plot_folds(fb, pts)

## ----more-schemes-------------------------------------------------------------
fk   <- make_folds(pts, k = 5, method = "knndm", prediction_points = map_pts,
                   seed = 1)
floo <- make_folds(pts, method = "buffered_loo", buffer = 180, max_test = 50,
                   seed = 1)
vor  <- build_tessellation(voronoi_seeds_kmeans(pts, 16), quiet = TRUE)
fv   <- make_folds(pts, k = 5, method = "block_kfold", blocks = vor$cells,
                   seed = 1)

schemes <- list(knndm = fk, buffered_loo = floo, voronoi_blocks = fv)
data.frame(
  folds   = sapply(schemes, function(f) f$k),
  reading = sapply(schemes, reading),
  RMSE    = sapply(schemes, function(f)
    cv_spatial(pts, "z", character(0), fit_fn = knn_fn, folds = f)$overall$RMSE)
)

## ----sac----------------------------------------------------------------------
sac <- estimate_sac_range(pts, "z")
c(range  = as.numeric(sac),
  nugget = sac_nugget(sac),
  sill   = sum(attr(sac, "variogram_model")$psill))

## ----alt-sac, include=FALSE---------------------------------------------------
alt_sac <- sprintf(paste(
  "Empirical variogram of z: semivariance against distance in metres, with",
  "points sized by the number of point pairs, a fitted curve that levels off",
  "near %.2f, and a dotted vertical line at the effective range of %.1f m."),
  sum(attr(sac, "variogram_model")$psill), as.numeric(sac))

## ----plot-sac, fig.height=4, fig.alt=if (runs) alt_sac else NULL--------------
plot(sac)

## ----auto-range---------------------------------------------------------------
fa <- make_folds(pts, k = 5, method = "block_kfold", response_var = "z",
                 auto_range = TRUE, seed = 1)
c(range  = as.numeric(fa$params$sac_range),
  width  = fa$params$block_width,
  height = fa$params$block_height)

## ----sweep--------------------------------------------------------------------
sw <- cv_block_size_sweep(pts, "z", character(0), fit_fn = knn_fn,
                          k = 5, n_sizes = 5, seed = 1, quiet = TRUE)
sw

## ----alt-sweep, include=FALSE-------------------------------------------------
sw_df  <- data.frame(sw)
sw_blk <- sw_df[!is.na(sw_df$block_size), ]
alt_sweep <- sprintf(paste(
  "Cross-validated RMSE against the smallest block edge asked for, in metres",
  "on a log scale. The error rises from %.2f at %.0f m to %.2f at %.0f m,",
  "above the dashed random-fold reference of %.2f. A shaded band gives the",
  "range across folds at each size, and a dotted line marks the estimated",
  "autocorrelation range of %.0f m."),
  sw_blk$value[1], sw_blk$block_size[1],
  sw_blk$value[nrow(sw_blk)], sw_blk$block_size[nrow(sw_blk)],
  sw_df$value[is.na(sw_df$block_size)], attr(sw, "sac_range"))

## ----plot-sweep, fig.height=4.5, fig.alt=if (runs) alt_sweep else NULL--------
plot(sw)

## ----sweep-separation---------------------------------------------------------
sizes <- data.frame(sw)[, c("block_size", "block_width", "value")]
sizes$reading <- sapply(attr(sw, "results"), function(r) reading(r$folds))
sizes

## ----sweep-text, include=FALSE------------------------------------------------
blk      <- !is.na(sizes$block_size)
matched  <- blk & sizes$reading == "matched"
largest  <- which.max(sizes$block_size)

## ----alt-metrics, include=FALSE-----------------------------------------------
fold_rmse <- cv_blocked$fold_metrics$RMSE
alt_metrics <- sprintf(paste(
  "RMSE for each of %d folds, with point size showing how many rows each held",
  "out. The values run from %.2f to %.2f around a dashed pooled line at %.2f."),
  length(fold_rmse), min(fold_rmse), max(fold_rmse),
  cv_blocked$overall$RMSE)

## ----plot-metrics, fig.height=4, fig.alt=if (runs) alt_metrics else NULL------
plot_cv_metrics(cv_blocked, metric = "RMSE")

## ----accounting-clean---------------------------------------------------------
c(attempted = cv_blocked$n_folds_attempted,
  succeeded = cv_blocked$n_folds_succeeded,
  dropped   = cv_blocked$n_dropped,
  orphans   = length(cv_blocked$orphan_rows),
  unknown   = cv_blocked$n_unknown_ids)

## ----failing-fold, warning=TRUE-----------------------------------------------
flaky <- function(train_sf, ...) {
  if (nrow(train_sf) < 320) stop("not enough training rows for this learner")
  knn_fit(train_sf, "z", k = 5L)
}
cv_flaky <- cv_spatial(pts, "z", character(0), fit_fn = flaky, folds = fb)

cv_flaky$fold_status
c(attempted = cv_flaky$n_folds_attempted,
  succeeded = cv_flaky$n_folds_succeeded)

## ----accounting, warning=TRUE-------------------------------------------------
holed <- pts
holed$z[c(3, 17, 42)] <- NA                       # three rows will be dropped
part  <- make_folds(pts[1:300, ], k = 4, method = "block_kfold", seed = 1)

cv_acc <- cv_spatial(holed, "z", character(0), fit_fn = knn_fn, folds = part)

c(n_dropped     = cv_acc$n_dropped,
  n_orphans     = length(cv_acc$orphan_rows),
  n_unknown_ids = cv_acc$n_unknown_ids)

## ----mirror-------------------------------------------------------------------
cv_rev <- cv_spatial(pts[1:300, ], "z", character(0), fit_fn = knn_fn,
                     folds = fb)
c(n_orphans = length(cv_rev$orphan_rows), n_unknown_ids = cv_rev$n_unknown_ids)

## ----calibration, eval=FALSE--------------------------------------------------
# cvb <- cv_bayes(pts, "z", character(0), folds = fb,
#                 coverage_levels = seq(0.1, 0.9, by = 0.1),
#                 fit_args = list(chains = 2, iter = 1000))
# plot_calibration(cvb)

