## ----setup, include=FALSE-----------------------------------------------------
# ranger fits the random forest, sp the GWR, gstat the variograms behind the
# autocorrelation ranges, and ggplot2 draws the figures. All four are
# Suggests, so the article is gated on them and R CMD build succeeds without
# them.
# `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`, or the article fails
# to build where a package is missing.
has_ranger <- requireNamespace("ranger",  quietly = TRUE)
has_sp     <- requireNamespace("sp",      quietly = TRUE)
has_gstat  <- requireNamespace("gstat",   quietly = TRUE)
has_ggplot <- requireNamespace("ggplot2", quietly = TRUE)
runs <- has_ranger && has_sp && has_gstat && has_ggplot

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("*(The code below needs `ranger`, `sp`, `gstat` and `ggplot2`, and at",
#     "least one of them is not installed here, so it is shown but not run.",
#     "`install.packages(c(\"ranger\", \"sp\", \"gstat\", \"ggplot2\"))`",
#     "installs them.)*\n")

## ----fixture------------------------------------------------------------------
library(sf)
library(spatialkit)

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

## ----rf-----------------------------------------------------------------------
rf <- fit_rf_model(pts, "z", c("a", "b"))
rf

## ----gwr----------------------------------------------------------------------
gwr <- fit_gwr_model(pts, "z", c("a", "b"))
gwr

## ----gwr-map, fig.height=4.5, fig.alt=if (runs) sprintf("Map of the local intercept of the GWR fit at the %d training points, from %.1f to %.1f, in patches that follow the simulated field.", nrow(pts), min(coef(gwr)[, 'Intercept']), max(coef(gwr)[, 'Intercept'])) else "Map of the local intercept of the GWR fit at the training points."----
plot(gwr, type = "coefficients", term = "Intercept")

## ----gwr-numbers, include=FALSE-----------------------------------------------
b_gwr   <- coef(gwr)
r_field <- cor(b_gwr[, "Intercept"], field)
a_range <- range(b_gwr[, "a"])

## ----bayes, eval=FALSE--------------------------------------------------------
# bayes <- fit_bayesian_spatial_model(pts, "z", c("a", "b"),
#                                     chains = 2, iter = 1000, seed = 1)
# bayes

## ----learner------------------------------------------------------------------
lm_fit <- function(train_sf, response_var = "z", predictor_vars = c("a", "b")) {
  d   <- st_drop_geometry(train_sf)
  # With no predictors the model is intercept-only: "z ~ 1", not "z ~ ".
  rhs <- if (length(predictor_vars)) paste(predictor_vars, collapse = " + ") else "1"
  fml <- as.formula(paste(response_var, "~", rhs))
  new_spatial_fit(
    subclass       = "lm_fit",
    engine         = lm(fml, data = d),
    formula        = fml,
    response_var   = response_var,
    predictor_vars = predictor_vars,
    data_sf        = train_sf
  )
}
predict.lm_fit <- function(object, newdata = NULL, ...) {
  if (is.null(newdata)) return(fitted(object$engine))
  as.numeric(predict(object$engine, newdata = st_drop_geometry(newdata)))
}
residuals.lm_fit <- function(object, ...) residuals(object$engine)
fitted.lm_fit    <- function(object, ...) fitted(object$engine)
# Registered so that spatialkit's own calls find the methods wherever this
# code runs; at the top level of a script they are found without it.
for (g in c("predict", "residuals", "fitted"))
  registerS3method(g, "lm_fit", get(paste0(g, ".lm_fit")))

fit <- lm_fit(pts)
fit

## ----folds--------------------------------------------------------------------
folds <- make_folds(pts, k = 4, method = "block_kfold", block_size = 400,
                    seed = 1)
round(c(width  = folds$params$block_width,
        height = folds$params$block_height))

## ----compare, warning=TRUE----------------------------------------------------
cmp   <- compare_models_cv(pts, "z", c("a", "b"), models = c("RF", "GWR"),
                           folds = folds, quiet = TRUE)
cv_lm <- cv_spatial(pts, "z", c("a", "b"), fit_fn = lm_fit, folds = folds)

scores <- rbind(cmp$overall, cbind(cv_lm$overall, model = "lm"))
scores[, c("model", "RMSE", "MAE", "R2", "n_pred")]

## ----compare-numbers, include=FALSE-------------------------------------------
rmse <- setNames(scores$RMSE, scores$model)

## ----compare-bayes, eval=FALSE------------------------------------------------
# cmp_all <- compare_models_cv(pts, "z", c("a", "b"),
#                              models = c("RF", "GWR", "Bayesian"),
#                              folds = folds,
#                              bayes_args = list(chains = 2, iter = 1000))
# cmp_all$overall

## ----moran--------------------------------------------------------------------
mi <- residual_morans_i(fit)
mi

## ----resid-map, fig.height=4.5, fig.alt="Map of the linear model's residuals at the training points. Positive and negative residuals sit in patches rather than mixed at random, the structure Moran's I measures."----
plot(fit, type = "residuals")

## ----keep-weights-------------------------------------------------------------
mi_w <- residual_morans_i(fit, keep_weights = TRUE)
dim(mi_w$weights)
str(mi$weights_summary[c("n", "storage", "neighbours", "kept")])

## ----moran-gwr----------------------------------------------------------------
mi_gwr <- residual_morans_i(gwr)
round(c(lm = mi$observed, gwr = mi_gwr$observed), 3)

## ----sac----------------------------------------------------------------------
sac <- estimate_sac_range(pts, "z", predictor_vars = c("a", "b"))
sac

## ----selection----------------------------------------------------------------
# select_features_forward() calls fit_fn(train_sf, vars), so the learner above
# needs an adapter that puts `vars` in the predictor slot. Step 0 fits it with
# no predictors at all, which is why lm_fit() builds "z ~ 1" for an empty set.
sel_fn <- function(train_sf, vars) lm_fit(train_sf, "z", vars)

sel <- select_features_forward(pts, "z", c("a", "b"), fit_fn = sel_fn,
                               k = 4, method = "block_kfold",
                               block_size = 400, seed = 1)
sel$selected
sel$history

## ----nested-------------------------------------------------------------------
chosen <- list()    # the set each outer fold chooses, kept to print below
select_then_fit <- function(train_sf) {
  s <- select_features_forward(train_sf, "z", c("a", "b"), fit_fn = sel_fn,
                               k = 3, auto_range = TRUE, seed = 1,
                               quiet = TRUE)
  chosen[[length(chosen) + 1]] <<- s$selected
  lm_fit(train_sf, "z", s$selected)
}
nested <- cv_spatial(pts, "z", c("a", "b"), fit_fn = select_then_fit,
                     folds = folds)
nested$overall[, c("RMSE", "MAE", "R2", "n_pred")]
vapply(chosen, paste, character(1), collapse = " + ")

## ----surface------------------------------------------------------------------
hull <- clip_target_for(pts, expand = 0.02, quiet = TRUE)
grid <- create_grid_polygons(hull, target_cells = 200, type = "square")
gp   <- suppressWarnings(st_centroid(grid))
set.seed(2)
gp$a <- rnorm(nrow(gp))
gp$b <- rnorm(nrow(gp), mean = 3)     # centred three standard deviations above the training mean
gp$a[1] <- NA                         # one missing predictor value

surface <- predict_surface(gwr, grid = gp)

## ----aoa----------------------------------------------------------------------
aoa <- area_of_applicability(gp, model = gwr, folds = folds)
aoa

## ----aoa-plot, fig.height=4.5, fig.alt=if (runs) sprintf("Cumulative distribution of the dissimilarity index. The training points, each measured to the nearest point outside its fold, rise steeply below the dashed threshold; the prediction locations rise more slowly, and %d of the %d with all predictors lie beyond it.", aoa$n_outside, aoa$n_new - aoa$n_na) else "Cumulative distribution of the dissimilarity index for the training points and the prediction locations, with the threshold dashed."----
plot(aoa)

## ----aoa-na-------------------------------------------------------------------
inside <- aoa$aoa$AOA %in% TRUE
c(inside = sum(inside), outside = aoa$n_outside, unknown = aoa$n_na)

## ----aoa-mask-----------------------------------------------------------------
surface$.pred[!inside] <- NA
round(100 * mean(!inside), 1)    # percent of locations masked

## ----aoa-map, fig.height=4, fig.alt=if (runs) sprintf("The GWR predictions of z at the %d grid locations over the training area, coloured by value, with the %d locations outside the area of applicability or with a missing predictor drawn grey.", nrow(surface), sum(!inside)) else "The GWR predictions on the grid, with the locations outside the area of applicability drawn grey."----
ggplot2::ggplot(surface) +
  ggplot2::geom_sf(ggplot2::aes(colour = .pred), size = 2) +
  ggplot2::scale_colour_viridis_c(name = "predicted z", na.value = "grey75") +
  ggplot2::theme_void()

