## ----setup, include=FALSE-----------------------------------------------------
# gstat fits the variograms behind the design effect and the kriging check,
# and ggplot2 draws the two maps. Both are Suggests, so the chunks that use
# them are gated and the rest runs on the hard dependencies.
# `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, or the article fails to build where the
# package is missing.
has_gstat  <- requireNamespace("gstat",   quietly = TRUE)
has_ggplot <- requireNamespace("ggplot2", quietly = TRUE)

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

## ----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)

prof <- resolution_profile(pts, "z")
size <- select_resolution(prof)
size$best

## ----methods------------------------------------------------------------------
bnd   <- clip_target_for(pts, expand = 0.02, quiet = TRUE)
seeds <- get_voronoi_seeds(n = size, sample_points = pts)

vor <- build_tessellation(seeds, boundary = bnd, method = "voronoi",
                          quiet = TRUE)
hex <- build_tessellation(pts, boundary = bnd, method = "hex",
                          approx_n_cells = size, quiet = TRUE)
sq  <- build_tessellation(pts, boundary = bnd, method = "square",
                          approx_n_cells = size, quiet = TRUE)

c(voronoi = nrow(vor$cells), hex = nrow(hex$cells), square = nrow(sq$cells))

## ----method-counts, include=FALSE---------------------------------------------
# Points per cell under each method, for the figure and the sentence below.
per_cell <- function(cells, method) {
  ids <- assign_features_to_polygons(pts, cells, polygon_id_col = "cell_id",
                                     quiet = TRUE)$cell_id
  cells$n <- tabulate(match(ids, cells$cell_id), nrow(cells))
  cells$method <- method
  cells[, c("method", "n")]
}
three <- rbind(per_cell(vor$cells, "Voronoi on seeds"),
               per_cell(hex$cells, "hex"),
               per_cell(sq$cells,  "square"))
three$method <- factor(three$method, c("Voronoi on seeds", "hex", "square"))
empty <- tapply(three$n == 0, three$method, sum)
three$n[three$n == 0] <- NA
methods_alt <- sprintf(paste(
  "Three maps of the same square area, each cell shaded by the points it",
  "holds. Of the %d Voronoi cells on seeds, %s empty; the hex grid of",
  "%d cells has %d empty cells and the square grid of %d cells has %d,",
  "shown in grey."),
  nrow(vor$cells), if (empty[[1]] == 0) "none is" else paste(empty[[1]], "are"),
  nrow(hex$cells), empty[[2]],
  nrow(sq$cells), empty[[3]])

## ----methods-map, eval=has_ggplot, fig.height=2.6, fig.alt=methods_alt--------
library(ggplot2)

ggplot(three) +
  geom_sf(aes(fill = n), colour = "white", linewidth = 0.2) +
  facet_wrap(~ method) +
  scale_fill_viridis_c(name = "points\nin cell", na.value = "grey85") +
  theme_void()

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

## ----seeds--------------------------------------------------------------------
nrow(seeds)   # the centres the profile scored
fresh <- get_voronoi_seeds(n = size$best, sample_points = pts, set_seed = 1)
nrow(fresh)   # a new density-weighted k-means

## ----assign-------------------------------------------------------------------
asg_v <- assign_features_to_polygons(pts, vor$cells, polygon_id_col = "cell_id")
head(asg_v$cell_id)

## ----assign-counts, include=FALSE---------------------------------------------
n_v <- tabulate(match(asg_v$cell_id, vor$cells$cell_id), nrow(vor$cells))

## ----group--------------------------------------------------------------------
nc <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
counties <- ensure_projected(nc[, c("NAME", "BIR74", "SID74")])
state    <- st_union(counties)
nc_cells <- build_tessellation(coerce_to_points(counties), boundary = state,
                               method = "hex", approx_n_cells = 12,
                               quiet = TRUE)$cells

grouped <- assign_features_to_polygons(counties, nc_cells,
                                       polygon_id_col = "cell_id")
joined  <- st_join(counties, nc_cells)

c(counties = nrow(counties), grouped = nrow(grouped), joined = nrow(joined))

