## ----setup, include=FALSE-----------------------------------------------------
# Everything in this article runs on the hard dependencies. ggplot2 draws one
# map and gstat estimates one range; both are Suggests, so those chunks are
# gated and the rest runs anywhere.
# `eval` gates chunks only: knitr does not apply it to inline `r ...` code,
# which runs regardless. An inline reference to something a gated chunk
# defines has to guard itself, as in `r if (has_gstat) x else NA`, or the
# article fails to build where the package is missing.
has_ggplot <- requireNamespace("ggplot2", quietly = TRUE)
has_gstat  <- requireNamespace("gstat",   quietly = TRUE)

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

## ----cells--------------------------------------------------------------------
library(sf)
library(spatialkit)

nc <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
counties <- ensure_projected(nc[, c("NAME", "BIR74", "SID74")])
counties$rate <- 1000 * counties$SID74 / counties$BIR74

centres  <- coerce_to_points(counties)
boundary <- clip_target_for(centres, expand = 0.01)
hex      <- build_tessellation(centres, method = "hex", approx_n_cells = 12,
                               boundary = boundary)$cells
nrow(hex)

## ----summarise----------------------------------------------------------------
grouped <- assign_features_to_polygons(counties, hex,
                                       polygon_id_col = "cell_id",
                                       largest = TRUE)
cells <- summarize_by_cell(grouped, response_var = "rate", id_col = "cell_id",
                           cells_sf = hex, conf_level = 0.95)
names(cells)

## ----outline, include=FALSE---------------------------------------------------
# The same request with the state outline as the boundary, for the sentence
# below.
outline <- build_tessellation(centres, method = "hex", approx_n_cells = 12,
                              boundary = st_union(counties))$cells
outline_used  <- assign_features_to_polygons(counties, outline,
                                             polygon_id_col = "cell_id",
                                             largest = TRUE)
outline_empty <- sum(!outline$cell_id %in% outline_used$cell_id)

## ----map, eval=has_ggplot, fig.height=3, fig.alt=sprintf("The North Carolina counties grouped into %d hexagonal cells, each shaded by the mean 1974 SIDS rate of the counties inside it. County outlines show underneath. %d cells hold no county and are grey.", nrow(cells), sum(is.na(cells$n)))----
library(ggplot2)

ggplot() +
  geom_sf(data = cells, aes(fill = resp_mean_rate), colour = "white") +
  geom_sf(data = counties, fill = NA, colour = "grey70", linewidth = 0.2) +
  scale_fill_viridis_c(name = "SIDS rate\nper 1,000", na.value = "grey92") +
  labs(title = "Counties grouped into hexagonal cells",
       subtitle = sprintf("%d cells, %d with a county; grey = no county inside",
                          nrow(cells), sum(!is.na(cells$n)))) +
  theme_void()

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

## ----membership---------------------------------------------------------------
sites <- st_as_sf(
  data.frame(site = c("Raleigh", "Wilmington", "Atlantic", "Norfolk VA"),
             lon  = c(-78.64, -77.95, -74.50, -76.29),
             lat  = c( 35.78,  34.23,  35.00,  36.85)),
  coords = c("lon", "lat"), crs = 4326)

inside <- assign_features_to_polygons(sites, cells, polygon_id_col = "cell_id",
                                      keep_unassigned = TRUE)
st_drop_geometry(inside)

## ----stable-ids---------------------------------------------------------------
hex$src <- seq_len(nrow(hex))

from_projected <- ensure_stable_poly_id(hex[, "src"])
from_lonlat    <- ensure_stable_poly_id(st_transform(hex[, "src"], 4326))

identical(from_projected$poly_id[order(from_projected$src)],
          from_lonlat$poly_id[order(from_lonlat$src)])

## ----export-------------------------------------------------------------------
dir <- tempfile()
dir.create(dir)
out <- ensure_stable_poly_id(cells)

st_write(out, file.path(dir, "cells.gpkg"), quiet = TRUE)
gpkg <- st_read(file.path(dir, "cells.gpkg"), quiet = TRUE)

