## ----setup, include=FALSE-----------------------------------------------------
# Everything here runs on the hard dependencies and sf's own nc.shp, with three
# exceptions: the maps need ggplot2, the model steps need ranger, and the
# block size from the data needs gstat, all Suggests.  Each gated chunk has a
# note chunk after it that prints when the package is absent, so the article
# builds either way.
has_ggplot <- requireNamespace("ggplot2", quietly = TRUE)
has_ranger <- requireNamespace("ranger", quietly = TRUE)
has_gstat  <- requireNamespace("gstat", quietly = TRUE)

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

## ----install, eval=FALSE------------------------------------------------------
# install.packages("spatialkit")

## ----install-dev, eval=FALSE--------------------------------------------------
# # install.packages("remotes")
# remotes::install_github("elkronos/gis_modeling_toolkit")

## ----read-file----------------------------------------------------------------
library(sf)
library(spatialkit)

nc <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
c(features = nrow(nc), geometry = as.character(unique(st_geometry_type(nc))))

## ----to-points----------------------------------------------------------------
counties <- ensure_projected(nc[, c("BIR74", "SID74", "NWBIR74")])
obs      <- coerce_to_points(counties)
obs$rate     <- 1000 * obs$SID74 / pmax(obs$BIR74, 1)   # the response
obs$nw_share <- obs$NWBIR74 / pmax(obs$BIR74, 1)        # one predictor

c(points = nrow(obs), geometry = as.character(unique(st_geometry_type(obs))))

## ----boundary-----------------------------------------------------------------
boundary <- st_as_sf(st_union(counties))

## ----read-table---------------------------------------------------------------
ll  <- st_coordinates(st_transform(obs, 4326))
tab <- data.frame(lon = ll[, 1], lat = ll[, 2],
                  births = obs$BIR74, sids = obs$SID74)
head(tab, 2)

pts_ll <- st_as_sf(tab, coords = c("lon", "lat"), crs = 4326)
pts    <- ensure_projected(pts_ll)

## ----crs----------------------------------------------------------------------
choice <- attr(counties, "crs_choice")
print(data.frame(name = choice$name,
                 error_percent = round(100 * choice$distance_error, 2),
                 chosen = choice$chosen), row.names = FALSE)
st_crs(counties)$units_gdal

## ----crs-missing, warning=TRUE------------------------------------------------
raw <- st_as_sf(data.frame(lon = c(-81.5, -81.1), lat = c(36.4, 36.5)),
                coords = c("lon", "lat"))
st_crs(ensure_projected(raw))$input

## ----harmonize----------------------------------------------------------------
pair <- harmonize_crs(obs[1:5, ], st_transform(boundary, 4326))
st_crs(pair$a) == st_crs(pair$b)

## ----pipeline-----------------------------------------------------------------
# Choose the number of cells.
n_cells <- select_resolution(resolution_profile(obs, "rate"))

# Draw hex cells over the state.
tess <- build_tessellation(obs, boundary = boundary, method = "hex",
                           approx_n_cells = n_cells, quiet = TRUE)

# Put each observation in a cell.
asg <- assign_features_to_polygons(obs, tess$cells)

# Summarise each cell; cells_sf attaches the geometry so the result maps.
cells <- summarize_by_cell(asg, "rate", cells_sf = tess$cells)

c(asked = n_cells$best, drawn = nrow(tess$cells))

## ----counts, include=FALSE----------------------------------------------------
n_drawn <- nrow(tess$cells)
n_empty <- sum(is.na(cells$n))
n_held  <- n_drawn - n_empty
area_km2 <- as.numeric(st_area(cells)) / 1e6
km2 <- function(x) format(round(x), big.mark = ",")
and_list <- function(x)
  if (length(x) < 2L) x else paste(paste(x[-length(x)], collapse = ", "), "and", x[length(x)])

