## ----setup, include=FALSE-----------------------------------------------------
# gstat fits the variogram behind two of the criteria, and ggplot2 draws the
# profile. Both are Suggests, so the article is gated on them here and
# R CMD build succeeds on a machine that has neither.
# `eval` gates chunks only: knitr does not apply it to inline `r ...` code,
# which runs regardless. Inline code that reads something a chunk defines
# goes through iv(), which leaves its argument unevaluated when the chunks
# do not run, or the article fails to build without these packages.
has_gstat  <- requireNamespace("gstat",   quietly = TRUE)
has_ggplot <- requireNamespace("ggplot2", quietly = TRUE)
runs <- has_gstat && has_ggplot
iv   <- function(x) if (runs) x else "(not run)"

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

## ----default-call, eval=FALSE-------------------------------------------------
# prof <- resolution_profile(pts, response_var = "z")
# sel  <- select_resolution(prof)

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

set.seed(42)
n  <- 500
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 / 100) + diag(1e-8, n))) %*% rnorm(n)) +
        rnorm(n, sd = 1)
pts  <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)

## ----size-default-------------------------------------------------------------
prof_default <- resolution_profile(pts, response_var = "z")
select_resolution(prof_default)

## ----size-profile-------------------------------------------------------------
sizes     <- c(12, 9, 6, 4.5, 3)
prof_size <- resolution_profile(pts, response_var = "z", obs_per_cell = sizes)
as.data.frame(prof_size)[, c("levels", "scored_per_cell", "loo",
                             "share_alone", "own_weight")]

## ----size-select--------------------------------------------------------------
sel_size <- select_resolution(prof_size, criterion = "size",
                              obs_per_cell = 4.5)
sel_size$best

## ----size-text, include=FALSE-------------------------------------------------
lowest <- prof_size$levels[which.min(prof_size$loo)]
lowest_txt <- sprintf("%d cells, %s", lowest,
                      if (lowest == max(prof_size$levels)) "the finest size offered"
                      else "which is not the finest size offered")

## ----size-trade, echo=FALSE, results='asis'-----------------------------------
at <- function(s) {
  tab <- as.data.frame(prof_size)
  tab[tab$levels == max(2, round(nrow(pts) / s)), ]
}
alone <- function(r) {
  if (r$share_alone == 0) "no observation sits alone in its cell"
  else sprintf("%s percent of the observations sit alone in their cell",
               format(round(100 * r$share_alone, 1)))
}
coarse <- at(max(sizes)); fine <- at(min(sizes))
cat(sprintf(paste("In the table, at %s observations per cell %s and the median",
                  "own weight is %.2f; at %s, %s and it is %.2f. A larger size",
                  "gives fewer cells, whose pooled values rest more on their own",
                  "observations.\n"),
            format(max(sizes)), alone(coarse), coarse$own_weight,
            format(min(sizes)), alone(fine), fine$own_weight))

## ----size-structured----------------------------------------------------------
data.frame(structured = sel_size$structured, loo = sel_size$loo,
           one_mean = sel_size$loo_one_cell)

## ----loo-profile--------------------------------------------------------------
prof_loo <- resolution_profile(pts, response_var = "z", estimate = "mean")
as.data.frame(prof_loo)[, c("levels", "scored_per_cell", "loo", "loo_se",
                            "share_alone")]

sel_loo <- select_resolution(prof_loo, criterion = "loo")
sel_loo

## ----loo-text, echo=FALSE, results='asis'-------------------------------------
if (is.na(sel_loo$edge)) {
  cat(sprintf(paste("The lowest error is at %d cells, inside the sizes offered,",
                    "so the criterion chose it.\n"), sel_loo$best))
} else {
  cat(sprintf(paste("The lowest error is at %d cells, which is %s: an end of",
                    "the ladder chose the count, and the functions that take",
                    "the selection warn of it (class",
                    "`spatialkit_bound_chosen`).\n"), sel_loo$best, sel_loo$edge))
}

## ----profile------------------------------------------------------------------
prof <- resolution_profile(pts, response_var = "z", n_levels = 16)
print(as.data.frame(prof)[, c("levels", "cell_n_median", "cell_diam_median",
                              "cp", "reliability", "loo", "moran_z")],
      digits = 3)

## ----bounds-------------------------------------------------------------------
str(attr(prof, "bounds")[c("floor", "ceiling", "ceiling_from", "supported",
                           "range")])