st_write(out, file.path(dir, "cells.shp"), quiet = TRUE)
shp <- st_read(file.path(dir, "cells.shp"), quiet = TRUE)

attr_names <- function(x) setdiff(names(x), attr(x, "sf_column"))
same_name  <- function(x) intersect(attr_names(x), attr_names(out))

c(columns = length(attr_names(out)),
  GeoPackage = length(same_name(gpkg)), shapefile = length(same_name(shp)))
attr_names(shp)

## ----export-names, include=FALSE----------------------------------------------
# The shapefile keeps the columns in their order, so its field names line up
# with the layer's column names.
stopifnot(length(attr_names(shp)) == length(attr_names(out)))
as_written <- stats::setNames(attr_names(shp), attr_names(out))
code_list  <- function(x) knitr::combine_words(x, before = "`",
                                                 oxford_comma = FALSE)

## ----export-shp---------------------------------------------------------------
short <- c(mean   = "resp_mean_rate",     se     = "..se_resp_rate",
           ci_lo  = "..ci_lo_resp_rate",  ci_hi  = "..ci_hi_resp_rate",
           pooled = "..pooled_resp_rate", pool_w = "..pooled_w_resp_rate")
for_shp <- out[, c("poly_id", "cell_id", "n", short)]
names(for_shp)[match(short, names(for_shp))] <- names(short)

st_write(for_shp, file.path(dir, "cells-short.shp"), quiet = TRUE)
write.csv(data.frame(field = names(short), column = short),
          file.path(dir, "cells-short-fields.csv"), row.names = FALSE)

## ----se-example---------------------------------------------------------------
populated <- cells[!is.na(cells$n), ]
range(populated$n)
range(populated$..se_resp_rate, na.rm = TRUE)

## ----value-fixture------------------------------------------------------------
set.seed(7)
sx <- runif(600, 0, 2e4)
sy <- runif(600, 0, 2e4)
obs <- st_as_sf(
  data.frame(x = 4e5 + sx, y = 4e6 + sy,
             yield = 50 + 6 * sin(sx / 3000) + 6 * cos(sy / 2500) +
               rnorm(600, sd = 3)),
  coords = c("x", "y"), crs = 32617)

## ----value-pipeline-----------------------------------------------------------
prof  <- resolution_profile(obs, "yield")
sel   <- select_resolution(prof)
seeds <- get_voronoi_seeds(n = sel, sample_points = obs)
tess  <- build_tessellation(seeds, method = "voronoi", quiet = TRUE)
asg   <- assign_features_to_polygons(obs, tess$cells,
                                     polygon_id_col = "cell_id")
vals  <- summarize_by_cell(asg, "yield", id_col = "cell_id",
                           cells_sf = tess$cells, obs_level = 0.90)

st_drop_geometry(vals)[1:4, c("cell_id", "n", "resp_mean_yield",
                              "..pooled_resp_yield", "..pooled_w_resp_yield",
                              "..obs_lo_resp_yield", "..obs_hi_resp_yield")]

## ----value-records------------------------------------------------------------
attr(vals, "pooled")
attr(vals, "count_rule")

## ----value-report-------------------------------------------------------------
rec <- attr(vals, "pooled")$columns$resp_yield
iv  <- attr(vals, "intervals")
cr  <- attr(vals, "count_rule")
say <- function(...) cat(strwrap(paste0("- ", ...), width = 76, exdent = 2),
                         sep = "\n")

say(sprintf("cells: %d, set by a %s of %s observations per cell; checked: %s",
            cr$cells, cr$rule, format(cr$obs_per_cell_asked), cr$check$cells))
say(sprintf(paste("value: the cell mean pooled toward its %d nearest cells;",
                  "median own weight %.2f"),
            rec$neighbours, rec$own_weight))
say(sprintf("%s: %g%% for %s", iv$columns[1], 100 * iv$level[1], iv$covers[1]))
say(sprintf(paste("leave-one-out mean squared error %.3g against %.3g for one",
                  "mean; structured: %s"),
            rec$loo, rec$loo_one_cell, rec$structured))