## ----group-used, include=FALSE------------------------------------------------
used <- length(unique(stats::na.omit(grouped$cell_id)))
used <- if (used == nrow(nc_cells)) paste("all", used) else
  paste(used, "of the", nrow(nc_cells))

## ----group-alt, include=FALSE-------------------------------------------------
grouped$cell <- factor(grouped$cell_id)
group_alt <- sprintf(paste(
  "The %d North Carolina counties, each filled with the colour of the",
  "hexagonal cell it overlaps most, under the outlines of the %d cells",
  "drawn over the state."), nrow(grouped), nrow(nc_cells))

## ----group-map, eval=has_ggplot, fig.height=2.6, fig.alt=group_alt------------
ggplot() +
  geom_sf(data = grouped, aes(fill = cell), colour = "grey40",
          linewidth = 0.1) +
  geom_sf(data = nc_cells, fill = NA, colour = "black", linewidth = 0.5) +
  scale_fill_manual(values = grDevices::hcl.colors(nlevels(grouped$cell),
                                                   "Set 3"),
                    guide = "none") +
  theme_void()

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

## ----summarise----------------------------------------------------------------
vals <- summarize_by_cell(asg_v, "z", id_col = "cell_id", cells_sf = vor$cells)
names(vals)
round(st_drop_geometry(vals)[1:4, -1], 3)

## ----se-cells-----------------------------------------------------------------
tess <- build_tessellation(pts, boundary = bnd, method = "square",
                           approx_n_cells = 24, quiet = TRUE)
asg  <- assign_features_to_polygons(pts, tess$cells)

c(cells = nrow(tess$cells), points = nrow(asg),
  median_per_cell = median(table(asg$poly_id)))

## ----deff, eval=has_gstat-----------------------------------------------------
sac  <- estimate_sac_range(pts, "z")
iid  <- summarize_by_cell(asg, "z", cells_sf = tess$cells, deff = 1)
kish <- summarize_by_cell(asg, "z", cells_sf = tess$cells, deff = "kish")
vgm  <- summarize_by_cell(asg, "z", cells_sf = tess$cells, deff = "variogram",
                          sac = sac)

data.frame(n         = iid$n,
           iid       = round(iid$..se_resp_z, 3),
           kish      = round(kish$..se_resp_z, 3),
           variogram = round(vgm$..se_resp_z, 3))[1:5, ]

## ----deff-inflation, echo=FALSE, results='asis', eval=has_gstat---------------
ik <- median(kish$..se_resp_z / iid$..se_resp_z, na.rm = TRUE)
iv <- median(vgm$..se_resp_z  / iid$..se_resp_z, na.rm = TRUE)
cat(sprintf(paste(
  "Across cells the standard error is a median %.2f times the naive one",
  "under `kish` and %.2f times under `variogram`. As an estimate of the population",
  "mean, a confidence interval built on the naive standard error is about",
  "%.0f percent of the width the variogram correction gives it on this",
  "field. For the cell's own mean the naive standard error is the better of",
  "the two, and close to right when the points are spread through the cell;",
  "the next section (`kriging_adequacy()`) measures how close on this",
  "field.\n"), ik, iv, 100 / iv))

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

## ----deff-attrs, eval=has_gstat-----------------------------------------------
attr(vgm, "deff_applied")$method
summary(attr(vgm, "deff_applied")$deff)
attr(kish, "icc")$resp

## ----kriging, eval=has_gstat--------------------------------------------------
ka <- kriging_adequacy(asg, "z", tess$cells, k = 4, seed = 1)
ka

## ----kriging-cols, eval=has_gstat---------------------------------------------
round(as.data.frame(st_drop_geometry(ka))[1:4, c("n", "mean", "se",
                                                 "plain_var", "kr_pred",
                                                 "kr_var", "kr_ratio",
                                                 "kr_gain", "kr_shift")], 3)

## ----kriging-reading, echo=FALSE, results='asis', eval=has_gstat--------------
ok    <- is.finite(ka$se) & is.finite(ka$plain_var) & ka$plain_var > 0 &
         ka$n >= 2