## ----summary-cols-------------------------------------------------------------
names(cells)
head(st_drop_geometry(cells)[, c("poly_id", "n", "resp_mean_rate",
                                 "..se_resp_rate", "..pooled_resp_rate")], 4)

## ----map-alt, include=FALSE---------------------------------------------------
mean_range <- range(cells$resp_mean_rate, na.rm = TRUE)
map_alt <- sprintf(paste(
  "North Carolina covered by %d hexagonal cells shaded by their mean SIDS",
  "rate, from %.1f to %.1f per thousand births, with %d small grey",
  "pieces at the state's edge that hold no county."),
  n_held, mean_range[1], mean_range[2], n_empty)

## ----map, eval=has_ggplot, fig.height=3.2, fig.alt=map_alt--------------------
plot_tessellation_map(cells, boundary = boundary, fill_col = "resp_mean_rate",
                      legend_title = "mean rate") +
  ggplot2::theme(legend.position = "bottom")

## ----no-ggplot, echo=FALSE, eval=!has_ggplot, results='asis'------------------
# cat("*(The map needs ggplot2, which is not installed here.)*\n")

## ----folds--------------------------------------------------------------------
# Build random folds and folds that hold out whole blocks.
random  <- make_folds(obs, k = 4, method = "random_kfold", seed = 1)
blocked <- make_folds(obs, k = 4, method = "block_kfold", block_size = 100e3,
                      seed = 1)
c(folds = blocked$k, blocks = blocked$params$blocks_used,
  block_width_km = round(blocked$params$block_width / 1e3))

## ----county-side, include=FALSE-----------------------------------------------
county_km <- sqrt(as.numeric(st_area(boundary)) / nrow(obs)) / 1e3

## ----auto-range, eval=has_gstat, warning=TRUE---------------------------------
auto <- make_folds(obs, k = 4, method = "block_kfold", auto_range = TRUE,
                   response_var = "rate", predictor_vars = "nw_share", seed = 1)

## ----no-gstat, echo=FALSE, eval=!has_gstat, results='asis'--------------------
# cat("*(This step needs gstat, which is not installed here.)*\n")

## ----cv, eval=has_ranger------------------------------------------------------
# Fit and score a random forest on each set of folds.
cv_random  <- cv_rf(obs, "rate", "nw_share", folds = random,
                    num_trees = 300, seed = 1)
cv_blocked <- cv_rf(obs, "rate", "nw_share", folds = blocked,
                    num_trees = 300, seed = 1)
rbind(random  = cv_random$overall[, c("RMSE", "MAE", "R2")],
      blocked = cv_blocked$overall[, c("RMSE", "MAE", "R2")])

## ----cv-folds, eval=has_ranger------------------------------------------------
rbind(random  = range(cv_random$fold_metrics$RMSE),
      blocked = range(cv_blocked$fold_metrics$RMSE))

## ----cv-text, echo=FALSE, eval=has_ranger, results='asis'---------------------
f2 <- function(x) sprintf("%.2f", x)
ratio <- cv_blocked$overall$RMSE / cv_random$overall$RMSE
rr <- range(cv_random$fold_metrics$RMSE); rb <- range(cv_blocked$fold_metrics$RMSE)
qr <- range(cv_random$fold_metrics$R2);   qb <- range(cv_blocked$fold_metrics$R2)
if (ratio > 1.15) {
  cat("The blocked RMSE is", f2(ratio), "times the random one. The random",
      "folds leave each test point's neighbours in the training set, and the",
      "blocked folds do not.\n\n")
} else {
  cat("The two pooled RMSEs differ by less than the folds do. The random",
      "folds' RMSE runs from", f2(rr[1]), "to", f2(rr[2]), "and the blocked",
      "folds' from", f2(rb[1]), "to", paste0(f2(rb[2]), ".\n\n"))
}
cat("R² is", f2(cv_random$overall$R2), "under random folds and",
    f2(cv_blocked$overall$R2), "under blocked ones. Fold by fold it runs from",
    f2(qr[1]), "to", f2(qr[2]), "under random folds and from", f2(qb[1]), "to",
    paste0(f2(qb[2]), " under blocked ones",
           if (max(qr[1], qb[1]) <= min(qr[2], qb[2]))
             ", so four folds of a hundred counties do not tell the two schemes apart",
           ". R² here is taken about each fold's training mean (`?cv_spatial`),",
           " and on blocks that mean can sit far from the held-out values, so a",
           " blocked R² above 0 does not show that the predictor does better than",
           " the mean of the nearby counties.\n\n"))