## ----criteria-table, echo=FALSE, results='asis'-------------------------------
cat(
"| criterion | measures | needs | direction |\n",
"|---|---|---|---|\n",
"| `elbow` | how far the log of the within-cluster sum of squares (WSS) of the coordinates sags below a power law (the straight log-log line from one cell to the last level); `NA` at every level when the points have no cluster structure | coordinates only | larger |\n",
"| `cp` | Mallows' \\(C_p\\) of the piecewise-constant approximation of the response by cell means: the fit of the cell means, penalised for the number of cells | a response, and a variogram for the nugget | smaller |\n",
"| `moran_z` | Moran's z of the cell means (of their regression residuals when predictors are given): whether neighbouring cells resemble each other | a response | none: a diagnostic, not a count rule |\n",
"| `reliability` | the share of the spread in the cell means that is signal rather than sampling noise | a variogram | larger |\n",
"| `loo` | the leave-one-out error of the cell value the profile scores, the pooled value by default | a response | smaller |\n",
sep = "")

## ----plot-alt, echo=FALSE-----------------------------------------------------
oxford <- function(x) if (length(x) < 2L) as.character(x) else
  paste(paste(x[-length(x)], collapse = ", "), "and", x[length(x)])
picks <- function(cr) select_resolution(prof, criterion = cr)$best
shown <- c(cp = "Mallows' Cp", reliability = "reliability",
           loo = "the leave-one-out error")
shown <- shown[vapply(names(shown), function(cr) any(is.finite(prof[[cr]])),
                      logical(1))]
plot_alt <- sprintf(paste(
  "Stacked panels against the number of cells, from %d to %d: %s of the",
  "pooled value, and the absolute Moran's z of the cell means. A dot and a",
  "dotted line mark the level selected for %s, with a shaded band over each",
  "flat region; the Moran panel has no selected level."),
  min(prof$levels), max(prof$levels), oxford(shown),
  oxford(sprintf("%s at %d cells", shown,
                 vapply(names(shown), picks, numeric(1)))))

## ----plot-profile, fig.height=8, fig.alt=plot_alt-----------------------------
plot(prof)

## ----cp-context, echo=FALSE---------------------------------------------------
vg  <- attr(prof, "variogram")
nug <- round(vg$nugget, 2); psl <- round(vg$psill, 2)
cp_sel <- select_resolution(prof, criterion = "cp")

## ----cp-text, echo=FALSE, results='asis'--------------------------------------
cat(sprintf("This fixture has a fitted nugget of %s against a partial sill of %s,", nug, psl),
    if (isTRUE(cp_sel$at_ceiling))
      "and `cp` still falls to the last level of the ladder: its minimum is the support ceiling, as `summary()` says below.\n"
    else
      "and `cp` turns around inside the ladder.\n")

## ----auto-on-ladder, warning=TRUE---------------------------------------------
auto <- select_resolution(prof)
auto$best

## ----auto-text, echo=FALSE, results='asis'------------------------------------
asked <- max(2, round(nrow(pts) / 4.5))
if (asked %in% prof$levels) {
  cat(sprintf("That asks for %d cells, a level of this ladder, so the call returns it.\n",
              asked))
} else {
  cat(sprintf(paste("That asks for %d cells, which this ladder does not have, so",
                    "the call warns (class `spatialkit_size_not_reached`) and",
                    "returns the nearest level, %d.\n"), asked, auto$best))
}

## ----select-------------------------------------------------------------------
sel <- select_resolution(prof, criterion = "reliability")
sel

## ----flags--------------------------------------------------------------------
c(at_floor = sel$at_floor, at_ceiling = sel$at_ceiling)

## ----flag-text, echo=FALSE, results='asis'------------------------------------
# Read in "From a count to cells", where the selection becomes seeds.
edge     <- sel$edge
on_bound <- if (is.null(edge) || is.na(edge)) " (this one does not)" else
  sprintf(", as this one does at %s", sub(" \\(.*\\)$", "", edge))
if (isTRUE(sel$at_floor)) {
  cat("`at_floor` is `TRUE` here. The reliability curve keeps rising toward",
      "coarser counts, and the floor from the autocorrelation range stops it",
      "there, so", sel$best, "is the coarsest count the range allows, set by",
      "the floor and not by the criterion; quote it as a bound, not as the",
      "criterion's choice. Changing `tol` will not move it.\n")
} else if (isTRUE(sel$at_ceiling)) {
  cat("`at_ceiling` is `TRUE` here: the support ceiling stopped the criterion,",
      "so take the number as a bound on the analysis.\n")
} else {
  cat("Both are `FALSE` here, so the optimum sits inside the ladder and the",
      "criterion chose it.\n")
}