ratio <- median(ka$se[ok]^2 / ka$plain_var[ok])
shift <- ka$kr_shift[is.finite(ka$kr_shift)]
naive <- if (ratio < 1) {
  sprintf("so the naive standard error is about %.0f percent too small",
          100 * (1 - sqrt(ratio)))
} else "so the naive standard error is not too small"
cat(sprintf(paste(
  "On this field the naive variance \\(s^2/n\\) is %.2f of `plain_var` in",
  "the median cell, %s for the cell's own mean. Kriging removes a median",
  "%.0f percent of the plain mean's error variance. `kr_shift` is beyond 1",
  "in %d of the %d cells and beyond 2 in %d, against about %.0f and %.0f",
  "for a right variogram, and the variance of the standardised errors is",
  "%.2f.\n"),
  ratio, naive, 100 * median(ka$kr_gain, na.rm = TRUE),
  sum(abs(shift) > 1), length(shift), sum(abs(shift) > 2),
  2 * pnorm(-1) * length(shift), 2 * pnorm(-2) * length(shift),
  attr(ka, "cv")$zscore_var))

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

## ----se-empty, include=FALSE--------------------------------------------------
se_empty <- sum(!tess$cells$poly_id %in% asg$poly_id)

## ----raised-------------------------------------------------------------------
raised <- function(expr) {
  seen <- character(0)
  withCallingHandlers(expr, warning = function(w) seen <<- c(seen, class(w)[1]))
  seen
}

## ----pooled-clean-------------------------------------------------------------
raised(summarize_by_cell(asg_v, "z", id_col = "cell_id", cells_sf = vor$cells))

## ----mismatch-----------------------------------------------------------------
w <- tryCatch(
  summarize_by_cell(asg_v, "z", id_col = "cell_id", cells_sf = vor$cells,
                    estimate = "mean"),
  spatialkit_estimate_mismatch = function(w) w)
writeLines(strwrap(conditionMessage(w), 76))
unlist(unclass(w)[c("chosen_for", "reported", "rule", "cells")])

## ----differ-------------------------------------------------------------------
w <- tryCatch(
  summarize_by_cell(asg_v[-(1:20), ], "z", id_col = "cell_id",
                    cells_sf = vor$cells),
  spatialkit_cells_differ = function(w) w)
writeLines(strwrap(conditionMessage(w), 76))
w$what
rbind(scored = unlist(w$scored), found = unlist(w$found))

## ----no-structure, warning=TRUE-----------------------------------------------
noise <- summarize_by_cell(asg_v, "b", id_col = "cell_id")
as.data.frame(attr(noise, "pooled")$columns$resp_b[
  c("loo", "loo_one_cell", "structure_p", "own_weight", "structured")])

## ----degenerate---------------------------------------------------------------
asg_v$flat <- 1
w <- tryCatch(summarize_by_cell(asg_v, "flat", id_col = "cell_id"),
              spatialkit_pool_degenerate = function(w) w)
writeLines(strwrap(conditionMessage(w), 76))
w$reason

## ----few-cells, warning=TRUE--------------------------------------------------
few   <- build_tessellation(pts, boundary = bnd, method = "square",
                            approx_n_cells = 4, quiet = TRUE)$cells
asg_f <- assign_features_to_polygons(pts, few, quiet = TRUE)
four  <- summarize_by_cell(asg_f, "z")
round(as.data.frame(four)[, c("poly_id", "n", "resp_mean_z", "..pooled_resp_z",
                              "..pooled_w_resp_z", "..pooled_target_resp_z")],
      3)

## ----values-at----------------------------------------------------------------
seeds$cell_id <- vor$index
where <- st_as_sf(data.frame(x = 5e5 + c(250, 600, 1300),
                             y = 5e6 + c(250, 700, 500)),
                  coords = c("x", "y"), crs = 32632)
at <- cell_values_at(where, vals, asg_v, "z", id_col = "cell_id", seeds = seeds)
at[c("value", "dist_ratio")] <- lapply(at[c("value", "dist_ratio")], round, 2)
at[, c("cell_id", "value", "estimate", "filled", "dist_ratio")]