cat("The gap between the schemes opens when a model can use its neighbours'",
    "values, through the coordinates or a spatially smooth predictor. The",
    "[quick start on the home page](https://elkronos.github.io/gis_modeling_toolkit/#quick-start)",
    "shows it on a simulated field.\n")

## ----cv-none, echo=FALSE, eval=!has_ranger, results='asis'--------------------
# cat("*(The model steps need ranger, which is not installed here. With only the",
#     "hard dependencies, `cv_spatial()` scores a learner you write with",
#     "`new_spatial_fit()`; `vignette(\"models\")` shows how.)*\n")

## ----surface, eval=has_ranger-------------------------------------------------
# Predict on a grid over the state, and mark where the model extrapolates.
fit  <- fit_rf_model(obs, "rate", "nw_share", num_trees = 300, seed = 1)
surf <- predict_surface(fit, n_cells = 4000, covariates = obs,
                        boundary = boundary)
aoa  <- area_of_applicability(surf, model = fit, folds = blocked)
aoa

## ----oob-text, echo=FALSE, eval=has_ranger, results='asis'--------------------
oob <- fit$info$oob_r_squared
if (is.finite(oob) && oob < 0.1)
  cat(sprintf(paste(
    "The forest's out-of-bag R², in the print above, is %.2f. Fitted on all",
    "hundred counties, the share of non-white births predicts the SIDS rate",
    "%s better than the mean rate does.\n"),
    oob, if (oob < 0) "no" else "little"))

## ----surface-map, eval=has_ranger && has_ggplot, fig.height=3.2, fig.alt="The random forest's predicted SIDS rate on a fine grid of points over North Carolina, clipped to the state outline, with the hundred county points drawn over it. The surface is low across the west and centre, and highest in one south-central patch and in parts of the east, following the share of non-white births it was fitted on."----
library(ggplot2)
ggplot() +
  geom_sf(data = surf, aes(colour = .pred), size = 1.1) +
  geom_sf(data = boundary, fill = NA, colour = "grey20") +
  geom_sf(data = obs, size = 0.5, colour = "black") +
  scale_colour_viridis_c(name = "predicted rate per thousand births") +
  theme_void() +
  theme(legend.position = "bottom")

## ----no-ggplot-surface, echo=FALSE, eval=has_ranger && !has_ggplot, results='asis'----
# cat("*(The map needs ggplot2, which is not installed here.)*\n")

## ----aoa-text, echo=FALSE, eval=has_ranger, results='asis'--------------------
if (aoa$n_inside == aoa$n_new) {
  cat(sprintf(paste(
    "All %s grid points are inside the area of applicability here, because",
    "the grid took its predictor from the nearest county, so no grid point",
    "holds a value the model has not seen.\n"),
    format(aoa$n_new, big.mark = ",")))
} else {
  cat(sprintf("Of the %s grid points, %s are inside the area of applicability.\n",
              format(aoa$n_new, big.mark = ","),
              format(aoa$n_inside, big.mark = ",")))
}

## ----scripts, eval=FALSE------------------------------------------------------
# dir <- system.file("scripts", package = "spatialkit")
# list.files(dir)
# 
# source(file.path(dir, "03-folds.R"))    # one topic
# source(file.path(dir, "00-run-all.R"))  # all ten, in order