say(sprintf("%.1f%% of observations are the only one in their cell",
            100 * rec$share_alone))

## ----value-at-----------------------------------------------------------------
seeds$cell_id <- tess$index
elsewhere <- st_as_sf(
  data.frame(x = 4e5 + c(5000, 12000, 26000), y = 4e6 + c(5000, 9000, 10000)),
  coords = c("x", "y"), crs = 32617)
at <- cell_values_at(elsewhere, vals, asg, "yield", id_col = "cell_id",
                     seeds = seeds)

shown <- c("cell_id", "value", "obs_lo", "obs_hi", "filled", "dist_ratio")
num   <- c("value", "obs_lo", "obs_hi", "dist_ratio")
at[num] <- lapply(at[num], round, 2)
at[, shown]
outside <- at[3, ]

## ----fixture------------------------------------------------------------------
set.seed(42)
xy    <- st_coordinates(centres)
D     <- as.matrix(dist(xy))
field <- as.numeric(t(chol(exp(-D / 120e3) + diag(1e-8, nrow(D)))) %*%
                      rnorm(nrow(D)))

pts <- centres
pts$elev <- rnorm(nrow(pts))
pts$z    <- 0.8 * pts$elev + 2 * field + rnorm(nrow(pts), sd = 0.3)

## ----learner------------------------------------------------------------------
trend_fit <- function(train_sf, ...) {
  d  <- st_drop_geometry(train_sf)
  co <- st_coordinates(train_sf)
  d$x <- co[, 1]; d$y <- co[, 2]
  new_spatial_fit(subclass = "trend_fit",
                  engine = stats::lm(z ~ elev + x + y, data = d),
                  formula = z ~ elev + x + y, response_var = "z",
                  predictor_vars = "elev", data_sf = train_sf)
}
predict.trend_fit <- function(object, newdata = NULL, ...) {
  if (is.null(newdata)) return(stats::fitted(object$engine))
  d  <- st_drop_geometry(newdata)
  co <- st_coordinates(newdata)
  d$x <- co[, 1]; d$y <- co[, 2]
  as.numeric(stats::predict(object$engine, newdata = d))
}
residuals.trend_fit <- function(object, ...) stats::residuals(object$engine)
fitted.trend_fit    <- function(object, ...) stats::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, "trend_fit", get(paste0(.g, ".trend_fit")))

folds <- make_folds(pts, k = 5, method = "block_kfold", block_size = 100e3,
                    seed = 1)
cv    <- cv_spatial(pts, "z", "elev", trend_fit, folds = folds)
fit   <- trend_fit(pts)

## ----report-------------------------------------------------------------------
m <- function(x) format(round(as.numeric(x)), big.mark = ",",
                        scientific = FALSE)

report <- list(
  folds = sprintf("%s, k = %d, %d by %d blocks of %s by %s m (asked for %s m)",
                  folds$method, folds$k, folds$params$grid_nx,
                  folds$params$grid_ny, m(folds$params$block_width),
                  m(folds$params$block_height), m(folds$params$block_size)),
  score = sprintf("RMSE %.2f (per fold %.2f to %.2f), R2 %.3f",
                  cv$overall$RMSE, min(cv$fold_metrics$RMSE),
                  max(cv$fold_metrics$RMSE), cv$overall$R2),
  coverage = sprintf(paste("%d of %d folds scored, %d rows dropped,",
                           "%d orphan, %d unknown id"),
                     cv$n_folds_succeeded, cv$n_folds_attempted, cv$n_dropped,
                     length(cv$orphan_rows), cv$n_unknown_ids)
)

## ----report-morans------------------------------------------------------------
mi <- residual_morans_i(fit)
report$residuals <- sprintf("Moran's I %.3f (z = %.1f, p = %.3g, %s null)",
                            mi$observed, mi$z, mi$p_value, mi$null)

## ----report-aoa---------------------------------------------------------------
surface <- predict_surface(fit, n_cells = 1500, covariates = pts,
                           boundary = counties)
aoa <- area_of_applicability(surface, model = fit, folds = folds)
report$applicability <- sprintf("%d of %d grid points outside (DI > %.3f)",
                                aoa$n_outside, aoa$n_new, aoa$threshold)