## ----compare-criteria---------------------------------------------------------
summary(prof)

## ----flat-text, echo=FALSE, results='asis'------------------------------------
# A flat region is a set: the curves are not monotone, so a flat region can
# skip levels. The sentences below read the rendered summary rather than
# quoting numbers that a different platform's k-means or variogram fit could
# move.
s      <- summary(prof)
lad    <- attr(s, "ladder")
flats  <- attr(s, "bands")[s$criterion]
common <- attr(s, "common")
pos    <- lapply(flats, function(b) sort(match(b, lad)))
holed  <- names(pos)[vapply(pos, function(p) any(diff(p) > 1L), logical(1))]
solid  <- names(pos)[vapply(pos, function(p) length(p) > 1L && all(diff(p) == 1L),
                            logical(1))]
example <- if (length(holed)) {
  p <- pos[[holed[1L]]]
  skipped <- lad[setdiff(seq(min(p), max(p)), p)]
  sprintf("the flat region of `%s` above holds %s and leaves out the %s between them.",
          holed[1L], oxford(lad[p]), oxford(skipped))
} else {
  "a flat region that skips a level prints as a comma-separated list."
}
run <- if (length(solid)) {
  p <- pos[[solid[1L]]]
  sprintf("A run of %d adjacent levels prints as a range, as `%s` does with `%d to %d`.",
          length(p), solid[1L], lad[min(p)], lad[max(p)])
} else "A run of adjacent levels prints as a range."
cat("A flat region is a set of levels and can skip some, because the criterion",
    "curves are not monotone:", example, run,
    "`attr(summary(prof), \"common\")` returns the levels that every flat region",
    "contains, for use in code, and `attr(summary(prof), \"bands\")` each",
    "criterion's flat region in full.",
    if (length(common))
      "Those common levels are counts that every criterion accepts.\n"
    else
      paste("Here no level is in every flat region, so no single count satisfies",
            "every criterion, and you have to say which question your analysis",
            "asks.\n"))

## ----elbow-clustered----------------------------------------------------------
set.seed(1)
centre <- data.frame(x = runif(6, 100, 900), y = runif(6, 100, 900))
k      <- sample(6, 300, replace = TRUE)
clus   <- st_as_sf(data.frame(x = 5e5 + centre$x[k] + rnorm(300, sd = 25),
                              y = 5e6 + centre$y[k] + rnorm(300, sd = 25)),
                   coords = c("x", "y"), crs = 32632)
determine_optimal_levels(clus, max_levels = 40)

## ----doi, warning=TRUE--------------------------------------------------------
lv <- determine_optimal_levels(pts, max_levels = 40)
lv

## ----split--------------------------------------------------------------------
prof_split <- resolution_profile(pts, response_var = "z", n_levels = 16,
                                 select_on = "split")
halves <- attr(prof_split, "split")
halves

## ----split-ladder-------------------------------------------------------------
str(attr(prof_split, "bounds")[c("floor", "ceiling", "n", "supported")])

## ----next-step, warning=TRUE--------------------------------------------------
bnd   <- clip_target_for(pts, expand = 0.02, quiet = TRUE)
seeds <- get_voronoi_seeds(boundary = bnd, method = "kmeans", n = sel,
                           sample_points = pts)
cells <- build_tessellation(seeds, boundary = bnd, method = "voronoi",
                            quiet = TRUE)
nrow(cells$cells)

## ----next-step-grid, warning=TRUE---------------------------------------------
hex <- build_tessellation(pts, boundary = bnd, method = "hex",
                          approx_n_cells = sel, quiet = TRUE)
nrow(hex$cells)

## ----grid-text, echo=FALSE, results='asis'------------------------------------
cat(sprintf(paste("The hex grid has %d cells for a request of %d. The target",
                  "is adjusted for hexagonal packing, and the hexagons the",
                  "boundary cuts are kept as cells, so `approx_n_cells` is",
                  "approximate. The seeded Voronoi tessellation has %s, because",
                  "the seeds are the cells.\n"),
            nrow(hex$cells), sel$best,
            if (nrow(cells$cells) == sel$best) "exactly the count asked for"
            else sprintf("%d", nrow(cells$cells))))