## ----report-range, eval=has_gstat---------------------------------------------
sac <- estimate_sac_range(pts, "z")
edge <- min(folds$params$block_width, folds$params$block_height)
report$range <- sprintf(paste("estimated range %s m against a narrowest",
                              "block edge of %s m"),
                        m(signif(sac, 2)), m(edge))

## ----report-print-------------------------------------------------------------
for (line in names(report)) say(line, ": ", report[[line]])

## ----block-vs-range, echo=FALSE, results='asis', eval=has_gstat---------------
# Which way the score errs for this map: the held-out distances of the folds
# against the distances from the surface's grid points to the same training
# data.
reading <- attr(fold_separation(folds, pts, sac = sac, prediction_points = surface),
                "target")$reading
says <- c(
  matched = "the held-out points sit about as far from their training data as the grid points do, so the score is the error of this map.",
  closer  = "the held-out points sit closer to their training data than the grid points do, so the score tends to read low for this map; wider blocks, or `make_folds(method = \"knndm\", prediction_points = surface)`, match it.",
  farther = "the held-out points sit farther from their training data than the grid points do, so the score tends to read high for this map; narrower blocks, or `make_folds(method = \"knndm\", prediction_points = surface)`, match it.",
  mixed   = "the two sets of distances cross, so they give no single direction.")
blocks <- if (edge < sac)
  "the blocks are narrower than the range, and a held-out point is still correlated with nearby training data" else
  "the blocks are at least as wide as the range"
cat(sprintf(paste0(
  "The narrowest block edge is %s m and the estimated range about %s m, so %s. ",
  "Whether that makes the score optimistic depends on how far the map's grid points ",
  "sit from the data. `fold_separation()` compares the two against the grid ",
  "points of the surface above and reads `%s`: %s ",
  "`vignette(\"spatial-cross-validation\")` explains the four readings.\n"),
  m(edge), m(signif(sac, 2)), blocks, reading, says[[reading]]))

## ----block-vs-range-nogstat, echo=FALSE, results='asis', eval=!has_gstat------
# cat("*(The range line needs `gstat`, which is not installed here. The range",
#     "line sets the block size beside the estimated autocorrelation range, and",
#     "`fold_separation()` with the map's cells as `prediction_points` says",
#     "which way the score errs for that map;",
#     "`vignette(\"spatial-cross-validation\")` explains the readings.)*\n")

## ----surface-out--------------------------------------------------------------
st_write(aoa$aoa, file.path(dir, "surface.gpkg"), quiet = TRUE)

## ----save-records-------------------------------------------------------------
st_write(vals, file.path(dir, "cell-values.gpkg"), quiet = TRUE)
saveRDS(vals, file.path(dir, "cell-values.rds"))

records <- c("pooled", "count_rule", "intervals")
kept <- function(x) sum(records %in% names(attributes(x)))
c(GeoPackage = kept(st_read(file.path(dir, "cell-values.gpkg"), quiet = TRUE)),
  RDS        = kept(readRDS(file.path(dir, "cell-values.rds"))))

## ----seeds-table, echo=FALSE, results='asis'----------------------------------
# Every exported function with a seed argument, read from its signature.
seeded <- do.call(rbind, lapply(sort(getNamespaceExports("spatialkit")), function(f) {
  fn <- getExportedValue("spatialkit", f)
  if (!is.function(fn)) return(NULL)
  arg <- intersect(c("seed", "set_seed"), names(formals(fn)))
  if (!length(arg)) return(NULL)
  value <- eval(formals(fn)[[arg]])
  data.frame(fun = f, arg = arg,
             default = if (is.null(value)) "NULL" else format(value))
}))
seeded <- seeded[order(seeded$default != "NULL", seeded$fun), ]
unseeded <- seeded$fun[seeded$default == "NULL"]
cat("| Function | Argument | Default |\n|---|---|---|\n",
    sprintf("| `%s()` | `%s` | `%s` |\n", seeded$fun, seeded$arg, seeded$default),
    sep = "")

