The hardware and bandwidth for this mirror is donated by METANET, the Webhosting and Full Service-Cloud Provider.
If you wish to report a bug, or if you are interested in having us mirror your free-software or open-source project, please feel free to contact us at mirror[@]metanet.ch.

Package {spatialkit}


Title: Spatial Tessellation, Modelling, and Cross-Validation Toolkit
Version: 3.0.0
Description: Constructs analysis regions from the distribution of the data itself, as an alternative to aggregating onto administrative boundaries that were drawn for unrelated purposes. Seeds and builds Voronoi, Delaunay, hexagonal and square tessellations with reproducible identifiers. Chooses a cell count, by default from a target number of observations per cell, or by scoring a ladder of counts against the spatial structure of the observations. Assigns features to cells and reports for each cell a count, a mean with its standard error and a pooled value pulled toward the mean of the observations in the 8 nearest cells. A design effect can correct the standard errors for autocorrelation within the cells. Projects lon/lat input to a projected coordinate reference system chosen for the extent of the data. Fits geographically weighted regression (its kernels, diagnostics and forward selection follow 'GWmodel'; Lu et al. (2014) <doi:10.1080/10095020.2014.917453>), Bayesian Gaussian process regression (via 'brms', using the Hilbert space approximation of Riutort-Mayol et al. (2023) <doi:10.1007/s11222-022-10167-2>) and random forests (via 'ranger', with the permutation importance of Strobl et al. (2007) <doi:10.1186/1471-2105-8-25>), each behind one S3 class with consistent predict, fitted, residuals and plot methods. Provides spatial cross-validation with random, block, buffered, leave-location-out and nearest-neighbour distance-matched folds (Milà et al. (2022) <doi:10.1111/2041-210X.13851>; Linnenbrink et al. (2024) <doi:10.5194/gmd-17-5897-2024>), forward variable selection, model comparison, prediction onto a regular surface, and the area of applicability of Meyer and Pebesma (2021) <doi:10.1111/2041-210X.13650> to flag where a fitted model extrapolates beyond its training data.
License: MIT + file LICENSE
URL: https://elkronos.github.io/gis_modeling_toolkit/, https://github.com/elkronos/gis_modeling_toolkit
BugReports: https://github.com/elkronos/gis_modeling_toolkit/issues
Encoding: UTF-8
Depends: R (≥ 4.1.0)
Imports: sf (≥ 1.0), dplyr (≥ 1.0), logger, digest, FNN, stats, methods, utils, parallel
Suggests: sp, GWmodel, ranger, brms (≥ 2.17.0), cmdstanr, loo, tibble, geometry, gstat, ggplot2 (≥ 3.4.0), patchwork, Matrix, nlme, spdep, testthat (≥ 3.1.7), knitr, rmarkdown, units, vctrs, withr
Additional_repositories: https://stan-dev.r-universe.dev
Config/testthat/edition: 3
VignetteBuilder: knitr
Config/roxygen2/version: 8.1.0
NeedsCompilation: no
Packaged: 2026-11-22 05:29:38 UTC; appleair
Author: Justin Chase [aut, cre, cph]
Maintainer: Justin Chase <jchase.msu@gmail.com>
Repository: CRAN
Date/Publication: 2026-11-23 08:10:02 UTC

spatialkit: Spatial Tessellation, Modelling, and Cross-Validation Toolkit

Description

Constructs analysis regions from the distribution of the data itself, as an alternative to aggregating onto administrative boundaries that were drawn for unrelated purposes. Seeds and builds Voronoi, Delaunay, hexagonal and square tessellations with reproducible identifiers. Chooses a cell count, by default from a target number of observations per cell, or by scoring a ladder of counts against the spatial structure of the observations. Assigns features to cells and reports for each cell a count, a mean with its standard error and a pooled value pulled toward the mean of the observations in the 8 nearest cells. A design effect can correct the standard errors for autocorrelation within the cells. Projects lon/lat input to a projected coordinate reference system chosen for the extent of the data. Fits geographically weighted regression (its kernels, diagnostics and forward selection follow 'GWmodel'; Lu et al. (2014) doi:10.1080/10095020.2014.917453), Bayesian Gaussian process regression (via 'brms', using the Hilbert space approximation of Riutort-Mayol et al. (2023) doi:10.1007/s11222-022-10167-2) and random forests (via 'ranger', with the permutation importance of Strobl et al. (2007) doi:10.1186/1471-2105-8-25), each behind one S3 class with consistent predict, fitted, residuals and plot methods. Provides spatial cross-validation with random, block, buffered, leave-location-out and nearest-neighbour distance-matched folds (Milà et al. (2022) doi:10.1111/2041-210X.13851; Linnenbrink et al. (2024) doi:10.5194/gmd-17-5897-2024), forward variable selection, model comparison, prediction onto a regular surface, and the area of applicability of Meyer and Pebesma (2021) doi:10.1111/2041-210X.13650 to flag where a fitted model extrapolates beyond its training data.

Where to start

vignette("getting-started", package = "spatialkit") takes a layer of points through the pipeline below, from a cell count to a cross-validated model and a map that marks where its predictions apply. Each step of the pipeline names the article that covers it.

Ten scripts, 01 to 10, each on one topic, are installed with the package; 00-run-all.R runs them in order. Each prints what it is doing and says what to look for in a figure before drawing it:

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"))  # 01 to 10 in order

Set SPATIALKIT_TOUR_OUTPUT to a folder to write the figures there instead of drawing them, and SPATIALKIT_TOUR_PAUSE to "no" to skip the pause between figures that an interactive session gets.

Three help topics hold what many functions share: spatialkit-geometry (how input geometry and CRSs are read), spatialkit-conditions (every warning and error class the package raises, and how to catch one) and spatialkit-options (the two work limits).

The pipeline, in order

Steps 1 to 5 build cells from the spatial structure of the observations and summarise the observations onto them. Steps 6 to 10 fit a model to the points and check it: spatial cross-validation scores the model on blocks held away from its training data, and the area of applicability marks where its predictions leave the range of that data. Use the steps your question needs, in this order.

  1. Prepare the data. ensure_projected(), harmonize_crs(), coerce_to_points() and prep_model_data() put the observations in a projected CRS as points with complete values. Article: vignette("getting-started").

  2. Measure spatial autocorrelation. estimate_sac_range() estimates the distance over which observations stay correlated, and sac_nugget() returns the nugget of its variogram. The range sets a floor on the number of cells, which select_resolution(criterion = "reliability") and resolution_profile(range_floor = TRUE) apply. Sizing blocks from it is one way to set how far the held-out points sit from their training data, and suits a map that has to reach that far from the data. Article: vignette("spatial-cross-validation").

  3. Choose a resolution. resolution_profile() scores candidate cell counts and select_resolution() reads the count off the profile; by default the count gives 4.5 observations per cell. determine_optimal_levels() reads a count off the elbow of the k-means WSS curve of the coordinates alone, and returns NA when the curve has no elbow. Article: vignette("resolution").

  4. Build the cells. build_tessellation() draws Voronoi, hex, square or Delaunay cells with reproducible identifiers; get_voronoi_seeds() places the Voronoi seeds and clip_target_for() builds the polygon that hex and square cells are clipped to. Article: vignette("cells").

  5. Assign and summarise. assign_features_to_polygons() puts each observation in one cell, and summarize_by_cell() reduces to one row per cell with a count, a standard error and a pooled value. cell_values_at() reads cell values at other locations, and kriging_adequacy() checks the cell mean against block kriging. Article: vignette("cells").

  6. Make folds. make_folds() builds spatial cross-validation folds: blocked, buffered, leave-location-out or nearest-neighbour distance-matched. A cross-validated error is the error at the distance the folds put between the held-out points and their training data: it reads low for predictions made farther from the data and high for predictions made closer, so the folds to use are the ones matched to where the model will predict. fold_separation() with prediction_points compares the two distances. cv_block_size_sweep() scores a range of block sizes. Article: vignette("spatial-cross-validation").

  7. Fit a model. fit_rf_model() (random forest), fit_gwr_model() (GWR, coefficients that vary across the map) and fit_bayesian_spatial_model() (Bayesian GP) return a spatial_fit with predict(), fitted(), residuals(), summary() and plot() methods, and coef() for GWR and the Bayesian GP. new_spatial_fit() builds a backend of your own. model_metrics(), evaluate_insample(), compare_models() and residual_morans_i() check a fit in sample. Article: vignette("models").

  8. Cross-validate and compare. cv_rf(), cv_gwr(), cv_bayes() and cv_spatial(), which takes any learner, score a model on held-out blocks; compare_models_cv() scores several backends on one set of folds. Articles: vignette("spatial-cross-validation") and vignette("models").

  9. Choose predictors. select_features_forward() chooses predictors inside the cross-validation, and gwr_model_selection() chooses GWR predictors by forward selection. Article: vignette("models").

  10. Predict a surface and check where it applies. predict_surface() predicts onto a regular grid, and area_of_applicability() marks where the predictors leave the range the model was trained and scored on. Article: vignette("models").

  11. Report. ensure_stable_poly_id() gives the cells identifiers that do not depend on the order of the rows. Article: vignette("reporting").

vignette("spatialkit_nc_demo") runs the pipeline on one simulated layer.

Two choices are the user's, and each has an argument with a default. estimate is the cell value to report: the plain mean of a cell's observations ("mean"), or the pooled value ("pooled", the default), which is that mean pulled toward the mean of the observations in the 8 nearest cells (nearest by the centroid of their observations). resolution_profile() scores a count for the value it is given, and summarize_by_cell() reports the value it is given and warns when the count was chosen for the other one. obs_per_cell is the size: how many observations a cell is to hold on average, 4.5 by default. For pooled values the size sets the count (select_resolution(criterion = "size")); for plain means the lowest leave-one-out error can set it (criterion = "loo"). select_resolution()'s default criterion, "auto", takes the rule that goes with the profile's estimate. The defaults that change results from 2.0.0, and the argument that restores each, are listed under Breaking changes in news(package = "spatialkit").

Defaults and their sources

Defaults that follow a reference, each cited on the help page of the function named:

Defaults chosen without a citation:

Author(s)

Maintainer: Justin Chase jchase.msu@gmail.com [copyright holder]

Authors:

See Also

Entry points by task: build_tessellation() (build cells), summarize_by_cell() (summarise observations onto them), make_folds() (split the data into cross-validation folds), compare_models_cv() (score several models on the same folds), area_of_applicability() (find where predictions leave the range of the training data).


Subset a layer that carries a row record

Description

prep_model_data() and assign_features_to_polygons() return a layer with an attribute recording what happened to its rows ("dropped" for the first; "ties" and "unassigned" for the second). Those records describe the rows the layer was built with, and [ on an sf object copies attributes through unchanged, which would leave a subset reporting its parent's numbers for a different set of rows. Subsetting therefore returns a plain layer with the record removed, and so do the dplyr verbs that select or reorder rows (filter(), slice(), arrange(), distinct()); read the record from the layer the function returned, before subsetting it. Binding such layers (rbind(), dplyr::bind_rows()) likewise returns a plain sf layer.

Usage

## S3 method for class 'spatialkit_rows'
x[...]

Arguments

x

A layer returned by prep_model_data() or assign_features_to_polygons().

...

Passed to the underlying sf or data frame method.

Details

Each record carries n_rows, the number of rows it was made for. sf::st_drop_geometry() keeps the rows, and with them the record: it returns a data frame of class c("spatialkit_rows", "data.frame"). Binding such data frames with rbind() or dplyr::bind_rows() keeps the first one's record and class, so the record then describes only the first input's rows: its n_rows no longer equals nrow() of the result. The package's own readers ignore a record whose n_rows does not match; when reading attr(x, "dropped"), attr(x, "ties") or attr(x, "unassigned") yourself from a layer that has been through such steps, check it the same way.

Value

The subset, without the row records and without this class. A subset that is not a data frame (a single column taken with drop = TRUE) is returned unchanged.

See Also

prep_model_data() and assign_features_to_polygons(), the two functions that attach the records this method removes.

Other data preparation: coerce_to_points(), ensure_projected(), harmonize_crs(), prep_model_data(), spatialkit-geometry

Examples

library(sf)
dat <- st_as_sf(
  data.frame(x = 1:5, y = 5:1,
             resp = c(1, 2, NA, 4, 5), pred = c(1, 2, 3, 4, Inf)),
  coords = c("x", "y"), crs = 32632
)
# prep_model_data() warns that it dropped 2 of the 5 rows.
clean <- suppressWarnings(prep_model_data(dat, "resp", "pred"))
attr(clean, "dropped")$n          # 2
attr(clean[1:2, ], "dropped")     # NULL: the record does not follow

Mark where a model's predictions apply

Description

Computes the dissimilarity index (DI) of Meyer and Pebesma (2021) for a set of prediction locations and flags those that fall inside the model's area of applicability (AOA), the region of predictor space where the model's cross-validated performance estimate can be expected to hold.

Usage

area_of_applicability(
  newdata,
  model = NULL,
  train_sf = NULL,
  predictor_vars = NULL,
  weights = "auto",
  folds = NULL,
  threshold = NULL,
  normalizer_max_n = 5000L,
  seed = 123L,
  chunk_size = NULL,
  use_fnn = requireNamespace("FNN", quietly = TRUE),
  coords = c("auto", "yes", "no"),
  categorical = c("refuse", "indicator", "drop")
)

Arguments

newdata

Prediction locations: an sf object (typically from predict_surface) or a data.frame, carrying the predictor columns. When location is measured (a gwr_fit, a bayesian_fit, a forest fitted with include_coords = TRUE, or coords = "yes") an sf object is required, non-POINT geometry is reduced to representative points, and a CRS mismatch with the training data is reconciled; see Models whose predictions depend on location.

model

A fitted spatial_fit, supplying the training data and predictor names, the importance weights = "auto" reads, and whether its predictions depend on location. Optional if train_sf and predictor_vars are given directly, which lets this be used with any model.

train_sf

Training data, if not taken from model. When location is measured it is read in x and y, as newdata is.

predictor_vars

Predictor names, if not taken from model.

weights

"auto" (default), NULL, or a named numeric vector of predictor importances. "auto" uses pmax(model$info$importance, 0) when model carries a finite importance with at least one positive value, naming every predictor in use, from a model with out-of-bag skill; otherwise every predictor counts equally and a logged note says why (see Weights). NULL is the explicit request for equal weights. For a vector of your own, any positive scale works. When model was fitted with include_coords = TRUE, the coordinates "..x" and "..y" are measured as predictors too, besides the location index, which no weight changes (see Models whose predictions depend on location). You are not expected to supply importances for them: any you leave out default to the mean of the weights you did supply, so in the predictor index the coordinates count about as much as a typical predictor. Naming them explicitly overrides that. An unnamed vector may have one value per predictor either with or without the two coordinate columns. Weights must be finite and non-negative, so pass permutation importance as pmax(importance, 0). (A forest with no out-of-bag rows, replace = FALSE with sample_fraction = 1, has NaN importance, which pmax() keeps and which is refused when passed by hand; "auto" uses equal weights for it.) pmax(importance, 0) is all zero when the model found no predictor useful, and then the weights cannot say anything: with a single predictor any weight gives the same index and zero is accepted; with several, all of them are weighted equally, as with weights = NULL, and a warning says so. The coordinate default above is the mean of the supplied weights, so a zero weight on the only covariate of a coordinate-using model zeroes the coordinates too, and that equal weighting applies.

folds

Cross-validation folds: a make_folds result, a list of train/test splits, or a vector of fold labels with one entry per training row. Default NULL (plain nearest neighbour). The folds you passed to cv_*(), built on the layer model was fitted from, may name rows that prep_model_data() removed (a missing or non-finite value, or no location): as in cv_*(), they are dropped from the folds, and a label vector with one entry per row of that layer loses theirs. Also as in cv_*(), a make_folds() result built on other data (another layer, or these rows in another order) is refused. That check is skipped when the folds were built on polygons and the training data are the points a fit reduced them to.

threshold

Optional numeric override for the DI threshold of the predictor index. The location index, when there is one, always takes its threshold from the rule.

normalizer_max_n

Subsample the training data to this many points when computing the mean pairwise distance, which is quadratic. Default 5000. The subsample is drawn from the training rows in a fixed order (by the predictors, and for the location index by the coordinates), so it does not depend on the row order of the training data.

seed

Seed for that subsample. Default 123.

chunk_size

Query rows per distance block on the dense path. Default NULL (chosen from the training size). Otherwise a single number of at least 1; a fractional value is truncated to a whole number of rows.

use_fnn

Use FNN for nearest-neighbour search when available. Exposed so the dense fallback can be tested. The two paths return the same distances: the dense one searches with a fast formula and then recomputes the nearest distance exactly, so an exact copy of a training row is at distance 0 on both.

coords

Whether location is measured: "auto" (default) measures it for a model whose predictions depend on it (a gwr_fit, a bayesian_fit, a forest fitted with include_coords = TRUE) and not otherwise; "yes" measures it whatever the model, and with no model; "no" never does, and logs a caution for a model that depends on it (for a forest it also leaves "..x" and "..y" out of the predictor index). See Models whose predictions depend on location.

categorical

What to do with factor and character predictors: "refuse" (default) stops with a message naming them and the two alternatives; "indicator" codes each level as a 0/1 column and marks a prediction row on a level no training row has as outside (DI = Inf); "drop" computes the index on the other predictors and logs which were left out. See Limitations for the scaling "indicator" uses.

Value

An object of class aoa: a list with

What the index is for

A fitted model returns a number for any location you hand it, including locations whose predictor values look nothing like anything it was trained on. Those predictions are extrapolations, and a cross-validation score says nothing about them, because the held-out folds were drawn from the same predictor distribution as the training data. The AOA marks where the score applies.

How it is computed

Predictors are centred and scaled using the training data's own means and standard deviations, then weighted by variable importance when the model carries one (see Weights). For a prediction point p, the DI is the distance to its nearest training point in that space, divided by the mean pairwise distance among training points. The same quantity is computed for the training data itself, using each point's nearest neighbour among the training rows of the fold that holds it out. That means everything outside its own fold for random and block folds, and the smaller training set that buffered and NNDM folds leave (see "The fold scheme"); without folds it is the nearest training row with different predictor values. The threshold is then the largest training DI that is not an upper outlier, i.e. not above the fence Q3 + 1.5 * IQR of the training DI, with the quartiles of stats::quantile()'s default type 7. Prediction points at or below that threshold are inside the AOA.

That is the paper's "outlier-removed maximum". CAST, the reference implementation, computes the same fence with the same quartiles but uses the fence itself as the threshold, capped at the largest training DI. The two agree whenever no training DI lies above the fence (n_outliers is 0); otherwise CAST's threshold is the larger, and so is its AOA. (Earlier CAST releases used grDevices::boxplot.stats(), which gives the rule used here but with Tukey's hinges as the quartiles, so they can also differ when the number of training points is even.) To apply the current CAST rule to the same training DI, pass threshold = min(quantile(res$train_DI, 0.75) + 1.5 * IQR(res$train_DI), max(res$train_DI)) for an earlier result res.

The DI is invariant to the overall scale of weights: the numerator and the normaliser carry the same factor. Importance values can be passed as-is.

Training rows with identical predictor values

Repeat visits to a site with static covariates, or covariates read off a raster coarser than the sampling, give training rows that are exact copies of each other in predictor space. A copy is the same point of that space, not a neighbour. Counted as a neighbour it gives a training DI of 0, and once about three quarters of the rows have one the threshold is 0 and only exact copies of a training row count as inside.

With folds = NULL each training row's reference is therefore its nearest row with different values: the search runs on the distinct rows and every row takes its point's distance. n_duplicates counts the rows that repeat an earlier one, and a layer with none is unaffected. The normaliser stays the mean pairwise distance over all the training rows, so a prediction point's DI is the same with and without folds.

With folds supplied the definition is applied as it stands: a held-out row whose copy is on the training side of its fold has a DI of 0, because that hold-out did have an identical row to learn from. If the threshold comes out 0 that way, a warning of class spatialkit_aoa_zero_threshold gives the count, so a script or a cross-validation loop can catch it with tryCatch(..., spatialkit_aoa_zero_threshold = ). Folds that keep the copies together (make_folds(method = "leave_location_out", group_var = ...)) give the threshold its meaning back. The same applies to the location index when training rows share a location.

The fold scheme

With folds = NULL the training reference is each point's nearest neighbour anywhere in the training data, which for clustered data is very close, giving a small threshold and a conservative AOA. Passing the folds you validated with makes the reference distances larger and the AOA wider. The AOA is defined relative to a performance estimate, and a spatially blocked estimate is a claim about predicting further away. Pass the same make_folds() result you passed to cv_spatial. Buffered and NNDM folds use the training set they left available, not everything outside the fold.

Weights

Meyer and Pebesma weight the predictors by the model's variable importance, and with the default weights = "auto" so does this function whenever model carries an importance that means something: pmax(model$info$importance, 0), which a forest from fit_rf_model has. Equal weights are used, with a logged note, when it does not: no model; a model with no importance (importance = "none", a GWR, a Bayesian fit); an importance that is not finite (NaN for a forest with no out-of-bag rows); one that names fewer predictors than are in use; no positive value; or a forest with no out-of-bag skill (oob_r_squared missing or at most 0), whose positive importances are noise. print() says which it was. weights = NULL asks for equal weights whatever the model carries.

Importance weights make the index react to shifts along the predictors the model uses and much less to shifts along those it does not, which leave its error unchanged. The cost is on the weak predictors. A weight multiplies the scaled column, so its square enters the distance, and a weak but real predictor is down-weighted by the square of its relative importance. A shift along such a predictor can then go unseen although it raises the error. weights = sqrt(pmax(importance, 0)) sits between equal weights and importance weights: a weak predictor loses less of its weight.

Limitations

Categorical predictors (factor or character columns) have no distance of their own, and by default they are refused and never silently dummy-coded. categorical = "indicator" codes each level that occurs in the training rows as a 0/1 column. The columns of one predictor share one scale, sqrt(1 - sum(p^2)) with p the levels' shares of the training rows, so two rows on different levels are the same distance apart whichever levels they are, two on the same level are 0 apart, and the predictor adds as much to the mean squared distance between training rows as one standardised numeric predictor. That scaling is a choice, so it is not the default. A prediction row on a level no training row has gets DI = Inf, is outside the AOA, and a warning gives the count. categorical = "drop" leaves the categorical predictors out and computes the index on the others; a level the training data never has then goes unseen.

Predictors whose training values do not vary beyond their rounding are dropped from the distance. A predictor is kept when sd > sqrt(.Machine$double.eps) * max(abs(x)), and otherwise when its standard deviation is more than 3 units in the last place of max(abs(x)). The same variable in metres and in gigametres is treated identically, and a predictor at an offset (a timestamp in seconds) is kept as it is at 0. A prediction point taking a value there outside the training range by more than 3 units in the last place of max(abs(x)) (of 1 for a column of zeros) is extrapolation along a direction the training data never varied in: its scaled distance along it is infinite, so it gets DI = Inf, is outside the AOA, and a warning gives the count. A point missing that value is judged on the other predictors. With equal weights every predictor counts the same, which overstates dissimilarity along directions the model barely uses; see Weights.

Models whose predictions depend on location

For three kinds of model the prediction is a function of where the point is, not only of its covariates, so the index has to measure location too. Without that a prediction point far outside the training extent but with ordinary covariate values reads as inside the area of applicability, which is exactly the extrapolation this index exists to catch. coords = "auto" (the default) measures location for all three; coords = "no" turns it off, with a logged caution; coords = "yes" measures it for any model, or for none.

A GWR (gwr_fit) has coefficients that vary over the map, a Bayesian GP fit (bayesian_fit) has a Gaussian-process term in the coordinates, and a forest fitted with include_coords = TRUE splits on the coordinates. For these, and under coords = "yes", location gets an index of its own, built like the predictor index but in the coordinates: DI_location is the distance to the nearest training point over the mean distance between training points; the training points' own values use the same folds; and the threshold is the same outlier-removed maximum. A prediction point is inside the AOA only if it is inside on both indices, and both DI columns are returned so the cause can be read off. Location is kept apart from the covariates because, as two more equally weighted columns, it would be diluted as covariates are added, and points well beyond the training extent would still read as inside.

Inside the extent the index marks an unsampled gap only where the gap is wider than the distance its threshold allows, and that distance depends on folds. With folds = NULL it is the spacing of the training points (the outlier-removed largest nearest-neighbour distance). With blocked folds it is the largest distance from a held-out point to the nearest row its fold trained on, outliers removed, which grows with the block size; a gap narrower than about twice that distance has no cell beyond it and reads as inside. This follows from the definition: the cross-validated error the index is paired with was earned on hold-outs that far from their training rows. With blocked folds the location index therefore says nothing about a gap narrower than about twice the cut-off; location$threshold * location$normalizer is the cut-off in CRS units, and print() shows it.

A forest splits on the coordinates like on any other column, so for a forest they also stay in the predictor index as "..x" and "..y", centred, scaled and weighted with the rest. Under weights = "auto" that weight is the forest's importance, which is small for a forest that barely splits on its coordinates, so points beyond the extent can read as inside on the predictor index. The location index counts location whatever weight the coordinates get.

Geometry is needed on both sides, so train_sf and newdata must both be sf objects; a data.frame is refused rather than quietly measured without location. Non-POINT newdata (grid polygons, say) is reduced to representative points first, as coerce_to_points would. If exactly one side carries a CRS the other is brought into it: reprojected when its coordinates look like longitude/latitude, stamped otherwise, with a warning either way; a CRS in longitude and latitude is not stamped on coordinates outside longitude -180 to 360 and latitude -90 to 90, which is refused (see spatialkit-geometry). Degrees fed into an index in metres would silently understate the distances. The location index measures distances in the coordinates and refuses training data in a geographic CRS. Both layers are read in x and y for the location: a layer whose geometries mix XY with XYZ or XYM (as rbind() of an XY and an XYZ layer gives), or carry M (XYM or XYZM), is read without its Z and M. Only one change reaches the result: for a forest fitted with include_coords = TRUE, newdata that mixes dimensions and is reprojected into the training CRS comes back in XY, with a warning of class "spatialkit_zm_dropped", as ensure_projected() returns such a layer; the points that non-POINT newdata is reduced to are in XY when they would mix dimensions or carry M.

A row without a location (an empty geometry, or a coordinate that is not finite or lies beyond 1e150) is read as one both as given and after a move into the other layer's CRS, which can bring a coordinate of 1e200 back finite. Such a row of newdata gets NA in DI_location, and for a forest fitted with include_coords = TRUE in "..x" and "..y" and so in DI; such a training row is left out of the reference distances, with a log line. A row of newdata without a location as given that is reprojected into the training CRS comes back in aoa with an empty geometry.

References

Meyer, H. and Pebesma, E. (2021). Predicting into unknown space? Estimating the area of applicability of spatial prediction models. Methods in Ecology and Evolution 12(9), 1620–1633. doi:10.1111/2041-210X.13650

See Also

predict_surface() to build the grid, make_folds() for the fold scheme, and plot.aoa() to draw the dissimilarity distribution.

Other prediction: plot.aoa(), predict_surface(), print.aoa()

Examples

suppressPackageStartupMessages(library(sf))
set.seed(1)
n <- 120
train <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             a = rnorm(n), b = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
train$z <- 2 * train$a - train$b + rnorm(n, 0, 0.3)

# Prediction points, some of them well outside the training predictor range
newpts <- st_as_sf(
  data.frame(x = 5e5 + runif(50, 0, 1000), y = 5e6 + runif(50, 0, 1000),
             a = c(rnorm(40), rnorm(10, 8)), b = rnorm(50)),
  coords = c("x", "y"), crs = 32632
)

res <- area_of_applicability(newpts, train_sf = train,
                             predictor_vars = c("a", "b"))
res
table(res$aoa$AOA)

Assign features to cells and attach a cell ID

Description

Gives every feature the ID of the polygon it falls in and returns the features, one row each, with that ID column added. Features in several polygons are settled by tie_break, and features in none are dropped or kept by keep_unassigned.

Usage

assign_features_to_polygons(
  features_sf,
  polygons_sf,
  polygon_id_col = "poly_id",
  keep_unassigned = FALSE,
  predicate = sf::st_intersects,
  largest = TRUE,
  tie_break = c("smallest_area", "first"),
  quiet = FALSE
)

Arguments

features_sf

An sf object containing features to assign. A layer whose geometries mix dimensions or carry M (XYM or XYZM) is joined in x and y, and the rows returned keep their Z and M (see "Z and M coordinates").

polygons_sf

An sf or sfc polygonal layer. Polygons whose geometries mix dimensions or carry M (XYM or XYZM) are read in x and y.

polygon_id_col

Name of the polygon identifier column: the column of polygons_sf the IDs are read from, and the name they are returned under. Default "poly_id". When polygons_sf has no column of that name, the IDs are read from the first of "poly_id", "polygon_id", "id", "cell_id" and "grid_id" it carries, and a message names the column that was used; when it has none of them, the polygons are numbered ⁠1, 2, ...⁠ in row order, and a message says so. The column the IDs are read from must hold one distinct, non-missing value per polygon: a duplicated or missing ID is an error, because features in different polygons would come back under one ID. That includes a unit stored as several rows that share its ID (a region split into POLYGON parts): merge the parts into one row per ID first, for example with ⁠dplyr::summarise(dplyr::group_by(polygons_sf, <ID column>))⁠, which keeps the unit one cell. Numbering the rows would make each part a cell of its own.

keep_unassigned

Logical; retain features that fall inside no polygon, carrying NA in the ID column. Default FALSE, which drops them with a warning of class "spatialkit_unassigned" that gives their number. Features that tie_break gives no polygon (see there) are kept or dropped with them.

predicate

Binary spatial predicate function. Default sf::st_intersects. Not used when largest applies: sf then assigns polygon features by overlap area and never calls the predicate. With sf::st_intersects a POINT or MULTIPOINT feature with a point within a margin of a polygon is in it: one part in 1e10 of the largest coordinate of the polygons, 0.44 mm at a UTM northing of 4,400 km, at most a millionth of the diagonal of their bounding box and at least four times the spacing of doubles at that coordinate (in longitude and latitude, that many degrees of arc on the sphere while sf::sf_use_s2() is on, and no margin while it is off). A point on the edge two polygons share is then in both in any unit and origin of the coordinates, and tie_break decides it, where the last bits of its coordinates put it inside one polygon or the other.

largest

Logical; when features_sf is itself polygonal, keep the polygon with the largest overlap. Default TRUE. Ignored for point and line features. A feature that only touches the polygon layer (shares an edge or a corner with it, with no overlap area) has no largest overlap and is unassigned, in any CRS; with largest = FALSE the default st_intersects counts touching, so such a feature is assigned. A feature that overlaps two or more polygons by exactly the same area (to 9 significant digits; a square split evenly across a cell edge) is counted in "ties" and given to the one tie_break names, so the choice does not depend on the order of the polygon rows; where "smallest_area" names none, the feature is given no polygon (see tie_break). Invalid geometries (usually a self-intersecting ring), whose overlap is undefined, are repaired with sf::st_make_valid() for the join, with a warning, and returned as they arrived. If the overlap still cannot be computed the function stops: falling back to predicate and tie_break would change the rule for every feature in the layer, so pass largest = FALSE to ask for that. In longitude and latitude with s2 on (sf's default), where s2 refuses a polygon of either layer as it arrived, the join by predicate meets that refusal too, and the error names the polygons and the transform instead (see "Joins in longitude and latitude"). In longitude and latitude the validity check, the repair and the overlaps run on s2 whatever sf::sf_use_s2() says; with s2 off the join by predicate runs with GEOS, and the error that names the polygons also offers largest = FALSE.

tie_break

Strategy for resolving features that match multiple polygons (with largest, that overlap several polygons equally): "smallest_area" (default) keeps the polygon with the smallest area and, among polygons of equal area (a point on the shared edge of two grid cells), the one whose bounding-box centre is lowest, then leftmost, then the one whose vertices' mean is lowest, then leftmost (the two triangles of a split square share a bounding box), so the choice does not depend on the order of the rows. Areas are compared to 9 significant digits, and centres and means within one part in 1e10 of the largest coordinate of the polygons, at most a millionth of the diagonal of their bounding box and at least four times the spacing of doubles at that coordinate (with any predicate, and in longitude and latitude whatever sf::sf_use_s2() says), so the choice does not depend on the unit or the origin of the coordinates either. Where polygons equal on every key are left (one polygon under two IDs, or a square and a rhombus of its area about its centre), the rule names no polygon: the feature is given none, NA in the ID column, counted in "ties" and listed in its unresolved, and a warning of class "spatialkit_ties_unresolved" gives how many such features there are (the condition carries n and total); it is kept or dropped as keep_unassigned says. Areas in longitude and latitude are measured on the sphere with s2, whatever sf::sf_use_s2() says. A polygon among those compared whose geometry is invalid (a ring whose edges cross, whose lobes GEOS measures as cancelling) is measured on a copy repaired with sf::st_make_valid(), with a warning, and returned as it arrived; in degrees, one s2 refuses even repaired (a bowtie) stops the call with the error of class "spatialkit_cells_degenerate" (see "Joins in longitude and latitude"). "first" keeps the polygon that comes first in the rows of polygons_sf, so the result depends on their order. On cells built from the centres a profile scored, a point on the edge between two of them is placed by the profile's rule whichever is given (see "Cells from a resolution profile").

quiet

Logical; suppress this function's message()s (the one naming a fallback ID column). It does not silence R warnings. Default FALSE.

Details

This is the step before summarize_by_cell(), which aggregates over the IDs. Unlike sf::st_join(), it settles a feature that matches several polygons by an explicit tie_break rule instead of duplicating the row, so the assigned layer keeps one row per input feature and each feature is counted in one cell. How the input layers are read in general (CRS, dimensions, rows without a location) is in spatialkit-geometry.

Value

An sf object with polygon_id_col attached, one row per input feature (fewer if keep_unassigned = FALSE dropped unmatched ones, and features tie_break gives no polygon), in the CRS features_sf arrived in. A column of features_sf already called polygon_id_col is dropped before the spatial join (with a warning), so re-assigning an already-assigned layer replaces the old IDs and does not fail. Every other column is kept, including one named like the polygons' own ID column when that is read from a fallback such as "id" (a site id joined to cells keyed by id). If no feature falls inside any polygon the result is empty (or all-NA with keep_unassigned = TRUE) and a warning is raised, since the usual cause is two layers in different places (a CRS that could only be stamped, not reprojected). A layer without a CRS is brought into the other layer's CRS as harmonize_crs() does; beside a layer in longitude and latitude, one with an x outside -180 to 360 or a y beyond 90 north or south cannot be in degrees, and the call stops with an error that names features_sf or polygons_sf and gives its box.

Ties and unassigned features

Features that fall inside no polygon are counted on the attribute "unassigned": a list with n, which (their row positions in features_sf) and n_rows. With keep_unassigned = FALSE they are not in the result, and a warning of class "spatialkit_unassigned" gives their number (tryCatch(spatialkit_unassigned = ) catches it without matching the message; the condition carries n and total). The usual causes are a polygon layer that stops short of the data (a coastline drawn at another scale, a tessellation of seeds built without a boundary or cover; see build_tessellation()) and points outside the study area. A feature with empty geometry, or with a coordinate that is not finite or lies beyond 1e150, or in a geographic CRS a vertex at a latitude beyond 90 degrees (read as given, before any move into the polygons' CRS), has no location to assign: it matches no polygon, and the warning says how many of them there are. With keep_unassigned = TRUE they are kept with an NA ID and no warning is raised, unless every feature is unassigned. A polygon of polygons_sf with a coordinate that is not finite or lies beyond 1e150 (read as given) has no location either: it takes no feature, and the features inside the rest of its ring are unassigned.

The attribute "ties" records how many features matched more than one polygon (with largest, overlapped several by exactly the same area) and had the tie_break rule decide for them: a list with n, which (their row positions in features_sf), rule, n_rows (the number of rows returned, which the record was made for) and, when the rule gave some of them no polygon (see tie_break), unresolved, the row positions of those among which. A large n means the polygon layer overlaps, and per-cell counts built from the result depend on the rule. The record describes the rows this call returned and does not survive subsetting: joined[i, ], like dplyr::filter(), slice() or arrange() of it, is a plain layer with no "ties" attribute, so nothing reports the parent's count for a different set of rows. sf::st_drop_geometry() keeps the record, since the rows are the same; see [.spatialkit_rows for what binding such data frames does. The "unassigned" record is stamped and removed the same way.

Cells from a resolution profile

When polygons_sf carries attr(, "count_rule"), the record of how its cell count was set (cells from build_tessellation() on seeds placed from a select_resolution() result or from a profile built with an estimate), the result carries the same record. summarize_by_cell() reads it and checks that the rows and cells it is given are the ones the count was scored on. It is a plain attribute: a row subset keeps it and dplyr::mutate(), dplyr::select() and dplyr::arrange() drop it, which is why the summary also looks for it on its cells_sf. The profile scores a feature that is not a point at one point of it (coerce_to_points(, "auto")), in the cell of the nearest centre; this function gives a polygon feature to the cell it overlaps most. A feature that straddles a cell boundary can therefore be assigned to another cell than the one it was scored in, and the summary does not compare the two for such a layer. To assign the features as they were scored, assign their points: assign_features_to_polygons(coerce_to_points(features_sf, "auto"), polygons_sf).

When that record says the cells are the ones the profile scored (scored_cells is TRUE: the cells build_tessellation() builds on a selection's seeds, or on the seeds a seeding function returns for one) and holds the centres it scored (count_rule$scored$centres), a point on the edge between two or more of those cells is given the cell resolution_profile() scored it in: that of its nearest centre, measured in the CRS the record names, and of centres the same distance away the lower-numbered one (a distance counts as the same as the least when its square is no more than the square of the least distance lengthened by a margin, plus one part in ten million of the least squared distance; the margin is one part in 1e10 of the largest coordinate of the centres, at most a millionth of the diagonal of their bounding box and at least four times the spacing of doubles at that coordinate). Such points occur on gridded locations (raster cell centres, a regular sampling grid), where a row can lie the same distance from two centres and the polygons hold it in either cell or in both. The rows each cell holds are then the rows its count was scored on, and summarize_by_cell()'s check of them reads "match". A point counts as on the edge when it lies within a margin of both cells: one part in 1e10 of the largest coordinate of the cells, 0.44 mm at a UTM northing of 4,400 km, at most a millionth of the diagonal of their bounding box and at least four times the spacing of doubles at that coordinate. For a point that two centres tie for while the cell holding it is that of the strictly nearer one, the margin also takes in the point's distance from the boundary between the two, measured in the CRS the record names: midway between centres far apart the tie reaches about 1.25e-8 of their distance from the boundary, which can exceed that margin. build_tessellation() draws such cells in the CRS the record names, around the centres as the record holds them, whatever CRS the seeds came back in (unless its crs names another projected CRS), so their corners carry only the rounding of that computation, far less than the margin. Cells it returns in a geographic crs are moved back into the record's CRS for the join (see "Joins in longitude and latitude"). In a UTM zone the round trip through degrees moves a corner by about 2e-9 m; in the equal-area CRS the profile works in for a layer wider than a zone it can move one by more than the margin (how far depends on the PROJ build), so a point on such an edge can keep the polygon that holds it, and the summary's check then reads "differ". A point farther from its nearest centre's cell keeps the polygon that holds it, and so do features that are not points, points without a CRS beside a record with one or with a CRS beside a record without one, and a join in longitude and latitude (polygons in degrees beside a record in degrees). A centre's cell is the one cell that holds it and no other centre; a centre outside a boundary that clipped its cell away from it has the cell, among those that hold no centre, whose inside is nearest it. Cells built from other seeds leave most centres without a cell, and their points to the polygons. Polygons without the record, such as polygons the caller brings, and cells whose record says scored_cells is FALSE or NA (other cells built from the count, such as a lattice sized by it) are placed by the polygons alone.

Joins in longitude and latitude

The join runs in the CRS of polygons_sf whenever that CRS is projected, so cell edges are the straight lines the cells were drawn with and overlap areas are planar. Cells in lon/lat whose record of their count says they are the cells a profile scored, and holds its centres in a projected CRS (the Voronoi cells build_tessellation() builds on the centres a profile scored and returns in a geographic crs; see "Cells from a resolution profile"), were drawn in the record's CRS, and the join runs there. A copy of features_sf is transformed for it, and the features come back with the coordinates they arrived with. Otherwise (other polygons in lon/lat, such as a hex or square lattice sized by a selection or the cells of centres refitted to every point, or polygons without a CRS) the join runs in the CRS of features_sf. In longitude and latitude, with s2 on (sf::sf_use_s2(), sf's default), sf joins on the sphere with s2, which refuses a polygon that is not valid there, such as one with two corners it reads as one point or with edges that cross; cells returned in lon/lat can hold two corners that differ only by rounding and fall on one point in degrees (see "Polygons in degrees" in spatialkit-geometry). A join by predicate then stops with an error of class "spatialkit_cells_degenerate" that gives the rows of the polygons s2 refuses (the condition carries them as rows), names the cause and says to transform polygons_sf to a projected CRS, where the join runs. The largest-overlap join repairs such polygons first (see largest), and stops with that error when s2 still refuses a polygon it repaired, such as one whose hole crosses its outer ring. A polygon of features_sf that s2 refuses stops the join by predicate with an error of class "spatialkit_features_degenerate", with the same fields, that gives its rows, quotes s2's reason and says to transform features_sf to a projected CRS, where the join runs; so does one s2 refuses even after the repair of the largest-overlap join. When that repair makes s2 accept the polygons of both layers and s2 then refuses a piece of an overlap of the two layers (a figure eight, one vertex listed twice, is repaired into two parts that touch at a point, and the piece can hold that point twice), the join stops with the error for the layer whose polygons s2 refused as they arrived; with s2 on (sf's default), the join by predicate meets those polygons too. When s2 refused no polygon of either layer as it arrived, the error says to pass largest = FALSE or to project both layers. Whether s2 refuses such a piece can differ between platforms and s2 versions. Where s2 accepts the piece, the join runs and gives each feature the polygon of its largest overlap. In longitude and latitude the largest-overlap join runs on s2, and the areas tie_break compares are measured on the sphere with s2, whatever sf::sf_use_s2() says, as the package's other areas in degrees are; the join by predicate runs with the engine the session names. With s2 off that engine is GEOS, which reads these polygons in degrees, so the largest-overlap join's error for a polygon s2 refuses also offers largest = FALSE.

Z and M coordinates

sf reads a layer in the dimension of its first geometry, so s2, GEOS and sf::st_transform() read a layer that mixes XY and XYZ (or XYM) geometries wrongly; rbind() of an XY and an XYZ layer gives one. When either layer mixes dimensions, the join runs on a copy of it without Z and M, and the rows come back with the geometry they arrived with, Z and M included. The same holds, with no warning, for a layer whose geometries carry M (XYM or XYZM), which GEOS does not read: the join is defined in x and y. Features without a CRS that mix dimensions and are moved from lon/lat into the polygons' CRS come back moved and in XY, with a warning of class "spatialkit_zm_dropped", unless their only geometries of another dimension than the first are empty and not points. Features without a CRS in one dimension that carry M come back with their own geometry: with the CRS they were given, or moved from lon/lat with sf::st_transform(), which keeps their M.

Coordinates far from the origin

Layers so far from the origin of their coordinates that doubles there are spaced more than a millionth of the extent of the two layers apart (0.125 at 1e15, beside a layer a few kilometres across) are joined with their edges and points held to that spacing, so a point that lies within it of an edge near the origin can fall in the polygon beside it. The join runs, and a warning of class "spatialkit_xy_imprecise" gives the spacing and the extent (the condition carries them as spacing and extent).

See Also

build_tessellation() to build the polygon layer; summarize_by_cell() for the aggregation step that consumes the result.

Other assign and summarise: cell_values_at(), kriging_adequacy(), summarize_by_cell()

Examples

library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(20, 0, 100), y = 5e6 + runif(20, 0, 100),
             val = rnorm(20)),
  coords = c("x", "y"), crs = 32632
)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
  c(5e5, 5e6), c(5e5 + 100, 5e6), c(5e5 + 100, 5e6 + 100),
  c(5e5, 5e6 + 100), c(5e5, 5e6)
))), crs = 32632))
grid <- create_grid_polygons(bnd, target_cells = 9, type = "square")
assigned <- assign_features_to_polygons(pts, grid)
table(assigned$poly_id)

Build Voronoi, triangle, hex or square cells from points

Description

Builds the cells the rest of the pipeline works on. It wraps the four tessellation methods behind one interface that handles CRS projection, clipping and stable cell IDs the same way, and returns the cells together with the point-to-cell index. The return shape does not change with method, so comparing "voronoi" with "hex" takes one argument. create_voronoi_polygons() and create_grid_polygons() are its parts; assign_features_to_polygons() and summarize_by_cell() take its cells next.

Usage

build_tessellation(
  points_sf,
  boundary = NULL,
  method = c("voronoi", "triangles", "hex", "square"),
  approx_n_cells = NULL,
  cellsize = NULL,
  expand = 0,
  clip = TRUE,
  keep_duplicates = FALSE,
  crs = NULL,
  quiet = FALSE,
  cover = NULL
)

Arguments

points_sf

An sf object with POINT/MULTIPOINT geometry. Points that mix XY and XYZ (or XYM), or that carry M, are read in x and y, since sf reads a layer in the dimension of its first geometry and GEOS refuses M.

boundary

Polygonal sf/sfc study area. Required for method = "hex" and method = "square", which have no extent of their own to lay a grid over and stop without it; pass the study-area polygon, or build one from the points with clip_target_for(). Optional for method = "voronoi" and method = "triangles", which derive their extent from the points themselves (for "voronoi", from cover when there is one) and use boundary only to clip the result when clip = TRUE. When points_sf holds seeds and not the observations, pass the study area here or the observations as cover: seeds lie inside the data, and cells clipped to the seeds' own hull leave its edge uncovered. "Coordinate reference systems" says how a boundary in another CRS, or with none, is read. Rows without a location, rows the repair leaves without a polygon, vertices at a latitude beyond 90 and mixed dimensions are handled as "Boundaries" in spatialkit-geometry says.

method

One of "voronoi" (default), "triangles", "hex" or "square"; see "Choosing a method".

approx_n_cells

Approximate number of cells. Read by method = "hex" and "square" only: "voronoi" grows one cell per input point and "triangles" one triangle per neighbouring triple, so neither has a count to set, and both warn that the argument was ignored. For a Voronoi cell count, place the seeds with get_voronoi_seeds() and tessellate those, passing the study area as boundary or the observations as cover (seeds made from a boundary or from sample_points carry their cover with them). For hex grids the target is adjusted for packing density; the count after clipping to an irregular boundary can differ from it. A selection, a profile or the ranked levels of determine_optimal_levels() are read as "Setting the cell count from a profile or selection" says. determine_optimal_levels() returns NA, which this argument refuses, when its WSS curve has no elbow.

cellsize

Numeric cell size, in the units of the working CRS. Read by method = "hex" and "square" only; the other two methods warn that it was ignored. When both cellsize and approx_n_cells are given, cellsize wins and approx_n_cells is ignored with a logged warning; supply one or the other. With a geographic crs it is in that CRS's degrees, and the grid is laid in degrees, as create_grid_polygons() lays it; where s2 refuses a row of boundary or a cell even repaired, the call stops with an error of class "spatialkit_cells_degenerate" that says to pass a projected crs or to size the grid by approx_n_cells. A side of the boundary's bounding box that exceeds a whole number of square cells by no more than a margin of one part in 1e10 of the largest coordinate of the boundary, at most a millionth of the diagonal of its bounding box and at least four times the spacing of doubles at that coordinate, gets that number of cells (see create_grid_polygons()).

expand

Buffer distance, in the working CRS's units, by which the Voronoi boundary is grown before the diagram is built. Applied by method = "voronoi" only; the "hex", "square" and "triangles" methods ignore it (the value you passed is still echoed back in params$expand). With clip = TRUE the cells are clipped to the grown boundary, which is the one returned as boundary: cells reach expand beyond the study area, and a point up to expand outside it is indexed.

clip

Logical; clip the cells to the boundary. Default TRUE.

keep_duplicates

Logical. With FALSE (the default), points are merged before a Voronoi diagram or a Delaunay triangulation is built when they round to one point in coordinates centred on the middle of their bounding box, divided by its diagonal and rounded to 2^-30 of it, so points within about a billionth of the extent of each other count as coincident in any unit or origin. With TRUE only points at exactly one location are merged. Every point is indexed to the cell that holds it.

crs

Optional target CRS: anything sf::st_crs() accepts, including an sf or sfc layer, whose CRS is used. A projected CRS is the working CRS. A geographic one (EPSG:4326, say) is the CRS the result is returned in: the cells are built in the local projected CRS ensure_projected() picks for the points, indexed there, and then transformed with long edges densified, so Voronoi cells are nearest-point cells on the ground and grid cells are laid in metres rather than degrees. The exception is a hex or square grid sized by cellsize, which is in degrees and so is laid in degrees. "Coordinate reference systems" gives the equal-area grid, the CRS of seeds a profile scored, and what s2 refuses in degrees.

quiet

Logical; suppress this function's progress message()s. It does not silence R warnings, nor the package's console log echo (see spatialkit_quiet for that). Default FALSE.

cover

Optional sf or sfc layer the cells have to hold: the observations (points), or a polygon. Read by method = "voronoi" when there is no boundary: the boundary is then derived from the cover (the convex hull of its points, or its polygons, grown by 2 percent of the diagonal) instead of from the hull of points_sf. Pass it when points_sf holds seeds. When NULL, the cover the seeding functions attach to their result is used (attr(points_sf, "cover"): the boundary the seeds were drawn in, or the hull of the points they were clustered from), so build_tessellation(voronoi_seeds_kmeans(obs, k)) holds every observation without it; rbind() of seed layers drops that attribute. Seeds with neither a boundary nor a cover are tessellated over their own hull, with a warning of class "spatialkit_no_cover". A cover with no CRS is read in the coordinates of points_sf; one in another CRS is transformed. With a boundary (and for the other methods) the cover sizes nothing: when it is a point layer, the number of its points that fall outside every cell is returned as params$cover_outside, with a warning of class "spatialkit_unassigned" when it is not 0. A cover, given or attached, that mixes XY and XYZ (or XYM) geometries, or that carries M, is read in x and y. A row of the cover with a coordinate that is not finite or lies beyond 1e150, read as given before any move, is read as an empty row. See create_voronoi_polygons().

Value

A list with components:

cells

An sf polygon layer, one row per cell. It always carries a cell_id column; the "hex" and "square" methods also carry poly_id, which holds the same values and follows the numbering of create_grid_polygons(), not that of create_grid_polygons_cached(). Pass polygon_id_col = "cell_id" to assign_features_to_polygons() and id_col = "cell_id" to summarize_by_cell() and cell_values_at() to keep that name through the pipeline. With the defaults, Voronoi and triangle cells, which carry only cell_id, have their IDs read from cell_id and returned as poly_id.

index

Integer vector of cell_id values, one per row of points_sf, and NA for a point that falls inside no cell, that is, one outside the study area. For seeds it holds the cell each seed generates. "Points on edges and outside every cell" gives the rules for points on an edge, points snapped to a cell, seeds and the warnings.

boundary

The boundary used (possibly derived and/or reprojected, and for "voronoi" grown by expand).

method

The method actually used.

params

The parameters the tessellation was built with, plus snapped, the record of that nearest-cell repair: a list with n, which (row positions in points_sf) and distance (how far outside every cell each sat, in CRS units, and in metres for cells in degrees; a point within the margin of an edge is in that cell and is not listed), which for seeds lists only those whose index entry is the cell they were snapped to; n_outside, the number of points of points_sf that fall in no cell (the NAs of index); and cover_outside, the number of cover points in no cell when a point cover was checked against the cells (NULL otherwise). For "voronoi" also boundary_source, where the boundary came from: "boundary", "cover", "seeds' cover" or "points", and, when points_sf is a layer of seeds that records the kind of partition that placed it (see get_voronoi_seeds()), partition: that record, a list with kind, init, density_power and density_k and, for seeds a seeding function placed itself, iter, iter_max and converged. The cells are the Voronoi cells of the seeds whatever kind placed them. For "hex" and "square" also cells_occupied and cells_empty, the number of cells that hold at least one point and that hold none. count_rule, the record of how the count was set, is present on two paths, and the cells then carry it too as attr(cells, "count_rule"). For "voronoi", when points_sf carries one (attr(points_sf, "count_rule"): the seeds of a select_resolution() result, or seeds get_voronoi_seeds() or voronoi_seeds_kmeans() placed from one): the record as the seeds carry it, whose scored_cells says whether these are the cells the profile scored, and FALSE when the seeds are fewer or more than its count. For "hex" and "square", when approx_n_cells is a selection that carries a record, or a profile built with an estimate, and no cellsize is given: that record with scored_cells FALSE, since a lattice at that count is not the partition the profile scored. assign_features_to_polygons() copies the record to the rows it assigns, and summarize_by_cell() checks its result against it.

Choosing a method

"voronoi" gives one cell per point, so the resolution follows sampling density. Use it when the observations themselves define the cells, or on seeds placed with get_voronoi_seeds() to set the count. "hex" and "square" give equal-area cells on a fixed grid, so you set the cell size and the data do not; hexagons avoid the axis-aligned artefacts of squares and put all six neighbours of a cell at the same distance. "triangles" returns the Delaunay triangulation, for interpolation and adjacency work; it is not meant as an aggregation unit.

"voronoi" and "triangles" are built on the points' vertices: a MULTIPOINT feature with several vertices gets one cell (or triangle corner) per vertex, and its index entry is the smallest cell_id among the cells it touches (see create_voronoi_polygons()). Points on one circle, such as the four corners of each square of a lattice, have more than one Delaunay triangulation. They are triangulated in coordinates centred on the middle of their bounding box, divided by its diagonal and rounded to multiples of 2^-30 of it, so they are split the same way in any unit or origin, except for a point with a coordinate within rounding error of the midpoint between two such multiples.

Setting the cell count from a profile or selection

approx_n_cells accepts, besides a number, what the level-selection step returned: the integer vector of ranked candidates from determine_optimal_levels() (its first element is used; its NA is refused with a note on where it came from), a select_resolution() result (its ⁠$best⁠), or a resolution_profile(). A profile built without an estimate is read with select_resolution() by cp; one built with estimate is read by criterion = "auto", the rule that goes with its estimate: a size for pooled values, the lowest leave-one-out error for plain means. The count used is returned as params$approx_n_cells and where it came from as params$approx_n_cells_from (NULL for a plain number).

A count read off a selection or a profile raises a warning of class "spatialkit_bound_chosen" when its optimum sits on a bound of the ladder and one of class "spatialkit_no_structure" when one cell for the whole layer scores as well (for a count set by a size: when cells of that size predict no better than one mean; the count stands). A profile without an estimate and with no cp to read is an error (class "spatialkit_no_default_criterion" when another criterion is finite). See resolution_profile().

A count read off a profile or selection is a number of k-means cells: every one occupied, and small where the points are dense. A lattice lays that many equal cells over the whole boundary, so on clustered points many of them hold no point; on evenly spread points it matches. params$cells_occupied and params$cells_empty report how the points filled the grid, and a count that came from a profile or selection warns when fewer than three quarters of it are occupied. For cells that follow the points, seed a Voronoi tessellation with ⁠get_voronoi_seeds(method = "kmeans", n = <the selection>, sample_points = <the points>)⁠: given the select_resolution() result or the profile itself, it returns the centres of the partition the profile scored, whose Voronoi cells are the cells the criteria judged (refitted to every point when the profile, without an estimate, was fitted to a subsample). Seeds made that way carry the hull of sample_points as their cover, so the cells built on them hold every point; made with neither sample_points nor a boundary, they carry the hull of the points the profile was computed on.

Coordinate reference systems

When exactly one of points_sf and boundary has a CRS, the other is interpreted in it, with a warning. CRS-less points, and a CRS-less boundary given with projected points, are read as harmonize_crs() does; CRS-less points that do not look like lon/lat cannot take a geographic boundary's CRS and are refused with an error. A CRS-less boundary given with lon/lat points is read as lon/lat when its coordinates fit the lon/lat envelope, and refused with an error otherwise. When neither has one, both are read by the lon/lat test of ensure_projected(): taken as EPSG:4326 and projected when the points look like degrees (a boundary whose coordinates do not fit the lon/lat envelope is then refused with an error), otherwise left in the same unnamed planar space. A boundary without a CRS that crs stamps with a geographic CRS is tested for a latitude beyond 90 as well.

Whenever the local projected CRS of ensure_projected() is picked for lon/lat points, or CRS-less ones taken as lon/lat (no crs, or a geographic one), a hex or square grid with a boundary is laid in it unless it distorts areas across the boundary by more than 1 percent (Web Mercator over a near-global extent, say). The grid is then laid, and the points indexed, in the equal-area CRS ensure_projected(purpose = "area") picks for the boundary, with a logged warning, as create_grid_polygons() does, so the cells stay equal-area.

Seeds that carry the record of how their count was set (attr(, "count_rule")) were scored in the CRS the profile worked in, each row in the cell of its nearest centre. When the record says they are the centres it scored and holds them (the seeds of a select_resolution() result, or those a seeding function returns for one), method = "voronoi" builds their cells in that CRS, with no crs or a geographic one, whatever CRS the seeds arrive in, and returns them there or in the geographic crs; see "Seeds a profile scored" in create_voronoi_polygons(). Voronoi cells built in another projected CRS, named in crs, are the nearest-seed cells of that CRS, so a row near a boundary can fall in the neighbouring cell, and summarize_by_cell() then reports that the cells are not the ones scored. Voronoi cells returned in a geographic crs can hold two corners at one point where four seeds stand the same distance from a corner (gridded locations), which sf's spherical engine (s2) refuses; "Polygons in degrees" in spatialkit-geometry says what still stops on them.

Points on edges and outside every cell

The edge of a cell has a margin of one part in 1e10 of the largest coordinate of the cells, at most a millionth of the diagonal of their bounding box and at least four times the spacing of doubles at that coordinate. A point within that margin of a cell's edge is in that cell, and a point in two or more cells (on a shared edge, or within that margin of it) takes the smallest cell_id among them, so a lattice point on a cell edge takes the same cell in any unit or origin.

A point outside every cell is snapped to the nearest cell only when it is within a thousandth of the median cell width of it, and a point the same distance from two cells, to one part in ten million, takes the smaller cell_id. For cells in degrees the distances of the snap are taken on the sphere, in metres, whatever sf::sf_use_s2() says, and the width is taken as an arc of the sphere, as the margin is. Points outside the study area are left as NA, so a summary built from index counts only the points the tessellation covers. When any point is NA, a warning of class "spatialkit_unassigned" gives the number (tryCatch(spatialkit_unassigned = ) catches it; the condition carries n and total).

For "voronoi" and seeds (a layer a seeding function returned, the seeds of a select_resolution() result, or points given with a cover), index holds the cell each seed generates, whether the seed lies inside the boundary or not: a k-means seed outside a boundary that is not convex has its cell, the part of the study area nearer it than any other seed. Only a seed whose cell the clip removed whole, or one without a location (an empty geometry, or a coordinate that is not finite or lies beyond 1e150), is NA, and the warning then names seeds. See create_voronoi_polygons().

For "voronoi" and "triangles", points so far from the origin of their CRS that doubles there are spaced more than a millionth of their extent apart (0.125 at 1e15, beside a layer a few kilometres across) have the cells' edges and their own cells read at that rounding; the cells are built, and a warning of class "spatialkit_xy_imprecise" gives the spacing and the extent. For "hex" and "square" the grid's warning says the same of the boundary (see create_grid_polygons()).

See Also

Other cell building: clip_target_for(), create_grid_polygons(), create_grid_polygons_cached(), create_voronoi_polygons(), ensure_stable_poly_id(), get_voronoi_seeds(), plot_tessellation_map(), voronoi_seeds_kmeans(), voronoi_seeds_random()

Examples

library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(20, 0, 100), y = 5e6 + runif(20, 0, 100)),
  coords = c("x", "y"), crs = 32632
)
tess <- build_tessellation(pts, method = "voronoi", quiet = TRUE)
tess$cells

Read cell values at new locations

Description

Gives each location of newdata the value of the cell it lies in, read from a summarize_by_cell() result: the pooled value when the summary holds one, the plain mean otherwise, with the interval for one observation when the summary holds it. Beside each value it returns the location's distance from the nearest observation, since a cell's value describes the part of the cell where its observations lie.

Usage

cell_values_at(
  newdata,
  values,
  points,
  response_var,
  id_col = "poly_id",
  seeds = NULL
)

Arguments

newdata

The locations: an sf layer. A feature that is not a point is reduced to one with coerce_to_points(, "auto"); a collection holding a polygon s2 cannot take a centroid of in longitude and latitude (edges that cross), or whose centroid GEOS puts outside it, stops the call with the error of class spatialkit_features_degenerate, raised in this function's name and naming its rows of newdata. No column of it is read. With no CRS while points has one, the call stops. A layer whose geometries mix dimensions or carry M (XYM or XYZM) is read in x and y (step 1).

values

The summarize_by_cell() result for points. It must hold the ID column and a cell value of response_var: the pooled value (estimate = "pooled") or the mean (the default agg_funs). With seeds = NULL it must also carry the cell polygons, which it does when it was made with cells_sf. A values with no row, or whose IDs are all NA, stops the call, with or without seeds. Its polygons are read in x and y when they mix dimensions or carry M (XYM or XYZM).

points

The assigned layer values was computed from: an sf layer with the ID column and response_var, and at least one scored row.

response_var

Name of the summarised column wanted: the response, or a predictor.

id_col

Name of the ID column, found as summarize_by_cell() finds it: when points has no column of that name, the first of "poly_id", "polygon_id" and "cell_id" it has. It cannot have the name of another column of the result (value, estimate, obs_lo, obs_hi, filled, filled_from, dist_nearest, dist_ratio).

seeds

NULL, or the seeds the cells were built on: an sf POINT layer with a column named as the ID column that gives each seed's cell. For cells from tess <- build_tessellation(seeds) that is seeds$cell_id <- tess$index when the ID column is "cell_id". For seeds a seeding function returned and the seeds of a select_resolution() result, index gives each seed the cell it generates. Other points are indexed by the cell that holds them, and one outside the boundary is NA, or the ID of the nearest cell, which can be the cell of another seed, when it lies within a thousandth of the median cell width of it; with the cell polygons in values a seed that is NA is given its cell when step 3 can tell which it is (it is not when the points inside several cells no seed names find it as their nearest seed), and without them the locations nearest it have none. Passed through get_voronoi_seeds(method = "provided", seeds = ) before the tessellation, points placed by hand are seeds (see create_voronoi_polygons()). Two seeds at different locations with one ID are an error; seeds that share a location share its cell, as index gives them. NA marks a seed without a cell. When no seed with a location has the ID of a cell of values (an ID column from another tessellation, IDs that are all NA, or the IDs of cells on seeds with an empty point or a coordinate that is not finite or lies beyond 1e150, as given or once placed in the working CRS, such as metres given EPSG:4326), counting the cells step 3 gives seeds outside the polygons, the call stops, since no location could take its own cell's value; one seed with such an ID and a location is enough, and a seed whose ID values has no row for stands for a cell without a value. Without a CRS beside points with one, the seeds are read as step 1 says.

Details

The function works in six steps.

  1. The working CRS. The CRS the summary measured in: the one in attr(values, "count_rule") when that record names a projected CRS, else the one in attr(values, "pooled"), else the CRS of points when it is projected and the one ensure_projected() picks for it when it is not. points, newdata and seeds are transformed to it. newdata, seeds and points are read in x and y: a layer whose points, or the points taken from its other features, do not all have the same dimensions (some with a Z or M coordinate) is read without its Z and M, since sf reads a layer in the dimension of its first point. So is a layer of points, polygons or lines in newdata or points whose geometries carry M (XYM or XYZM), which GEOS does not read. So are the polygons of values when they do not all have the same dimensions. Polygons of values whose geometries carry M are read in x and y as well. When neither points nor newdata has a CRS the coordinates are used as they are, unless those of points look like longitude and latitude: both are then read as EPSG:4326, as summarize_by_cell() reads points, with ensure_projected()'s warning; newdata or seeds with an x outside -180 to 360 or a y beyond 90 north or south cannot be in degrees, and stop the call. seeds without a CRS beside points with one are read as build_tessellation() reads a boundary without a CRS, with a warning: beside a projected CRS, coordinates that look like longitude and latitude are taken as EPSG:4326 and transformed, and others are taken to be in the CRS of points; beside a geographic CRS, coordinates within the ranges of longitude and latitude are taken to be in it, and others stop the call. newdata without a CRS beside points with one stops the call.

  2. The scored rows. The rows of points with a finite response_var, a cell ID and a location: a point whose coordinates are finite and within 1e150, as given and in the working CRS. Their distinct locations are the observations every distance below is taken from.

  3. The cell of a location. With seeds, the cell of the nearest seed. That is the Voronoi cell before its clip to the cover, so every location has one, unless its nearest seed has an NA ID: a location nearest such a seed has no cell. build_tessellation() gives each seed of a layer it takes for seeds (see create_voronoi_polygons()) the cell it generates, a seed outside a boundary that is not convex (a k-means centre over a bay) included, and NA only to a seed whose cell the clip removed whole. Other points, such as points placed by hand, are indexed by the cell that holds them, so one outside a boundary that is not convex is NA although its cell is built. One that lies in no cell but within a thousandth of the median cell width of a cell takes the ID of the nearest cell instead, which beside a boundary that is not convex can be the cell of another seed; two seeds with one ID stop the call (see seeds). When values carries the cell polygons, a seed that is NA is given its cell here: a seed with an NA ID that lies in no polygon of values takes the ID of the polygon, among those no seed names, that a point inside it finds as its nearest seed. That is the cell the seed generates, since every point of a Voronoi cell is nearer its own seed than any other. A seed that the points inside several such polygons find as their nearest seed generates at most one of them (the seeds of the others are missing from seeds or have no location), and nothing says which: it keeps its NA ID, with a warning, so the locations nearest it have no cell and are filled (step 5). A seed with an NA ID inside a polygon keeps it, and so does one whose cell values does not hold. Without seeds, the polygon of values that holds the location, by assign_features_to_polygons() with its default tie_break and the summary's record of the count, so a location on the edge between two cells the profile scored is placed as that function places such a row (see "Ties"); a location in no polygon has no cell. Polygons without a CRS are read as that function read them for the rows of points: the locations are handed to it in the CRS of points, whatever CRS newdata arrived in. Where that join runs on the sphere and s2 refuses a polygon of values (see "Joins in longitude and latitude" in assign_features_to_polygons()), the call stops with an error of class "spatialkit_cells_degenerate" that gives the rows of values s2 refuses (rows on the condition), names the cause and says to transform values to a projected CRS.

  4. The value. The cell's pooled value of response_var, ⁠..pooled_<prefix><response_var>⁠ with the prefix resp_ or pred_, when values has that column; otherwise its mean, ⁠<prefix>mean_<response_var>⁠. The column estimate says which. For a column summarised as response and as predictor the response's columns are read. The interval is the cell's ⁠..obs_lo_<prefix><response_var>⁠ and ⁠..obs_hi_<prefix><response_var>⁠ when values has them.

  5. The fill. A location with no cell, or whose cell holds no scored row and has no value in values, takes the value and interval of the cell of its nearest scored row. filled is then TRUE and filled_from is that cell's ID. The ID column still holds the location's own cell, as step 3 finds it, so the two columns together say where a location lies and where its value came from. A cell that holds a scored row is not filled. Where values has no value for such a cell (the summary could not compute the pooled columns, or has no row for the cell), its locations have value = NA and filled = FALSE; a filled value is NA in the same case, when the cell it is taken from has none.

  6. The distance. dist_nearest is the distance from the location to the nearest location of a scored row, in the units of the working CRS. dist_ratio is that distance over the layer's spacing: the median, over the distinct locations of the scored rows, of the distance to the nearest other one.

Cell IDs are matched as text. The ID column of values is character when the summary joined a cells_sf whose IDs were of another class than the assigned layer's, while points and seeds keep the class they had; the IDs of all three are written out as text before any match, and both ID columns returned have the class of the ID column of values wherever that class can hold every ID (see Value).

Value

A data frame with one row per row of newdata, in its order:

the ID column

The cell the location lies in, under the name of the ID column; NA for a location in no cell.

value

The cell's value, or for a filled row the value of the cell in filled_from.

estimate

"pooled" or "mean": which value of the summary value is.

obs_lo, obs_hi

The interval for one observation, when values holds it.

filled

TRUE when the location has no cell, or its cell neither a scored row nor a value, and the value is that of the cell of the nearest scored row.

filled_from

For a filled row, the ID of the cell the value came from; NA otherwise.

dist_nearest

Distance to the nearest location of a scored row, in the units of the working CRS.

dist_ratio

dist_nearest over the spacing; NA when the scored rows sit on one location.

A row of newdata with an empty geometry, or with a coordinate that is not finite or lies beyond 1e150 as given or in the working CRS, has NA in every column. The two ID columns have the class of the ID column of values; when a cell that values has no row for has an ID that class cannot hold (a string beside numbers), both are character.

What produced the frame is in attr(, "values_at"), a list of class "spatialkit_values_at" with a print method: assignment ("seeds" or "polygons"), crs (the working CRS), column (response_var), estimate, obs_level (the level of the interval columns; NULL without them, and NA when values holds them and no longer says at what level), n (the scored rows), locations (their distinct locations), spacing (what dist_ratio divides by; NA with one location), filled (how many rows of newdata were filled) and count_rule (the summary's record of how the cell count was set, or NULL). It describes the call: a subset of the frame's rows keeps it as it is.

The function raises no classed warning of its own; the warning that says how seeds without a CRS were read (step 1) and the one that counts the seeds outside the polygons of values left without a cell (step 3) are plain ones. It passes on the conditions that coerce_to_points(), a CRS transformation and assign_features_to_polygons() raise, with two exceptions. The error of class spatialkit_features_degenerate with which coerce_to_points() refuses a polygon s2 cannot take a centroid of, or a centroid GEOS puts outside its feature, is raised in this function's name, with the same class and fields, naming newdata or points and its rows. The warning assign_features_to_polygons() raises when no location at all falls in a polygon is neither raised nor logged, since every such row has filled = TRUE, which says the same row by row.

Ties

A distance to a seed, a centre or a scored location counts as the same as the least when its square is no more than the square of the least distance lengthened by a margin, plus one part in ten million of the least squared distance. The margin is one part in 1e10 of the largest coordinate of the seeds, centres or scored locations searched, at most a millionth of the diagonal of their bounding box and at least four times the spacing of doubles at that coordinate. A location the same distance from two seeds takes the one that comes first in seeds. For the seeds of a select_resolution() result that is the lower-numbered centre, the rule resolution_profile() scores with. When the summary's record of the count holds the centres the profile scored and seeds are those centres (the seeds a selection carries, or those a seeding function returns for it), in any order and any CRS, the distances are taken to the centres as the record holds them, a tie goes to the lower-numbered centre, and each centre gives the ID of the seed that stands at it. Seeds count as the centres when they are as many and each lies at a different centre, within a thousandth of its distance from the next nearest one, so a seed that came back from another CRS with its coordinates rounded, or seeds sorted by their cell, do not settle a tie another way. A location on the edge between two such cells then takes the cell assign_features_to_polygons() gives a row there, with seeds and without. Other seeds, among them a subset of the centres, are searched as given. A location the same distance from two locations of scored rows takes the one in the lower column (x values within one part in ten million of the diagonal of the scored locations' bounding box, or within one part in 1e10 of their largest coordinate (at most a millionth of that diagonal, and at least four times the spacing of doubles at that coordinate) where that is more, counting as one), then the one lower in y, y values read the same way; among scored rows at one location that lie in different cells, the cell that comes first in the order of the IDs (ascending for numbers, the C-locale order for strings, the order of the levels for a factor), and the same among locations in one column and one row (two records of one station that differ only in the last bits of their coordinates, which are the same distance from any location, however near, while they lie within the margin of each other). Neither rule depends on the order of the rows of points, or on whether the FNN package is installed. A tie is a tie between distances computed from the coordinates in the working CRS, so on gridded locations the same layer in another projected CRS can put a location on a boundary in the other cell; another unit or origin of the same CRS moves only the last bits of the distances and settles the ties the same way, with one exception. The margin grows with the largest coordinate (about 0.46 mm at a UTM northing near 4,550 km, about half a micrometre once the origin lies next to data 5 km across), so a location whose distances to two of them differ by less than the margin with one origin and by more with another is a tie with the first, settled as above, and takes the nearer with the second.

Away from the observations

The value and the interval describe locations among the observations. The interval's two ends are quantiles of leave-one-out errors, each the error of predicting an observation from the others around it, so it says nothing of a location far from every observation: a gap in the layer, or ground beyond its edge. Away from the observations no interval here is calibrated. dist_nearest and dist_ratio say how far each location is from the data. No threshold is applied to either and no location is flagged or left out. area_of_applicability() and fold_separation() are the tools for deciding where a prediction applies.

The interval's coverage falls as dist_ratio grows; "How this was checked" gives the figures.

Without the FNN package

The function makes three nearest-neighbour searches: each location's nearest scored location, each location's nearest seed (and that of a point inside each cell no seed names, when a seed with an NA ID lies outside every cell; see step 3), and each scored location's nearest other one (for the spacing). With FNN each uses a kd-tree. Without it each compares every pair, and a search that would compare more than getOption("spatialkit.exact_pairs_max", 2e9) pairs stops the call first, with an error of class spatialkit_work_limit that names the search (the fields work, limit and what). The search for the spacing does not depend on the number of locations asked for: above about 44,700 distinct scored locations the call stops without FNN however few they are. The result is the same with and without the package.

How this was checked

A simulation shows how the interval's coverage falls with dist_ratio (dev/sim-pooled-values.R in the package's GitHub repository; "How this was checked" in summarize_by_cell() describes it). Each of 200 layers has 1,500 clustered observations in 333 cells, 300 further observations held out at random among them and 300 held out as a block, which leaves a gap in the layer. Over the held-out observations of all layers, the interval at obs_level = 0.90 held 91.5 percent of those with a dist_ratio below 1, 89.2 percent from 1 to 2, 83.9 percent from 2 to 4, 77.9 percent from 4 to 8 and 69.5 percent above 8. It held 89.6 percent of the observations held out at random and 75.1 percent of those in the block.

See Also

summarize_by_cell(), which computes values; build_tessellation(), whose index gives each seed's cell; area_of_applicability() and fold_separation() for where a prediction applies.

Other assign and summarise: assign_features_to_polygons(), kriging_adequacy(), summarize_by_cell()

Examples

library(sf)
set.seed(1)
n <- 400
east  <- runif(n, 0, 1e4)
north <- runif(n, 0, 1e4)
all_pts <- st_as_sf(
  data.frame(x = 5e5 + east, y = 5e6 + north,
             income = 30 + 5 * sin(east / 2000) + 5 * cos(north / 1500) +
               rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
pts    <- all_pts[1:350, ]
newpts <- all_pts[351:400, ]

# The count from a size, the cells, the observations in them, the values,
# all at the defaults: pooled values at 4.5 observations per cell.
prof  <- resolution_profile(pts, "income")
sel   <- select_resolution(prof)
seeds <- get_voronoi_seeds(method = "kmeans", n = sel, sample_points = pts)
tess  <- build_tessellation(seeds, method = "voronoi", quiet = TRUE)
asg   <- assign_features_to_polygons(pts, tess$cells, polygon_id_col = "cell_id")
out   <- summarize_by_cell(asg, "income", id_col = "cell_id",
                           cells_sf = tess$cells, obs_level = 0.90)

# The value at other locations, each placed in the cell of its nearest
# seed.  `tess$index` gives the cell of each seed.
seeds$cell_id <- tess$index
at <- cell_values_at(newpts, out, asg, "income", id_col = "cell_id",
                     seeds = seeds)
head(at)
attr(at, "values_at")

# Without the seeds a location is placed in the polygon that holds it.  One
# beyond the layer's edge lies in no polygon: it is filled from the cell of
# the nearest observation, and `dist_ratio` says how far that is.
beyond <- st_sf(geometry = st_sfc(st_point(c(5e5 + 2e4, 5e6 + 5e3)), crs = 32632))
cell_values_at(rbind(st_sf(geometry = st_geometry(newpts[1:2, ])), beyond),
               out, asg, "income", id_col = "cell_id")

Clear the cached fitted values of a Bayesian GP fit

Description

Removes the cached fitted() values of a bayesian_fit, so the next call recomputes them from the posterior. You need it only after editing the brmsfit engine in place. A change to data_sf, or a refit, invalidates the entry on its own (see "The Bayesian GP cache" in spatial_fit-fitted). On any other fit it does nothing.

Usage

clear_fitted_cache(object)

Arguments

object

A bayesian_fit object.

Details

Every copy of a fit shares the cache, so clearing it through one copy clears it for all of them; the others recompute.

Value

object, invisibly.

See Also

Other options and caches: clear_grid_cache(), spatialkit-conditions, spatialkit-options, spatialkit_quiet()

Examples

## Not run: 
# Needs brms and a Stan toolchain, and takes minutes.
library(sf)
set.seed(1)
n <- 60
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             elev = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
dat$price <- 10 + 2 * dat$elev + rnorm(n)
fit <- fit_bayesian_spatial_model(dat, "price", "elev", chains = 2,
                                  iter = 1000, compute_loo = FALSE)
f1 <- fitted(fit)          # computed from the posterior and cached
clear_fitted_cache(fit)
f2 <- fitted(fit)          # computed again
all.equal(f1, f2)

## End(Not run)

Clear the in-session grid cache

Description

Empties the cache that create_grid_polygons_cached() fills, and returns the number of grids removed.

Usage

clear_grid_cache(cache_env = .gmt_cache)

Arguments

cache_env

The cache to clear. The default is the package's own; pass an environment only if you passed the same one to create_grid_polygons_cached(cache_env = ).

Value

Invisibly, the number of entries removed.

See Also

create_grid_polygons_cached(), which fills the cache.

Other options and caches: clear_fitted_cache(), spatialkit-conditions, spatialkit-options, spatialkit_quiet()

Examples

library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
  c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
invisible(clear_grid_cache())   # start from an empty cache
g1 <- create_grid_polygons_cached(bnd, target_cells = 9)
g2 <- create_grid_polygons_cached(bnd, target_cells = 9)   # cache hit
print(clear_grid_cache())   # 1: the grid cached above
print(clear_grid_cache())   # 0: already empty

Build the area to tessellate within, from points or a boundary

Description

Builds the area that the hex and square cells of build_tessellation() are clipped to. With a boundary it is that boundary, row for row; without one it is the axis-aligned bounding box of points_sf in the working CRS. Either can be buffered by expand.

Usage

clip_target_for(points_sf, boundary = NULL, expand = 0, quiet = FALSE)

Arguments

points_sf

An sf object with POINT/MULTIPOINT geometry. Points that mix XY and XYZ (or XYM), or that carry M, are read in x and y, since sf reads a layer in the dimension of its first geometry and GEOS refuses M. A point that is empty, or has a coordinate that is not finite or lies beyond 1e150, has no location and takes no part in the bounding box. With no boundary, points none of which has a location (as given, or after the move of lon/lat points into a projected CRS) are refused with an error that says so. Points that take the buffer, so far from the origin of their CRS that doubles there are spaced more than a millionth of the target's size apart (0.125 at 1e15, beside a disk of radius 1), give a buffer drawn at that rounding, with a warning of class "spatialkit_xy_imprecise" that gives the spacing and the radius. Where the buffer comes back empty or with no area, as a radius below that spacing can make it, the call stops with an error of class "spatialkit_xy_imprecise_error". Shift such points nearer the origin, or pass boundary.

boundary

Optional polygonal sf object. One with no CRS, given with points that have one, is interpreted in the points' own CRS, with a warning. With points in a projected CRS it is read as harmonize_crs() does: coordinates that look like lon/lat are taken as EPSG:4326 and reprojected, anything else is stamped with the points' CRS. With lon/lat points it is read as lon/lat when its coordinates fit the lon/lat envelope, and refused with an error otherwise. Rows without a location, rows the repair leaves without a polygon, vertices at a latitude beyond 90 and mixed dimensions are handled as "Boundaries" in spatialkit-geometry says.

expand

A single non-negative number. Below 1 it is a fraction of the longer side of the bounding box (of boundary when one is given, otherwise of points_sf); 1 or more is a distance in the units of the CRS the target is built in. Default 0 (no buffer). Lon/lat input is first projected to a local projected CRS (see Value), so both forms are in that CRS's units.

quiet

Logical; suppress this function's progress message()s. It does not silence R warnings, nor the package's console log echo (see spatialkit_quiet for that). Default FALSE.

Details

Use it to build the boundary that method = "hex" and "square" require, to check that a study-area polygon contains the observations before tessellating, or to pass the same envelope to create_voronoi_polygons() and create_grid_polygons() so that two tessellations of one dataset cover the same ground.

It is not the target build_tessellation() derives on its own: method = "voronoi" without a boundary clips to the convex hull of the points (or of their cover, for seeds) buffered by 2 percent of its diagonal, and there expand is always a distance. A bounding box over a non-rectangular point cloud includes corners with no data, so a hex or square grid laid over it has cells that hold no points; pass the study-area polygon when there is one.

Value

An sf polygon layer representing the clip target. For lon/lat input the layer is returned in the automatically selected local projected CRS, not the input CRS; a message reports this unless quiet = TRUE.

Points with no extent

Points that all share one x or one y, or nearly so (the short side of their bounding box below a millionth of the long side, or below about 1.5e-154, a length whose square doubles cannot hold), get a small buffer around them instead of a box. When every point sits at one location, or the share of their spread the buffer would take (5 percent, or a fractional expand) is below that length, the box has no extent to take a share of, and the target is a disk of radius 1 unit of the CRS around it (1 m in a metre CRS, 1 km in a kilometre CRS), unless expand is 1 or more, which is then the radius; the message says so. Pass boundary for a target of real size.

See Also

Other cell building: build_tessellation(), create_grid_polygons(), create_grid_polygons_cached(), create_voronoi_polygons(), ensure_stable_poly_id(), get_voronoi_seeds(), plot_tessellation_map(), voronoi_seeds_kmeans(), voronoi_seeds_random()

Examples

library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(30, 0, 100), y = 5e6 + runif(30, 0, 100)),
  coords = c("x", "y"), crs = 32632
)
# No boundary: the bounding box, expanded by 10% of the extent
box <- clip_target_for(pts, expand = 0.1, quiet = TRUE)
st_area(box)

Reduce each geometry to one representative point

Description

Replaces the geometry of each row of an sf object with a point, by the rule mode names. The result has one row per row of x, in the same order.

Usage

coerce_to_points(
  x,
  mode = c("auto", "centroid", "point_on_surface", "surface", "line_midpoint",
    "bbox_center"),
  tmp_project = TRUE
)

Arguments

x

An sf object.

mode

How each geometry becomes a point: "auto" (default), "centroid", "point_on_surface", "surface" (an alias for "point_on_surface"), "line_midpoint" or "bbox_center". See "Modes".

tmp_project

Logical; take line midpoints in a temporary projection. Default TRUE. With FALSE, lines in longitude and latitude get their centroid. When x has no CRS and the lon/lat test of ensure_projected() takes its coordinates for degrees, the temporary projection reads them as EPSG:4326 (with a warning), and the midpoints returned are geodesic ones brought back to the input's numbers, not planar midpoints. Set the CRS, or pass tmp_project = FALSE, for planar data.

Value

An sf object with its geometry reduced to POINTs, row for row with x; an empty input geometry gives an empty POINT.

Modes

"auto" (default)

POINT rows are kept. POLYGON and MULTIPOLYGON rows get a point on the surface. A LINESTRING gets its midpoint, and a MULTILINESTRING the midpoint of its longest part (see "Lines"). MULTIPOINT rows and rows of other types, such as geometry collections, get their centroid.

"centroid"

The centroid of every row.

"point_on_surface" (alias "surface")

A point that lies on each geometry, taken with GEOS.

"line_midpoint"

The midpoint of each LINESTRING, taken in a temporary projection (with tmp_project = FALSE on lon/lat data, its centroid). Rows of other types (points, polygons and their MULTI forms) get their centroid. A MULTILINESTRING or GEOMETRYCOLLECTION row is an error: cast it to LINESTRING first, or use "auto", which takes the midpoint of a MULTILINESTRING's longest part.

"bbox_center"

The centre of each row's bounding box.

Empty geometries and rows without a location

An empty geometry of any type, lines included, becomes an empty POINT in its own row; prep_model_data() and make_folds() then drop such rows, as they drop any other empty geometry. An empty part inside a non-empty feature is ignored, so the feature gets the point its other parts give.

A geometry with no location (see spatialkit-geometry, "Rows without a location") gets an empty POINT in every mode, as an empty geometry does. So does a geometry of a layer in a geographic CRS with a vertex at a latitude beyond 90 degrees, and a warning of class spatialkit_lat_beyond_90 gives its rows of x (rows).

Lines

Modes "auto" and "line_midpoint" take the midpoint of a line in a temporary projection (tmp_project), the one ensure_projected() chooses for the lines. A line that projection returns empty or without some of its vertices is not sampled: the call stops with an error of class spatialkit_features_degenerate (see "Errors").

In mode "auto" a MULTILINESTRING gets the midpoint of its longest part. When several parts share the greatest length (to one part in ten million, measured in the projection used), their midpoints are taken and the one lowest in x, then in y, is kept, so the point does not depend on the order in which the feature lists its parts. x values within one part in ten million of the diagonal of the midpoints' bounding box count as one, so y decides between midpoints whose x differ only in their last bits, and the point does not move with the origin of the coordinates.

Longitude and latitude

Modes "auto" (for polygons) and "point_on_surface" take the point with GEOS, which reads a layer in longitude and latitude on the plane in degrees, under either sf::sf_use_s2() setting. sf's warning that such a point "may not give correct results for longitude/latitude data" is not passed on. A polygon that spans more than 180 degrees of longitude (one written across longitude 180, from 179.5 to -179.5) GEOS reads the long way round the globe, so its point is tested on the polygon read on the sphere with s2; when it does not lie on it, the point is taken again with the longitudes below 0 read from 180 to 360, and brought back into -180 to 180. A polygon whose point lies on it neither way, or that s2 cannot read, keeps GEOS's point, and a warning of class spatialkit_surface_point_off gives its rows of x (rows). When x has no CRS and the lon/lat test of ensure_projected() takes its coordinates for degrees, its polygons that span more than 180 units are read so too, as EPSG:4326, and a warning names the rows whose point that reading moves; the points keep the missing CRS.

Mode "bbox_center", and the centroids that GEOS takes on the plane in degrees (a lon/lat layer with s2 off) under "centroid", for the rows other than LINESTRINGs under "line_midpoint", and for MULTIPOINTs and collections under "auto", read a geometry written across longitude 180 the same way: one that spans more than 180 degrees of longitude as written, and no more than 180 with the longitudes below 0 read from 180 to 360, gets the centre of that box, or GEOS's centroid of the geometry so read, brought back into -180 to 180. A layer without a CRS that the lon/lat test takes for degrees is read so too, with the same warning. A geometry wider than 180 degrees in both readings, such as one around a pole, keeps the centre of its box on the plane, or GEOS's planar centroid. The centroids s2 takes on the sphere are not changed.

With s2 on, sf takes the centroids of a lon/lat layer with s2 (under "centroid", for the rows other than LINESTRINGs under "line_midpoint", and for collections under "auto"), and s2 refuses some polygons GEOS accepts. A polygon s2 refuses because a vertex repeats the one before it, on its own or inside a collection, gets the centroid of the same ring without the repeat; the ring's points are unchanged. A polygon s2 refuses for another reason (edges that cross, a figure eight) is an error (see "Errors"). With s2 off, the centroids are GEOS's, planar in degrees.

Z and M coordinates

A layer whose geometries do not all have the same dimensions (XY beside XYZ or XYM, as rbind() of an XY and an XYZ layer gives) is read in x and y, and its points come back in XY with a warning of class spatialkit_zm_dropped whose rows are the rows that carried Z or M (see spatialkit-geometry, "Mixed dimensions, Z and M"). A layer in one dimension, XY or XYZ throughout, is read as it is, and so is a layer whose only geometries of another dimension than the first are empty and not points.

GEOS does not read M coordinates. When the mode reduces a geometry that carries M (XYM or XYZM) to a point (any such geometry under "centroid", "point_on_surface" and "line_midpoint", any that is not a POINT under "auto"), the layer is reduced in x and y: Z and M are dropped from every geometry, the points come back in XY, and a warning of class spatialkit_zm_dropped says so, with the rows whose geometry carries M as its rows. Empty geometries are not counted. A POINT layer that carries M is returned as it is under "auto". Mode "bbox_center" reads the box of each geometry and gives XY points for any layer, with no warning about Z or M.

Errors

Each of these is an error of class spatialkit_features_degenerate that gives the rows of x (rows on the condition):

A polygon s2 refuses

In longitude and latitude with s2 on, a polygon whose centroid s2 cannot take even without its repeated vertices. The message quotes s2 and says to transform x to a projected CRS or to use another mode.

A centroid outside its feature

GEOS, which takes the centroids in a projected CRS, without a CRS, and in degrees with s2 off, weights each part of a ring by its signed area. Where the edges of a ring cross (a bowtie), or a hole lies outside its shell, parts of the feature count with opposite signs, and the point can lie far outside the feature. A centroid outside the bounding box of a feature GEOS reports invalid is refused: the condition carries site = "geos_centroid" and GEOS's reason for each row (reasons), and the message says to pass mode = "point_on_surface" or to repair the features with sf::st_make_valid(). A centroid inside the box is returned as GEOS gives it.

A line the temporary projection cannot place

A line that the projection returns empty or without some of its vertices. The condition carries site = "projection", and the message says to pass mode = "centroid" or tmp_project = FALSE, which take the point in longitude and latitude, without the projection.

The functions that reduce a layer they are given to points this way (prep_model_data(), make_folds(), fold_separation(), estimate_sac_range(), resolution_profile(), determine_optimal_levels(), cell_values_at(), summarize_by_cell(), select_features_forward(), compare_models_cv(), area_of_applicability(), predict_surface()) raise each of these errors in their own name, with the same class and fields, naming their argument and its rows. spatialkit-conditions lists every class.

See Also

spatialkit-geometry for how input geometry and CRSs are read.

Other data preparation: [.spatialkit_rows(), ensure_projected(), harmonize_crs(), prep_model_data(), spatialkit-geometry

Examples

library(sf)
poly <- st_sf(
  id = 1,
  geometry = st_sfc(st_polygon(list(rbind(
    c(0, 0), c(2, 0), c(2, 2), c(0, 2), c(0, 0)
  ))), crs = 32632)
)
coerce_to_points(poly, "auto")  # a point on the polygon's surface

Compare fitted models in sample

Description

The table from evaluate_insample(), plus AICc (GWR), LOOIC (Bayesian GP), convergence and GP-adequacy flags and the residual Moran's I of each fit. No model is refitted. For scores on held-out blocks use compare_models_cv().

Usage

compare_models(fits, newdata = NULL, ...)

Arguments

fits

A spatial_fit, or a named list of them. The names label the rows and must be unique (see evaluate_insample()); a single fit is labelled by its class.

newdata

Optional sf object of held-out rows, carrying the response and the predictors.

...

Passed to predict() when newdata is given. Without newdata nothing reads them, so any argument here is an error, which catches a misspelt newdata.

Details

The metrics are those of model_metrics(): see its sections "What the metrics are computed on" and "Percentage errors on responses with zeros".

Value

A data.frame with one row per model and these columns:

model and the metric columns

As in evaluate_insample().

metric_basis

What each row's metrics were computed on (see evaluate_insample). A table that mixes "out-of-bag" and "in-sample" rows does not rank the models, and says so in the log.

AICc (GWR) and LOOIC (Bayesian)

Sums over the rows a model was fitted to, so each column is set to NA, with a warning, when the fits carrying it were fitted to different rows (a predictor with missing values drops rows, for example) or to different responses (a transformed response on the same rows), and the warning says which.

convergence_ok

TRUE or FALSE for a Bayesian fit whose convergence was checked (see fit_bayesian_spatial_model) and NA otherwise. A fit that did not converge is ranked like the others, so it also raises a warning.

gp_adequacy

What the posterior of a Bayesian fit said about its Gaussian-process basis ("ok", "below_resolution", "unresolved_short_range", "no_signal_above_floor" or "not_checked"; see "What the basis resolves" in fit_bayesian_spatial_model) and NA for the other backends. A basis found too coarse scores like one that was adequate, so read the column beside the metrics.

resid_morans_I, resid_morans_z, resid_morans_p

Moran's I of the residuals, from residual_morans_i().

resid_morans_null

The null each model was scored against, since that choice is per fit and governs how much the p-value is worth.

resid_morans_basis

Which residuals the statistic was computed on: always those of the rows the model was fitted to, also when newdata is given, so the column reads "in-sample", or "out-of-bag" for a forest, and never "newdata". Beside metric_basis = "newdata" the Moran columns describe the training residuals, not the prediction errors on newdata, and the two can differ in sign.

A significant p-value is noted in the log (not raised as an R warning): positive autocorrelation as structure the model may have missed, negative (resid_morans_z < 0) as the alternating residuals of a model that tracks its data closely. Read the caveats in residual_morans_i() before treating silence as evidence of no residual structure.

See Also

Other in-sample checks: evaluate_insample(), model_metrics(), print.morans_i(), residual_morans_i()

Examples


library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(60, 0, 1000), y = 5e6 + runif(60, 0, 1000),
             a = rnorm(60), b = rnorm(60)),
  coords = c("x", "y"), crs = 32632
)
# An offset keeps the response away from zero, where MAPE is undefined.
pts$z <- 10 + 2 * pts$a - pts$b + rnorm(60, 0, 0.3)
# Two predictor sets for the same learner: the model that leaves `b` out
# against the one that has it.  These are out-of-bag numbers;
# compare_models_cv() scores the same question on spatial folds.
fits <- list(
  a_only  = fit_rf_model(pts, "z", "a", num_trees = 100, seed = 1),
  a_and_b = fit_rf_model(pts, "z", c("a", "b"), num_trees = 100, seed = 1))
cmp <- compare_models(fits)
cmp[, c("model", "RMSE", "R2", "metric_basis", "resid_morans_I",
        "resid_morans_p")]


Compare models on the same cross-validation folds

Description

Cross-validates one or more backends on one set of folds and returns a comparison table. Unlike compare_models(), this fits the models, once per fold.

Usage

compare_models_cv(
  data_sf,
  response_var,
  predictor_vars,
  models = c("GWR", "Bayesian"),
  k = 5,
  seed = 123,
  folds = NULL,
  boundary = NULL,
  pointize = "auto",
  gwr_args = list(),
  bayes_args = list(),
  rf_args = list(),
  summary = c("mean", "median"),
  quiet = FALSE,
  block_size = NULL,
  auto_range = FALSE,
  metrics = NULL
)

Arguments

data_sf

An sf object. When the folds are built here, a feature that is not a point is reduced to one, and the layer is read in x and y (see spatialkit-geometry).

response_var

Response column name.

predictor_vars

Predictor column names.

models

Character vector: any subset of c("GWR", "Bayesian", "RF"), in any order. Each is cross-validated on the same folds. Names outside that set raise a warning and are dropped; if nothing recognised remains, this is an error. A recognised model whose backend package is not installed is dropped with a message, so the call still returns the models that could run. If none of the requested backends is installed, the call stops with "no viable models.". Guard with requireNamespace() when the model set is not known in advance.

k

Number of folds to build when folds is NULL; not read when folds is supplied. Default 5.

seed

RNG seed. Default 123.

folds

Optional fold definitions, in any of three shapes: a make_folds() return value; a bare list of list(train =, test =) pairs of ..row_id values; or a vector of fold labels, one per row, which becomes leave-that-label-out splits (blockCV::cv_spatial() returns one as $folds_ids). Train and test must be disjoint (a fold that trains on its own test rows is not a cross-validation split and is refused with an error), and IDs naming no row in the prepared data are dropped with a logged count (expected when rows were removed for missing values; a sign the folds came from other data when they were not). When it is NULL, one set of block_kfold folds is built and every model is scored on it. With folds = NULL the score estimates the error at the distance the block grid built here puts between the held-out points and their training data, which overstates the error of a map where the samples cover the area it predicts over. The excess is how much the model's error grows from the map's distances to the data to the block grid's, and is small for a model whose error changes little with the distance from the data. fold_separation() with prediction_points compares the held-out distances with those of the locations the model will predict at, and make_folds(method = "knndm", prediction_points = ) builds folds matched to them.

boundary

Optional polygon sf/sfc. When the folds are built here, the block grid is clipped to it, as in make_folds(). It is also passed to each backend's cv_*() function, which projects the data to its CRS before fitting, with supplied folds too.

pointize

How a feature that is not a point is reduced to one (see coerce_to_points()); default "auto". It also decides where a polygon or line row falls in the shared blocks, so each row is placed by the point every model is fitted at.

gwr_args

Extra arguments for cv_gwr. Only names that are formal arguments of cv_gwr() are forwarded (it has no ...), so entries meant for fit_gwr_model() alone (e.g. longlat) cannot be passed this way. Anything dropped is named in a warning; call cv_gwr() directly if you need it.

bayes_args

Extra arguments for fit_bayesian_spatial_model(). Forwarded whole as cv_bayes(fit_args = ), so an unrecognised name raises an error from fit_bayesian_spatial_model() and is not dropped silently. compute_loo, boundary and pointize are overridden by the CV internals.

rf_args

Extra arguments for cv_rf, which passes anything it does not recognise on to fit_rf_model and thence to ranger::ranger().

summary

"mean" or "median" for the Bayesian GP's predictions.

quiet

Logical; suppress this function's progress message()s. It does not silence R warnings, nor the package's console log echo (see spatialkit_quiet for that). Default FALSE.

block_size

Optional minimum block edge length for the shared spatial CV blocks (projected CRS units), passed to make_folds() when folds is NULL. Default NULL. Beside supplied folds it has nothing to size and raises a warning (class spatialkit_fold_args_ignored); so does auto_range = TRUE.

auto_range

Logical. If TRUE and folds is NULL, the autocorrelation range of the response (detrended on predictor_vars) is estimated and used as the minimum block size of the shared folds, as in make_folds(). Default FALSE: geometric blocks. Either way the fold set is built once and every backend is scored on it. When it cannot be built (a block_size or estimated range that leaves a single block, say) the call is an error, as it is for each backend on its own; no model is scored on a design other than the one asked for.

metrics

Optional scoring function of your own, handed to every backend's cv_*(): a function(y, yhat) returning a named numeric vector, applied per fold and to each backend's pooled predictions, whose names become columns of by_fold and overall beside the built-in ones. See "Your own metrics" on cv_spatial() for the contract. Because the backends are scored on the same folds and, in overall, on the same rows (see Value), the columns are comparable across rows of overall.

Value

A list with these elements:

overall

One row per model with the pooled metrics, n_pred (the rows they are computed on, see "Rows the overall table is computed on"), the coverage and CRPS columns described in "Coverage and CRPS in the overall table" when a Bayesian GP ran, and model as its last column. MAPE and SMAPE skip rows whose denominator is zero; n_MAPE and n_SMAPE count the rows they used, and for a count or other non-Gaussian response RMSE, MAE and the Bayesian GP's CRPS are the numbers to compare (see "Percentage errors on responses with zeros" and "Which metrics survive a non-Gaussian response" in model_metrics()).

by_fold

The fold_metrics of every model that ran, stacked, with a model column.

gwr_cv, bayes_cv, rf_cv

The full cv_gwr(), cv_bayes() and cv_rf() result of each model that ran.

Coverage and CRPS in the overall table

A model can predict well on average and still be badly calibrated, so a comparison read from RMSE alone can prefer the model whose uncertainty is wrong. Heaton et al. (2019) found good point prediction routinely alongside poor interval coverage. When "Bayesian" is among the models that ran, overall therefore also carries the columns of cv_bayes()$predictive_coverage: coverage_50, coverage_80, coverage_95 (the share of held-out rows inside the posterior predictive interval at each level, averaged across folds weighted by each fold's n_pred) and mean_CRPS (the continuous ranked probability score, lower is better). They are NA on the GWR and RF rows, which produce point predictions and no draws, and absent when no Bayesian GP ran. Read coverage against its nominal level: 0.95 at coverage_95 is calibrated, well below it is overconfident, well above it is wider than it needs to be.

Rows the overall table is computed on

Shared folds do not guarantee shared rows: a model that fails on a fold (GWR with a fixed bandwidth across a gap in the data, say) or predicts NA for some rows pools fewer rows, usually without the hardest ones. When the models predicted different rows, the function warns and recomputes every model's pooled metrics, your own metrics included, on the rows all of them predicted, so n_pred is the same on every row that has predictions; a model that predicted nothing stays an NA row. Each model's metrics over all the rows it predicted stay in its *_cv element and in attr(overall, "all_rows"), a table of the same shape. by_fold and the Bayesian coverage and CRPS columns are per fold and are not recomputed.

Every model is cross-validated on the layer as passed, so the warnings prep_model_data() raises about that layer (class spatialkit_rows_dropped, counting the incomplete rows dropped, and spatialkit_constant_predictor) are raised once for the comparison, not once per model.

Only the models that ran appear, so check which names are present: a backend whose package is missing is dropped with a message. When no requested backend is available the function stops with "no viable models." rather than returning an empty comparison.

References

Heaton, M. J., Datta, A., Finley, A. O., Furrer, R., Guinness, J., Guhaniyogi, R., Gerber, F., Gramacy, R. B., Hammerling, D., Katzfuss, M., Lindgren, F., Nychka, D. W., Sun, F. and Zammit-Mangion, A. (2019). A case study competition among methods for analyzing large spatial data. Journal of Agricultural, Biological and Environmental Statistics, 24(3), 398–425. doi:10.1007/s13253-018-00348-w

See Also

plot_cv_metrics() to draw the per-fold scores of every model, and plot_calibration() for the Bayesian GP's intervals.

Other cross-validation: cv_bayes(), cv_gwr(), cv_rf(), cv_spatial(), plot_calibration(), plot_cv_metrics()

Examples


library(sf)
set.seed(1)
n <- 120
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             elev = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
dat$price <- 10 + 0.01 * (st_coordinates(dat)[, 1] - 5e5) +
  2 * dat$elev + rnorm(n)
# The random forest, and GWR beside it when sp is installed, on the same
# folds.  "Bayesian" is left out here because a Stan fit per fold takes
# minutes; add it to `models` for a run to report.
models <- c("RF", if (requireNamespace("sp", quietly = TRUE)) "GWR")
cmp <- compare_models_cv(dat, "price", "elev", models = models, k = 3,
                         rf_args = list(num_trees = 100),
                         gwr_args = list(bandwidth = 30))
cmp$overall[, c("model", "RMSE", "R2", "n_pred")]


Create square or hexagonal grid polygons over a boundary

Description

Lays a regular grid of equal-area cells over boundary and clips it to that boundary. Use it rather than create_voronoi_polygons() when you set the cell size yourself instead of letting the observations set it: per-cell rates comparable across the map, or a resolution that stays fixed as the sample grows. Hexagons (type = "hex") avoid the axis-aligned artefacts of squares and put all six neighbours of a cell at the same distance.

Usage

create_grid_polygons(
  boundary,
  target_cells = NULL,
  type = c("square", "hex"),
  cellsize = NULL,
  n = NULL,
  clip = TRUE,
  crs = NULL,
  quiet = FALSE,
  max_cells = 1e+06
)

Arguments

boundary

Polygonal sf or sfc object, the study area the grid is laid over and clipped to. Rows without a location, rows the repair leaves without a polygon, vertices at a latitude beyond 90 and mixed dimensions are handled as "Boundaries" in spatialkit-geometry says. A boundary without a CRS that crs stamps with a geographic CRS is tested for its latitude in the same way.

target_cells

Optional approximate desired number of cells. Besides a number it accepts what approx_n_cells of build_tessellation() accepts and reads it the same way: the ranked levels of determine_optimal_levels() (the first is used), a select_resolution() result (its ⁠$best⁠) or a resolution_profile(), with the warnings and errors described there. The cell size is derived from it as sqrt(area / target_cells), where area is that of the boundary's bounding box, so square grids get square cells; for hex grids the count is adjusted for hexagonal packing density and the size rounded so that a whole number of hexagon widths spans the longer side of the box. The size does not depend on which way the boundary lies; the count can, because hexagon rows are 0.87 cellsize apart while columns are cellsize apart (about 10 percent on a moderately elongated box, up to 1.7 times on a strip narrower than one hexagon). The count is approximate: square cells over an elongated bounding box need more cells than rectangles would (a 1000 x 1 strip at target_cells = 9 gives cells of side 10.5 and about 95 of them), and clipping to an irregular boundary moves the count again. Pass cellsize when the count matters more than the shape.

type

Grid type: "square" (the default) or "hex".

cellsize

Optional numeric cell size (length 1 or 2), in the units of the working CRS. Takes precedence over n and target_cells: if either is also supplied, cellsize is used, the other is ignored and a warning is logged. Supply exactly one of target_cells, cellsize and n. For type = "hex" a hexagon is defined by a single edge-to-edge distance, so only cellsize[1] is used and a differing cellsize[2] is ignored with a logged warning. A side of the boundary's bounding box that exceeds a whole number of square cells, of this size or of the size derived from target_cells, by no more than a margin of one part in 1e10 of the largest coordinate of the boundary, at most a millionth of the diagonal of its bounding box and at least four times the spacing of doubles at that coordinate, gets that number of cells, so a box of 9000 by 6000 at 1000 gets 9 by 6 cells in any unit or origin, where rounding could add a row or column. A boundary so far from the origin of its coordinates that doubles there are spaced more than a millionth of its extent apart (0.125 at 1e15, beside a boundary a few kilometres across) has its grid lines rounded to that spacing; the grid is laid, and a warning of class "spatialkit_xy_imprecise" gives the spacing and the extent.

n

Optional grid resolution (integer, length 1 or 2) giving the number of columns and rows to divide the boundary's bounding box into; the cell size is derived from it. sf::st_make_grid() derives hexagon placement from cellsize alone, so for type = "hex" n does not set the number of cells, although it does change the grid, because the cellsize derived from it is what the hexagons are built with. Ignored (with a logged warning) when cellsize is also supplied. Passing both would otherwise truncate the grid to n[1] x n[2] cells anchored at the bounding-box corner, covering only part of the boundary. Wins over target_cells, which is then ignored with a logged warning.

clip

Logical; clip the grid to the boundary. Default TRUE. In a projected or CRS-less grid, a cell that meets the boundary only within a margin of the cell's edge (the margin cellsize gives: one part in 1e10 of the largest coordinate of the boundary, within its bounds; a cell whose edge lies on the boundary's edge up to rounding) is dropped, rather than kept as a sliver. The call stops when the clip leaves no cell, as it does when the lattice has none: in degrees with s2 on, a boundary edge that spans more than 180 degrees of longitude is read as the shorter great-circle arc, the other way round the globe.

crs

Optional target CRS: anything sf::st_crs() accepts, including an sf or sfc layer, whose CRS is used. When NULL (default) a lon/lat boundary is projected with ensure_projected(), which changes the CRS of the returned grid; a message reports this unless quiet = TRUE. When that CRS would distort cell areas across the boundary by more than 1 percent (Web Mercator over a near-global extent, a UTM zone stretched well past its width), ensure_projected(purpose = "area") is used instead, with a logged warning, so the cells stay equal-area; a local extent keeps its UTM zone. A geographic crs (EPSG:4326, say) is the CRS the grid is returned in: a grid sized by target_cells or n is laid in that projected CRS and then transformed, with long edges densified. A cellsize is in the units of crs, so with a geographic crs it is in degrees and the grid is laid in degrees, as asked; such cells are not equal-area. With sf::sf_use_s2() on (the default) such a grid is clipped with sf's spherical engine s2, and s2 measures and joins its cells after; s2 refuses a polygon that is not valid on the sphere. The rows of boundary and the cells are checked with s2 whatever sf::sf_use_s2() says. Before the clip, a row of boundary that s2 refuses is repaired, with crossing edges split. A cell that lists a corner twice in a row, or two corners within 1e-12 degrees of each other, which s2 reads as one point, is returned with one of them, which moves no corner and changes the cell's area by rounding. A row of boundary, or a cell, that s2 refuses even then (a cell of a grid laid past latitude 90, say) stops the call with an error of class "spatialkit_cells_degenerate" that names its rows and s2's reason, and says to pass a projected crs or to size the grid by target_cells or n.

quiet

Logical; suppress this function's progress message()s. It does not silence R warnings, nor the package's console log echo (see spatialkit_quiet for that). Default FALSE.

max_cells

Upper bound on the number of cells the grid may have, estimated from the boundary's bounding box before anything is built. Default 1e6. A cellsize in the wrong units (metres on a boundary in kilometres, say) asks for a grid that cannot be built, and this refuses it with a message before memory is exhausted. Set to Inf to disable.

Details

Size the grid with exactly one of target_cells (roughly how many cells you want; the package derives the rest), cellsize (a fixed edge length in CRS units) or n (a fixed number of columns and rows). When more than one is given, cellsize wins over the other two and n wins over target_cells; each argument ignored is named in a logged warning.

Value

An sf polygon layer with one column, poly_id, numbering the cells in the order sf::st_make_grid() lays them (row by row from the bottom left). The numbering differs from that of create_grid_polygons_cached() and ensure_stable_poly_id(), which sort cells by position; pass the result to ensure_stable_poly_id() for IDs that do not depend on how the grid was built. Use one builder throughout an analysis, since a summary keyed on the IDs of one drawn on the cells of the other puts the values on the wrong cells.

See Also

Other cell building: build_tessellation(), clip_target_for(), create_grid_polygons_cached(), create_voronoi_polygons(), ensure_stable_poly_id(), get_voronoi_seeds(), plot_tessellation_map(), voronoi_seeds_kmeans(), voronoi_seeds_random()

Examples

library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
  c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
grid_sq  <- create_grid_polygons(bnd, target_cells = 100, type = "square")
grid_hex <- create_grid_polygons(bnd, target_cells = 100, type = "hex")
nrow(grid_sq)
# The hex count runs above the target: clipping keeps every hexagon that
# overhangs the boundary, and that adds more, in proportion, at a small
# target_cells.
nrow(grid_hex)

Create and cache grid polygons over a boundary

Description

Builds a grid with create_grid_polygons(), gives it stable IDs with ensure_stable_poly_id(), and keeps it, so a repeat call with the same arguments returns the kept grid.

Usage

create_grid_polygons_cached(
  boundary,
  target_cells = NULL,
  type = c("square", "hex"),
  ...,
  cache_env = .gmt_cache,
  max_entries = 50L
)

Arguments

boundary

An sf or sfc polygonal object. One that mixes XY and XYZ (or XYM) geometries, or whose geometries carry M (XYM or XYZM), is read without Z and M, as in create_grid_polygons(), and shares its cache entry with the same boundary in XY. Its rows without a location, and those the repair leaves without a polygon, are left out, and a boundary with none left, or in a geographic CRS with a latitude beyond 90 degrees, is refused, as in create_grid_polygons(); a boundary shares its cache entry with its rows that have a location.

target_cells

Approximate desired number of cells, or what target_cells of create_grid_polygons() accepts besides a number (a selection, a profile or ranked levels, read as a count first). Default NULL, as in create_grid_polygons(), so the grid can be sized by cellsize or n passed through ... instead.

type

Grid type: "square" (the default) or "hex", matching create_grid_polygons().

...

Further arguments to create_grid_polygons(), such as cellsize, n or crs.

cache_env

Environment the grids are kept in. The default is the package's own cache, which clear_grid_cache() empties; pass a new environment to keep a separate cache.

max_entries

Maximum number of grids the cache holds. Default 50. Once full, adding a grid evicts the one added earliest, so a loop over many boundaries holds at most this many grids (about 2 MB per 2,500-cell grid) rather than every grid it ever built for the life of the session. clear_grid_cache empties it outright.

Details

A grid returned in degrees (a geographic crs passed through ...) is cached once per sf::sf_use_s2() setting: a grid laid in degrees is clipped by s2 with the setting on and by GEOS with it off, and ensure_stable_poly_id() rebuilds the cells s2 or GEOS calls invalid with s2's rebuild with the setting on and repairs every cell with GEOS with it off, so the grid differs between the two settings. A call is handed the grid of the session's setting. A grid laid and returned in a projected CRS is clipped and repaired by GEOS under either setting and is cached once.

Value

An sf data frame with a stable poly_id column. The rows are re-ordered and re-numbered by ensure_stable_poly_id(), which create_grid_polygons() does not do: the same cell therefore carries a different poly_id depending on which of the two builders produced it. Use one builder throughout an analysis; joining a summary keyed on IDs from one onto geometries from the other draws the values on the wrong polygons.

See Also

clear_grid_cache() to empty the cache.

Other cell building: build_tessellation(), clip_target_for(), create_grid_polygons(), create_voronoi_polygons(), ensure_stable_poly_id(), get_voronoi_seeds(), plot_tessellation_map(), voronoi_seeds_kmeans(), voronoi_seeds_random()

Examples

library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
  c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
g <- create_grid_polygons_cached(bnd, target_cells = 16, type = "hex")
# 27, not 16: clipping keeps every hexagon that overhangs the boundary,
# which adds more at a small target (see ?create_grid_polygons)
nrow(g)
# The IDs come from ensure_stable_poly_id(), so they follow the geometry:
# the same request with the boundary's vertices in another order gives the
# same ID to the same cell.
bnd2 <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
  c(100, 100), c(0, 100), c(0, 0), c(100, 0), c(100, 100)
))), crs = 32632))
g2 <- create_grid_polygons_cached(bnd2, target_cells = 16, type = "hex")
same_cell <- match(st_as_text(st_geometry(g2)), st_as_text(st_geometry(g)))
all(g2$poly_id == g$poly_id[same_cell])

Build Voronoi cells around points

Description

Gives every location in the study area to its nearest input point, so each point gets one cell. Use it when the observations themselves define the cells (sampling sites, monitoring stations, service points): cell size then follows sampling density, with small cells where the points are dense and large ones where they are sparse. Use create_grid_polygons() instead for equal-area cells, or for a resolution that does not depend on where the data are.

Usage

create_voronoi_polygons(
  points_sf,
  boundary = NULL,
  expand = 0,
  clip = TRUE,
  keep_duplicates = FALSE,
  crs = NULL,
  quiet = FALSE,
  cover = NULL
)

Arguments

points_sf

An sf object with POINT/MULTIPOINT geometries. Points with no CRS whose coordinates look like lon/lat (the heuristic ensure_projected() applies, with its warning) are taken as EPSG:4326 and projected, as lon/lat points are. Points that mix XY and XYZ (or XYM), or that carry M, are read in x and y, since sf reads a layer in the dimension of its first geometry and GEOS refuses M; the attributes the seeding functions set on them are kept.

boundary

Optional polygonal sf object. When exactly one of points_sf and boundary has a CRS, the other is interpreted in it, with a warning. CRS-less points, and a CRS-less boundary given with projected points, are read as harmonize_crs() does (lon/lat-looking coordinates are reprojected from EPSG:4326, others are stamped); CRS-less points that do not look like lon/lat cannot take a geographic boundary's CRS, and are refused with an error. A CRS-less boundary given with lon/lat points (or with CRS-less points taken as lon/lat) is read as lon/lat when its coordinates fit the lon/lat envelope, and refused with an error otherwise. Rows without a location, rows the repair leaves without a polygon, vertices at a latitude beyond 90 and mixed dimensions are handled as "Boundaries" in spatialkit-geometry says.

expand

Numeric; absolute distance, in the working CRS's units, by which the boundary (or the hull derived from the points) is grown before the diagram is built. With clip = TRUE the cells are clipped to the grown boundary, so they reach expand beyond the study area, and a point up to expand outside it gets a cell and an index value. The grown boundary is the one returned as boundary.

clip

Logical; clip the cells to the boundary. Default TRUE.

keep_duplicates

Logical. With FALSE (the default), points are merged before the diagram is built when they round to one point in coordinates centred on the middle of their bounding box, divided by its diagonal and rounded to 2^-30 of it, so points within about a billionth of the extent of each other count as coincident in any unit or origin and share one cell. With TRUE only points at exactly one location are merged. Every point is indexed to the cell that holds it.

crs

Optional target CRS: anything sf::st_crs() accepts, including an sf or sfc layer, whose CRS is used. A projected CRS is the working CRS. A geographic one (EPSG:4326, say) is the CRS the result is returned in: the cells are built in the local projected CRS ensure_projected() picks for the points, so they are nearest-point cells on the ground, and are then transformed, with long edges densified. Seeds that are the centres a profile scored are built in the CRS the profile worked in instead (see "Seeds a profile scored"). Where four seeds stand the same distance from one point, as on gridded locations, two cells can meet there at two corners that differ only by rounding, which the transform to degrees can put at one point, and sf's spherical engine (s2) refuses such a cell. assign_features_to_polygons() joins the cells of the centres a profile scored in the CRS they were built in, while they carry the record that says so (scored_cells = TRUE). sf::st_area() and sf::st_union() stop on such a cell in degrees with s2's error. The package's other joins and measures of it stop with an error of class "spatialkit_cells_degenerate" ("Polygons in degrees" in spatialkit-geometry gives the exceptions). Transform the cells to a projected CRS first.

quiet

Logical; suppress this function's progress message()s. It does not silence R warnings, nor the package's console log echo (see spatialkit_quiet for that). Default FALSE.

cover

Optional sf or sfc layer the cells have to hold, read when there is no boundary: the observations (points), or a polygon. The boundary is then derived from it instead of from points_sf: the convex hull of the cover's points, or its polygons, grown by 2 percent of the diagonal. This is what seeds need, because seeds lie inside the data they stand for and their own hull stops short of it (see "Details"). When NULL, the cover the seeding functions attach is used (attr(points_sf, "cover"), set by get_voronoi_seeds(), voronoi_seeds_kmeans() and voronoi_seeds_random()). A cover with no CRS is read in the coordinates of points_sf, and one in another CRS is transformed. A generator outside the cover keeps its ground (the hull of the generators is added); a cover that holds none of the generators is set aside with a warning. With a boundary, the boundary sets the cells and cover is only checked against them: the number of its points that fall outside every cell is returned as params$cover_outside, with a warning of class "spatialkit_unassigned" when it is not 0 (a polygon cover is not checked). A cover, given or attached, that mixes XY and XYZ (or XYM) geometries, or that carries M, is read in x and y. A row of the cover with a coordinate that is not finite or lies beyond 1e150, read as given before any move, is read as an empty row.

Details

sf::st_voronoi() builds the diagram. This function projects lon/lat input, builds and buffers an envelope so edge cells are bounded, clips to boundary, restores the point-to-cell correspondence that st_voronoi() scrambles, and numbers the cells with stable cell_id values.

The generators are the points' vertices, not the features. A MULTIPOINT feature with several vertices therefore gets one cell per vertex, and its index entry is the smallest cell_id among the cells it touches; the others are referenced by no feature. Other functions in the package (prep_model_data(), make_folds()) reduce such a feature to its centroid instead, so cast to POINT, or take centroids, first if one cell per feature is what you want.

With no boundary the cells are clipped to a boundary derived from the data. For observations that is their own convex hull grown by 2 percent of its diagonal, so every observation has a cell. Seeds are different: k-means centres, random points in a study area and the centres a resolution profile scored all lie inside the ground they stand for, and cells clipped to the hull of the seeds leave the edge of that ground uncovered. The boundary is therefore derived from the cover when there is one: the argument, or the cover the seeding functions attach to their result. A layer that looks like seeds and has neither a boundary nor a cover (seeds bound with rbind(), which drops the attribute, or built by hand) gets the seeds' own hull and a warning of class "spatialkit_no_cover".

A seed stands for its cell, so index gives each seed the cell it generates. A k-means seed is a mean of observations and can lie outside a boundary that is not convex, in a bay or a bend of a coast (see get_voronoi_seeds()). Its cell, the part of the study area nearer it than any other seed, is built, and its index entry is that cell's cell_id, although the seed lies in no cell. A seed is NA only when every part of the study area is nearer another seed, so the clip removed its cell whole, or when it has no location (its geometry is empty, or a coordinate is not finite or lies beyond 1e150). The points are seeds when a seeding function returned them (get_voronoi_seeds(), voronoi_seeds_kmeans(), voronoi_seeds_random(), rbind() of such layers included), when they are the seeds of a select_resolution() result, and when a cover is passed with them. A selection's seeds are seeds by the attributes they carry, which rbind() and a write to a file drop. Any other points are indexed by the cell that holds them, so a point outside the study area is NA, unless it lies within a thousandth of the median cell width of a cell, whose ID it then takes (see index in build_tessellation()); that includes observations that carry a selection's record of the count, as assign_features_to_polygons() returns them. Seeds placed by hand, and a selection's seeds that lost their attributes, are seeds once they pass through get_voronoi_seeds(method = "provided", seeds = ).

Value

A list with these elements:

cells

The cells, one polygon per unique point, with a stable cell_id.

index

One cell_id per row of points_sf, and NA for a point that falls outside every cell: outside the study area (grown by expand when it is positive), and farther than a thousandth of the median cell width from the nearest cell, so a summary built from it counts only the points the tessellation covers. Such points are counted in params$n_outside, and a warning of class "spatialkit_unassigned" gives their number. For seeds (see "Details") index holds the cell each seed generates, whether the seed lies inside the boundary or not, and NA only for a seed whose cell the clip removed whole or without a location (an empty geometry, or a coordinate that is not finite or lies beyond 1e150); params$n_outside counts those, the warning names them as seeds, and params$snapped lists only the seeds whose entry is the cell they were snapped to.

boundary

The boundary the cells were built in: the one supplied or derived, grown by expand.

method

"voronoi".

params

The settings and diagnostics of the build, among them:

  • boundary_source: where the boundary came from, "boundary" (the argument), "cover" (the cover argument), "seeds' cover" (the cover attached to points_sf) or "points" (the hull of points_sf itself);

  • cover_outside: the number of cover points outside every cell when a point cover was given with a boundary, and NULL otherwise;

  • partition: present when points_sf is a layer of seeds that records the kind of partition that placed it (attr(points_sf, "partition"), see get_voronoi_seeds()), the same list, so the cells say what built them. Seeds of plain k-means record nothing, and params then has no such element; neither has it for points that are not seeds;

  • count_rule: present when points_sf carries the record of how its count was set (attr(points_sf, "count_rule"): the seeds of a select_resolution() result, or seeds a seeding function placed from one), the same list, with scored_cells = FALSE when the seeds are fewer or more than its count. The cells carry it too, as attr(cells, "count_rule"); assign_features_to_polygons() copies it to the rows it assigns, and summarize_by_cell() checks its result against it.

Seeds a profile scored

The seeds of a select_resolution() result, and the seeds get_voronoi_seeds() or voronoi_seeds_kmeans() return for one, are the centres resolution_profile() scored, and their record of the count (attr(, "count_rule")) says so (scored_cells = TRUE) and holds the centres in the CRS the profile worked in. (On a profile without an estimate fitted to a subsample the seeds are those centres refitted to every point, which carry attr(, "refit"); their record says scored_cells = FALSE, and their cells are built as other seeds' are. So are seeds fewer or more than the record's count, such as a selection's seeds cut down to some of its rows: they are not the centres the profile scored, and their record is handed on with scored_cells = FALSE, as get_voronoi_seeds() (method = "provided") marks such seeds.) Unless a projected crs is given, their cells are built in that CRS, whatever CRS the seeds arrive in (degrees, or the CRS of a boundary they were placed in), and returned in it, or in a geographic crs when one is given. When the seeds are those centres (as many, each at a different centre, within a thousandth of its distance from the next nearest), each is first put at its centre as the record holds it, so rounding the seeds took on in another CRS does not move an edge. The cells are then the cells each row was scored in, and assign_features_to_polygons() gives a point on an edge between two of them the cell the profile scored it in.

Points far from the origin of their CRS

Points so far from the origin of their CRS that doubles there are spaced more than a millionth of their extent apart (0.125 at 1e15, beside a layer a few kilometres across) have the cells' edges and their own cells read at that rounding, so two points that close can fall in one cell. The cells are built, and a warning of class "spatialkit_xy_imprecise" gives the spacing and the extent.

See Also

Other cell building: build_tessellation(), clip_target_for(), create_grid_polygons(), create_grid_polygons_cached(), ensure_stable_poly_id(), get_voronoi_seeds(), plot_tessellation_map(), voronoi_seeds_kmeans(), voronoi_seeds_random()

Examples

library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(15, 0, 100), y = 5e6 + runif(15, 0, 100)),
  coords = c("x", "y"), crs = 32632
)
res <- create_voronoi_polygons(pts, quiet = TRUE)
res$cells   # one polygon per unique point, with stable cell_id
res$index   # cell_id assignment for each input point

Cross-validate a Bayesian GP with spatial folds

Description

Refits the Gaussian-process model of fit_bayesian_spatial_model() on each training fold and scores it on the held-out fold. Besides the point-prediction metrics the other ⁠cv_*()⁠ functions report, it scores the whole predictive distribution: predictive_coverage gives the share of held-out observations inside the 50, 80 and 95 percent intervals, and mean_CRPS rates sharpness and calibration together. A Bayesian model is often chosen for its uncertainty, and held-out coverage shows whether those intervals are honest at locations the model has not seen.

Usage

cv_bayes(
  data_sf,
  response_var,
  predictor_vars,
  folds = NULL,
  k = 5,
  seed = 123,
  boundary = NULL,
  pointize = "auto",
  fit_args = list(),
  summary = c("mean", "median"),
  compute_pred_intervals = TRUE,
  coverage_levels = c(0.5, 0.8, 0.95),
  block_size = NULL,
  auto_range = FALSE,
  parallel = FALSE,
  metrics = NULL
)

Arguments

data_sf

An sf layer with the response and the predictors.

response_var

Name of the response column.

predictor_vars

Character vector of predictor column names.

folds

Optional fold definitions, in one of three shapes: a make_folds() result; a bare list of list(train =, test =) pairs of ..row_id values; or a vector of fold labels, one per row, which becomes leave-that-label-out splits. The label vector is how folds built by another package are used here: blockCV::cv_spatial() returns one as ⁠$folds_ids⁠, while its ⁠$folds_list⁠ holds two unnamed vectors per fold and is refused by name. Train and test must be disjoint; a fold that trains on its own test rows is not a cross-validation split and is refused with an error. IDs naming no row of the prepared data are dropped with a logged count (expected when rows were removed for missing values; a sign the folds came from other data when they were not). When NULL, the folds are make_folds(method = "block_kfold"), built with k, seed, boundary, block_size and auto_range. With folds = NULL the score estimates the error at the distance the block grid built here puts between the held-out points and their training data, which overstates the error of a map where the samples cover the area it predicts over. The excess is how much the model's error grows from the map's distances to the data to the block grid's, and is small for a model whose error changes little with the distance from the data. fold_separation() with prediction_points compares the held-out distances with those of the locations the model will predict at, and make_folds(method = "knndm", prediction_points = ) builds folds matched to them.

k

Number of folds to build when folds is NULL; not read when folds is supplied. Default 5.

seed

Seed for building the folds when folds is NULL and, through one seed drawn per fold, for each fold's Stan sampler, so two seeds give different posteriors even on identical folds. A seed in fit_args overrides the per-fold draw with one fixed sampler seed. Default 123.

boundary

Optional polygon layer (sf or sfc). Data without a CRS are aligned to it, and the blocks built when folds is NULL are clipped to it (see make_folds() and spatialkit-geometry).

pointize

How a feature that is not a point is reduced to one before fitting: a mode of coerce_to_points(). Default "auto".

fit_args

Named list of extra arguments for fit_bayesian_spatial_model(). A gp_k given here is used in every fold; without one, the GP rank is chosen in each training fold. compute_loo, boundary and pointize are always set by the cross-validation. A categorical or ordinal family (brms::categorical(), cumulative, sratio, cratio, acat) is refused before anything is fitted: its prediction is a probability per response category, and every score here needs one number per row.

summary

"mean" (default) or "median": the summary of the posterior predictive draws used as each held-out row's prediction.

compute_pred_intervals

Logical, default TRUE: draw the posterior predictive distribution of the held-out rows. FALSE skips the draws and saves time, and leaves the ⁠coverage_*⁠ columns, CRPS, n_draws, predictive_coverage and predictions$yhat_sd NA.

coverage_levels

Numeric vector of the nominal coverage levels to score, as proportions strictly between 0 and 1 (0.95, not 95), each given once; anything else is an error. Each becomes a column ⁠coverage_<percent>⁠ of fold_metrics, named at full precision (0.975 gives coverage_97.5).

block_size

Optional minimum block edge length, in the units of the CRS the folds are built in, for the blocks built when folds is NULL; see make_folds(). It is a size you choose and is compared with the autocorrelation range only when one can be estimated, in which case a smaller size is warned about. Beside supplied folds it has nothing to size and raises a warning of class spatialkit_fold_args_ignored.

auto_range

Logical, default FALSE. TRUE with folds = NULL estimates the autocorrelation range and uses it as the minimum block size. TRUE beside supplied folds raises the same warning as block_size.

parallel

Logical or positive integer. TRUE detects the number of cores and fits the folds in parallel with parallel::mclapply() (macOS and Linux; sequential on Windows); an integer above 1 uses that many cores. Default FALSE (sequential). Mind the memory: every fold compiles its own Stan model, and one compilation can take several GB, so parallel = n runs n of them at once. A compiler killed for lack of memory fails its fold with rstan's "invalid connection" error, which fold_status records; use fewer cores if you see it.

metrics

Optional scoring function of your own, a ⁠function(y, yhat)⁠ returning a named numeric vector; its names become columns of fold_metrics (per fold) and overall (pooled) beside the built-in ones. See the section "Your own metrics" in cv_spatial() for the contract. yhat is the posterior predictive summary (mean or median) of each held-out row; a score that needs the draws belongs in predictive_coverage and CRPS, which this function computes itself.

Details

Every fold is a full MCMC run, so this is the slowest of the ⁠cv_*()⁠ functions. Use few folds, and parallel = TRUE if you have the cores. For a quicker first pass on the same question, cross-validate a random forest with cv_rf() and come back here once the predictor set has settled.

Value

A list with the elements cv_spatial() returns (overall, fold_metrics, predictions, folds, n_folds_attempted, n_folds_succeeded, fold_status, orphan_rows, n_unknown_ids and n_dropped; see its Value for each, and for the five fold statuses), plus:

formula

The model formula, as text.

predictive_coverage

One entry per coverage_levels value, plus mean_CRPS: averages across folds weighted by each fold's n_pred. The per-fold values in fold_metrics are means over that fold's test rows, so an unweighted average would not be the pooled quantity when fold sizes differ, as they do for spatial blocks.

coverage_levels

The nominal levels, named by their ⁠coverage_*⁠ column.

fold_status keeps the error text of a fold whose sampler failed. predictions also carries yhat_sd, the posterior predictive standard deviation of each held-out row, from the same draws that give the coverage (NA when compute_pred_intervals = FALSE or the draws failed for that fold). overall$Adj_R2 is always NA, as for every ⁠cv_*()⁠.

fold_metrics also carries gp_k, gp_n_basis, n_draws, CRPS, the ⁠coverage_*⁠ columns, convergence_ok and gp_adequacy. convergence_ok is TRUE or FALSE as fit_bayesian_spatial_model() judged that fold's sampler (divergent transitions, R-hat, effective sample size and E-BFMI; see its check_convergence), and NA when fit_args sets check_convergence = FALSE. A fold that did not converge is scored like the others, so a run with any FALSE raises one warning of class spatialkit_convergence naming those folds and the checks each failed. gp_adequacy is what that fold's posterior said about its Gaussian-process basis ("ok", "below_resolution", "unresolved_short_range", "no_signal_above_floor" or "not_checked"; see "What the basis resolves" in fit_bayesian_spatial_model()). A fold whose basis was found too coarse is scored like the others too; see the section "Warnings from the folds".

Warnings from the folds

fit_bayesian_spatial_model() warns about a fit under four condition classes: spatialkit_gp_basis_size, spatialkit_gp_resolution, spatialkit_convergence and spatialkit_gp_adequacy (see its section "Warnings"). Each fold is a fit, and none of those warnings says which fold it came from, so they are collected as the folds run and each class is raised once after the last fold, under this function's name and with the same class. Each warning names the folds and carries folds (their labels) and fold_messages (every fold's own text, named by fold) as fields of the condition. The convergence warning covers the folds that were scored and gives the checks each failed, also as the field failed; the other three quote the first fold's own text. Each fold's own line is in the log. Warnings that Stan or brms raise themselves are not collected and are passed on.

Percentage errors on responses with zeros

MAPE divides by the observed value and SMAPE by |y| + |\hat{y}|, so neither is defined where its denominator is zero. Neither returns Inf or NaN. Both are averaged over the rows whose denominator is non-zero, and are NA when no row qualifies. Non-zero is judged at the scale of the data: a denominator no larger than 100 machine epsilons times the largest one counts as zero, so the rule does not depend on the units of the response. The n_MAPE and n_SMAPE columns record how many rows that was; the n column (n_pred in a cross-validation result) counts finite observation/prediction pairs. Read a percentage error next to that count: when n_MAPE is smaller, MAPE is an average over a subset of the data, whatever its value.

Any response taking exact zeros is affected: counts, rainfall, abundance, claim amounts. On a zero-inflated response with 62 zeros out of 120, MAPE averages the 58 non-zero rows and n_MAPE is 58. SMAPE drops the rows where observation and prediction are both near zero, which on a well-fitted zero-inflated model are the rows it got right, so it averages the harder rows only and reads worse than the fit deserves. n_SMAPE shows how many rows it kept; it does not correct the average.

RMSE, MAE and R^2 use every finite row; prefer them whenever the response can be zero. For a Bayesian GP fit, cv_bayes() also reports CRPS and interval coverage, which are proper scoring rules and are defined at zero.

Which metrics survive a non-Gaussian response

RMSE and MAE are defined for any numeric response and are what to read for a count, a rate or a bounded outcome. MAPE and SMAPE assume a response that is rarely zero (see "Percentage errors on responses with zeros"), and R^2 and adjusted R^2 compare residual variance to total variance, which suits a Gaussian response and fits loosely anything whose variance tracks its mean. On a Poisson or zero-inflated response read the four as a rough summary rather than a score.

For the Bayesian GP, cv_bayes() also reports CRPS and interval coverage at its coverage_levels (50, 80 and 95 percent by default). Both are proper scoring rules computed from posterior draws, so they are meaningful for any family that predicts one number per row (a count, a rate, a binary or bounded outcome), and they are the numbers to compare when the response is not Gaussian. A categorical or ordinal family predicts a probability per response category instead, so cv_bayes() refuses one before fitting anything. When every fold fails, the fold_metrics frame cv_bayes() returns carries the CRPS column but not the coverage_* columns, so code that reads those columns must allow for their absence.

See Also

Other cross-validation: compare_models_cv(), cv_gwr(), cv_rf(), cv_spatial(), plot_calibration(), plot_cv_metrics()

Examples

## Not run: 
# Not run: fits with Stan, which needs a working C++ toolchain and takes
# minutes of MCMC.
library(sf)
set.seed(1)
n <- 60
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             elev = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
dat$price <- 10 + 0.01 * (st_coordinates(dat)[, 1] - 5e5) +
  2 * dat$elev + rnorm(n)
# Two short chains per fold keep this to a few minutes and leave the
# posterior rough, so the intervals below will run narrow; a run to
# report uses the defaults of brms (chains = 4, iter = 2000).
cv <- cv_bayes(dat, "price", "elev", k = 2,
               fit_args = list(chains = 2, iter = 1000))
cv$overall
cv$predictive_coverage  # coverage at 50, 80 and 95 percent, and mean CRPS

## End(Not run)

Cross-validate at a ladder of block sizes

Description

Runs cv_spatial() once per block size on a ladder of sizes, and by default once with random folds as the reference, whose held-out points keep most of their neighbours in the training data. It returns the pooled metric and its fold-to-fold spread at each size, with the estimated autocorrelation range alongside. The wider the blocks, the farther the held-out points sit from their training data. The rise of the curve with block size measures the error at that distance from the data: how much worse the model predicts a location the farther it lies from the observations. It is the error of a map only at locations that far from the data, so the curve does not by itself say which size to report. The size to read is the one whose held-out distances match those of the locations the model will predict at: fold_separation() with prediction_points reads the folds of each size (the ⁠$folds⁠ of each element of attr(x, "results")) against them.

Usage

cv_block_size_sweep(
  data_sf,
  response_var,
  predictor_vars,
  fit_fn,
  block_sizes = NULL,
  n_sizes = 6L,
  k = 5L,
  metric = "RMSE",
  include_random = TRUE,
  max_fits = 60L,
  sac = NULL,
  seed = 123L,
  quiet = FALSE,
  ...
)

## S3 method for class 'block_size_sweep'
plot(x, ...)

Arguments

data_sf

An sf layer with the response and the predictors.

response_var

Name of the response column.

predictor_vars

Character vector of predictor column names.

fit_fn

A ⁠function(train_sf)⁠ returning a spatial_fit, as for cv_spatial(); see the example for wrapping a built-in backend.

block_sizes

Optional numeric vector of block edge lengths to sweep, in the units of the CRS the folds are built in (plain numbers; a units object is refused). Default NULL: the ladder described in the section "The ladder". A size at which the grid would hold fewer than k blocks is not run, with a warning naming it and the largest size that still gives k blocks; if no size is left, the call is an error.

n_sizes

Number of sizes in the default ladder. Default 6.

k

Folds per cross-validation. Default 5.

metric

Which column of overall to read. Default "RMSE".

include_random

Also cross-validate with random folds, as the reference: the error of predicting among the samples, where each held-out point keeps most of its neighbours in the training data. Default TRUE.

max_fits

The most model fits the sweep may run, the random reference included; a sweep that needs more refuses to start. Default 60. See the section "The fit budget".

sac

Optional sac_range from estimate_sac_range() to mark on the curve, or a single number in the units of the CRS the folds are built in. An estimate_sac_range() result records the CRS it was fitted in; when that is not the sweep's, the range is converted to the sweep's units, with a warning. Default NULL: estimated here from the response, detrended on predictor_vars, when gstat is installed.

seed

Seed for the folds at every size, for each cv_spatial() run (which draws one seed per fold for fit_fn, so a learner that draws random numbers gives the same curve on every run), and for the range estimate when sac is NULL. Default 123.

quiet

Suppress the progress messages. Default FALSE.

...

For cv_block_size_sweep(), passed to cv_spatial() at every size (predict_args, p, parallel, metrics, ...); block_size, folds, k, seed and auto_range are set here and cannot be passed. Ignored by plot().

x

A block_size_sweep, for plot().

Value

A data.frame of class "block_size_sweep" with one row per cross-validation: block_size (NA for the random reference), method, blocks_used, k (the folds built), n_folds_succeeded, value (the pooled metric), fold_min, fold_max and fold_sd (its spread across folds), and block_width and block_height (the width and height of the grid cells built at that size, NA for the random reference). Attributes: metric, sac_range (the effective range, or NA), crs, k (the folds requested, which print() and plot() report), n_fits (the fits planned, which the max_fits check reads; print() and plot() count the fits made from the k column), response_var, and results, the full cv_spatial() result at every size.

plot() returns a ggplot object (see the section "The plot").

The fit budget

Each block size is a full cross-validation, so the cost is length(block_sizes) * k fits, plus k for the random reference. max_fits caps that (default 60: room for up to eleven sizes at k = 5 plus the reference; the default six-size ladder at k = 5 needs at most 35). A sweep that would run past the cap refuses to start, naming the number of fits it would have needed; lower n_sizes or k to cut it (with block_sizes supplied: pass fewer block_sizes or a smaller k), or pass include_random = FALSE when the count includes the reference. The random forest of the example takes seconds; a Bayesian fit_fn takes minutes per fit, so raise max_fits with that in mind.

The ladder

When block_sizes is NULL, n_sizes values are log-spaced from a twenty-fifth of the shorter side of the data's extent (of the longer side when the points lie on one line parallel to an axis) to the largest size, at most half that side, at which the grid still holds k blocks. Half the side gives a grid two blocks across, enough for k up to 4 and, for larger k, on an extent long enough in the other direction; on a roughly square extent at the default k = 5 the top is about a third of the side. Any size at which the grid would hold more than the 1,000,000 blocks make_folds() will build is dropped; when that drops every size, the sweep refuses and names the largest size whose grid holds k blocks, to pass as block_sizes. The count is of grid cells: on clustered data a grid of k or more cells can have fewer than k that hold points, and make_folds() then lowers k at that size, which the k column shows; the sweep warns once, naming the sizes. On an extent much longer than it is wide every rung can fall below the autocorrelation range while longer blocks would still fit k times along the longer side; the sweep warns when that happens, and block_sizes is then the way to reach past the range.

Sizes are in the units of the CRS the folds are built in (the params$crs of make_folds(), metres for lon/lat input), and the returned table records that CRS. Each is the minimum block edge handed to make_folds(), which fits a whole number of cells across each axis of the extent, so on an axis at least as long as the size the cells are somewhat longer than it (up to just under twice as long). An axis shorter than the size is spanned by one row or column of cells, which are then shorter than the size there. The block_width and block_height columns give the cells built at each size.

Warnings raised once for the sweep

Every size is a cv_spatial() on the same layer. The warnings prep_model_data() raises about that layer (class spatialkit_rows_dropped, counting the incomplete rows dropped, and spatialkit_constant_predictor) are raised once, not once per size. With a GWR learner, the two warnings in which predict() counts held-out locations ("spatialkit_gwr_not_estimable" and "spatialkit_gwr_extrapolation") are raised once each, under this function's name, with the totals over every size; the same rows are predicted at every size, so a location can be counted once per size (see predict.gwr_fit()).

The plot

plot() draws the curve as a ggplot2 object: the pooled metric at each block size asked for, the fold-to-fold range as a band, the random-fold reference as a dashed line, and the estimated autocorrelation range as a dotted vertical line. The curve rises as the blocks widen because the held-out points sit farther from their training data: its height at a size is the error at that distance from the data, and the error of a map only where the locations it predicts at sit that far from the observations. The caption says which way is better: higher for R2 and Adj_R2, closer to the nominal level for a ⁠coverage_*⁠ column (0.975 for coverage_97.5), since over-coverage is miscalibration too, and lower for everything else. print() shows the same results as a table.

See Also

fold_separation() to read the folds of each size against the locations a map will predict at, and make_folds() for the blocks.

Other folds: fold_separation(), make_folds(), plot_folds()

Examples


library(sf)
set.seed(1)
n <- 200
x <- 5e5 + runif(n, 0, 1000); y <- 5e6 + runif(n, 0, 1000)
d <- as.matrix(dist(cbind(x, y)))
field <- as.numeric(t(chol(exp(-d / 100) + diag(1e-6, n))) %*% rnorm(n))
dat <- st_as_sf(data.frame(x = x, y = y, a = rnorm(n)), coords = c("x", "y"),
                crs = 32632)
dat$z <- field + 0.5 * dat$a + rnorm(n, 0, 0.2)
rf_fn <- function(train_sf)
  fit_rf_model(train_sf, "z", "a", include_coords = TRUE, num_trees = 100,
               seed = 1)
sw <- cv_block_size_sweep(dat, "z", "a", fit_fn = rf_fn, k = 4, n_sizes = 4,
                          quiet = TRUE)
sw        # the curve as a table, with the random-fold reference

# Dashed: the random-fold reference.  Dotted: the estimated
# autocorrelation range.
if (requireNamespace("ggplot2", quietly = TRUE)) plot(sw)


Cross-validate a GWR with spatial folds

Description

Refits a geographically weighted regression from scratch on each training fold and scores it on the held-out fold, so the reported error is the model's at locations it did not see. Use it for an accuracy figure for a GWR: the in-sample R^2 that model_metrics() reports on a gwr_fit says little, because a local regression with a small bandwidth can track the training points almost exactly. The bandwidth is selected again in each fold unless bandwidth fixes it, so the selection itself is inside the cross-validation, with no tuning on the full data first.

Usage

cv_gwr(
  data_sf,
  response_var,
  predictor_vars,
  folds = NULL,
  k = 5,
  seed = 123,
  adaptive = TRUE,
  bandwidth = NULL,
  kernel = c("bisquare", "gaussian", "tricube", "boxcar", "exponential"),
  boundary = NULL,
  pointize = "auto",
  block_size = NULL,
  auto_range = FALSE,
  parallel = FALSE,
  metrics = NULL
)

Arguments

data_sf

An sf layer with the response and the predictors.

response_var

Name of the response column.

predictor_vars

Character vector of predictor column names.

folds

Optional fold definitions, in one of three shapes: a make_folds() result; a bare list of list(train =, test =) pairs of ..row_id values; or a vector of fold labels, one per row, which becomes leave-that-label-out splits. The label vector is how folds built by another package are used here: blockCV::cv_spatial() returns one as ⁠$folds_ids⁠, while its ⁠$folds_list⁠ holds two unnamed vectors per fold and is refused by name. Train and test must be disjoint; a fold that trains on its own test rows is not a cross-validation split and is refused with an error. IDs naming no row of the prepared data are dropped with a logged count (expected when rows were removed for missing values; a sign the folds came from other data when they were not). When NULL, the folds are make_folds(method = "block_kfold"), built with k, seed, boundary, block_size and auto_range. With folds = NULL the score estimates the error at the distance the block grid built here puts between the held-out points and their training data, which overstates the error of a map where the samples cover the area it predicts over. The excess is how much the model's error grows from the map's distances to the data to the block grid's, and is small for a model whose error changes little with the distance from the data. fold_separation() with prediction_points compares the held-out distances with those of the locations the model will predict at, and make_folds(method = "knndm", prediction_points = ) builds folds matched to them.

k

Number of folds to build when folds is NULL; not read when folds is supplied. Default 5.

seed

Seed for building the folds when folds is NULL, and for the one seed drawn per fold before it is fitted. With a seed, the caller's random stream is restored afterwards. Default 123.

adaptive

Logical; use an adaptive bandwidth, a number of neighbours, rather than a fixed distance. Default TRUE.

bandwidth

Optional bandwidth, applied to every fold. For adaptive = TRUE a whole number of neighbours; for adaptive = FALSE a distance in the units of the projected CRS the folds are fitted in (lon/lat input is projected first, so a value in degrees is read as metres). NULL (default) selects a bandwidth in each fold from that fold's training rows, by the search fit_gwr_model() runs (its section "Bandwidth selection": AICc, or the leave-one-location-out sum of squares when observations share a location), and reports it in fold_metrics$bandwidth.

kernel

The kernel that weights each location's neighbours: "bisquare" (default), "gaussian", "tricube", "boxcar" or "exponential", as in fit_gwr_model().

boundary

Optional polygon layer (sf or sfc). Data without a CRS are aligned to it, and the blocks built when folds is NULL are clipped to it (see make_folds() and spatialkit-geometry).

pointize

How a feature that is not a point is reduced to one before fitting: a mode of coerce_to_points(). Default "auto".

block_size

Optional minimum block edge length, in the units of the CRS the folds are built in, for the blocks built when folds is NULL; see make_folds(). It is a size you choose and is compared with the autocorrelation range only when one can be estimated, in which case a smaller size is warned about. Beside supplied folds it has nothing to size and raises a warning of class spatialkit_fold_args_ignored.

auto_range

Logical, default FALSE. TRUE with folds = NULL estimates the autocorrelation range and uses it as the minimum block size. TRUE beside supplied folds raises the same warning as block_size.

parallel

Accepted so that every ⁠cv_*()⁠ function takes the same arguments, but the GWR folds always run one after another in this R process, where the warnings predict() raises for each fold are collected into one. A value asking for more than one core raises a warning saying so. Default FALSE.

metrics

Optional scoring function of your own, a ⁠function(y, yhat)⁠ returning a named numeric vector; its names become columns of fold_metrics (per fold) and overall (pooled) beside the built-in ones. See the section "Your own metrics" in cv_spatial() for the contract.

Details

Folds default to spatial blocks (make_folds(method = "block_kfold")), not random ones. A random split leaves a held-out point's neighbours in the training set, so its score is the error of predicting among the samples; blocks hold out whole areas, and folds says what their score estimates. Use cv_bayes() for the same treatment of a Bayesian GP, cv_rf() for a random forest, and compare_models_cv() to score several backends on one set of folds.

Value

A list with the elements cv_spatial() returns (overall, fold_metrics, predictions, folds, n_folds_attempted, n_folds_succeeded, fold_status, orphan_rows, n_unknown_ids and n_dropped; see its Value for each, and for the five fold statuses), plus:

formula

The model formula, as text.

adaptive

Whether the bandwidth was adaptive.

fold_metrics also carries each fold's bandwidth. Adj_R2 is NA in both overall and fold_metrics: the pooled predictions have no single parameter count, and a GWR's effective parameter count is not its predictor count.

A held-out location whose local regression cannot be estimated has yhat NA, and one beyond the reach of its fold's fit is predicted and scored; each case raises one warning for the whole run (classes "spatialkit_gwr_not_estimable" and "spatialkit_gwr_extrapolation"), with the totals over the folds that had any. See predict.gwr_fit(). Where a fold's fit took the response about a centre (a response at a large offset; see fit_gwr_model()), predictions also carries y_centre (that centre, 0 in the rows of a fold fitted on the raw response), yhat_centred and y_train_mean_centred (yhat and y_train_mean less the centre, which keep digits that rounding at the response's size would lose), and the metrics are those of the centred values, as model_metrics() computes them.

Percentage errors on responses with zeros

MAPE divides by the observed value and SMAPE by |y| + |\hat{y}|, so neither is defined where its denominator is zero. Neither returns Inf or NaN. Both are averaged over the rows whose denominator is non-zero, and are NA when no row qualifies. Non-zero is judged at the scale of the data: a denominator no larger than 100 machine epsilons times the largest one counts as zero, so the rule does not depend on the units of the response. The n_MAPE and n_SMAPE columns record how many rows that was; the n column (n_pred in a cross-validation result) counts finite observation/prediction pairs. Read a percentage error next to that count: when n_MAPE is smaller, MAPE is an average over a subset of the data, whatever its value.

Any response taking exact zeros is affected: counts, rainfall, abundance, claim amounts. On a zero-inflated response with 62 zeros out of 120, MAPE averages the 58 non-zero rows and n_MAPE is 58. SMAPE drops the rows where observation and prediction are both near zero, which on a well-fitted zero-inflated model are the rows it got right, so it averages the harder rows only and reads worse than the fit deserves. n_SMAPE shows how many rows it kept; it does not correct the average.

RMSE, MAE and R^2 use every finite row; prefer them whenever the response can be zero. For a Bayesian GP fit, cv_bayes() also reports CRPS and interval coverage, which are proper scoring rules and are defined at zero.

See Also

Other cross-validation: compare_models_cv(), cv_bayes(), cv_rf(), cv_spatial(), plot_calibration(), plot_cv_metrics()

Examples


library(sf)
set.seed(1)
n <- 60
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             elev = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
dat$price <- 10 + 0.01 * (st_coordinates(dat)[, 1] - 5e5) +
  2 * dat$elev + rnorm(n)
cv <- cv_gwr(dat, "price", "elev", k = 3, bandwidth = 30)
cv$overall          # pooled over the held-out rows of every fold
cv$fold_metrics     # and fold by fold


Cross-validate a random forest with spatial folds

Description

A wrapper over cv_spatial() that refits a ranger forest on each training fold. By default it holds out whole spatial blocks, so most neighbours of a held-out point are not in the training set; the forest's out-of-bag error holds out single rows. The folds you pass decide what the score measures (see "Fold methods" in make_folds()).

Usage

cv_rf(
  data_sf,
  response_var,
  predictor_vars,
  folds = NULL,
  k = 5,
  seed = 123,
  parallel = FALSE,
  block_size = NULL,
  auto_range = FALSE,
  boundary = NULL,
  pointize = "auto",
  metrics = NULL,
  ...
)

Arguments

data_sf

An sf object.

response_var

Response column name.

predictor_vars

Predictor column names.

folds

Optional fold definitions, in any of three shapes: a make_folds() return value; a bare list of list(train =, test =) pairs of ..row_id values; or a vector of fold labels, one per row, which becomes leave-that-label-out splits. The label vector is how folds built by another package are used here, since blockCV::cv_spatial()'s $folds_list holds two unnamed vectors per fold and is refused by name. That function returns a label vector as $folds_ids. Train and test must be disjoint: a fold that trains on its own test rows is not a cross-validation split and is refused with an error. IDs naming no row in the prepared data are dropped with a logged count. Built via block_kfold when NULL, as in cv_spatial(). With folds = NULL the score estimates the error at the distance the block grid built here puts between the held-out points and their training data, which overstates the error of a map where the samples cover the area it predicts over. The excess is how much the model's error grows from the map's distances to the data to the block grid's, and is small for a model whose error changes little with the distance from the data. fold_separation() with prediction_points compares the held-out distances with those of the locations the model will predict at, and make_folds(method = "knndm", prediction_points = ) builds folds matched to them.

k

Number of folds when folds is NULL. Default 5.

seed

RNG seed. Default 123. It seeds fold construction and, through a per-fold draw, each fold's forest, so two different seeds give different results even on identical folds. To grow every fold's forest from one fixed ranger seed instead, call cv_spatial with your own fit_fn wrapping fit_rf_model(seed = ).

parallel

Passed to cv_spatial. Default FALSE. Under forked workers each fold's forest runs single-threaded unless num_threads is passed explicitly, so parallel = 4 means four threads in total, where it would otherwise mean four times the session's mc.cores.

block_size, auto_range, boundary

Passed to cv_spatial. block_size and auto_range = TRUE size the blocks built when folds is NULL; beside supplied folds they have nothing to size and raise a warning of class spatialkit_fold_args_ignored.

pointize

How non-POINT geometry is reduced to a point before fitting; passed to cv_spatial. Default "auto".

metrics

Optional scoring function of your own, passed to cv_spatial; see Your own metrics there.

...

Passed to fit_rf_model on every fold: num_trees, mtry, importance, include_coords and so on. data_sf, response_var, predictor_vars and .already_prepped are set by this function and must not be passed here (every fold would fail with "matched by multiple actual arguments"). seed is this function's own argument and never reaches fit_rf_model() through here; see seed above for growing every fold's forest from one fixed seed.

Value

The cv_spatial() result. MAPE and SMAPE skip rows whose denominator is zero; n_MAPE and n_SMAPE count the rows they used (see "Percentage errors on responses with zeros" in model_metrics()).

Comparing the forest with and without coordinates

Whether include_coords = TRUE lowers the error depends on how far from the training data the predictions are (see "Coordinates as predictors" in fit_rf_model), so it is a comparison to make on your own data, at the block size the map will be used at. Score the two forests on the same folds: build the folds once with make_folds and pass the result as folds to two calls, one with include_coords = TRUE and one without. Each fold then holds out the same rows in both, so the two overall rows compare like with like and the two fold_metrics tables pair up fold by fold. A difference in overall that is small beside the spread of the per-fold differences is not evidence for either forest. The example below runs the comparison. compare_models_cv() takes one set of forest arguments (rf_args) per call, so it scores only one of the two forests.

See Also

fit_rf_model() for the forest's arguments, and plot_cv_metrics() to draw the per-fold scores.

Other cross-validation: compare_models_cv(), cv_bayes(), cv_gwr(), cv_spatial(), plot_calibration(), plot_cv_metrics()

Examples


library(sf)
set.seed(1)
n <- 200
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             a = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
# An offset keeps the response away from zero, where MAPE is undefined.
dat$z <- 10 + 2 * dat$a + rnorm(n, 0, 0.3)
cv_rf(dat, "z", "a", k = 4)$overall

# The forest with and without the coordinates, on the same blocked
# folds.  The second call logs the include_coords caution once per
# session.  This response has no spatial structure, so here the
# coordinates can only cost accuracy.
folds   <- make_folds(dat, k = 4, method = "block_kfold", seed = 1)
plain   <- cv_rf(dat, "z", "a", folds = folds, num_trees = 200)
with_xy <- cv_rf(dat, "z", "a", folds = folds, num_trees = 200,
                 include_coords = TRUE)
c(plain = plain$overall$RMSE, with_xy = with_xy$overall$RMSE)
# Fold by fold: positive where the coordinates lowered the error.
plain$fold_metrics$RMSE - with_xy$fold_metrics$RMSE


Cross-validate any learner with spatial folds

Description

You supply fit_fn(train_sf), which fits on one fold's training rows and returns a spatial_fit; cv_spatial() builds or takes the folds, calls fit_fn once per fold, predicts the held-out rows and returns pooled and per-fold scores. cv_rf() is a wrapper over it.

Usage

cv_spatial(
  data_sf,
  response_var,
  predictor_vars,
  fit_fn,
  folds = NULL,
  k = 5,
  seed = 123,
  boundary = NULL,
  pointize = "auto",
  predict_args = list(),
  fold_info_fn = NULL,
  p = NULL,
  block_size = NULL,
  auto_range = FALSE,
  parallel = FALSE,
  metrics = NULL,
  .caller = "cv_spatial"
)

Arguments

data_sf

An sf layer with the response and the predictors.

response_var

Name of the response column.

predictor_vars

Character vector of predictor column names.

fit_fn

A function of one argument, the training slice of data_sf, returning a spatial_fit built with new_spatial_fit(). It is called once per fold on the training rows only, so anything done inside it (scaling, tuning, an inner variable sweep) is already nested and leak-free. The subclass it stamps must have a ⁠predict.<subclass>()⁠ method registered, since that is how each fold is scored. The fit models response_var (its response_var is the call's): a fold whose fit models another column fails, with the two names in fold_status, since its predictions are scored against response_var.

folds

Optional fold definitions, in one of three shapes: a make_folds() result; a bare list of list(train =, test =) pairs of ..row_id values; or a vector of fold labels, one per row, which becomes leave-that-label-out splits. The label vector is how folds built by another package are used here: blockCV::cv_spatial() returns one as ⁠$folds_ids⁠, while its ⁠$folds_list⁠ holds two unnamed vectors per fold and is refused by name. Train and test must be disjoint; a fold that trains on its own test rows is not a cross-validation split and is refused with an error. IDs naming no row of the prepared data are dropped with a logged count (expected when rows were removed for missing values; a sign the folds came from other data when they were not). When NULL, the folds are make_folds(method = "block_kfold"), built with k, seed, boundary, block_size and auto_range. With folds = NULL the score estimates the error at the distance the block grid built here puts between the held-out points and their training data, which overstates the error of a map where the samples cover the area it predicts over. The excess is how much the model's error grows from the map's distances to the data to the block grid's, and is small for a model whose error changes little with the distance from the data. fold_separation() with prediction_points compares the held-out distances with those of the locations the model will predict at, and make_folds(method = "knndm", prediction_points = ) builds folds matched to them.

k

Number of folds to build when folds is NULL; not read when folds is supplied. Default 5.

seed

Seed for building the folds when folds is NULL, and for the one seed drawn per fold before fit_fn runs, so a learner that draws random numbers gives the same scores on every run, sequential or parallel. With a seed, the caller's random stream is restored afterwards. Default 123; NULL draws the per-fold seeds from the session's RNG state, and advances it.

boundary

Optional polygon layer (sf or sfc). Data without a CRS are aligned to it, and the blocks built when folds is NULL are clipped to it (see make_folds() and spatialkit-geometry).

pointize

How a feature that is not a point is reduced to one before fitting: a mode of coerce_to_points(). Default "auto".

predict_args

A list of extra arguments for predict() on each fold's fit.

fold_info_fn

Optional ⁠function(fit, test_sf, y, yhat)⁠ returning a named list (or a named vector) of per-fold extras (a bandwidth, a tuning value, anything read off the fitted object), added as columns of fold_metrics. It sees the fit and the held-out layer, which metrics does not; it is applied per fold only, and its values are not pooled. An element ..per_row that is a data frame with one row per held-out observation is spliced into predictions instead (NA in the rows of a fold that returned none; one of the wrong length is dropped and logged); its columns must be named, once, and not reuse a column predictions already has (..row_id, fold, y, yhat, y_train_mean). Every other element must be named, hold one value, and not reuse a column fold_metrics already has; anything else is an error. A fold_info_fn that throws on a fold is logged, its columns are NA for that fold, and fold_status$message says so; the fold is kept.

p

Number of predictors for the per-fold adjusted R^2, or NULL to skip it. It applies only to models with one global parameter count; pass NULL for models with spatially varying coefficients, such as GWR.

block_size

Optional minimum block edge length, in the units of the CRS the folds are built in, for the blocks built when folds is NULL; see make_folds(). It is a size you choose and is compared with the autocorrelation range only when one can be estimated, in which case a smaller size is warned about. Beside supplied folds it has nothing to size and raises a warning of class spatialkit_fold_args_ignored.

auto_range

Logical, default FALSE. TRUE with folds = NULL estimates the autocorrelation range and uses it as the minimum block size. TRUE beside supplied folds raises the same warning as block_size.

parallel

Logical or positive integer. TRUE detects the number of cores and fits the folds in parallel with parallel::mclapply() (macOS and Linux; sequential on Windows); an integer above 1 uses that many cores. Default FALSE (sequential). A learner that runs OpenMP code (a function of GWmodel, or an xgboost built with GNU libgomp) can hang the forked workers once it has run in the session; keep such a fit_fn sequential.

metrics

Optional scoring function of your own; see the section "Your own metrics". Default NULL: the built-in metrics only.

.caller

For package wrappers; do not set it.

Value

A list with:

overall

One row of metrics pooled over the held-out rows of every fold that produced predictions.

fold_metrics

One row per fold that produced predictions: fold, n_train, n_test, n_pred, the metrics, and the columns of fold_info_fn and metrics.

predictions

One row per held-out row scored: ..row_id, fold, y, yhat and y_train_mean, the mean response of that fold's training rows.

folds

The splits as run, each with its fold_id.

n_folds_attempted, n_folds_succeeded

The folds supplied (or built) and the folds scored. A fit_fn that fails on every fold otherwise looks like a run that scored NA, so compare the two before reading overall.

fold_status

A data frame with one row per fold supplied: fold, status and message. status is one of

  • "ok": message is empty unless fold_info_fn failed on the fold;

  • "error": the fit or its predict() threw, and message is the error text;

  • "skipped": nothing to score (too few matched rows, a prediction of the wrong length, or no finite pair of observed and predicted values);

  • "dropped": an empty test set, or fewer than two training rows once incomplete rows were removed, so the fold never reached the fitter;

  • "worker_error": a parallel worker died, for example killed for lack of memory.

Every fold missing from fold_metrics has its reason here, after the console output of a long run is gone.

orphan_rows

The ..row_ids of rows in the data that no fold names: they enter no training set and are never scored. It is empty unless the folds were built on a different or subsetted layer.

n_unknown_ids

The number of distinct row IDs the folds name that the data do not have (expected when rows were removed for missing values). Each such row is named by every fold, once as a test row and once in each other fold's training set, and this counts the row, not the mentions.

n_dropped

The number of rows prep_model_data() removed for missing or non-finite values or a bad geometry before any fold was fitted.

A failure costs that fold only: with parallel = TRUE each fold runs in its own worker, and a sequential run catches the error per fold. An error that stops a sequential run (a metrics or fold_info_fn return value of the wrong shape) stops a parallel one too, naming the fold. When some folds, but not all, end as "error", "skipped" or "worker_error", the function warns, naming them and how many rows overall covers: it is pooled over the folds that produced predictions, and the fold that fails is often the hardest to predict, so it may flatter the model. A "dropped" fold has its own warning.

The fold column of fold_metrics, predictions and fold_status carries the fold's index in the folds object that was supplied, so it lines up with make_folds()$assignment$fold even when some folds were unusable and dropped. Splits that already carry a fold_id, as the folds of a ⁠cv_*()⁠ result do, keep it: handing one run's folds to another labels each fold as the first run and fold_separation() do, a dropped fold's gap included.

R2 is the out-of-sample R^2: the total sum of squares is taken about the mean of the training rows (in overall, each held-out row about its own fold's training mean), the null prediction available when the fold is predicted, and not about the held-out rows' own mean, a null model that would know the test data. On spatial blocks the two can differ widely; R2 is below 0 when the model predicts worse than the training mean. model_metrics(newdata = ) uses the same baseline. overall$Adj_R2 is always NA: the pooled out-of-sample predictions come from k separately fitted models and have no single parameter count to adjust for. The per-fold fold_metrics$Adj_R2 carries the adjusted value when p is supplied, and is NA otherwise. A fit_fn that returns a gwr_fit of a response at a large offset gives predictions the columns y_centre, yhat_centred and y_train_mean_centred (see cv_gwr()).

Name collision with blockCV

The blockCV package exports a function of the same name that does the opposite job: blockCV::cv_spatial() builds spatial folds, where this function runs a cross-validation over folds it is given. With both packages attached, whichever was attached last masks the other; spatialkit::cv_spatial() always resolves to this one. The two work together: blockCV::cv_spatial() returns its fold assignment as ⁠$folds_ids⁠, a vector of fold labels, and that vector is accepted as the folds argument here and in every other ⁠cv_*()⁠ function.

Your own metrics

The built-in columns (RMSE, MAE, MAPE, SMAPE, R2, Adj_R2) are the Gaussian regression set; see "Which metrics survive a non-Gaussian response" in model_metrics() for which of them hold up on a count or a bounded response. metrics scores what they cannot: a ⁠function(y, yhat)⁠ that returns a named numeric vector (a named list of scalars, or a one-row data frame, also serve), for example a Poisson deviance, a log score on a probability, or a loss with your own weights. It is applied twice, as the built-in metrics are: once per fold, to that fold's held-out rows, so each name becomes a column of fold_metrics; and once to the pooled out-of-sample predictions of every fold, so each name becomes a column of overall. Only the pairs the built-in metrics use reach the function (both y and yhat finite), so its columns describe the same rows as RMSE, and n_pred counts them.

The contract: every element named, names unique and not one of the built-in column names, one number per name. The built-in names include the per-fold extras of the backend or of your fold_info_fn (bandwidth for cv_gwr(); CRPS, ⁠coverage_*⁠, gp_k, gp_n_basis and n_draws for cv_bayes()), and mean_CRPS, which compare_models_cv() writes. Anything else is an error, since a scoring function that returns the wrong shape is a mistake to report, not a fold to skip. A function that throws on a fold is logged and its columns are NA for that fold (and for overall, if it throws on the pooled predictions); a fold is never dropped for it. When no fold produced a prediction the empty fold_metrics frame still carries the function's columns, typed, provided the function can be called on zero-length input.

fold_info_fn is the per-fold half of the same mechanism, with access to the fitted object and the held-out layer; metrics sees only the two vectors but is also pooled. compare_models_cv() hands one metrics to every backend, so the columns are comparable across the rows of its overall.

Warnings a learner raises in every fold

A warning from a fold's fit or from its predict() reaches the caller as it is raised, so a learner that warns in every fold warns once per fold. Two groups of the package's own warnings are collected over the folds instead and raised once per call, under this function's name and with the class they had:

With parallel above one core a fold's warnings are raised after the folds have run, once per distinct text; one of the package's own classes keeps its class and its fields.

Percentage errors on responses with zeros

MAPE divides by the observed value and SMAPE by |y| + |\hat{y}|, so neither is defined where its denominator is zero. Neither returns Inf or NaN. Both are averaged over the rows whose denominator is non-zero, and are NA when no row qualifies. Non-zero is judged at the scale of the data: a denominator no larger than 100 machine epsilons times the largest one counts as zero, so the rule does not depend on the units of the response. The n_MAPE and n_SMAPE columns record how many rows that was; the n column (n_pred in a cross-validation result) counts finite observation/prediction pairs. Read a percentage error next to that count: when n_MAPE is smaller, MAPE is an average over a subset of the data, whatever its value.

Any response taking exact zeros is affected: counts, rainfall, abundance, claim amounts. On a zero-inflated response with 62 zeros out of 120, MAPE averages the 58 non-zero rows and n_MAPE is 58. SMAPE drops the rows where observation and prediction are both near zero, which on a well-fitted zero-inflated model are the rows it got right, so it averages the harder rows only and reads worse than the fit deserves. n_SMAPE shows how many rows it kept; it does not correct the average.

RMSE, MAE and R^2 use every finite row; prefer them whenever the response can be zero. For a Bayesian GP fit, cv_bayes() also reports CRPS and interval coverage, which are proper scoring rules and are defined at zero.

See Also

new_spatial_fit() for the constructor a fit_fn must use; cv_gwr(), cv_bayes() and cv_rf() for the built-in backends.

Other cross-validation: compare_models_cv(), cv_bayes(), cv_gwr(), cv_rf(), plot_calibration(), plot_cv_metrics()

Examples

library(sf)
set.seed(1)
n <- 80
site <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             elev = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
site$price <- 10 + 0.01 * (st_coordinates(site)[, 1] - 5e5) +
  2 * site$elev + rnorm(n)

# 1. A fit_fn returning a spatial_fit of your own subclass.
lm_fit <- function(train_sf) {
  new_spatial_fit(
    subclass       = "lm_fit",
    engine         = lm(price ~ elev, st_drop_geometry(train_sf)),
    formula        = price ~ elev,
    response_var   = "price",
    predictor_vars = "elev",
    data_sf        = train_sf
  )
}

# 2. The predict() method cv_spatial() scores each fold with. Without it
#    every fold fails and `overall` comes back all-NA.
predict.lm_fit <- function(object, newdata = NULL, ...) {
  if (is.null(newdata)) newdata <- object$data_sf
  as.numeric(stats::predict(object$engine, st_drop_geometry(newdata)))
}
registerS3method("predict", "lm_fit", predict.lm_fit)

cv <- cv_spatial(site, "price", "elev", fit_fn = lm_fit, k = 3, seed = 1)
cv$overall
# Compare these before reading the metrics above; fold_status says why
# any fold is missing from fold_metrics.
c(attempted = cv$n_folds_attempted, succeeded = cv$n_folds_succeeded)
cv$fold_status

# 3. A metric of your own beside the built-in ones: per fold and pooled.
med_ae <- function(y, yhat) c(MedAE = stats::median(abs(y - yhat)))
cv2 <- cv_spatial(site, "price", "elev", fit_fn = lm_fit, k = 3, seed = 1,
                  metrics = med_ae)
cv2$overall$MedAE
cv2$fold_metrics[, c("fold", "RMSE", "MedAE")]

Choose a cell count from the elbow of the k-means WSS curve

Description

Fits k-means to the coordinates at k = 1 to max_levels cells and returns the count at the elbow of the within-cluster sum of squares (WSS), read on log-log axes, with its two neighbours. Points with no cluster structure have no elbow, and the result is then NA with a warning. For a count chosen from the response, use resolution_profile().

Usage

determine_optimal_levels(
  data_sf,
  max_levels = 12L,
  top_n = 3L,
  sample_n = 1500L,
  set_seed = 123L,
  response_var = NULL,
  predictor_vars = NULL,
  criterion = c("geometric", "morans_i", "combined"),
  select_on = c("all", "split"),
  on_no_elbow = c("na", "warn", "error")
)

Arguments

data_sf

An sf object. Non-point geometries are reduced to points with coerce_to_points(). Features without a location are dropped with a warning, and a layer that mixes XY and XYZ geometries or carries M is read in x and y (see spatialkit-geometry).

max_levels

Integer upper bound on levels. Default 12. The sweep also stops at the number of distinct locations (k-means cannot place more centres) and one short of the number of points.

top_n

Integer; how many candidates to return. Default 3. Under criterion = "geometric" the candidate set is the elbow and its two immediate neighbours, so at most 3 values are returned however large top_n is; only the model-aware criteria can return more. Under those it also sets the counts scored, the elbow plus or minus max(4, top_n): a top_n above 4 scores more counts, and under "morans_i" one of them can rank first. A count scores the same whichever top_n puts it in the window.

sample_n

Integer; subsample size for speed. Default 1500.

set_seed

Integer RNG seed for the subsample and the k-means++ restarts; restored afterwards. Default 123. The rows are put in coordinate order before either, so the answer does not depend on the order they come in.

response_var

Name of the response column (numeric or logical), or NULL. Read under criterion = "morans_i", which ranks the counts around the elbow by Moran's I of the cell means, and "combined", which reports that statistic beside the elbow's ranking; under "geometric", the default, it is not read. Logicals are read as 0/1; a factor or character response raises an error and is never coerced, because the residuals of an OLS fit to arbitrary level codes carry no meaning to test for autocorrelation. Rows where it, or a predictor, is missing or non-finite stay in the WSS sweep and the cells and are left out of Moran's I; a logged warning gives their number.

predictor_vars

Optional predictor column names, read where response_var is. Must be numeric or logical (logicals are read as 0/1); factor/character columns raise an error. Without them the model-aware criteria regress the cell means on an intercept alone, as resolution_profile() does.

criterion

One of "geometric" (default: the elbow and its two neighbours, read off the coordinates alone), "morans_i" (among the candidates around the elbow, the k at which Moran's I of the cell means, or of their regression residuals, is least significant: the count at which neighbouring cells stop resembling each other, which need not be the count that represents the response best), or "combined" (the candidates around the elbow in the order of the WSS curve's log-log sag, the quantity the elbow is read from, with Moran's I of the cell means and its z in the diagnostics; the statistic does not take part in the ranking). Under "morans_i" a warning of class spatialkit_diagnostic_ranking says that the ranking is by a diagnostic of the cell means; its condition carries k (the count ranked first), criterion, first_computable (the first count at which the statistic is finite) and window (the first and last count tried). "morans_i" and "combined" fall back to "geometric", with a warning, when response_var is not given, and with a logged warning when no candidate clears the nine-cell floor described under "Model-aware criteria". A response_var or predictor_vars naming a column that is not in data_sf is an error under every criterion. Supplying both response_var and predictor_vars does not change the criterion: under "geometric" neither is read, and a line logged at the INFO level says that "combined" reports Moran's I.

select_on

"all" (default) selects on every point; "split" reads the response on one spatially blocked half of the points only and returns the other half as the set to estimate on, so that the standard errors computed downstream on the chosen cells are not post-selection. The count is still chosen for the whole layer. See "Post-selection inference".

on_no_elbow

What to do when the count is not a finding about the data: the WSS curve has no elbow, the ladder is too short to show one, or there are too few points or locations for a ladder at all. Each choice raises a condition of class spatialkit_no_elbow there, which carries k (the count the chord rule or the ladder gives), sag (the largest log-log sag of the curve; an elbow needs \log 1.25) and structured = FALSE, so a caller can catch it without matching the message. "na" (default) returns NA_integer_ there, with a warning of that class, and every result under "na" carries the attributes structured (TRUE when the WSS curve has an elbow, FALSE with the NA) and sag, so one test of attr(k, "structured") covers both outcomes. "warn" returns the counts the chord rule or the ladder gives (see Value), with the same warning; its results carry neither attribute. "error" stops with an error of that class. Under the model-aware criteria the candidates are scored around the elbow: with no elbow, "na" and "error" score none, and under "warn" the ladder places that window.

Value

An integer vector of candidate counts, best first:

"geometric"

The elbow, then its lower and upper neighbours.

"morans_i"

The candidates in the order of |z|, with a warning of class spatialkit_diagnostic_ranking.

"combined"

The candidates around the elbow in the order of the sag.

No elbow

NA_integer_, with a warning of class spatialkit_no_elbow; under on_no_elbow = "warn", the ladder's choice and its neighbours, with the same warning. So it is when the ladder is too short to show an elbow (max_levels of 1 or 2), and for a layer with fewer than three points or every point on one location, which has no ladder (1 under "warn"). A layer with no points is an error.

k[1] is the top-ranked count, or NA, on every path, and top_n = 1 returns it alone. The vector can carry these attributes:

structured, sag

Under the default on_no_elbow = "na", on every result: structured is TRUE when the WSS curve has an elbow and FALSE with the NA, and sag is the curve's largest log-log sag. None under "warn" or "error". The geometric path carries no other attribute.

diagnostics

Under "morans_i" and "combined": a list with per-k Moran's I (moran_i) and standardised deviates (moran_z), the WSS curve (wss) with the relative between-restart spread at each k (wss_spread), the number of rising steps on it (wss_bumps), the restart budget (nstart), the elbow the scored neighbourhood was drawn around (knee_k), whether the WSS curve has an elbow (structured) and its largest log-log sag (sag), the k at which k-means failed (failed_k; their wss entries are interpolated from the neighbours, not measured) and the k the model-aware pass scored (eval_ks, the elbow's neighbourhood). Under "combined" it also carries the WSS of the re-run clustering at those k (wss_eval, the clustering Moran's I is computed on; reported, not ranked on), the rank of the sag of wss that ordered them (combined_rank, named by k; with no elbow every candidate ties and the order is by distance from knee_k) and criterion = "combined". When "combined" returned the geometric ranking because the elbow is below ten cells, it carries criterion = "geometric" and fallback (the reason) in place of combined_rank. The NA the default returns on a model-aware call whose WSS curve has no elbow (or a ladder too short to show one) carries the attribute too, with what the sweep measured: moran_i and moran_z all NA and eval_ks empty, since no count was scored, knee_k the count the chord rule lands on, and structured = FALSE. Under "combined", Moran's I computable at no candidate of a neighbourhood that reaches ten cells leaves the attribute in place, with moran_i and moran_z all NA, and a logged warning says so. The attribute is absent when the model-aware path falls back to the geometric result (no viable k in the elbow's neighbourhood, a neighbourhood that ends at nine cells or fewer, or, under "morans_i", Moran's I computable at no candidate); these fallbacks are logged as warnings. It is absent too on the NA of a layer with no ladder (fewer than three points, one location, or k-means failing at every k from 2).

split

With select_on = "split", on every path: a list with selection and estimation (integer row positions in data_sf), method and seed.

A rising WSS curve is logged on every path. For a per-level table of criteria, cell support, restart spread and the flat region, see resolution_profile().

How the elbow is read

Points with no cluster structure have a WSS curve close to c/k. The classical rule, the point furthest below the chord from the first to the last k, still finds a "knee" on such a curve on linear axes, at about \sqrt{K_{max}}: 4 at the default max_levels = 12 and 13 at 160, whatever the data. On \log k against \log WSS that curve is a straight line, while separated clusters fall faster than it until there is one cell per cluster and like it after, a bend at the cluster count. The elbow is therefore the k whose \log WSS sags furthest below the straight line joining k = 1 and K_{max} on those axes, and it counts as one only when the sag is at least \log 1.25 (the WSS a fifth below the power law through the ends).

An elongated extent also bends, at about its aspect ratio, because the first cuts go across its long axis; past the threshold that bend is reported as an elbow, and it describes the shape of the extent rather than clusters in it. When locations repeat (stations visited many times), the sweep can reach one cell per distinct location, where the WSS is zero (to within 10^{-12} of the total). That k has no place on log axes and is left out of the line, but the fall to zero is the sharpest bend there is: when the rest of the curve has no elbow, the number of distinct locations is the elbow.

When there is no elbow

With no elbow the function returns NA, so that a count which is not a finding is not passed on as one. The result carries structured = FALSE and the largest sag as sag, and a warning of class spatialkit_no_elbow says why. The count the linear-axis rule gives there is the ladder's and not the data's: about \sqrt{K_{max}}, 3 or 4 cells at the default, close to one mean for the whole layer. The warning carries it as k and the largest sag as sag. on_no_elbow = "warn" returns that count all the same, with the same warning, and "error" stops.

Model-aware criteria

Under criterion = "morans_i" or "combined", with a response_var, the elbow is supplemented with Moran's I of the cell means at each candidate k: the cell means are regressed on the cell-mean predictors (on an intercept alone when no predictor_vars are given) and Moran's I is computed on the residuals over each cell's 8 nearest cells. Under "geometric", the default, response_var and predictor_vars are not read, whether one or both are given.

Moran's I of the cell means tests whether neighbouring cells are independent. It does not measure the autocorrelation the cells leave unexplained in the response, and it does not say how well they represent it: on an autocorrelated response it grows as the cells get finer than the range, because neighbouring cells then resemble each other, and it is close to 0 at about 10 to 20 cells whatever the data, where the neighbour graph is nearly complete.

"morans_i" prefers the candidate with the smallest |z|: the count at which neighbouring cell means stop resembling each other, cells about as wide as the range. Only the elbow's neighbourhood is scored, so the response moves the answer by at most a few cells either side of the elbow. That ranking is by a diagnostic of the cell means and not by a count rule, and it is returned with a warning of class spatialkit_diagnostic_ranking that says so and gives the count ranked first, the first count the statistic could be computed at and the counts scored. select_resolution() refuses the same statistic unless asked with diagnostic = TRUE; here the criterion is asked for by name, so the count is returned and the warning carries the caveat.

"morans_i" ranks on the standardised deviate |z| = |I - E[I]| / \mathrm{sd}(I), using the Cliff and Ord regression residual moments, and not on |I|: both E[I] and Var[I] depend on the number of cells, so |I| falls as k grows whether or not the finer cells capture anything, and a ranking by |I| would prefer the largest candidate for arithmetic reasons alone. The cell-level residuals are OLS residuals by construction, which is the case those moments are derived for, but the derivation also assumes errors of equal variance, and a cell mean over n_j points has a variance proportional to 1/n_j, so z is less reliable where single-point cells sit next to cells of many points. Where structure remains, |z| mixes its size with the number of cells it is measured on, since \mathrm{sd}(I) shrinks as cells are added. Both quantities are reported in the "diagnostics" attribute, as moran_i and moran_z.

Moran's I is computed with an 8-nearest-neighbour weight matrix, so it carries information only once there are more than nine cells. At nine or fewer, every cell is a neighbour of every other, the row-standardised weight matrix is complete, and Moran's I is exactly -1/(k - 1) for any residual vector. The residual moments then give E[I] = I and \mathrm{Var}[I] = 0, so the standardised deviate is 0/0: those candidates return NA and are left out of the ranking of "morans_i". When no candidate in the elbow's neighbourhood clears the floor, the call falls back to the geometric ranking and logs a warning that says so. On points with no cluster structure the elbow sits near \sqrt{K_{max}} and the neighbourhood is the elbow plus or minus max(4, top_n), so the neighbourhood reaches ten cells only from about max_levels = 40. On such a layer resolution_profile(), which scores Moran's z at every level of its ladder, is the model-aware view.

"combined" is the elbow's ranking of the counts around it, best sag first, with Moran's I of the cell means and its z beside it in the diagnostics; Moran's I does not take part in the ranking, and the result is not an estimate of the number of clusters. The sag is read off the sweep's WSS curve, the one the elbow is read from, so with an elbow the first count is the elbow and the counts after it come in order of sag; they can differ from the two neighbours "geometric" returns. An elbow below ten cells is a count Moran's I cannot score: the geometric ranking is returned, the elbow and its two neighbours, with a logged warning, and the diagnostics record it (see Value). When the WSS curve has no elbow (under on_no_elbow = "warn") the sag is flat, every candidate tied, and the window comes out in order of distance from the count the chord rule lands on, which is the geometric order. The k-means re-run at each candidate, whose cells Moran's I is computed on, can land in another optimum than the sweep; its WSS is reported as wss_eval and does not rank. Where Moran's I can be computed at no candidate of a window that reaches ten cells (a constant response, too few cells holding a row with one, or too few in the half that select_on = "split" reads), moran_i and moran_z are NA, the log gives the reason at the WARN level, and the counts are ranked as they would be otherwise.

Use "geometric" when the cell count should follow the clustering of the points, "morans_i" for a ranking by the diagnostic, and resolution_profile() when the response should drive the count.

The k-means sweep

The WSS curve is read for its shape, so it is fitted to be smooth. Every point on it is a k-means local optimum, and with a few random restarts the curve mixes level effects with optimisation noise and can rise from one k to the next. Each k is therefore fitted as the best of 25 restarts seeded by k-means++ (Arthur and Vassilvitskii 2007). A fixed budget of restarts follows Fränti and Sieranoja (2019), and Steinley (2003) shows why the usual handful is not enough; 25 is the package's choice, not a published figure. A curve that still rises somewhere is reported and not refused. A logged warning names the number of rising steps, and the model-aware paths return it as wss_bumps in the "diagnostics" attribute beside wss_spread, the relative spread of WSS across the restarts at each k.

The sweep is plain k-means, whatever the cells are built with afterwards. This function has no partition argument: the elbow is a reading of the sum of squares that plain k-means minimises, and the cells behind Moran's z are that partition's. A count returned here says nothing about density-weighted cells; resolution_profile(), whose cells are of that kind by default, scores counts of those.

To keep memory use and run time bounded for large max_levels, the sweep records only the WSS at each k, without the cluster assignments. Moran's I is then evaluated on demand: k-means is re-run only for a neighbourhood around the elbow (plus or minus 4 by default, or plus or minus top_n if larger). The re-run at each count draws its starts from a stream of its own, seeded before the sweep, so for one set_seed a count gets the same cells, wss_eval and Moran's I in any neighbourhood that holds it, whichever top_n and max_levels set the neighbourhood: a larger top_n adds counts to the neighbourhood and leaves the scores of the others as they were.

Post-selection inference

When the selection reads the response (here, under criterion = "morans_i" with a response), everything estimated afterwards on the chosen cells is estimated on data that already influenced the choice, and its standard errors are post-selection ones: descriptive, not at nominal coverage (Gao, Bien and Witten 2022; Chen and Witten 2023 give the exact selective test for two k-means clusters, the first link of this chain). The exposure is narrower than "the partition was chosen on the response": every partition here is k-means on the coordinates alone, and the response only decides which count is ranked first. It is not zero, because the count determines every cell the downstream standard errors are computed over. Under "combined" the response reaches the diagnostics and not the ranking, which is the same whether or not Moran's I can be computed.

select_on = "split" is sample splitting: the layer is cut into two spatially blocked halves (make_folds(k = 2, method = "block_kfold")), the criteria that read the response (Moran's I on the cell means) read the first half only, and the row positions of both halves come back in the "split" attribute (selection and estimation). The WSS curve and the k-means cells still use every point: they read coordinates alone, and the count is for a tessellation of every point, so it is chosen on that layer's extent and clusters rather than on half of them. Build the tessellation on every point (cells are geometry), but aggregate and fit on data_sf[attr(x, "split")$estimation, ], whose response the selection never saw. That keeps the selection's use of the response out of the estimates, but only as far as the two halves are independent: the split has no buffer, so points near the border between them are correlated with the selection half over the autocorrelation range, and coverage is nominal only when that range is short against the blocks. The price is precision: half the points estimate, and García Rasines and Young (2023) show a contiguous spatial half is less efficient than the exchangeable split the i.i.d. theory assumes, because the two halves are not interchangeable. Two alternatives keep the whole sample: data thinning for count responses (Neufeld et al. 2024) and data fission for Gaussian-like ones (Leiner et al. 2023). Neither is implemented here; the split needs no distributional assumption. Under "combined" the split changes only the rows the diagnostics read. Selection on coordinates alone ("geometric", whatever variables are given) is not exposed in this way, and "split" then changes nothing but the attribute.

The estimation rows cover only the estimation half's blocks, while the cells cover the whole layer, so the estimation rows do not fill every cell. A cell inside the selection half gets none and comes back NA; a cell across the border between the halves is estimated from its estimation-half points alone, and its standard error describes that part, not the cell. Count, per cell, how many of its points are estimation rows, and read inferential results only off cells whose points all are.

References

Arthur, D. and Vassilvitskii, S. (2007). k-means++: the advantages of careful seeding. Proceedings of the 18th Annual ACM-SIAM Symposium on Discrete Algorithms, 1027–1035.

Fränti, P. and Sieranoja, S. (2019). How much can k-means be improved by using better initialization and repeats? Pattern Recognition, 93, 95–112. doi:10.1016/j.patcog.2019.04.014

Steinley, D. (2003). Local optima in K-means clustering: what you don't know may hurt you. Psychological Methods, 8(3), 294–304. doi:10.1037/1082-989X.8.3.294

Gao, L. L., Bien, J. and Witten, D. (2022). Selective inference for hierarchical clustering. Journal of the American Statistical Association, 119, 332–342. doi:10.1080/01621459.2022.2116331

Chen, Y. T. and Witten, D. M. (2023). Selective inference for k-means clustering. Journal of Machine Learning Research, 24(152), 1–41. https://jmlr.org/papers/v24/22-0371.html

García Rasines, D. and Young, G. A. (2023). Splitting strategies for post-selection inference. Biometrika, 110(3), 597–614. doi:10.1093/biomet/asac070

Leiner, J., Duan, B., Wasserman, L. and Ramdas, A. (2023). Data fission: splitting a single data point. Journal of the American Statistical Association, 120(549), 135–146. doi:10.1080/01621459.2023.2270748

Neufeld, A., Dharamshi, A., Gao, L. L. and Witten, D. (2024). Data thinning for convolution-closed distributions. Journal of Machine Learning Research, 25(57), 1–35. https://jmlr.org/papers/v25/23-0446.html

See Also

build_tessellation() and get_voronoi_seeds(), which accept this function's result directly as approx_n_cells and n (the first candidate is used, and the output records that it came from here; an NA from it stops them with a note on where it came from); assign_features_to_polygons() and summarize_by_cell() for the steps that follow.

Other resolution: plot.resolution_profile(), resolution_profile(), select_resolution(), summary.resolution_profile()

Examples

library(sf)
set.seed(1)
# Two clearly separated clusters: the elbow should sit near k = 2
pts <- st_as_sf(
  data.frame(x = 5e5 + c(runif(25, 0, 10), runif(25, 90, 100)),
             y = 5e6 + c(runif(25, 0, 10), runif(25, 90, 100))),
  coords = c("x", "y"), crs = 32632
)
determine_optimal_levels(pts, max_levels = 6)   # 2 1 3: the elbow first

# Points spread evenly have no elbow: NA, with structured = FALSE and a
# warning of class spatialkit_no_elbow that says why (printed here
# wrapped, in place of the warning)
even <- st_as_sf(data.frame(x = 5e5 + runif(200, 0, 100),
                            y = 5e6 + runif(200, 0, 100)),
                 coords = c("x", "y"), crs = 32632)
withCallingHandlers(
  determine_optimal_levels(even, max_levels = 6),
  spatialkit_no_elbow = function(w) {
    writeLines(strwrap(conditionMessage(w), 76))
    invokeRestart("muffleWarning")
  }
)

Project an sf object to a CRS suited to its extent

Description

Returns a spatial object in a projected CRS, so that distances and areas computed on it are close to true. Without target_crs, an object that already has a projected CRS is returned as it is, and lon/lat input is moved to a CRS chosen from its extent; with target_crs, the object is moved to that CRS.

Usage

ensure_projected(x, target_crs = NULL, purpose = c("distance", "area"))

Arguments

x

An sf or sfc object (other objects are returned unchanged).

target_crs

Optional target CRS (sf object, integer EPSG, or crs). Must resolve to a usable CRS via sf::st_crs(); an unusable value (one that resolves to NA_crs_) raises an error, so x is never left unprojected without a word.

purpose

"distance" (default): the candidate that distorts pairwise distances least, which is what ranges, block sizes, bandwidths and length-scales read off the coordinates. "area": an equal-area projection, for densities or rates per cell. For lon/lat input the choice is then made among a Lambert azimuthal centred on the data and an Albers conic (where its parallels do not degenerate or pass a pole), whichever distorts distances less; a UTM zone, which is not equal-area, never enters that comparison, and global coverage gets Equal Earth in place of Web Mercator. For input already projected, the area distortion is measured and a warning is logged above 1 percent; see "Equal-area check". Ignored when target_crs is given.

Details

Without target_crs, only geographic (lon/lat) input is transformed, and the CRS chosen depends on the extent of the data:

Local extents

The UTM zone containing the data's centre (EPSG:326xx north of the equator, EPSG:327xx south). Distances and areas are close to true over a few degrees of longitude, which is the case this package is usually in. The centre is the centroid on the sphere, computed with s2 whatever sf::sf_use_s2() is set to, so data near a zone edge get the same zone in every session.

Wide extents

Once the data reach well beyond the roughly 3 degrees a UTM zone is designed for, a single zone can distort distances by several percent, and that error propagates into variogram ranges, block sizes, GWR bandwidths and GP length-scales. The projection used is then the one with the smallest measured distortion among the zone, a Lambert azimuthal equal-area centred on the data and (where its standard parallels do not degenerate or pass a pole) an Albers conic. Each is scored by projecting representative points of the data and comparing planar with geodesic distances over the pairs at least 1 mm apart. A non-POINT layer is reduced to one point per feature, plus the vertices of its outline when fewer than 40 distinct points remain, so a single study-area polygon is scored too, however many rows repeat it; copies of one location count once, and rows without a finite location are left out. A candidate must place every location of the layer to be used: one under which a vertex of the layer has no coordinates (a UTM zone about 90 degrees or more from its central meridian) gets distance_error NA and is not chosen, and the log line names it. A vertex at a latitude beyond 90, which no CRS places, takes no part in this test. When no candidate places every vertex, Web Mercator (Equal Earth for purpose = "area") is used. The choice, its distance error and the zone's, and this argument are logged (see spatialkit_quiet()); they are not R warnings, so tryCatch(warning = ) does not see them.

Antimeridian

Data straddling longitude 180 have a bounding box wider than a hemisphere. The wrap is detected from the coordinates (one very large gap in the sorted longitudes) and an equal-area projection centred on the true extent is used.

Around a pole

Data spanning more than 180 degrees of longitude with no such gap surround a pole. When every point also lies on one side of the equator (Antarctic stations, a pan-Arctic network), a Lambert azimuthal equal-area centred on that pole is used, provided it measures a smaller distance error than the global fallback. Web Mercator splits such a layer at longitude 180 and stretches it towards the pole. Only the coverage left over, spanning both hemispheres or a low-latitude belt the polar projection fits worse, falls back to EPSG:3857 (Equal Earth for purpose = "area").

Missing CRS

A layer without a CRS is read by the lon/lat test of spatialkit-geometry ("Layers without a CRS"). With no target_crs, coordinates the test takes for degrees are read as EPSG:4326, with a warning, and the rules above then apply; coordinates it declines are left as they are. With target_crs, coordinates the test takes for degrees are read as EPSG:4326 and reprojected to the target, with a warning, and any others have the target stamped on without reprojection. A stamp is a relabel, logged only, so check that the coordinates are in that CRS. Set the CRS on x to avoid either. A target_crs in longitude and latitude is not stamped on coordinates that cannot be in it: an x outside -180 to 360 or a y beyond 90 north or south, in the box of the coordinates that have a location, stops the call with an error that gives the box.

Rows without a location

Such rows (see spatialkit-geometry, "Rows without a location") take no part in the lon/lat test or the choice of a projection. The lon/lat test reads the coordinates that have a location vertex by vertex, so a polygon with one vertex beyond 1e150 is read on its other vertices. A layer in which no row has a location, or each row of which is empty, has no location or has a vertex at a latitude beyond 90, gets Web Mercator (Equal Earth for purpose = "area"). Moved to another CRS, a row without a location comes back empty, in its own geometry type. A row that has a location and that the move cannot place in full comes back empty, or without the vertices the CRS cannot place, with a warning of class spatialkit_rows_unplaced that names the rows (rows on the condition). With the projection chosen here that happens only at a coordinate no CRS places, such as a latitude beyond 90; with a target_crs, wherever that CRS cannot place the layer.

target_crs overrides all of this. Pass it whenever you need a specific, reproducible projection: comparing runs, matching an existing layer, or fixing the units that make_folds()'s block_size will be interpreted in.

A layer that mixes XY and XYZ (or XYM) geometries is returned in XY when it is transformed, with a warning of class spatialkit_zm_dropped, and the projection is chosen from the layer in XY; see spatialkit-geometry, "Mixed dimensions, Z and M". A layer that is not transformed is returned with its own geometry.

Value

x in target_crs when one is given. Otherwise x in the projected CRS chosen here, as it came when it already had a projected CRS, or without a CRS when it had none and the lon/lat test declined it (see "Missing CRS"). Two attributes record how the CRS was reached:

crs_choice

Present when a projection was chosen here (lon/lat input, no target_crs): a data.frame with one row per projection considered, holding name, crs (its definition), the measured worst-case distance_error (relative, over sampled pairs; NA where it could not be measured) and chosen. The figure is measured for the single candidate on the paths where no comparison runs (a UTM zone on a local extent, the equal-area projection chosen for a layer straddling the antimeridian). NULL when no local projection was chosen here: input that already had a projected CRS, a target_crs you supplied, or an extent no local projection fits, which falls back to Web Mercator or Equal Earth.

crs_assumed

On input without a CRS: "EPSG:4326" when the lon/lat test took the coordinates for degrees, "none" when it declined. The attribute is also read on the way in: an object already carrying "none" is returned as it is, without the test, which is how a predict() method replays a fit's decision so that a subset of the training rows is not judged differently from the whole.

Equal-area check

Under purpose = "area", input that already has a projected CRS is returned as it is, but its area distortion over the extent is measured and logged as a warning when it exceeds 1 percent. The measure is the spread of planar-to-geodesic area ratios over probe polygons. The probes are the layer's distinct polygons (exact copies of a polygon count once). A 6 by 6 grid over the bounding box is used instead for a layer without polygons, a layer of one distinct polygon, which gives one ratio and no spread, and a layer with a polygon s2 cannot measure in degrees (edges that cross, a spike) or that sf::st_is_valid() rejects in its CRS (a hole outside its shell), whose planar area is not the area it encloses. When the grid gives no figure either (a single point, a line along one axis), a warning says that the distortion could not be measured. An equal-area projection still shows some spread, from the sphere the geodesic areas are computed on against the ellipsoid the projection uses. summarize_by_cell() applies the same check before it computes a density.

See Also

spatialkit-geometry for how input geometry and CRSs are read.

Other data preparation: [.spatialkit_rows(), coerce_to_points(), harmonize_crs(), prep_model_data(), spatialkit-geometry

Examples

library(sf)
pts_ll <- st_as_sf(
  data.frame(lon = c(9.1, 9.2), lat = c(48.7, 48.8)),
  coords = c("lon", "lat"), crs = 4326
)
# A local extent gets the containing UTM zone; the zone's measured
# distance error over the extent travels with the result.
st_crs(ensure_projected(pts_ll))$epsg  # 32632
attr(ensure_projected(pts_ll), "crs_choice")

# A continental extent is scored against the zone and may get an
# equal-area projection instead.  The choice is logged with its distance
# error and the zone's, not raised as an R warning (see ?spatialkit_quiet);
# crs_choice holds every candidate scored.
wide <- st_as_sf(
  data.frame(lon = c(-120, -70), lat = c(30, 48)),
  coords = c("lon", "lat"), crs = 4326
)
wide_p <- ensure_projected(wide)
st_crs(wide_p)$proj4string
attr(wide_p, "crs_choice")[, c("name", "distance_error", "chosen")]

# target_crs overrides the choice.
st_crs(ensure_projected(pts_ll, target_crs = 3035))$epsg  # 3035

# For densities per cell the CRS has to be equal-area.  Two candidates are
# scored, an Albers conic and a Lambert azimuthal, both centred on the data,
# and whichever distorts distance less over the extent is used: here Albers.
st_crs(ensure_projected(pts_ll, purpose = "area"))$proj4string

Give cells IDs that follow their position

Description

Numbers the polygons of a layer from west to east, and from south to north among polygons at the same longitude, by a representative point of each (its centroid by default) taken by default in EPSG:4326 (transform_for_sort); ties go to the smaller area. The same polygons get the same IDs whatever their row order or projection, except as transform_for_sort says, so use it before joining summaries made from different runs.

Usage

ensure_stable_poly_id(
  polygons_sf,
  id_col = "poly_id",
  method = c("centroid", "surface_point", "bbox_center"),
  make_valid = TRUE,
  transform_for_sort = 4326
)

Arguments

polygons_sf

An sf or sfc object containing polygonal features. Polygons that mix XY and XYZ (or XYM) geometries are keyed without Z and M, since sf reads a layer in the dimension of its first geometry (see make_valid for the rows returned).

id_col

Name of the ID column to write. Default "poly_id". An existing column of that name is replaced.

method

The point each polygon is sorted by: "centroid" (default), "surface_point" (a point inside the polygon, sf::st_point_on_surface()) or "bbox_center" (the centre of its bounding box).

make_valid

Logical; apply st_make_valid() first. Default TRUE. The copy the sort key is measured on is repaired as well, after it has been transformed (see Details); with FALSE neither is. On a layer in longitude and latitude with sf::sf_use_s2() on, the repair is s2's rebuild, which can move the corners of a polygon it rebuilds and return a POLYGON as a MULTIPOLYGON, so only the rows s2 or GEOS does not call valid are rebuilt, and the other rows are returned as they arrived. s2's rebuild does not split crossing edges, so a row it leaves invalid (crossing edges, parts that overlap) is repaired by GEOS on its coordinates, as with s2 off. A projected layer, or one in degrees with s2 off, is repaired by GEOS. The rows returned are the repaired polygons, made in x and y whenever polygons_sf carries Z or M: polygons that mix XY and XYZ (or XYM) geometries, and polygons that all carry Z or M, are repaired in XY and returned in XY, with a warning of class "spatialkit_zm_dropped". With FALSE the rows come back with the geometry they arrived with, Z and M included. An empty polygon in Z or M has no coordinates to drop and raises no warning. An empty polygon is not repaired and comes back as it arrived. A ring of fewer than four points encloses no area and is dropped before the repair: GEOS stopped on a ring of two, and in degrees sf reads such a ring as the whole globe. A row the repair turns into a collection keeps its polygonal parts, and a row it leaves with no polygon at all (a ring with no area, which GEOS turns into lines or an empty collection) comes back as it arrived, with one warning of class "spatialkit_cells_degenerate" that gives its rows of polygons_sf (rows).

transform_for_sort

CRS used only for computing sort-key coordinates. Default 4326. This is the whole mechanism by which the IDs are stable (sorting in one common CRS is what makes the same layer get the same IDs whichever projection it arrives in), so if the transform fails the function says so rather than quietly sorting in the input's own CRS. A transform that cannot place every polygon with a location (a projected layer far outside its CRS's area, whose rows PROJ returns empty) counts as failed in the same way: the whole layer is sorted in its own CRS, and the log says so. In a geographic CRS the sort key is rounded to 7 decimal degrees (about 1 cm) before ordering, so the floating-point noise of a round trip through a different projection does not reverse two neighbouring cells, except where two cells' centres lie within about that step of the same longitude, as fine cells stacked north-south near a projection's central meridian do. No rounding step removes that, so to match cells computed in different projections, join them on geometry rather than on the ID. The key is computed on the sphere (s2) whether or not sf::sf_use_s2() is on, so the session setting does not change the IDs. Set to NULL to sort in the input CRS, which gives IDs that are reproducible but not comparable across projections.

A key in a CRS that is not geographic (with NULL, for a layer without a CRS, after a failed transform, or in a projected sort CRS) is rounded to a step that grows with the magnitude of the coordinates: the power of two at or above 2^-44 of the layer's largest coordinate, never under 1e-7 of its unit, so a layer within about 1.7e6 units of its origin is rounded to 7 decimals. Keys that tie at that step are ordered by keys rounded at the step of each polygon's own largest coordinate. Cells 1e12 units out are then not ordered by the last bits of their centres, which doubles do not hold there, and take the order they have at the origin.

Details

A feature that is valid in its own CRS is not always one s2 can measure. Only the vertices are transformed to the sort CRS, and on the sphere they are joined by great-circle arcs, so a long edge that is straight in the layer's CRS and passes about a metre from another vertex of the same ring can end up on the other side of that vertex. The ring then crosses itself, and s2 refuses it. The repair of the sort copy does not split crossing edges, so a feature s2 still refuses is handled on its own. Its sort copy is repaired a second time with the crossing edges split. If s2 refuses that as well, or with make_valid = FALSE, which asks for no repair, the feature's centroid and area are measured as plane geometry in the layer's own CRS and the centroid is transformed to the sort CRS. With the methods "surface_point" and "bbox_center" only the area needs this, because those points are not taken with s2.

The function warns once, saying how many features took each route. Their keys are close to the spherical ones and not equal to them, so a feature measured in the plane can sort on the other side of a neighbour whose centre is nearly at its own longitude. Every other feature's key is unaffected, and the geometry returned is never the sort copy.

A polygon of a layer in a geographic CRS with a vertex at a latitude beyond 90 degrees is no place on the Earth. It is keyed as an empty polygon is, after every polygon with a location, it is not repaired and comes back as it came, and a warning of class spatialkit_lat_beyond_90 gives its rows of polygons_sf (rows).

Value

An sf polygon layer re-ordered, with sequential IDs in id_col. Non-polygonal rows are dropped (with a warning), so the result can have fewer rows than the input; if no polygonal rows remain, an error is raised.

See Also

Other cell building: build_tessellation(), clip_target_for(), create_grid_polygons(), create_grid_polygons_cached(), create_voronoi_polygons(), get_voronoi_seeds(), plot_tessellation_map(), voronoi_seeds_kmeans(), voronoi_seeds_random()

Examples

library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
  c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
g <- create_grid_polygons(bnd, target_cells = 9)
# Reverse the rows and re-derive the IDs: the same cell gets the same ID,
# which is the property a row-position ID does not have.  The check joins
# the two layers on geometry, because comparing sorted ID vectors would
# pass for any two permutations of 1:9.
fwd <- ensure_stable_poly_id(g)
rev <- ensure_stable_poly_id(g[nrow(g):1, ])
same_cell <- match(st_as_text(st_geometry(rev)), st_as_text(st_geometry(fwd)))
all(rev$poly_id == fwd$poly_id[same_cell])

Estimate the spatial autocorrelation range from data

Description

Fits an exponential variogram model with a nugget and returns the effective range: three times the fitted range parameter, where the semivariance reaches about 95 percent of the sill. Beyond it two observations are close to uncorrelated, so it is the distance a block or a buffer has to exceed. The range is in the units of the projected CRS the variogram is fitted in. Pass it as the block_size of make_folds(), or let make_folds(auto_range = TRUE) estimate it, so that the blocks are at least as wide as the autocorrelation range.

Usage

estimate_sac_range(
  points_sf,
  response_var,
  predictor_vars = NULL,
  n_max = 5000L,
  cutoff = 0.5,
  range_frac = 1,
  seed = 123L,
  detrend = c("ols", "reml"),
  reml_max_n = 400L,
  keep_directional_fits = FALSE,
  lags = c("adaptive", "equal"),
  n_lags = 15L,
  structure_alpha = 0.05
)

## S3 method for class 'sac_range'
print(x, ...)

Arguments

points_sf

An sf layer of points. A lon/lat layer is projected first (spatialkit-geometry); other geometry is reduced to representative points, and Z and M are dropped, since gstat::variogram() would otherwise measure distances in three dimensions. Rows without a location are dropped with a logged count.

response_var

Name of the response column. Rows where it is missing or infinite are left out before anything else is done, so they take no part in the choice of projection for lon/lat input and do not use up the n_max subsample. For a count or other response whose variance tracks its mean, see the section "Count and other non-Gaussian responses": the range is still estimated, but it is less reliable than for a Gaussian response.

predictor_vars

Optional character vector of predictor column names. When given, the trend on these predictors is removed first and the variogram describes the residual autocorrelation, the part a spatial model has to handle once the covariates have done their work. How the trend is removed is set by detrend (see the section "Detrending and the residual-variogram bias"). Rows whose response or predictor is missing or infinite are left out of that fit, and so of the variogram, with a logged count; when that leaves fewer than 30 rows, or fewer than 30 distinct locations, the result is the unclassed NA that says how many were left (see Value). When no row has every predictor (one is missing on every row) no trend can be fitted, and the variogram is of the raw response, with an R warning and detrended set to FALSE. Where nothing is fitted then either (fewer than 30 distinct locations, a constant response, or points with no extent), the result is the NA with its reason, and there is no such warning.

n_max

The most points the variogram is computed on, at least 30; Inf for no limit. Variogram estimation is O(n^2), so this bounds the run time. A layer with more rows that carry a value is cut to a seeded random subsample of this size, drawn after the rows with nothing to model are left out and with the rows in a fixed order, so the subsample does not depend on how the layer is sorted. The counts are returned as the attributes n_used, n_missing and n_subsampled. The floor of 30 distinct locations applies to the rows the variogram is computed on, and a subsample of a layer with many rows a location can hold fewer locations than the layer. When the layer itself has 30 locations or more and the subsample holds fewer, the reason of the NA says "of the n_max subsample", and a larger n_max keeps more of them; when the layer has fewer than 30, the reason gives the layer's counts.

cutoff

Fraction of the largest distance between two points to use as the variogram lag cutoff, above 0 and at most 1. That distance is the farthest pair, found on the convex hull, not the diagonal of the bounding box, which depends on how the axes are oriented. Default 0.5.

range_frac

A positive number, default 1. A fitted range beyond range_frac * cutoff * max_dist (at the default, beyond the longest lag the empirical variogram was fitted over) is treated as unidentified and the result is NA. A model fit gives a finite number even when the variogram never reaches a sill, and such a value extrapolates past the observed lags; passed to make_folds(auto_range = TRUE) it would collapse the block grid to a single block. Raise range_frac to accept ranges extrapolated beyond the fitted lags. The bound does not guarantee room for two blocks: at the defaults it is half the farthest-pair distance, about 0.71 of the side of a square layer, and a block grid needs a range below half the width of the bounding box in one direction or the other. An accepted range between the two leaves make_folds(auto_range = TRUE) room for a single block of that size (see its auto_range argument). Lowering range_frac to fit the grid would turn those estimates into NA and the blocks into geometric ones smaller than the range.

seed

RNG seed for the n_max subsample, the reml_max_n subsample, and the draw of one row a location that detrend = "reml" makes on a layer with repeat visits. With a seed, the caller's random stream is restored afterwards. Default 123, so the same layer gives the same range on every run; NULL leaves the draws unseeded, and another number shows how sensitive the estimate is to the subsample. It has no effect where nothing is drawn. On a layer whose rows crowd onto few locations the subsample can also decide whether 30 distinct locations remain, and so whether a range is estimated at all (see n_max).

detrend

How the trend on predictor_vars is removed; ignored when there are none. "ols" (default) fits it by ordinary least squares and fits the variogram to the residuals, which underestimates the range (see the section "Detrending and the residual-variogram bias"). "reml" fits the trend and an exponential-plus-nugget covariance together by residual maximum likelihood with nlme::gls(), returns the REML range, and attaches the empirical variogram of the REML residuals for inspection. It needs nlme, costs O(n^3) and so runs on at most reml_max_n points, and takes one row a location. When it is not fitted (no nlme), cannot be fitted (the design of the trend cannot be built, as on a factor with one level) or does not converge, the "ols" path runs instead with an R warning that says which. The start of the fit is chosen from the profile REML likelihood on a grid of ranges and nugget proportions, and when more than one start is fitted the fit with the largest log-likelihood is kept.

reml_max_n

A whole number of at least 30, default 400. With detrend = "reml", the trend and covariance are fitted on a seeded random subsample of this many points when the layer has more, and the fitted trend is then removed from every point. The fit takes one row a location: where a location has several rows (repeat visits), one of them is drawn at random under seed, so the nugget fitted is the variance between visits and not that of their minimum or of their mean. Raise it for a better-determined fit at a cubic cost.

keep_directional_fits

TRUE or FALSE, default FALSE. Attach each direction's empirical variogram and fitted model as directional_fits. The four variograms are most of the object's size; the numbers read from them (directional, directional_fitted, directional_status, anisotropy) are attached either way, and plot() draws the all-pairs variogram from its own attribute.

lags

How the lags are binned: "adaptive" (default) or "equal"; see the section "The lags".

n_lags

A whole number from 5 to 100, default 15. With lags = "equal", the number of bins. With lags = "adaptive", the most bins spaced geometrically past the first; fewer are used when that many would hold under 30 pairs each.

structure_alpha

The level of the test for spatial structure, above 0 and at most 1; default 0.05. A layer whose adjusted p-value is not below it gets no range. 1 switches the refusal off; the test is still computed and attached.

x

A sac_range object, for print().

...

Ignored.

Details

The layer is first tested for spatial structure, and a range the data cannot identify is refused: the answer is then NA, with the reason and the evidence attached (see Value). plot.sac_range() draws the variogram behind the estimate, and sac_nugget() reads its nugget.

Value

A single number, in one of three shapes, each of which behaves as an ordinary number. A range that was fitted, and a range fitted and refused, are of class sac_range; a call that could fit nothing returns an unclassed NA. The attributes and the class do not affect is.na() or is.finite(), so code that tests for a missing range treats all three alike.

Success

A positive effective range in the units of the projected CRS, with the fit attached as attributes:

  • crs: the projected CRS the variogram was fitted in, which gives the unit of the range; max_dist and cutoff_dist: the farthest pair and the lag cutoff.

  • variogram: the empirical variogram, in the units of the response's variance; variogram_model: the fitted model, in gstat's layout, or with detrend = "reml" one built from the REML parameters.

  • lags, lag_boundaries and lag_fallback: the binning behind the result, its upper bin edges, and TRUE when adaptive lags were asked for and the equal-lag result is returned (see the section "The lags").

  • first_lag: the mean separation in the first bin, the shortest lag resolved, from which the nugget is extrapolated; bins_below_range: how many bins lie inside the fitted range (with fewer than three, the split between nugget and structure rests on very little).

  • structures and short_range: how many structures the model has besides the nugget, and the effective range of the short one when there are two (NA otherwise).

  • nugget (the model's nugget variance), nugget_at_bound, nugget_floor, short_lag_semivariance, short_lag_pairs, short_lag_dist, zero_lag_semivariance and zero_lag_pairs: the nugget and the evidence to judge it by, described in sac_nugget(). zero_lag_semivariance is NA and zero_lag_pairs 0 when no location has two rows.

  • structure_p, morans_i and structure_test: the adjusted p-value of the test for spatial structure, Moran's I on the 8 nearest neighbours, and the statistic, z and p for each neighbourhood size.

  • directional: the ranges at azimuths 0, 45, 90 and 135 degrees, named by azimuth, NA where that direction's fit was unusable; directional_status: per azimuth, why a direction is NA in directional: "ok", "over_cutoff" (its range ran past the largest lag fitted), "not_converged" (its fit has no minimum inside the ranges searched) or "no_fit" (a flat variogram, or too few bins); directional_fitted: the range each direction's fit reported, usable or not, so a refused directional range stays recoverable; directional_fits: with keep_directional_fits = TRUE, a list by azimuth of each direction's empirical variogram and fitted model (NULL where there is none), and NULL otherwise; anisotropy: the largest directional range over the smallest; anisotropy_used: always FALSE, since the all-pairs fit is the estimate.

  • detrended: whether the variogram is of the residuals on predictor_vars (TRUE) or of the raw response. A predictor that is not a column is an error, and a detrending fit that fails warns and falls back to the raw response with this set to FALSE. detrend_method: "ols" or "reml" when detrended, NA otherwise. reml: with detrend = "reml", a list with n_used, subsampled, nugget_prop, sigma2, logLik (the REML log-likelihood of the fit kept), logLik_gain (its gain over the same trend with independent errors) and n_fits (the starts fitted); NULL otherwise.

  • n_used, n_missing and n_subsampled: the points the variogram was computed on, the rows left out for a missing response or predictor, and the rows the n_max subsample left out.

Rejected range

NA_real_ when no range is identified. It is classed sac_range as well, so it prints as NA without dumping its attributes, and it carries every attribute of a success (the evidence for the rejection), plus rejected_range (the value that was refused, NA when none was fitted) and rejected_reason, one of:

  • "no spatial structure detected at the nearest-neighbour scale": the test in the section "The test for spatial structure". The model attached is a pure nugget at the variance of the modelled variable, and nothing fitted is handed on.

  • "the empirical variogram is flat: no spatial structure at the lags resolved": no model with a range fits the variogram better than a constant. The model attached is that constant, a pure nugget.

  • "empirical variogram decreases with distance": the semivariance falls over the shorter lags (a net fall of more than 15 percent of the mean semivariance there, weighted by pairs), which is the shape of a periodic, hole-effect structure or of a variance that differs between a dense cluster and the rest of the layer. Sampling noise in the short-lag bins of a small sample can make that fall too.

  • "fitted range exceeds the largest lag fitted": the range is past range_frac * cutoff * max_dist (see range_frac). An unremoved trend ends here when the variogram rises past the fitted lags; a milder trend only lengthens the fitted range and passes, which is what predictor_vars is for.

  • "fitted range is below the shortest lag fitted": too few pairs of points lie inside the range to identify it, because it is shorter than the shortest lag the empirical variogram resolves (first_lag) or, with detrend = "reml", than the distance within which 30 pairs of the points the REML fit used lie, when that is shorter (the REML range is fitted to the point pairs, not to the bins). A structure that short cannot be told from a nugget. range_floor holds the distance the refused range fell short of.

  • "fitted range is non-positive or non-finite".

  • "no variogram model could be fitted: fewer than three lag bins hold point pairs". variogram_model is then NULL and nugget is NA.

The reason names one ground for the refusal, in the order above. attr(attr(range, "variogram_model"), "converged") says one thing more about the model: it is FALSE when the least-squares criterion is still falling at an edge of the ranges searched (a variogram with no sill inside four cutoffs), and the nugget and sill of such a model are that edge and not fitted values. For a model with two structures the flag is that of the equal-lag fit the long range came from: when that fit has no minimum, the long structure's range and partial sill are the edge of its search and the flag is FALSE, although the nugget and the short structure were fitted at the adaptive lags. A model built from REML parameters carries no such attribute. resolution_profile() reads it, and takes no nugget from a model marked FALSE.

No fit

An unclassed NA_real_ when estimation could not be attempted at all, whose one attribute, rejected_reason, says why: "package 'gstat', which the variogram needs, is not installed", "<n> points, fewer than the 30 a variogram range is estimated from", "<n> point(s) with a finite value to model, fewer than the 30 a variogram range is estimated from" (the count is of the whole layer's rows with a value), "<k> distinct location(s) among the <n> point(s) with a finite value to model, fewer than the 30 a variogram range is estimated from" (rows that share a location count once; when the layer has 30 or more locations and the n_max subsample kept fewer, the counts are the subsample's and "of the n_max subsample" stands in place of "with a finite value to model"), "the response is constant", "the residuals on predictor_vars are constant: the predictors explain the response exactly" or "the points have no extent (the largest distance between them is zero or could not be computed)". Nothing is fitted, so none of the other attributes exist: no variogram, variogram_model or rejected_range, which is what tells it from a range that was fitted and refused.

What is estimated

The estimate is the omnidirectional (all-pairs) fit of an exponential model with a nugget. Only the exponential family is fitted. On fields smoother than exponential that makes the range long, and blocks sized from it come out larger: they still hold the test points at least the field's range from their training data, which blocks sized from a short range do not. Choosing the family by the smaller weighted sum of squares would correct a spherical field but send exponential fields short, and blocks sized from them smaller than the range.

The model is fitted without iteration. The criterion is gstat's weighted least squares (weights N / h^2) on lags divided by the cutoff. For each trial range the nugget and the partial sill are solved exactly, both kept at or above zero, and the range is found by a search over a logarithmic grid from a quarter of the first lag to four cutoffs, refined in one dimension. There is no start value, no iteration limit and no fit that fails to converge.

The test for spatial structure

A variogram model can be fitted to anything, and on a layer with no structure the fit returns a finite range for a large share of draws. So Moran's I of the modelled variable is computed first, on its 2, 4, 8 and 16 nearest neighbours, each standardised with the moments that fit the variable (those of regression residuals when predictor_vars are given), and the smallest one-sided p-value is multiplied by four. When that adjusted p-value is not below structure_alpha, the result is NA with rejected_reason "no spatial structure detected at the nearest-neighbour scale", a pure-nugget model and no fitted range. The test uses no random numbers, and structure_p, morans_i and structure_test are attached to every classed result. Its power is limited where few neighbours lie inside the range, so a short range on a sparse layer can be refused; structure_alpha = 1 switches the refusal off.

Neighbours tied at the k-th distance, those whose squared distances are within one part in ten million of the k-th's, share its slot's weight equally, as in residual_morans_i(). The graphs then do not depend on the unit or the origin of the coordinates wherever the doubles hold them to better than about one part in 1e8 of the distances between neighbours. Where they do not, and a distance lies past a tie by less than that rounding, the call warns with class "spatialkit_xy_imprecise" (see spatialkit-geometry), as it does for the nearest other location of the short-lag semivariances. The results are those the coordinates as stored give.

Rows that share a location (repeat visits) are one place and not each other's neighbours, so on such a layer the test is made on the means of the locations: it asks whether locations near each other are alike, which a location's own effect, however large, does not answer. With very unequal numbers of visits the p-value is approximate. For the same reason a layer needs 30 distinct locations, not only 30 rows; below that the result is the unclassed NA whose reason gives the count (see Value), and nothing is fitted. Five locations visited 20 times give ten pairs of locations and five means, from which neither a range nor a verdict on structure can be read. Two rows are at one location when both their coordinates are equal to the last bit after the projection, so repeat visits recorded with slightly different coordinates count as separate locations; round the coordinates first to pool them.

The lags

With lags = "adaptive" (the default) the first bin runs from zero to the distance within which the closest max(50, n / 4) pairs of distinct locations lie, and up to n_lags further bins are spaced geometrically from there to the cutoff; a bin holding fewer than 30 pairs is merged with the next. The short lags, which the nugget and a short range are read from, are then resolved at the spacing of the points. With lags = "equal" there are n_lags bins of equal width out to the cutoff, as gstat bins by default. Each is cutoff * max_dist / n_lags wide; a structure shorter than the first of them is counted as nugget, and the range fitted is that of whatever longer structure the layer has. Below about a hundred points neither binning resolves much, and the adaptive bins bring no gain.

The adaptive lags put little weight on the long ones, and a weak, long structure under much noise can be clear at equal lags while the adaptive fit runs past the largest lag. So when the adaptive range is refused as past the fitted lags and the equal-lag fit has a range it would itself return, the result is the equal-lag one, whole, as lags = "equal" gives it, with lags saying "equal" and lag_fallback set to TRUE. Its nugget is then the equal-lag nugget. No other refusal falls back.

Structure at two scales

One structure fitted to lags that resolve the spacing of the points follows the shortest structure of the layer. A layer can have a weaker structure several times longer as well, and blocks sized from the short one would leave the long one across folds. So with lags = "adaptive" the equal-lag fit is made too, and when its range is at least twice the adaptive one, a model with a nugget and both structures, at those two ranges, is fitted to the adaptive variogram. That model is returned (structures is 2 and short_range holds the range of the short structure) and the range is the long one, unless the long structure carries under 3 percent of the model's semivariance at the largest lag; then the single structure stands.

The bar is low because the two mistakes are not alike. A long structure that is missed is lost: the range returned is the short one alone. One that is believed in error returns the equal-lag range, which is too long, and short_range still holds the short one. When the equal-lag range is one that lags = "equal" would itself refuse (past the fitted lags, as under an unremoved trend), the model with it is refused as well, the answer is taken away and not lengthened, and the long structure has to carry 10 percent. The nugget comes from the adaptive lags either way. A long structure whose equal-lag range is under twice the adaptive one is not separated: the range is then that of the single fit, which lies between the two.

Directional ranges and anisotropy

Directional variograms are fitted as well, at azimuths of 0 (north-south), 45, 90 (east-west) and 135 degrees, each with a tolerance of 22.5 degrees either way. Those four windows tile all 180 distinct azimuths once, and their ranges are returned in the directional attribute, with their largest-over-smallest ratio in anisotropy. They are a diagnostic and never the answer, for two reasons. Each direction sees about a quarter of the point pairs, and the maximum of four quarter-sample fits is biased upward. And the windows are fixed to the coordinate axes, so any answer built from them changes when the layer is rotated, which a property of the field must not do. The all-pairs fit is the best-powered estimate available and does not change under rotation. When it identifies no range, no range is returned: the largest directional range does not stand in for it.

A direction whose variogram is flat or has too few bins, whose range runs beyond the longest fitted lag, or whose fit has no minimum inside the ranges searched is left out and recorded as NA in directional.

Where a field is known to be anisotropic and blocks are to be at least as large as its autocorrelation range in every direction, size them from the longest directional range yourself. Read it from directional_fitted, not directional: on a strongly anisotropic field the major axis is the direction most likely to run past the fitted lags, which leaves it NA in directional, so max() of that is NA, or with na.rm = TRUE the second-longest range. Check directional_status first: a major axis marked "over_cutoff" has no identified range at all, and a longer cutoff or make_folds(method = "nndm") is the way on. A ratio above 1.5 is written to the package log at INFO level with that advice, which reaches the session log file but not the console (the ratio passes 1.5 on most isotropic fields too).

The nugget

The model is fitted with a nugget. A nugget-free model forces the curve through the origin, and on a measurement that has a nugget the N / h^2 weights buy that constraint by collapsing the range. The fitted nugget can sit at its lower bound of zero; the result then carries nugget_at_bound = TRUE, and sac_nugget() lists what else is attached to judge a nugget by.

Two rows at one location are a pair at zero separation and are in no bin, whichever the binning, since the variogram and the model describe positive separations. Their semivariance, the variance between visits to a location, is returned on its own as zero_lag_semivariance. The nugget fitted to the variogram is not let under it when the layer has 30 or more rows beyond one a location to estimate it from; a model from detrend = "reml" takes no such floor.

Detrending and the residual-variogram bias

Fitting a variogram to the residuals of a least-squares trend underestimates both the sill and the range, because the trend fit absorbs part of the long-wavelength spatial variation (Lark, Cullis and Welham 2006). Blocks sized from that range are then narrower than the field's range, and hold the test points less far from their training data than range-sized blocks are meant to. How large the effect is depends on how smooth the trend terms are in space and on how many there are: it is small for ordinary covariates and large for trend surfaces in the coordinates. Iterating between a GLS trend fit and a variogram refit (Neuman and Jacobson 1984) recovers only part of it, because the variogram of GLS residuals is biased too. REML fits no variogram to residuals, which is why detrend = "reml" returns its own range estimate. Its price is a single family (exponential with nugget), a cubic cost in n, and a somewhat wider sampling spread. The default is "ols"; a script that detrends on smooth or coordinate-based terms should pass detrend = "reml", or size its blocks with a margin above the range returned, to make up the shortfall. Detrending removes a trend the predictors explain; it does not make an unidentified range identified.

Count and other non-Gaussian responses

The empirical variogram assumes second-order stationarity: a variance that is the same everywhere, so that semivariance depends on separation alone. A count response breaks that assumption by construction, because its variance tracks its mean, and so does any response with a mean-variance relationship (rates, proportions, skewed amounts). On such data the variogram mixes distance-dependence with mean-dependence: where the mean is high the semivariance is inflated whatever the distance, which flattens the curve and can lengthen or shorten the apparent range depending on where the high-mean areas sit.

Detrending on predictor_vars removes the part of the mean the covariates explain, but it does not fix the variance structure: the residuals of an OLS fit to a count still have a variance that tracks the fitted mean. The remedy is a variogram of Pearson residuals from a model in the right family, which this function does not compute. Treat the range from a count response as no more than an order of magnitude, since it can come out long or short, and prefer make_folds(method = "nndm"), which needs no fitted range.

Numerical behaviour

The result is a function of the data alone. The same layer gives the same answer whatever the unit of the response or of the coordinates and whatever the order of its rows, and a change in the last bits of the values changes the answer by about as much.

The rows are sorted by their coordinates as supplied, then by the response and the predictors, before anything else, so the projection chosen for lon/lat input, the n_max subsample and the pair sums do not depend on their order. First coordinates within 1e-7 of the diagonal of the points' bounding box count as one column, sorted by the second coordinate, so a lattice whose first coordinates in one column differ in their last bits after a change of unit or origin gets the same order and the same subsample in each. Rows that share a location are therefore in the order of their values, and no step treats the first of them as special.

The variogram is computed on the standardised variable. A response is called constant only when its standard deviation is under 1e-12 of its largest absolute value, which no change of unit alters, and the values centred on their median and scaled have a standard deviation of at most three units in the last place of that value. Residuals of the predictors are called constant when they are no more than the rounding of the regression, taken on the size of the fit's terms, or three such units of the response, whether or not the floor finds spread in them, as the test for cp of resolution_profile() reads them. So 1e15 plus a spread of 1, stored to an eighth, is not constant, and the residuals of a response the predictors fit exactly are, on a predictor far from 0 (a northing) as well. A response that loses its spread on the raw values is centred on its median before the predictors are fitted to it and before the test for spatial structure, neither of which changes under a shift; so is a response whose OLS residuals on the raw values lose their spread (1e15 plus 1e5 times a predictor plus a spread of 1, on that predictor).

The test for spatial structure, the semivariances and the REML fit are taken on the response divided by a power of two near its spread. A response near 1e-160 or 1e160, whose squares lie past what doubles hold, then gives the range, the test and the folds it gives in ordinary units. The variogram, the nugget, the short-lag semivariances and the REML variance are returned in the response's units squared, which near 1e160 are Inf and near 1e-160 are subnormal doubles that keep few bits, or 0. A response so far from zero that doubles there are spaced more than a millionth of its standard deviation apart (a standard deviation of 1 at about 1e10, 2^33, or beyond) is read as stored, rounded to that spacing, with a warning of class spatialkit_response_imprecise.

With detrend = "reml" the REML fit reads the coordinates of the rows it uses centred on the middle of their bounding box, divided by its diagonal and rounded to 2^-30 of it, and the response and each numeric predictor centred on the middle of their range on those rows, divided by it and rounded the same way. Its range, coefficients and variance are taken back to the layer's units. Where the REML range is not identified the likelihood is flat, and whether the fit converges or falls back to OLS is set by the last bits of the coordinates, the response and the predictors; in that frame it does not depend on their units or origins. A value within its own rounding noise of the middle of a step, about a billionth of the diagonal or the range, can still fall on either side of it.

Printing

print() shows the effective range as a plain number, and beneath it the directional ranges and their ratio when the directional fit is available. A direction whose fit was unusable is labelled with why (directional_status) and the range its fit reported (directional_fitted) when the object carries them, and unidentified otherwise. A last line names the unit and the CRS the range is a length in (attr(x, "crs"), which for lon/lat input is the projected CRS the estimate chose; for a layer with no CRS, it says the range is in that layer's own coordinate units), and whether the variogram is of the response or of its residuals on predictor_vars (detrended, detrend_method). print() returns x invisibly.

References

Cliff, A. D. and Ord, J. K. (1981). Spatial Processes: Models and Applications. Pion, London.

Lark, R. M., Cullis, B. R. and Welham, S. J. (2006). On spatial prediction of soil properties in the presence of a spatial trend: the empirical best linear unbiased predictor (E-BLUP) with REML. European Journal of Soil Science, 57(6), 787–799. doi:10.1111/j.1365-2389.2005.00768.x

Neuman, S. P. and Jacobson, E. A. (1984). Analysis of nonintrinsic spatial variability by residual kriging with application to regional groundwater levels. Mathematical Geology, 16(5), 499–521. doi:10.1007/BF01886329

See Also

sac_nugget() for the nugget behind the estimate, and plot.sac_range() to see the variogram the estimate rests on.

Other spatial autocorrelation: plot.sac_range(), sac_nugget()

Examples


library(sf)
# A Gaussian random field with an exponential covariance: range parameter
# 100, so the true effective range is 3 x 100 = 300, plus a small nugget.
set.seed(9)
n <- 150
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(0.1, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
r <- estimate_sac_range(pts, response_var = "z")
r                            # the effective range, in metres
attr(r, "directional")       # the four directional ranges
attr(r, "variogram_model")   # the fitted model behind it
attr(r, "nugget_at_bound")   # TRUE: the fit put the nugget at its bound;
                             # ?sac_nugget says how to read that
attr(r, "structure_p")       # the test for spatial structure

# A field whose range the data cannot pin down: the variogram never
# reaches a sill within the lags fitted, so the answer is NA, with the
# refused value and the reason attached.
xy$trend <- sin(xy$x / 400) + rnorm(n, sd = 0.2)
r2 <- estimate_sac_range(st_as_sf(xy, coords = c("x", "y"), crs = 32632),
                         response_var = "trend")
r2
attr(r2, "rejected_reason")
attr(r2, "rejected_range")

# White noise: no structure, so no range.
xy$noise <- rnorm(n)
r3 <- estimate_sac_range(st_as_sf(xy, coords = c("x", "y"), crs = 32632),
                         response_var = "noise")
attr(r3, "rejected_reason")


Compute the metrics of several fitted models

Description

Runs model_metrics() on each fit in a list and binds the rows, with a model column and a metric_basis column saying whether each row is in-sample, out-of-bag or on newdata. It takes a single spatial_fit too. No model is refitted: the fitted values are read with fitted(), and newdata is scored with predict(). compare_models() adds information criteria and residual Moran's I to the same table.

Usage

evaluate_insample(fits, newdata = NULL, ...)

Arguments

fits

A spatial_fit object, or a named list of them (e.g. list(GWR = gwr_obj, Bayesian = bayes_obj)). The names are used as the model labels and every element must have one; an unnamed list is an error, and so are duplicated names. model is the key the comparison table is assembled on, so two fits sharing a name cannot be told apart in the output.

newdata

Optional sf object for out-of-sample evaluation. Must contain the response variable and all predictors. If NULL, in-sample metrics are computed.

...

Passed to predict() when newdata is given. Without newdata nothing reads them, so any argument here is an error, which catches a misspelt newdata.

Details

The metrics are those of model_metrics(): see its sections "What the metrics are computed on" and "Percentage errors on responses with zeros".

Value

A data.frame with one row per model and columns for model name, all regression metrics, and metric_basis: what the row's metrics were computed on, "in-sample" (fitted values), "out-of-bag" (an rf_fit's fitted values, see "What the metrics are computed on") or "newdata". Rows with different bases do not compare like for like. An element that is not a spatial_fit is skipped, with a logged warning, and has no row; a list in which no element is a spatial_fit is an error.

See Also

Other in-sample checks: compare_models(), model_metrics(), print.morans_i(), residual_morans_i()

Examples


library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(60, 0, 1000), y = 5e6 + runif(60, 0, 1000),
             a = rnorm(60)),
  coords = c("x", "y"), crs = 32632
)
# An offset keeps the response away from zero, where MAPE is undefined.
pts$z <- 10 + 2 * pts$a + rnorm(60, 0, 0.3)
# Fit on 40 rows and keep 20 back, so the second call is out of sample.
fit <- fit_rf_model(pts[1:40, ], "z", "a", num_trees = 50, seed = 1)
evaluate_insample(fit)                           # out-of-bag for a forest
evaluate_insample(fit, newdata = pts[41:60, ])   # on the 20 held-out rows


Fit a Bayesian Gaussian-process regression with brms

Description

Fits a regression whose residual spatial structure is modelled as a Gaussian process over the coordinates, and so kept out of the errors. Every quantity has a posterior, so predictions come with intervals; cv_bayes() reports their held-out coverage and CRPS. The spatial term is a smooth surface at a stated resolution. The Gaussian process is fitted through a reduced-rank basis, and that basis has a floor: an effective range below which it cannot represent structure, reported in CRS units as $info$gp_resolution and by print(). With the defaults the floor is about 32 km along each axis on points spread evenly over a 100 km square. Structure shorter than the floor is counted as noise: the fitted range comes out too long, the residual standard deviation too large, and the intervals too narrow where the structure is. See "What the basis resolves" below.

Usage

fit_bayesian_spatial_model(
  data_sf,
  response_var,
  predictor_vars,
  family = NULL,
  gp_k = NULL,
  gp_c = NULL,
  gp_iso = FALSE,
  prior = NULL,
  chains = 4,
  iter = 2000,
  warmup = floor(iter/2),
  cores = getOption("mc.cores", 1L),
  seed = 123,
  backend = c("auto", "cmdstanr", "rstan"),
  control = list(),
  compute_loo = TRUE,
  standardize_predictors = FALSE,
  check_convergence = TRUE,
  pointize = "auto",
  boundary = NULL,
  gp_resolution = NULL,
  .already_prepped = FALSE
)

Arguments

data_sf

An sf object with response, predictors, and geometries.

response_var

Response column name.

predictor_vars

Predictor column names. May be character(0) for an intercept-only model: the response is then explained by the intercept and the spatial Gaussian process alone, the baseline for asking how much of the surface is spatial structure and how much covariate effect, and the null model to compare a covariate model with in compare_models().

family

A model family accepted by brms::brm(): a stats family function such as poisson(), or a brms family object such as brms::zero_inflated_poisson(), brms::negbinomial(), brms::hurdle_poisson(), brms::bernoulli() or brms::Beta(). Default NULL, resolved to stats::gaussian(). The family reaches brms::brm() unchanged with the spatial GP term still in the formula. A factor response is accepted only under brms::categorical() or an ordinal family, and those fits have no single expected value per row, so several methods cannot use them; see "Non-Gaussian responses" for what each family supports, and the count example below.

gp_k

Positive integer giving the number of GP basis functions per dimension, or NULL (default) to derive it from the length-scale/domain ratio. The fitted model carries gp_k^2 basis functions, not gp_k (see "GP basis count and boundary factor"). A value above the derived one makes the basis finer, and the length-scale prior's lower tail moves down to the length-scale that basis resolves, because a finer basis under the default prior gains almost nothing. A value below the derived one leaves the prior where it was, mostly below what the basis resolves; that share is stored as $info$gp_adequacy$prior_mass_below, logged when it passes 10 percent and flagged by print(). To ask for a resolution in CRS units, use gp_resolution and leave this NULL.

gp_c

Positive numeric boundary factor for the approximate GP, or NULL (default) to derive it alongside gp_k. The boundary must be wide enough to contain the longest plausible effective range; a value that is too small truncates the domain and degrades the approximation for smooth, long-range surfaces. When you set gp_c and leave gp_k = NULL, gp_k is derived for your boundary: a wider boundary needs more basis functions to resolve the same length-scale, so raising gp_c raises the derived gp_k with it, up to the cap of 50 per dimension (a capped value is logged).

gp_iso

Logical; passed to brms::gp(iso = ). FALSE (the default) fits a separate length-scale per coordinate axis, so the model learns any directional structure from the data. TRUE fits a single length-scale shared by both standardised axes, which makes the kernel anisotropic in the original CRS by the ratio sd(X)/sd(Y), because the coordinates are standardised per axis beforehand. See "Coordinate scaling and anisotropy".

prior

Optional brms prior specification. When NULL and standardize_predictors = TRUE, a weakly informative prior is set on the regression coefficients, on the scale of the linear predictor: normal(0, 2.5 * sd(y)) under an identity link (gaussian, student, skew-normal and mixtures of them), normal(0, 2.5 * sd(log(y))) for the lognormal families, whose location is on the log scale, and the fixed normal(0, 5) under any other link (log, logit and so on), where the linear predictor has a scale of its own. sd() is taken over the training rows. The result therefore does not depend on the units of the response. The prior brms used is stored as $info$b_prior and shown by print(). When prior is given, no slope prior is added. A prior given here on a class that lives on the response's scale (b, Intercept, sigma, sdgp, and beta of exgaussian()) keeps the response as it is; see "The response's centre and scale". A GP length-scale prior set from the data is added unless prior already contains an entry with class = "lscale".

chains

Number of MCMC chains. Default 4.

iter

Total iterations per chain. Default 2000.

warmup

Warmup iterations. Default floor(iter / 2).

cores

Number of cores for the sampler, one chain per core. Default getOption("mc.cores", 1L), the convention brms uses itself, so options(mc.cores = 4) once per session runs the four default chains in parallel everywhere.

seed

Integer seed. Default 123.

backend

"auto" (default), "cmdstanr" or "rstan". "auto" uses cmdstanr only when a CmdStan build is available, and rstan otherwise, which brms always brings. The cmdstanr package is a thin interface and can be installed without a CmdStan build (cmdstanr::install_cmdstan() builds one). An explicit "cmdstanr" with no usable CmdStan raises an error that says how to install it, before the sampler starts.

control

Named list of sampler controls, merged over the package defaults list(adapt_delta = 0.99, max_treedepth = 12) rather than replacing them, so list(max_treedepth = 15) keeps adapt_delta = 0.99. See "Sampler settings".

compute_loo

Logical; compute PSIS-LOO. Default TRUE.

standardize_predictors

Logical; centre and scale numeric predictors before fitting. Default FALSE. When TRUE, the centre and scale of each predictor are stored in $info$predictor_scaling and applied again by predict(). The model is then fitted on the standardised predictors, so coef() reports a slope per standard deviation of each predictor and an intercept at the predictor means, not the raw-unit values stats::lm() would give (see spatial_fit-coef).

check_convergence

Logical, default TRUE. After fitting, read the sampler's diagnostics and the GP basis against the posterior and the residuals, and set $info$convergence_ok and $info$gp_adequacy. See "Convergence checks" and "What the basis resolves". FALSE skips both, leaves convergence_ok NA (not checked) and sets the adequacy status to "not_checked".

pointize

How a feature that is not a point is reduced to one: one of "auto" (default), "centroid", "point_on_surface", "surface", "line_midpoint" or "bbox_center"; see coerce_to_points().

boundary

Optional polygonal sf/sfc whose CRS the data are projected to. It is not a clip: rows outside it are kept.

gp_resolution

The shortest effective range the basis should resolve, as a single positive number in the units of the data's CRS (metres for a UTM layer), or NULL (default) for the rule described under "GP basis count and boundary factor". gp_k is derived from it, and the length-scale prior's lower tail moves with the basis. It can only refine: a value the default basis already resolves leaves the default basis in place. It is an error when the basis it needs exceeds the cap of 50 functions per dimension (2,500 in all); the message gives the basis size needed and the shortest range the cap reaches on this layout. Cost grows with gp_k^2. Give gp_resolution or gp_k, not both.

.already_prepped

Internal; leave at the default.

Details

The fitted length-scale is an estimate of how far the spatial dependence reaches only when its posterior sits clear of both that floor and its prior. $info$gp_adequacy says whether it does, and when it does $info$gp_adequacy$effective_range holds the posterior effective range per axis in CRS units (the raw lscale draws are in per-axis standardised units and are not a distance).

Choose it over fit_gwr_model() when you want one global relationship plus a spatial random field, with posterior intervals; choose GWR when the question is how a coefficient varies across the map. Choose fit_rf_model() when predictive accuracy matters more than an interpretable model and the response is non-linear in the predictors. The cost is time: this is full MCMC through brms and Stan, so a fit takes minutes rather than seconds, and the basis size (gp_k) trades fidelity against run time.

Value

A bayesian_fit object (inherits from spatial_fit). Supports predict(), fitted(), residuals(), coef(), summary(), and model_metrics(). Model-specific metadata lives in $info (coords: the names of the scaled coordinate columns handed to brms::gp(); coord_scaling, predictor_scaling, gp_k, gp_c, gp_iso, gp_n_basis, gp_ell_min, gp_resolution: the smallest effective range the basis resolves, as c(x, y) in CRS units; gp_resolution_requested: the gp_resolution argument, or NULL; gp_prefit: the check made before sampling, a list with status ("ok"; "below_floor", the one that warns; "below_floor_no_autocorrelation" and "below_floor_long_range", a range below the floor that the short-lag or the floor-distance test did not bear out; "not_estimated" or "not_run"), range (the estimated range in CRS units), floor, k_needed, moran and moran_floor (the two Moran's I tests, each with I, z and a one-sided p; NULL where the test is not run, or where the residuals are the rounding of an exact fit), reason and unit; gp_adequacy: a list with status (see "What the basis resolves"), frac_below (the share of length-scale draws below gp_ell_min), identified and identified_by ("spatial_share" or "length_scale", the rule that decided it; see "What the basis resolves"), contraction (one minus the ratio of posterior to prior variance, per length-scale, negative when the posterior is the wider of the two) and prior_gap (the largest gap between the posterior's and the prior's distribution functions, per length-scale; both NA for a length-scale prior this function did not set), spatial_share and sdgp (2.5, 50 and 97.5 percent quantiles; the share only for a gaussian or lognormal family), effective_range (the posterior effective range per axis in CRS units, same quantiles), residual_moran (the test on the residuals the status rests on: I, z, a one-sided p and k, the number of neighbours; absent when it could not be run, and residual_untested then says why), resolution, unit and prior_mass_below; b_prior: the slope prior brms used ("(flat)" for its default, NA for a model with no slopes), and b_prior_source: where it came from; predictor_levels: the levels each factor or character predictor has in the training rows, which predict() holds new data to; gp_S: the pooled centred range brms::gp(c = ) multiplies; gp_cmeans: the column means brms centred the scaled coordinates on; gp_xy_range: the training extrema of the scaled coordinates, which predict() uses, with gp_S and gp_cmeans, to hold the GP boundary at its fitted value; gp_lengthscale_bounds: the c(lower, upper) the length-scale prior was calibrated over; gp_lscale_prior: the length-scale prior brms::validate_prior() reports the model will actually use, which is not necessarily the one this function requested (several entries, semicolon-separated, if brms resolved the axes differently); loo, looic, convergence_ok (TRUE or FALSE, and NA when nothing was checked, as under check_convergence = FALSE), convergence_diagnostics: n_divergent, n_max_treedepth, ebfmi (per chain), max_rhat, min_neff_ratio, min_ess (the smallest bulk or tail effective sample size) and ess_required (100 per chain), and rhat_failed / neff_failed / ess_failed, the parameters that failed each check by name with their values (R-hat, ESS ratio and ESS; empty when none failed), which is what makes a failed check actionable, rhat_caution, the parameters whose R-hat is between 1.01 and 1.05 with enough effective draws, which do not fail the verdict, plus gp_lscale_below_resolution and gp_adequacy, the share and status described under "What the basis resolves"; and n_dropped: the rows prep_model_data() removed for missing or non-finite values or a bad geometry, so $n can be read against nrow(data_sf)); response_scaling: the centre and scale the response was handed to brms with, absent when it was handed over as it is (see "The response's centre and scale"). The raw brmsfit is in $engine.

Sampler settings

adapt_delta defaults to 0.99, not Stan's 0.8, because one divergent transition sets convergence_ok to FALSE (see "Convergence checks") and lower values can leave a few on ordinary data. A lower value, such as list(adapt_delta = 0.9), runs faster, since the smaller step of 0.99 costs sampling time. Some divergent transitions can remain at 0.99 too, for example on a layer whose spatial field is weak against the noise; then raise it to 0.995 or 0.999, which costs more time again.

Convergence checks

Under check_convergence = TRUE the verdict in $info$convergence_ok follows Stan's own diagnostics, with these thresholds:

An R-hat between 1.01 and 1.05 on a parameter with enough effective draws is a caution, not a failure: it is stored by name in $info$convergence_diagnostics$rhat_caution, logged, and counted by print(). The model has one weight per basis function, about 540 parameters at the basis derived for points spread evenly over a square, and among that many the largest R-hat sits near 1.01 in a fit that has converged. Vehtari et al. give 1.01 beside an effective sample size above 400, so the two are read together here.

Transitions that stop at max_treedepth are counted and logged but do not change the verdict: Stan treats them as a cost, not as invalid draws. A failed verdict sets convergence_ok to FALSE, raises one R warning of class spatialkit_convergence naming each failed check with its count and its first five parameters, and print() flags it; $info$convergence_diagnostics holds every value. The warning closes with the remedy for the checks that failed: a higher adapt_delta for divergent transitions, which more iterations do not remove, and more iterations for R-hat and effective sample size. A short run usually fails on effective sample size. cv_bayes() marks such folds in fold_metrics$convergence_ok and compare_models() names such a model.

The same step checks the GP basis against the posterior and the residuals (see "What the basis resolves") and stores the result as $info$gp_adequacy. The residuals need the fitted values, one pass over the posterior that fitted() caches for later calls. That check is about the approximation, not the sampler, so it does not change convergence_ok; print() and summary() show its status, and two of its states raise a warning of class spatialkit_gp_adequacy.

GP basis count and boundary factor

brms::gp() builds a full tensor grid over its covariates, so a term gp(..x, ..y, k = gp_k) carries gp_k^2 basis functions: the gp_k argument is the count per dimension, not the total rank. Both gp_k and gp_c are therefore chosen from the ratio of the estimated length-scale to the domain extent, following Riutort-Mayol et al. (2023): gp_c is set large enough to contain the upper length-scale bound, and gp_k large enough to resolve the lower one. The derived value depends on the layout, not on n: about 23 for points spread evenly over a square; other layouts give other values, up to the cap of 50.

The domain extent used is the one brms::gp(c = ) itself multiplies: the full pooled range of the column-centred coordinates (brms:::choose_L(), taken over the unique coordinate rows, because brms:::.data_gp() reduces the covariates to unique rows first under the default gr = TRUE, so repeat visits to one location do not widen the domain), not the per-axis half-range in which Riutort-Mayol et al. state their inequalities. Both constraints are on the boundary L = c \times S, and stating them in brms's units keeps gp_c, gp_k and $info$gp_ell_min describing the basis brms builds. A gp_c derived on the half-range convention and handed to brms::gp() produces a boundary twice as wide as intended, against which gp_k under-resolves by a factor of two.

The GP term is built with scale = FALSE. brms::gp() otherwise rescales its covariates so the maximum Euclidean distance between two points is 1, and reports lscale in that space; since this function already standardises the coordinates, and the length-scale prior, gp_c and the adequacy check below are all expressed in those standardised units, a second normalisation would leave every length-scale quantity in the wrong units.

What the basis resolves

The smallest length-scale the chosen basis can resolve is 1.75 * gp_c * S / gp_k, stored in standardised units as $info$gp_ell_min. As an effective range (the distance at which the squared-exponential correlation has fallen to 5 percent, 2.45 length-scales) and in CRS units it is $info$gp_resolution, one value per axis because each coordinate is divided by its own standard deviation. The floor is soft: the basis keeps 99 percent of a process's variance at the floor, 69 percent at half of it and 41 percent at a third. The default length-scale prior is what makes it bind, with 1 percent of its mass below the floor and about one part in a hundred million below half of it.

Three checks hold the basis against the data.

  1. Before anything is compiled, the autocorrelation range of the response (of its OLS residuals when there are predictors) is estimated with estimate_sac_range() and compared with the coarser axis's floor. That range is a variogram estimate and can be wrong in both directions, so a range below the floor raises a warning only when two other things agree with it. The same variable is autocorrelated at short range (Moran's I over 4 nearest neighbours, one-sided, at 5 percent): a variogram fitted to a response with no spatial structure can still return a short range, though estimate_sac_range() refuses most such layers itself. And it is no longer autocorrelated at the floor's distance (Moran's I over the pairs 0.75 to 1.25 floors apart is not both above 0.05, the correlation that defines an effective range, and significant at 5 percent): a variogram can also return a short range for a surface that is smooth over long distances. The warning has class spatialkit_gp_resolution, gives both numbers and the basis size that would resolve the range, says that it is an estimate which the check after sampling tests against the residuals of the fitted model, and says when the basis size is past the cap or past the number of rows, where kriging is the better tool if the range is right. A short range the floor-distance test contradicts is logged and shown by print() without a warning: it can still mean short-range structure beside a longer one, which the basis counts as noise. Nothing before sampling separates the two; the residuals after it do (the third check). A range that cannot be estimated is logged with the reason and shown by print(); the result is in $info$gp_prefit. An exponential field has structure at every scale, so the warning on one is not plainly wrong.

  2. Also before sampling, the share of the length-scale prior below the floor is computed ($info$gp_adequacy$prior_mass_below). A derived basis keeps it near 0.01; a small gp_k does not, and a share above 0.10 is logged and flagged by print().

  3. After sampling, under check_convergence = TRUE, the posterior and the residuals are read. The posterior says whether the Gaussian process carries a share of the variance and where its length-scale sits against the floor. It cannot say what the surface left behind, so the residuals are tested for autocorrelation at short range in every fit (Moran's I over 4 nearest neighbours, one-sided, at 5 percent; $info$gp_adequacy$residual_moran). $info$gp_adequacy$status is one of:

    "ok"

    The Gaussian process carries a share of the variance, its length-scale is clear of the floor, and the residuals show no autocorrelation at short range. A surface smoother than the prior expects (a plane, a range longer than the extent) is "ok": its length-scale posterior sits on the long side of the prior and is wider than it.

    "below_resolution"

    The Gaussian process carries a share of the variance and more than 10 percent of the length-scale draws fall below the floor. The 10 percent trigger is this package's operationalisation of the check Riutort-Mayol et al. recommend, not a figure from the paper.

    "unresolved_short_range"

    The residuals are autocorrelated at short range: the signature of structure finer than the basis, counted as noise. It is reached two ways, and $info$gp_adequacy$identified says which. The Gaussian process carries no variance that can be told from zero (FALSE): all of the structure is below the floor. Or it carries a share and its length-scale is clear of the floor (TRUE): it fitted a surface, and finer structure sits beside it, as with a regional trend plus short-range structure.

    "no_signal_above_floor"

    The Gaussian process carries no variance that can be told from zero, and the residuals show nothing left over. A response with no spatial structure gives this, so it is not a failure by itself.

    "not_checked"

    check_convergence = FALSE.

    The second and third raise a warning of class spatialkit_gp_adequacy; the fourth is logged. When the residuals cannot be tested (an ordinal or categorical family has no residual per row; a posterior that cannot be drawn), the status rests on the posterior alone, a line is logged, the reason is in $info$gp_adequacy$residual_untested, and print() keeps its flag on a variogram range that was below the floor.

    On a fit with nothing left over the test is conservative, because the surface takes up part of the noise and leaves the residuals slightly negatively autocorrelated. It is not sharp just below the floor, where the length-scale draws report the structure ("below_resolution"). An exponential field has structure at every scale and can be reported with a range above the floor. The 5 percent level is the usual one and is not tuned; with many rows a small leftover autocorrelation is significant, so read the size of I beside its p.

    "No variance that can be told from zero" is decided on the Gaussian process's share of the variance, sdgp^2 / (sdgp^2 + sigma^2): its 2.5 percent quantile is under 0.01. It does not mark off a response whose structure is all below the floor: such a process can still carry a share, and the residual test reports it. The share exists for a gaussian or lognormal family. For any other family the length-scales decide instead: the process is not identified when on every axis the posterior kept more than three quarters of its prior's variance and the largest gap between its distribution function and the prior's is under 0.30. $info$gp_adequacy$identified_by says which rule was used. The width of the length-scale posterior does not decide by itself, because a posterior that moved to longer length-scales is wider than its prior; and the share of draws below the floor cannot detect an unidentified process, because a posterior the data did not move puts 1 percent below the floor, the same as the prior.

A response whose range is below the floor needs a finer basis and a prior that allows the shorter length-scale, both of which gp_resolution sets, up to the cap. Past the cap this model cannot resolve the range, and kriging, which has no such floor, is the better tool; see kriging_adequacy() for cell means.

Coordinate scaling and anisotropy

Before fitting the GP, X and Y coordinates are each centred and divided by their own standard deviation. This is a conditioning step: easting and northing frequently span very different ranges in a projected CRS, and handing Stan raw metres samples poorly.

Because the axes are scaled independently, a single shared length-scale in the scaled space corresponds to an anisotropic kernel in the original CRS, stretched by the ratio sd(X)/sd(Y). That ratio is a property of how the sampling locations are laid out, not of the process being modelled.

gp_iso = FALSE (the default) therefore fits one length-scale per axis, letting the model estimate directional structure from the data instead of inheriting it from the standardisation. Set gp_iso = TRUE for one length-scale shared by both standardised axes.

gp_iso does not affect cost: brms::gp() builds a tensor grid either way, so the model carries gp_k^2 basis functions regardless. The stored $info$coord_scaling list records the scaling strategy, and $info$gp_iso records which kernel was used.

Warnings

Every warning this function raises carries a condition class, so a caller can catch or muffle exactly one of them by name:

spatialkit_rows_dropped, spatialkit_constant_predictor

From prep_model_data(): incomplete rows were dropped, with the counts; a predictor takes one value in every row kept.

spatialkit_response_scale

The response lies far from zero or its standard deviation far from 1, and prior sets a prior on a class on the response's scale, so the response is handed to brms as it is; see "The response's centre and scale".

spatialkit_gp_basis_size

Fewer than one row per ten basis functions.

spatialkit_gp_resolution

A variogram fitted before compiling puts the response's range below what the basis resolves, and the autocorrelation of the response agrees. An estimate; the check after sampling tests it against the residuals of the fitted model.

spatialkit_convergence

The sampler's diagnostics fail.

spatialkit_gp_adequacy

The basis is too coarse for the data: the posterior asks for a shorter length-scale than it resolves ("below_resolution"), or the residuals are autocorrelated at short range ("unresolved_short_range").

A response that takes a single value is an error, raised before anything is compiled, and so is one whose values differ only by rounding (1e15 and the next double). A fit that comes back from brms with no posterior draws, as when Stan rejects every starting value, is an error that names the response's size as brms was given it. The convergence warning carries the checks that failed as failed ("divergent", "ebfmi", "rhat", "ess"). cv_bayes() fits once per fold; it collects the last four classes from its folds and raises each once for the run, naming the folds, and cv_spatial() does the same for a fit_fn that calls this function.

The response's centre and scale

Stan starts every parameter between -2 and 2, and brms sets its default priors for the intercept, the residual standard deviation and the Gaussian process's standard deviation from the response it is given, with scales of at least 2.5 in its units. A response at 1e8 plus a spread of 1, or in units of 1e-20, lies far from both, and brms can miss the data by orders of magnitude. So under the gaussian, student, skew_normal, exgaussian and asym_laplace families with an identity link, a response whose centre is more than 1,000 times its spread from zero is handed to brms less that centre, and one whose standard deviation lies outside 2^{-20} to 2^{20} is divided by the power of two nearest that standard deviation. Under exgaussian and asym_laplace the rule is narrower: a centre more than 4 times the spread from zero is taken off, and a standard deviation outside 2^{-2} to 2^{2} is divided out, because brms's default prior on exgaussian's beta and Stan's starting values do not follow the response. Both steps are exact, and the model is the same model of the response: the shift moves the location only, and the scale multiplies the location, sigma and the mean beta of exgaussian's exponential part, and leaves the degrees of freedom of student, the skewness of skew_normal and the quantile of asym_laplace as they are. Every other response, and every response under another family, is handed over as it is.

fitted(), predict() and its draws, residuals(), coef(), $info$loo, $info$looic and $info$gp_adequacy$sdgp are put back in the response's units, and $info$b_prior gives the automatic slope prior in those units. The same data from another origin or in other units then give the same fit, up to Monte Carlo error. The centre and scale are in $info$response_scaling. $engine is the fit of the response brms was given, so brms's own functions on it (brms::fixef(), brms::posterior_epred()) answer on that scale.

A prior given in prior on a class on the response's scale (b, Intercept, sigma, sdgp, and beta of exgaussian) is read by brms on the response it is given. With such a prior the response is handed over as it is, and the warning spatialkit_response_scale says so.

Non-Gaussian responses

Nothing in this function is Gaussian-specific except its default. A numeric count, binary (0/1 or logical) or bounded response passes through to brms under the family you name, with the GP term in the formula and the length-scale prior attached to each distributional parameter's GP.

The response check is family-aware. A factor or character response is accepted only under brms::categorical() or an ordinal family (cumulative, sratio, cratio, acat), and refused under every other family before anything is compiled; under gaussian a logical response is refused too. The case to watch is a two-level factor under brms::bernoulli(): brms would fit it, but residuals(), summary(), model_metrics() and cv_bayes() could not score a factor, so convert it to 0/1 first.

An ordinal or categorical fit has a probability per response category, not one expected value per row. predict() with its default type = "epred", fitted(), residuals(), summary() and model_metrics() therefore stop with a message saying so, and cv_bayes() refuses the family before fitting anything. predict(type = "predict", draws = TRUE) returns the posterior predicted categories, as category indices, for new rows as well as the training ones (the share of draws in each category estimates its probability), and brms::posterior_epred(fit$engine) the probabilities for the training rows.

For the numeric families two things follow. First, the metrics that come back from model_metrics() and the cv_*() functions are not all meaningful for such a response: RMSE and MAE are, MAPE, SMAPE and R-squared are Gaussian-shaped, and for this backend cv_bayes()'s CRPS and interval coverage are the proper scores to read. See model_metrics(), section "Which metrics survive a non-Gaussian response". Second, estimate_sac_range() fits a variogram to the raw response (or OLS residuals), whose variance tracks its mean for a count; the range it reports is then less trustworthy than for a Gaussian response, and its help page says how.

The response check reads the family's name through brms's own accessor. If brms cannot name the family object, the check is skipped, and a wrong response type surfaces as a Stan error with no message from this function.

Spatial confounding

A fixed-effect coefficient estimated alongside a spatial random effect is a different quantity from the same coefficient in a non-spatial fit. When a covariate is itself spatially smooth, the GP term absorbs part of its effect and the two estimates can disagree sharply; when the response is smoother than the covariate, the estimate can shrink toward zero regardless of the true effect (Bolin and Wallin 2026). Under a correctly specified spatial model this is not a bias but a change of estimand (Zimmerman and Ver Hoef 2022): the spatial coefficient is the effect net of whatever the spatial field can explain, and the non-spatial one is not. The right one depends on the question, so report both side by side, unadjusted: fit the same formula with stats::lm() or stats::glm() and compare. Compare like with like: under standardize_predictors = TRUE the coefficients here are per standard deviation of each predictor, so either fit the non-spatial model on the same standardised columns or divide these slopes by $info$predictor_scaling[[name]]$scale first (see spatial_fit-coef).

Published work on remedies is unsettled, and this function takes no side. Restricted spatial regression (Hughes and Haran 2013) projects the spatial effect off the covariate space; later work argues it does not deliver what it promises (Hanks et al. 2015; Khan and Calder 2022). Within this backend, modelling the covariate and the spatial field as explicitly correlated (Marques, Kneib and Klein 2022) is expressible in a brms formula with no new code, and a spectral adjustment (Guan et al. 2023) is the principled route that suits a Hilbert-space basis; this function does not implement it.

References

Betancourt, M. (2016). Diagnosing suboptimal cotangent disintegrations in Hamiltonian Monte Carlo. arXiv:1604.00695.

Vehtari, A., Gelman, A., Simpson, D., Carpenter, B. and Burkner, P.-C. (2021). Rank-normalization, folding, and localization: an improved R-hat for assessing convergence of MCMC (with discussion). Bayesian Analysis 16, 667–718. doi:10.1214/20-BA1221

Riutort-Mayol, G., Burkner, P.-C., Andersen, M. R., Solin, A. and Vehtari, A. (2023). Practical Hilbert space approximate Bayesian Gaussian processes for probabilistic programming. Statistics and Computing 33, 17. doi:10.1007/s11222-022-10167-2

Bolin, D. and Wallin, J. (2026). Spatial self-confounding: smoothness-related estimation bias in spatial regression models. Biometrika 113(1), asaf076. doi:10.1093/biomet/asaf076

Guan, Y., Page, G. L., Reich, B. J., Ventrucci, M. and Yang, S. (2023). Spectral adjustment for spatial confounding. Biometrika 110, 699–719. doi:10.1093/biomet/asac069

Hanks, E. M., Schliep, E. M., Hooten, M. B. and Hoeting, J. A. (2015). Restricted spatial regression in practice: geostatistical models, confounding, and robustness under model misspecification. Environmetrics 26, 243–254. doi:10.1002/env.2331

Hughes, J. and Haran, M. (2013). Dimension reduction and alleviation of confounding for spatial generalized linear mixed models. Journal of the Royal Statistical Society: Series B 75, 139–159. doi:10.1111/j.1467-9868.2012.01041.x

Khan, K. and Calder, C. A. (2022). Restricted spatial regression methods: implications for inference. Journal of the American Statistical Association 117, 482–494. doi:10.1080/01621459.2020.1788949

Marques, I., Kneib, T. and Klein, N. (2022). Mitigating spatial confounding by explicitly correlating Gaussian random fields. Environmetrics 33, e2727. doi:10.1002/env.2727

Zimmerman, D. L. and Ver Hoef, J. M. (2022). On deconfounding spatial confounding in linear models. The American Statistician 76, 159–167. doi:10.1080/00031305.2021.1946149

See Also

cv_bayes() to score the fit on spatial folds; predict() (spatial_fit-predict) and coef() (spatial_fit-coef); gp_lengthscale_bounds() for the length-scale range the prior is set over.

Other model fitting: fit_gwr_model(), fit_rf_model(), gp_lengthscale_bounds(), new_spatial_fit()

Examples

## Not run: 
# Not run: fits with Stan, which needs a working C++ toolchain and takes
# minutes of sampling.
if (requireNamespace("brms", quietly = TRUE)) {
  library(sf)
  set.seed(1)
  n <- 60
  dat <- st_as_sf(
    data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
               elev = rnorm(n)),
    coords = c("x", "y"), crs = 32632
  )
  dat$price <- 10 + 0.01 * (st_coordinates(dat)[, 1] - 5e5) +
    2 * dat$elev + rnorm(n)
  # Two short chains keep this to a few minutes; Stan may warn about
  # effective sample size, which is the cost of that.  Use its defaults
  # (chains = 4, iter = 2000) for a fit to report.
  fit <- fit_bayesian_spatial_model(dat, "price", "elev",
                                    chains = 2, iter = 1000,
                                    compute_loo = FALSE)
  print(summary(fit))
  head(predict(fit, newdata = dat))

  # A zero-inflated count.  The family is the only thing that changes.
  # summary()'s R2 and MAPE assume a Gaussian response, so for a count
  # read the coefficients here and score the model with cv_bayes(), whose
  # CRPS and interval coverage are defined for any response.
  dat$count <- rpois(n, exp(0.5 + 0.8 * dat$elev)) * rbinom(n, 1, 0.7)
  fit_zip <- fit_bayesian_spatial_model(dat, "count", "elev",
                                        family = brms::zero_inflated_poisson(),
                                        chains = 2, iter = 1000,
                                        compute_loo = FALSE)
  coef(fit_zip)
}

## End(Not run)

Fit a geographically weighted regression (GWR)

Description

Fits a Gaussian GWR on an sf layer with an adaptive or a fixed bandwidth. Each location gets its own regression, weighted towards nearby observations, so the coefficients can vary across the map. Use it when that variation is the question; fit_bayesian_spatial_model() fits one global relationship plus a spatial random field.

Usage

fit_gwr_model(
  data_sf,
  response_var,
  predictor_vars,
  adaptive = TRUE,
  bandwidth = NULL,
  kernel = c("bisquare", "gaussian", "tricube", "boxcar", "exponential"),
  .already_prepped = FALSE
)

Arguments

data_sf

An sf object with response, predictors, and geometries.

response_var

Response column name.

predictor_vars

Predictor column names (numeric columns; a name given twice counts once). character(0) fits the model with a local intercept alone: the fitted value at a location is the kernel-weighted mean of the response around it. That is the baseline a GWR with predictors has to beat, since any GWR beats a global mean through its local intercept, and select_features_forward() fits it as the null model of a GWR sweep.

adaptive

Logical; use adaptive bandwidth. Default TRUE. When TRUE, bandwidth is an integer number of nearest neighbours. When FALSE, bandwidth is a fixed distance in CRS units.

bandwidth

Optional numeric bandwidth value. For adaptive mode this is an integer (number of neighbours); for fixed mode a distance in the units of the projected CRS the fit runs in. prep_model_data() projects geographic input before the bandwidth is used, so 0.2 supplied for lon/lat data is 0.2 metres, not 0.2 degrees. Read the CRS off sf::st_crs(fit$data_sf), or pass target_crs to ensure_projected beforehand to fix the units yourself. If NULL (default), the bandwidth with the lowest AICc is searched for (the lowest leave-one-location-out error when observations share a location); see Bandwidth selection. With adaptive = FALSE, a bandwidth smaller than a ten-thousandth of the data's extent raises a warning naming the extent and the CRS the fit runs in: every local window then holds its own observation alone. With adaptive = TRUE the count is rounded, and one too small for the model is raised, with a warning, to the smallest that gives every local regression more points of non-zero weight than parameters: the number of predictors plus 3 for the bisquare and tricube kernels (which give the farthest neighbour in a window weight 0), plus 2 for the others. That floor is enough unless several neighbours tie at the kernel's edge (a regular grid), which leaves a window fewer weighted points; then use a larger bandwidth. A count above the number of observations is capped at it, with a warning (a distance meant for adaptive = FALSE, most often).

kernel

Weighting kernel: one of "bisquare" (default), "gaussian", "tricube", "boxcar" or "exponential". The boxcar gives weight 1 within the bandwidth (with an adaptive bandwidth, the distance to the bandwidth-th nearest neighbour) and 0 beyond it; see "The local solve" for how a neighbour at the edge is counted.

.already_prepped

Internal; leave at the default.

Details

The kernels, the bandwidth conventions and the diagnostics are those of GWmodel. This package solves the local regressions itself, each as a weighted least squares by pivoted QR, so a window whose design is rank deficient neither stops the fit nor returns coefficients made of rounding error.

Value

A gwr_fit object (inherits from spatial_fit). Supports predict(), fitted(), residuals(), coef(), summary(), and model_metrics(). Model-specific metadata lives in $info: bandwidth, adaptive, kernel, AICc (NA, with a warning, where AICc is undefined: its effective number of parameters tr(S) is not below n - 2, the local regressions all but interpolate the data, and the large negative value the formula gives would rank the fit above any other; also where the fit reproduces the mean of the observations at each location, see Observations that share a location), bandwidth_is_fallback (TRUE when no bandwidth could be selected: the search failed and the arbitrary fallback was used, or no bandwidth has a defined criterion and the widest was used), condition_index (the global index), local_collinearity (one row per observation: row, x, y, n_window, cn and cn_slopes, see Collinearity diagnostics, then rank, the rank the local solve found, and leverage, the observation's diagonal of the hat matrix), n_local_collinear (the locations whose slopes count as collinear), n_local_singular (the locations with a local coefficient that is NA), n_rank_deficient (the windows whose rank is below the number of parameters), n_saturated (the windows whose fitted value is their own observation: leverage 1), nonfinite_coef (a logical matrix, one row per observation and one column per term, with Intercept first, TRUE where the local coefficient is NA, so the count in n_local_singular can be placed), n_dropped (the rows prep_model_data() removed for missing or non-finite values or a bad geometry, so $n can be read against nrow(data_sf)), n_locations (the distinct locations of the rows fitted; see Observations that share a location), tr_S, enp, edf and sigma2 (the trace of the hat matrix, the effective number of parameters 2\,tr(S) - tr(S^\top S), the effective residual degrees of freedom and the residual variance, as GWmodel defines them), global_ols (RSS, RMSE and AICc of one least-squares regression on the same rows, the AICc by the same formula with the regression's rank as its trace; a GWR whose AICc is no lower has not shown that its coefficients vary, and summary() prints the two side by side), rank_tolerance, max_kernel_width (the widest kernel at any observation, which predict() measures new locations against) and bandwidth_search (see Bandwidth selection; NULL when a bandwidth was supplied).

$engine holds the fit in the layout of the object GWmodel::gwr.basic() returns, under the same names: SDF (a SpatialPointsDataFrame of the local coefficients, y, yhat, residual, CV_Score, Stud_residual, the standard errors <term>_SE, the t values <term>_TV and Local_R2), GW.diagnostic, GW.arguments and lm (the global least-squares fit). It is a plain list, not a gwrm object. Where a predictor or the response was taken less its centre (see "The local solve"), lm is solved on the centred columns and returned as the fit at the data's origin: its coefficients, fitted values, qr and effects are those of the raw columns, so summary(), vcov(), confint() and predict() on it give the intercept at the data's 0 and its standard error, and the slopes and residuals are those of the centred fit. With a predictor more than about 1e7 times its spread from 0, predict(se.fit = TRUE) on it stops with "singular matrix": qr.solve() reads the triangular factor at the data's origin as singular. predict() on the fit itself has no such limit. centres holds what was taken off: predictors, the centre of each column of the design (Intercept first, 0 for a column used as it is), NULL where none was, and response, 0 where none was.

The local solve

At every observation the model is a weighted least squares on the observations whose kernel weight is above zero. It is solved by a Householder QR with column pivoting of the window's weighted design, never by inverting X^\top W X. Before the factorisation each row is multiplied by the square root of its weight over the window's largest weight, and each predictor is divided by its standard deviation over the whole data and centred in the window, so nothing below depends on a predictor's origin or units: an indicator coded 0/1 and one coded 288.7/289.3 give the same fit.

Under the boxcar kernel an observation whose squared distance is within one part in ten million of the window's edge counts as at the edge, and inside, so on a regular grid every neighbour tied with the last one is in the window in any unit and at any origin where the doubles hold the coordinates to better than about one part in 1e8 of the distances between neighbours. Farther from the origin the doubles round the coordinates more coarsely, and where a neighbour lies past the edge by less than that rounding the call warns, with class "spatialkit_xy_imprecise" (see "Coordinates far from the origin" in spatialkit-geometry); the windows are those the coordinates as stored give.

A predictor whose centre is more than 1000 times its spread (a timestamp in seconds, a northing, 1e8 plus a spread of 1) is taken less its centre first. So is a response whose centre is more than 1000 times its spread (1e8 plus a spread of 1), whose raw values lose their spread to rounding (1e15 plus a spread of 1, stored to an eighth), or whose least-squares residuals on the predictors do. The bandwidth search, the local regressions, the global least-squares fit and the centred condition indices (info$condition_index, cn_slopes) then work on the spread and not on the rounding of the offset, and the centres are added back only to what is returned in the data's units: the fitted values, the local intercepts, the intercept and fitted values of $engine$lm, and predict()'s values, which take a new row's predictors about the same centres. Residuals, slopes and their standard errors, AICc and the bandwidth are those of the same values at 0, to rounding; the fitted values and predictions of a response at 1e15 are held to the eighth a double holds there. model_metrics(), summary() and the cross-validations score the fit on the response, the fitted values and the predictions less the response's centre, so their RMSE, MAE and R-squared are those of the same values at 0 too. Every other predictor and response is used as it is.

A response whose values, less any centre, reach beyond 1e100, or whose spread is below 1e-100, is divided by a power of two, which rounds nothing: the residual sum of squares, AICc and the bandwidth search square the residuals, and at 1e160 those squares overflow and at 1e-160 they lose their bits. The bandwidth is then that of the same values in ordinary units, and the fitted values, the residuals, the coefficients, their standard errors and $engine$lm are those of the same values times the factor; AICc, the AICc of info$bandwidth_search among them, gains 2 n \log of the factor, and a cross-validation score of the search is multiplied by its square. The residual sum of squares, info$sigma2 and such a score are in the response's units squared, and are NA, with a warning, where a double cannot hold them there; predict(se.fit = TRUE) then takes its standard errors from the residual standard deviation, which it can hold.

One tolerance, 1e-7, decides what a window can estimate:

A window of deficient rank does not stop the fit. A warning of class "spatialkit_gwr_rank_deficient" says how many windows are affected and how many coefficients of each term are NA; info$n_rank_deficient, info$n_local_singular, info$nonfinite_coef and the rank column of info$local_collinearity locate them. When many windows hold a predictor constant, a local coefficient is the wrong model for it: its effect is identified only as one global coefficient (a mixed GWR, as GWmodel::gwr.mixed() fits).

The leverage of each observation, the trace of the hat matrix, the residual sum of squares, AICc and the coefficients' standard errors come from the same decomposition. On a window of full rank every one of them equals what GWmodel::gwr.basic() returns, to rounding error: the largest relative difference in any cell of the six fits the package's tests compare is 3e-12. They are not bit-identical, since GWmodel inverts the normal equations.

Bandwidth selection

With bandwidth = NULL the AICc is scored on 16 bandwidths spaced evenly in the logarithm over the whole range, and then refined by a golden-section search between the grid points either side of the best (and, for a count of neighbours, at the counts next to the one it ends on). That is about 20 to 35 fits of the model in all. The range runs, for an adaptive bandwidth, from the smallest count the model's parameters allow to every observation; for a fixed one, from the distance at which half of the windows hold one observation more than the model has parameters (a third of it for the Gaussian and exponential kernels) to the largest distance between two observations. The bandwidth returned is the best of all those scored.

A golden-section search over the whole range, which GWmodel::bw.gwr() runs, assumes the criterion has one minimum. It has several when the coefficients vary at a range that only a few dozen observations resolve, and that search then returns a bandwidth near the top of the range, a nearly global regression, as the selected one.

A candidate bandwidth with windows of deficient rank is scored on its fitted values, which those windows do estimate. One at which AICc is undefined (tr(S) not below n - 2) cannot be selected, and neither can one at which a term of the model is estimable at no location: the fit would have no coefficient for it anywhere.

The criterion at a candidate comes from the local solve. Under a Gaussian or an exponential kernel, which weight every observation at every location, the fitted value and leverage of a window that is far from rank deficient are computed from its centred cross-products, many windows to one matrix product, and the windows that are not are left to the QR; the two routes agree to rounding error (1e-9 relative in the package's tests) and take the same rank decisions. With several strongly correlated predictors more windows are left to the QR and the search is slower. The fit at the selected bandwidth is always the QR's.

Everything scored is kept in info$bandwidth_search: approach (the criterion minimised, "AICc" or "CV"), by_location and n_locations (see Observations that share a location), curve (bandwidth, criterion, trace of the hat matrix, windows of deficient rank, and whether the point belongs to the grid or the refinement), undefined (how many of the bandwidths scored have no criterion, by reason), n_local_minima and multimodal (local minima on the grid), within and flat (the range of bandwidths whose AICc is within 2 of the minimum, and whether half the grid is), near_global (the widest bandwidth of the range is within 2 of the minimum), at_upper and at_lower (the minimum is at an end of the range). When any of these holds, one logged line says so (on the console, unless spatialkit_quiet() is on; in the trace only for the folds of a cross-validation); it is a message, not a warning, because a minimum at or near the top of the range is the ordinary outcome for a process whose coefficients do not vary. Read near_global as "AICc does not tell this fit from one global regression".

AICc is an in-sample criterion and rewards interpolation between neighbours. The bandwidth it selects can score worse than a wider one on held-out spatial blocks; cv_gwr with a supplied bandwidth is the check.

Observations that share a location

Rows with the same coordinates (several years at one station, replicate samples of one plot, records geocoded to one address) get one kernel weight at every regression point. info$n_locations is the number of distinct locations, and when it is below n a warning of class "spatialkit_gwr_repeated_locations" gives the counts.

The bandwidth is then not selected by AICc. AICc counts the rows at one location as independent observations. When a location has an effect of its own, a window that holds little but the location reproduces its mean, the residual sum of squares falls to the spread within locations, and AICc is lowest where the windows interpolate, which is where the error of predicting new sites is largest. A floor on the bandwidth does not repair that, because the criterion keeps falling towards the floor. With bandwidth = NULL the search therefore minimises the leave-one-location-out sum of squares: each location's observations are predicted by the local regression there without any of them, the kernel keeping its width, and the squared errors are summed. It is computed from the hat matrix of the fit at each bandwidth, without refitting. A bandwidth at which some location cannot be predicted from the others cannot be selected. info$bandwidth_search$approach is then "CV" and by_location is TRUE. On a layer without repeat locations nothing changes: the criterion is AICc.

The range of the search counts locations. For an adaptive bandwidth it starts at the smallest count that gives every window one location more than the model has parameters, and for a fixed bandwidth at the distance at which half the windows hold that many locations.

AICc and the standard errors still assume independence. info$AICc, the comparison with the global regression in summary() and the standard errors of coef(se = TRUE) and predict(se.fit = TRUE) treat every row as an independent observation. With an effect shared by the rows of a location the standard errors are too small, and AICc compared across bandwidths favours the small ones. info$AICc is NA, with a warning, when the fit (nearly) reproduces the mean of the observations at each location: tr(S) is then not below the number of rows that differ in location or in a predictor, minus 2, and the value the formula gives measures only the spread among observations that share a location. If the repeats are replicates of one measurement, fit their means, one row per location.

Collinearity diagnostics

The function computes scaled condition indices of the design and warns when one exceeds 30, the conventional threshold, which Wheeler & Tiefelsdorf (2005) carry over to the local designs of GWR. An index is the ratio of the largest to the smallest singular value (from an SVD) after each column is scaled (Belsley, Kuh & Welsch 1980); an exactly singular design gives Inf, which counts as the worst case, not an exempt one. Scaling makes the index independent of the predictors' units; kappa() on the raw matrix is not, and a threshold on it is a threshold on nothing in particular.

A global index is computed on the predictors centred at their means (with the intercept, which centring makes orthogonal to them), and kept as info$condition_index. It measures how nearly the predictors are collinear with one another over the whole study area; it is 1 for a single predictor, and a change of origin (degrees C or kelvin, a year or years since 2000) does not move it.

Local indices are then computed at every location, on the weighted design of the local regression there: each row weighted by the square root of its kernel weight at the bandwidth the model is fitted with (supplied or selected), with rows of negligible weight (below 1e-8) dropped. A window left with fewer rows than columns counts as singular. Two indices are kept for each window, as columns of info$local_collinearity:

cn

Belsley's index of the intercept plus the predictors, scaled to unit length but not centred. A predictor whose values in the window are far from 0 against their spread (a year, a temperature in kelvin) is collinear with the intercept and raises it: the local intercept is then an extrapolation to 0 and is ill-determined, but the slopes are not.

cn_slopes

The index for the slopes: the predictors centred at their weighted mean in the window and each divided by its standard deviation over the whole study area. It is 1 when the predictors vary as much, and as independently, inside the window as they do across the study area; it grows as a predictor becomes nearly constant inside the window (a regional covariate) or two predictors move together there. It does not depend on the predictors' origin or units.

A window's slopes count as collinear when cn_slopes is above 30 or singular. Those windows are counted in info$n_local_collinear. A predictor that is constant, or nearly so, inside a window is caught this way whether it is alone or has company, so a single predictor is surveyed too. cn does not enter: the local solve centres each predictor in its window, so a predictor far from zero (a year, a temperature in kelvin, a coordinate) has the slopes it would have at any other origin, and is not flagged, however large cn is. The one exception is a cn that is singular to machine precision, where the predictor's spread is lost in the rounding of its own values.

A warning is issued whenever any location has collinear slopes; the wording reports a percentage when more than 25% of locations are affected and a count otherwise. Both are real R warnings, not log lines. Coefficients at a near-singular window are least-squares estimates with little to rest on, and can be implausibly large. An exactly singular window (an indicator that is constant inside it, or fewer observations than parameters) is of deficient rank: the coefficients it cannot estimate are NA and the fit is returned (see "The local solve"). A window with only cn above 30 raises no warning: plot(fit, type = "coefficients", term = "Intercept") masks it, and slope maps do not. Centre such a predictor if you want an interpretable local intercept. The survey is a caution about how well a coefficient is determined, on rows whose weight is not negligible; the solve's rank is the statement about whether it is determined at all.

A further warning counts local regressions that have no fitted value. That happens where the kernel weights are undefined: with an adaptive bandwidth of k, a location where k or more observations share the same coordinates has a kernel of zero width, and every kernel but the boxcar divides 0 by 0 there. The warning names that cause when it applies. fitted(), residuals(), summary() and model_metrics() all drop those rows, so when this warning fires the metrics describe only the part of the study area that fitted.

See Also

cv_gwr() to score the fit on spatial folds; predict() (spatial_fit-predict) and coef() (spatial_fit-coef) for predictions and local coefficients; gwr_model_selection() and select_features_forward() to choose the predictors; plot.spatial_fit() to map the coefficients.

Other model fitting: fit_bayesian_spatial_model(), fit_rf_model(), gp_lengthscale_bounds(), new_spatial_fit()

Examples


library(sf)
set.seed(1)
n <- 80
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             elev = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
# The slope on elev rises from 1 in the west to 3 in the east.
east <- (st_coordinates(dat)[, 1] - 5e5) / 1000
dat$price <- 10 + (1 + 2 * east) * dat$elev + rnorm(n, 0, 0.3)
fit <- fit_gwr_model(dat, "price", "elev", bandwidth = 30)
summary(fit)
# The local slopes follow the west-east change.
summary(coef(fit)$elev)
head(coef(fit, se = TRUE)$se)          # their standard errors
head(predict(fit, newdata = dat))


Fit a random forest with ranger

Description

Fits a regression random forest on an sf layer and returns it as a spatial_fit, so it works with cv_spatial(), predict_surface(), area_of_applicability() and the plot() method like any other backend. A forest suits a response that is non-linear in its predictors when predictive accuracy matters more than an interpretable model.

Usage

fit_rf_model(
  data_sf,
  response_var,
  predictor_vars,
  num_trees = 500L,
  mtry = NULL,
  min_node_size = NULL,
  importance = c("permutation", "impurity", "none"),
  include_coords = FALSE,
  replace = TRUE,
  sample_fraction = NULL,
  seed = 123L,
  num_threads = NULL,
  .already_prepped = FALSE,
  ...
)

Arguments

data_sf

An sf object with response, predictors and geometry.

response_var

Response column name.

predictor_vars

Predictor column names.

num_trees

Number of trees. Default 500.

mtry

Predictors sampled per split. NULL uses ranger's default.

min_node_size

Minimum node size. NULL uses ranger's default.

importance

"permutation" (default), "impurity" or "none". Impurity importance is biased towards continuous and high-cardinality predictors (Strobl et al. 2007), so permutation importance is the default although it costs more.

include_coords

Add the coordinates as predictors. Default FALSE, which leaves the forest with no spatial information; see Coordinates as predictors.

replace

Logical; grow each tree on a bootstrap sample drawn with replacement (TRUE, ranger's default and this one) or on a subsample drawn without replacement (FALSE). Strobl et al. (2007) show that bootstrap sampling with replacement is itself a source of bias in variable importance toward predictors with many distinct values or categories, and recommend subsampling without replacement. The forest's predictions change slightly with the choice. The setting is recorded in $info and printed with the fit.

sample_fraction

Fraction of rows drawn for each tree. NULL (default) uses ranger's rule: all rows when replace = TRUE, 0.632 (the expected share of distinct rows in a bootstrap sample) when replace = FALSE. A single number in (0, 1] overrides it. replace = FALSE with sample_fraction = 1 grows every tree on every row, so nothing is out of bag: the fit warns (see "Fitted values are out-of-bag").

seed

Seed passed to ranger. Default 123.

num_threads

Threads for ranger. Default NULL means getOption("mc.cores", 1L): one thread unless the session has set more, the convention brms and parallel use. Predictions do not depend on the thread count; pass parallel::detectCores() to use every core.

.already_prepped

Internal; leave at the default.

...

Passed to ranger::ranger(). ranger's own spellings of the arguments this function already sets (num.trees, min.node.size, num.threads, mtry, importance, seed, replace, sample.fraction, x, y) are rejected with a message naming the wrapper argument to use instead. respect.unordered.factors passed here overrides the "order" this function sets when a predictor is categorical; see Categorical predictors.

Value

An rf_fit object (inherits from spatial_fit). $info carries num_trees, mtry, min_node_size, importance_type, importance (a named numeric, or NULL when importance = "none"), include_coords, categorical_predictors (the unordered factor and character predictors, possibly none) and respect_unordered_factors (how ranger was told to split them: "order" unless overridden through ..., and NA when there is none and nothing was passed), replace and sample_fraction (the sampling each tree was grown on, with sample_fraction resolved to the number ranger used), oob_rmse and oob_r_squared (each NA_real_ when ranger did not compute it; forwarding oob.error = FALSE through ... is one way to get there), fitted_are_oob (always TRUE; summary() reads it to label its metrics), seed and n_dropped (the rows prep_model_data() removed for missing or non-finite values or a bad geometry, so $n can be read against nrow(data_sf)), and response_centre and response_scale (below). The raw forest is in $engine.

The forest is grown on the response taken about its centre where that centre is more than 1000 times the response's spread (as at 1e8 plus a spread of 1), and divided by a power of two where the response is so large or its spread so small that its squares overflow or lose their bits (beyond about 1e100 or 1e-100). The splits of a forest do not change under a shift or a scale of the response, and ranger's split scores, formed from squares of the response, read the rounding of the offset otherwise. $info$response_centre (0 where none is taken) and $info$response_scale (1 where none is applied) record them, and they are put back on fitted(), predict(), residuals(), oob_rmse and importance (squared units, so multiplied by the scale twice; beyond the range of doubles it is Inf or loses its bits, and a WARN line says so). The permutation importance under scale.permutation.importance = TRUE and the impurity importance under splitrule = "maxstat" have no units and are left as ranger reports them. The forest in $engine predicts (y - response_centre) / response_scale, and its own predictions and prediction.error are in those units. Every other response is passed to ranger as it is.

Coordinates as predictors

include_coords = TRUE adds the x and y coordinates to the predictors. They are the only spatial information a forest can be given: without them it sees the covariates alone, and print() says "no spatial information used". The default is FALSE.

The gain from the coordinates depends on where the predictions are wanted. A forest splits on location as on any column, so it follows the training surface closely between sampled points, and has only the nearest edge of the data to go on beyond them. Between sampled points the coordinates can lower the error, most where the covariates carry little of the spatial structure themselves, and the gain fades with distance from the training data. Beyond the autocorrelation range, or in an area the data never visited, the coordinates can make predictions worse (Meyer et al. 2019). With covariates that carry the spatial structure themselves, expect less from the coordinates.

Score the forests with and without coordinates on the same folds, at the distances the map will be used at (see "Fold methods" in make_folds(); "Out-of-bag error" below says why the out-of-bag error does not serve). Build the folds once and pass them to cv_rf() with and without the coordinates:

folds   <- make_folds(dat, k = 5, method = "block_kfold")
plain   <- cv_rf(dat, "z", c("a", "b"), folds = folds)
with_xy <- cv_rf(dat, "z", c("a", "b"), folds = folds,
                 include_coords = TRUE)
c(plain = plain$overall$RMSE, with_xy = with_xy$overall$RMSE)

The example on cv_rf() runs this comparison and reads it fold by fold. Setting include_coords = TRUE logs this advice once per session, as a log line rather than an R warning, and not once for every fold of a cross-validation.

Categorical predictors

A predictor that is an unordered factor or a character column is split with respect.unordered.factors = "order": ranger orders its levels by mean response once, before growing, and splits on that order, the handling ranger's own help recommends. ranger's default for a regression forest, "ignore", splits on the order the levels are stored in (alphabetical, for most data), which for a nominal variable is arbitrary. Pass respect.unordered.factors through ... to choose otherwise ("ignore", or "partition" for every two-way split of the levels, which is slow beyond a few levels). Ordered factors are left alone and split on their own order, and with splitrule = "extratrees" ranger's own default for that rule, "partition", is kept. The setting is recorded in $info$respect_unordered_factors and printed with the fit.

Out-of-bag error

ranger's out-of-bag (OOB) error holds each observation out of the trees that did not sample it. That is a random hold-out: the trees that did not see a point almost always saw its neighbours, so under spatial autocorrelation it is the error of predicting among the samples, as random k-fold is, and reads low for predictions made farther from the data than the samples sit from each other (see make_folds()). It is reported as $info$oob_rmse and $info$oob_r_squared and labelled as OOB wherever it appears. Use cv_rf() for a spatial estimate.

Fitted values are out-of-bag

fitted() on an rf_fit returns out-of-bag predictions, as the random forest packages themselves do. In-sample predictions from a forest come close to reproducing the training data, and their R^2 says little about new data. summary() therefore reports out-of-bag metrics for a forest and in-sample metrics for a GWR or a Bayesian GP fit, and the two do not compare; compare_models_cv() scores every backend on the same folds.

A row that every tree sampled has no out-of-bag prediction, and ranger reports NaN for it. That is every row under replace = FALSE with sample_fraction = 1, and a few under a small num_trees. The fit warns with the count; fitted() and residuals() are NaN on those rows, and summary() says how many rows its metrics were computed on. With no row out of bag at all, the OOB error (NA in $info$oob_rmse and $info$oob_r_squared) and the permutation importance (NaN) are undefined too, and print() says so. cv_rf() scores its fold forests on the held-out rows, never out of bag, so it warns once with the number of folds affected rather than once per fold.

References

Meyer, H., Reudenbach, C., Wöllauer, S. and Nauss, T. (2019). Importance of spatial predictor variable selection in machine learning applications – moving from data reproduction to spatial prediction. Ecological Modelling 411, 108815. doi:10.1016/j.ecolmodel.2019.108815

Strobl, C., Boulesteix, A.-L., Zeileis, A. and Hothorn, T. (2007). Bias in random forest variable importance measures: illustrations, sources and a solution. BMC Bioinformatics 8, 25. doi:10.1186/1471-2105-8-25

See Also

cv_rf() to score the forest on spatial folds; predict() (spatial_fit-predict) and predict_surface() to predict; area_of_applicability() to mark where the predictions apply (it weights the predictors by this forest's importance).

Other model fitting: fit_bayesian_spatial_model(), fit_gwr_model(), gp_lengthscale_bounds(), new_spatial_fit()

Examples


library(sf)
set.seed(1)
n <- 150
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             a = rnorm(n), b = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
dat$z <- 2 * dat$a - dat$b + rnorm(n, 0, 0.3)
fit <- fit_rf_model(dat, "z", c("a", "b"))
fit
fit$info$importance     # permutation importance of a and b


Measure how far the held-out points sit from their training data

Description

Returns, for each fold, how far the held-out points sit from their nearest training point. make_folds() only compares the block size with the estimated autocorrelation range; this measures the folds that were built. Nothing is estimated: the distances come from the geometry, and the range, when one is shown, is the one the folds carry (make_folds(auto_range = TRUE) records it) or the one you pass as sac.

Usage

fold_separation(folds, data_sf, sac = NULL, prediction_points = NULL)

Arguments

folds

A make_folds() result, or its ⁠$folds⁠ element (a list of train/test splits).

data_sf

The layer the folds were built on. Row identifiers are matched through ..row_id when the layer carries one, and by row position otherwise, as in make_folds() and every ⁠cv_*()⁠ function. As in ⁠cv_*()⁠, a make_folds() result whose recorded rows sit at other locations here (folds built on another layer, such as the points before assign_features_to_polygons() dropped some) is refused; the location check is skipped when one of the two layers is POINT and the other is not. A layer that mixes dimensions or carries M is read in x and y, for the distances and for that check (spatialkit-geometry). A row without a location, as given or in the CRS the distances are measured in, is left out of the distances.

sac

Optional: an estimate_sac_range() result or a single number. Defaults to the range the folds carry, if any. Supplying one adds the mean_cor column and, with a prediction target, the gap on the correlation scale. A range that records its CRS (the folds' own, or an estimate_sac_range() result) is compared with distances measured in that CRS, whatever CRS data_sf is in. A bare number is taken to be in the units the distances are otherwise measured in: those of data_sf if it is projected, and for lon/lat input metres, in the CRS ensure_projected() chooses (as for the block_size of make_folds()), not degrees. A units object is refused.

prediction_points

Optional sf or sfc layer of the locations the model will predict at: the grid from predict_surface(), or a grid over the region of interest (sf::st_make_grid(region, what = "centers")). A layer of other geometry is reduced to one representative point per feature, as in make_folds(method = "nndm"), so pass grid cells or points, not one polygon of the region. It is brought into the CRS the distances are measured in, and read in x and y when it mixes dimensions or carries M (spatialkit-geometry). Default NULL: no target and no reading, except for NNDM and kNNDM folds (method = "nndm" and "knndm"), which carry the distances from the prediction points they were built for and are compared against those, measured to all sites. The carried distances are lengths in the CRS the folds were built in (folds$params$crs). When the distances here are measured in another CRS (data_sf is in another projected CRS, or sac records another), the two are not compared, print() says so, and passing prediction_points has the target measured here. A prediction point without a location, as given or in the CRS the distances are measured in, takes no part in the target and is not counted.

Details

The distances do not say by themselves which way a score errs. A cross-validated error reads low when the held-out points sit closer to their training data than the locations the model will predict at, and high when they sit farther, so the same held-out distances can go with either, depending on the target. Random folds on evenly sited data, scored for a map of the sampled area, are close to unbiased although nearly every held-out point has a training neighbour inside the range; range-sized blocks on the same data read high; random folds on clustered data scored for a map of the whole region read low. So without a prediction target the function reports the distances and draws no conclusion. Give it prediction_points and it sets the held-out distances beside the distances from those points to the same training data, and words its reading by the signed gap between the two.

cv_block_size_sweep() gives the cross-validated error at each block size, but not which size matches a map. This function does, read on the folds of each size (the ⁠$folds⁠ of each element of attr(sweep, "results")) with the map's locations as prediction_points.

Value

A data.frame of class fold_separation, one row per fold: fold (the fold's number: for the $folds of a cv_*() result, the fold_id its fold_metrics use, which differs from the list position once a fold has been dropped), n_train, n_test, n_blocks (NA for a scheme with no blocks), min_dist and median_dist (distance from a held-out point to its nearest training point, in the units of the CRS the crs attribute names), mean_cor, target_median_dist (the median distance from the prediction points to the fold's training data) and dist_gap (the fold's mean held-out distance minus its mean prediction distance); the last two are NA without a target, and print() shows them under the headings target and gap.

mean_cor is a mean correlation, NA without a range: the mean over the fold's held-out points of \rho(d), the correlation the range leaves between a point and its nearest training point at distance d. It is 1 for a point on top of training data and falls towards 0 beyond the range, so a point at a twentieth of the range counts for more than one at nine tenths of it. \rho(d) is \exp(-3 d / range), the exponential model whose effective range is the range given (0.05 at the range), or the spherical model when the range comes from an estimate_sac_range() fit that was spherical; the range_model attribute says which.

Attributes: method, sac_range, range_model, crs (the CRS the distances were measured in), n_unknown_ids (the number of distinct rows the folds name that data_sf does not have, each counted once however many folds mention it, as in the cv_*() field of the same name), pooled (a list with the number, minimum, median and mean of the held-out distances over all folds, and the pooled mean_cor) and target: NULL without a prediction target, otherwise a list with n_prediction_points, source, basis ("each fold's training data" or "all sites"), held_out_mean, held_out_median, target_mean, target_median, target_all_mean, target_all_median (the prediction distances to all sites), mean_diff, w1, cor_gap, cor_w1 (NA without a range), scale ("correlation" or "distance"), tolerance, reading (see the section "Reading the gap") and nndm_out_of_reach (for NNDM and kNNDM folds, the params$target_out_of_reach that make_folds() recorded; NA for other schemes). not_compared is NULL, or, for NNDM or kNNDM folds whose carried target was not compared because the distances here are measured in another CRS, one sentence naming the two CRSs; target is then NULL and print() gives the sentence where it would otherwise say that no target is given.

Reading the gap

With a target, the held-out distances and the prediction distances are compared as two distributions. Each fold's prediction distances are measured to that fold's own training rows, so that a five-fold design is not read as too far only because each fold trains on four fifths of the sites; the distances to all sites are reported beside them. With more than 50 folds, as in the leave-one-out schemes, every training set is nearly the whole sample, and the prediction points are measured against all sites once. Folds count by their share of the held-out points.

Two numbers summarise the comparison: the signed difference of the means, held-out minus prediction (the signed area between the two cumulative distributions), and the Wasserstein distance W_1 (the unsigned area). When a range is available both are also given on the correlation scale, after each distance d is replaced by 1 - \rho(d), with \rho the correlation the range implies (see mean_cor under Value). That scale counts a difference between two distances well inside the range and ignores one between two distances beyond it.

The reading is taken on the correlation scale when there is a range, with a tolerance of 0.1, and otherwise on the mean distance, with a tolerance of a quarter of the prediction mean. When the prediction points are measured to all sites and every one lies on a site, as when the sites themselves are passed as prediction_points to a leave-one-out design, the prediction mean and with it that tolerance are 0: held-out distances above 0 then read "farther", and held-out distances that are all 0 as well read "matched". With 50 folds or fewer the points are measured to each fold's own training rows, which leave out that fold's held-out sites, so the mean is above 0 and the quarter rule gives the reading.

"closer"

The gap is below minus the tolerance and at least half of W_1 in size: the held-out points sit closer to their training data than the prediction points do, and the cross-validated error tends to read low for that target.

"farther"

The gap is above the tolerance and at least half of W_1: the held-out points sit farther, and the error tends to read high for that target.

"matched"

The gap is within the tolerance and W_1 within twice the tolerance.

"mixed"

The two distributions cross, closer at some distances and farther at others (the gap is under half of W_1, or it is within the tolerance while W_1 is not), so the distances give no single direction.

The reading is a statement about nearest-neighbour distances, not a measured bias. A learner that draws on several neighbours can still score low on clustered samples whose nearest-neighbour distances match.

See Also

make_folds() for the fold schemes and the block sizing this measures the outcome of, plot_folds() to map the folds, and cv_block_size_sweep() for the cross-validated error at each block size.

Other folds: cv_block_size_sweep(), make_folds(), plot_folds()

Examples

library(sf)
set.seed(1)
n <- 200
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000)),
  coords = c("x", "y"), crs = 32632
)

# Random folds put a training point close to every held-out one; blocked
# folds hold out whole neighbourhoods, so the distances grow.  The median
# distance from a held-out point to its nearest training point, per fold:
random  <- make_folds(pts, k = 4, method = "random_kfold", seed = 1)
blocked <- make_folds(pts, k = 4, method = "block_kfold",
                      block_size = 250, seed = 1)
round(fold_separation(random, pts, sac = 200)$median_dist)
round(fold_separation(blocked, pts, sac = 200)$median_dist)

# Which of the two suits a map of the sampled square?  Compare each with
# the distances from the cells of that map to the training data.
cells <- st_make_grid(pts, n = c(20, 20), what = "centers")
print(fold_separation(random, pts, sac = 200, prediction_points = cells))
print(fold_separation(blocked, pts, sac = 200, prediction_points = cells))

Place seeds for a Voronoi tessellation

Description

Creates an sf POINT layer of seed locations, one per cell of the Voronoi tessellation built on them: k-means centres of a cloud of points, points drawn uniformly inside a boundary, or points you provide.

Usage

get_voronoi_seeds(
  boundary = NULL,
  method = c("kmeans", "random", "provided"),
  n = NULL,
  seeds = NULL,
  sample_points = NULL,
  kmeans_nstart = NULL,
  kmeans_iter = 100,
  set_seed = NULL,
  partition = c("density", "kmeans"),
  init = NULL,
  density_power = 1,
  density_k = 8
)

Arguments

boundary

Optional polygonal sf object defining the sampling area. Rows without a location, rows the repair leaves without a polygon, vertices at a latitude beyond 90 and mixed dimensions are handled as "Boundaries" in spatialkit-geometry says; "Sampling inside the boundary" gives how points are drawn in it.

method

How to place the seeds: "kmeans" (default; cluster centres of sample_points, or of points drawn in boundary), "random" (uniform in boundary) or "provided" (the points in seeds).

n

Integer; number of seeds to return. Required for method = "kmeans" and method = "random". Ignored for method = "provided", where every row of seeds is returned; a mismatch between n and nrow(seeds) is reported as a warning.

For method = "kmeans" it is an upper bound only: k-means cannot produce more centres than there are distinct positions in the sampling cloud, nor as many centres as there are rows. When n exceeds either ceiling it is clamped, with a warning naming the count used. Asking for as many seeds as there are points (n = nrow(sample_points)) gives nrow(sample_points) - 1. Check nrow() on the result; do not assume n.

Besides a number, n accepts what the level-selection step returned: the integer vector of ranked candidates from determine_optimal_levels() (its first element is used; its NA is refused with a note on where it came from), a select_resolution() result (its ⁠$best⁠), or a resolution_profile(). A profile built without an estimate is read with select_resolution() by cp. A profile built with estimate is read by criterion = "auto", the rule that goes with its estimate: a size for pooled values and the lowest leave-one-out error for plain means. The size is the profile's own when it was built at one, and 4.5 rows per cell otherwise, and the count is the profile's level for that size, or the built level nearest to max(2, round(n / obs_per_cell)) when the profile has none for it (with a warning of class "spatialkit_size_not_reached"). select_resolution(profile) with no criterion reads such a profile the same way, since its default criterion is "auto". A profile built with obs_per_cell and without an estimate is read by cp like any profile without one; pass select_resolution(profile, criterion = "size") for the count its size gives. The result then carries attr(, "n_from") saying which. A count read off a selection or a profile comes with what the selection found: a warning of class "spatialkit_bound_chosen" when the optimum sits on a bound of the ladder, so the bound chose the count, and one of class "spatialkit_no_structure" when one cell for the whole layer scores as well. A count set by a size has no optimum, so no bound can choose it; its "spatialkit_no_structure" warning says that the count stands and that the cell values will say little that one mean does not. A profile without an estimate and with no cp to read is an error (class "spatialkit_no_default_criterion" when another criterion is finite); see resolution_profile().

With method = "kmeans", a selection or profile also carries the centres of the partition the profile scored at that count, and those are returned instead of a new k-means: a k-means partition, weighted or not, is the Voronoi partition of its centres, so their cells are the cells the criteria judged. On a profile without an estimate whose centres were fitted to a subsample, select_resolution() refits them to every point first, and those centres are returned, with attr(, "refit"): their cells are near the cells judged but not the same. sample_points, when given, is then only assigned to them (for attr(, "kmeans")) and gives the cover, and boundary only sets the CRS and the cover; kmeans_nstart, kmeans_iter and set_seed are not used, and neither are partition, init and the density settings: the centres are of the kind the profile was built with, and naming another here is a warning of class "spatialkit_partition_unused". A call names what it supplies: a partition or an init passed in the call; with partition = "density" passed, both density settings at their values, defaults included; without it, a density setting other than its default. A call that supplies none of the four is told nothing, whichever kind and settings the profile was built with. Pass the count as a number (n = sel$best) for a fresh k-means instead.

seeds

sf POINT object of user-provided seeds (method = "provided"). Methods "kmeans" and "random" do not read it, and ignore it with a warning; so does a call that passes ⁠seed =⁠, which R matches to seeds (the seed of the random stream is set_seed). Seeds in another CRS than boundary are returned in the boundary's CRS; seeds that mix XY and XYZ (or XYM) points are then returned in XY, with a warning of class "spatialkit_zm_dropped", since sf reads a layer in the dimension of its first geometry.

sample_points

Optional sf POINT cloud for k-means clustering. Method "random" places its seeds in boundary and does not read it; it is ignored there with a warning. Only the first two coordinate columns are clustered, so a Z or M dimension does not join the distance calculation and dominate it; rows without a location (an empty point, a coordinate that is not finite or lies beyond 1e150, or in a geographic CRS a latitude beyond 90 degrees, read as given before any move) are dropped with a warning, so they never reach stats::kmeans(), which fails on them without naming a cause. A lon/lat cloud, or one with no CRS whose coordinates look like lon/lat (the heuristic ensure_projected() applies, with its warning), is projected before clustering. A cloud that mixes XY and XYZ (or XYM) points is read without Z and M before it is projected or clustered, since sf reads a layer in the dimension of its first geometry.

kmeans_nstart

The number of starts, of which the best is kept. NULL (default) uses 3 starts for partition = "density" and 10 for partition = "kmeans". Under partition = "kmeans" from random starts it is nstart of stats::kmeans(). A fresh partition is not the one resolution_profile() scored a count on; pass the selection or profile itself as n for that one (see n). Under partition = "density", and with init = "kmeans++", it has to be NULL or a positive whole number, so a number that is not whole, which partition = "kmeans" takes, stops a call that names no kind. It is not read by method = "random" or "provided".

kmeans_iter

Integer; iter.max for stats::kmeans(). Default 100 for both kinds (voronoi_seeds_kmeans() uses 50 for plain k-means by default). Under partition = "density" it is the most steps of Lloyd's iteration a start takes. Under partition = "density", and with init = "kmeans++", it has to be a positive whole number, and a kept start that was cut off at it is a warning of class "spatialkit_not_converged" (partition = "kmeans" from random starts keeps the warning stats::kmeans() gives).

set_seed

Optional integer seed for the random draws. Default NULL: the draws come from the session's random-number stream, so set.seed() before the call makes it reproducible. A number gives the same seeds every time and leaves the caller's stream as it was. (voronoi_seeds_kmeans() defaults to 456 instead.)

partition

For method = "kmeans": what the seeds minimise. "density" (default) is the sum of squared distances from the points of the cloud to their nearest seed, each point weighted by its local density to the power density_power: compact cells, many small ones where the points are dense and a few large ones where they are sparse. At the default power they hold about the same number of points each once n is above the number of dense places (clusters) in the cloud; below that the counts are about as uneven as under "kmeans". "kmeans" is the same sum unweighted: compact cells, with several times the points in a cell of a dense place that a cell of a sparse place holds. It is stats::kmeans() from 10 random starts on the rows as they come, with the coordinates centred, divided by the diagonal of their bounding box and rounded to 2^-30 of it, so that the seeds do not move with the unit or the origin; where the locations span less than a kilometre a change of unit or origin can still move them (see "The partition" in resolution_profile()). The density kind follows the density of sample_points; a cloud this function draws inside boundary is uniform and has none to follow. Without the FNN package the density kind finds its weights by comparing every pair of distinct locations, so its time grows with the square of their number; the seeds are the same, and nothing stops the call. See "The partition" in resolution_profile() for what each kind does and how.

init

For method = "kmeans": how each start is drawn, "random" (n distinct locations at random, as stats::kmeans() draws them) or "kmeans++" (the seeds one at a time, each in proportion to its squared distance from those already drawn, times its weight under partition = "density"). NULL (default) is each kind's own rule: "random" for partition = "kmeans" and "kmeans++" for partition = "density". Under partition = "kmeans" from random starts the cloud is clustered in the order its rows come in; with init = "kmeans++", and under partition = "density", the rows are put in coordinate order first, so the seeds do not depend on their order.

density_power

For partition = "density": the power the local density is raised to for a point's weight, from 0 to 2. Default 1, which evens out the cell counts once the cells outnumber the dense places; 0 weights every point alike. Setting it under partition = "kmeans" is a warning.

density_k

For partition = "density": the number of nearest neighbours the local density is read from. Default 8.

Details

Seeds lie inside the ground they stand for (k-means seeds inside the hull of the points they were fitted to, random seeds inside the boundary), so Voronoi cells clipped to the seeds' own hull would leave its edge uncovered. The result therefore carries that ground as attr(, "cover"): the boundary when one was given, otherwise the convex hull of sample_points (for lon/lat points, the hull of their coordinates in degrees, with the longitudes of points on both sides of 180 degrees taken from 0 to 360, -170 as 190), otherwise (for the scored centres of a resolution_profile() or a select_resolution() result passed as n) the hull of the points the profile was computed on. build_tessellation() and create_voronoi_polygons() derive their default boundary from it, so build_tessellation(seeds, method = "voronoi") holds every observation without a boundary. Seeds with no cover are tessellated over their own hull unless a boundary or cover is passed then: method = "provided" seeds given with neither boundary nor sample_points have none, and no warning is raised for them, since they may be the observation sites themselves. The attribute survives sf::st_transform() and row subsetting; rbind() drops it.

A k-means seed is a mean of the points of its cluster, weighted under the density kind, so it can lie outside a boundary that is not convex, in a bay or a bend of a coast, even when every point lies inside. Tessellated within that boundary, its cell is built if any of it lies inside: the part of the study area nearer the seed than any other seed. build_tessellation() gives the seed that cell in index, as it gives every seed the cell it generates, so seeds$cell_id <- tess$index holds each seed's cell for cell_values_at(). A seed with every part of the study area nearer another seed has no cell, NA in index, and a warning of class spatialkit_unassigned gives the number.

Value

An sf POINT object with seed_id and method columns. With method = "kmeans" it also carries attr(, "kmeans"), the run behind the seeds: cluster (the seed_id each clustered cloud point was assigned to), rows (those points' positions in the cloud, since rows with unusable coordinates are dropped first), size (points per seed), withinss and tot_withinss (the within-cluster sums of squares), iter and nstart. For the scored centres of a selection or profile (see n) it describes sample_points assigned to them, each point to its nearest seed, with iter NA and nstart the profile's restarts, and is absent when no sample_points were given. A point the same distance from two seeds (squared distances within one part in ten million) goes to the lower seed_id, the rule the profile scores its cells by, so the record is the same in another unit or with another origin. Under partition = "density" withinss and tot_withinss count every point once, about its cell's mean. A run this call makes with partition = "density" or init = "kmeans++" also records converged, whether the kept start stopped before kmeans_iter, and under partition = "density" objective, the weighted sum the seeds minimise; scored centres have neither. Seeds placed with partition = "density" or init = "kmeans++", and the scored centres of a profile of the density kind or from random starts, carry attr(, "partition"): a list with kind, init, density_power and density_k, and for seeds this call placed iter, iter_max and converged (the iterations the kept start took, the limit, and whether it stopped before the limit). build_tessellation() returns the list as params$partition. Seeds with no such record are plain k-means: from random starts when this call placed them, or the scored centres of a k-means profile from k-means++ starts. Every method also attaches attr(, "cover") when the call says what ground the seeds stand for (see "Details"): an sfc holding the boundary's polygons or the hull of the clustered points, in its own CRS.

When n is a select_resolution() result that carries count_rule, or a profile built with an estimate or read by cp, the seeds carry that record as attr(, "count_rule"): how the count was set, for which cell value, and what the profile scored at it. Its scored_cells is TRUE for the scored centres method = "kmeans" hands on, and FALSE for centres refitted to every point (see n) and for seeds this call places itself at that count: a k-means of its own when the selection holds no centres at the count, and every method = "random" seeding. method = "provided" does not read n and writes no record; seeds that already carry one (sel$seeds) keep it, marked FALSE when their number is not the record's count. build_tessellation() and assign_features_to_polygons() hand the record on, and summarize_by_cell() checks its result against it. A count given as a number, or read off a profile without an estimate by cp or elbow, has no record.

Sampling inside the boundary

Seeds drawn by method = "random", and the cloud method = "kmeans" draws when no sample_points are given, are sampled inside boundary. Its rows are repaired with sf::st_make_valid() before they are unioned. In longitude and latitude the union runs with s2, and a row s2 still refuses (crossing edges, a vertex listed twice) is repaired again, with crossing edges split as GEOS splits them in a projected CRS; a row s2 refuses even then stops the call with an error of class "spatialkit_cells_degenerate" that names it and says to transform boundary to a projected CRS.

In longitude and latitude, a boundary whose bounding box is over 10,000 times its area (small pieces far apart), which sf does not sample whole, is sampled piece by piece, the points shared among the pieces in proportion to their areas; a piece whose own box is over 10,000 times its area stops the call with an error that says to transform boundary to a projected CRS. A boundary whose bounding box has no height or no width (three vertices on one parallel) is refused. In longitude and latitude s2 reads the edges as great circles, which leave the bounding box read from the coordinates, and sf (without lwgeom) draws in that box: a boundary whose box has less than half its area on the sphere (three vertices on or near one parallel) is refused too. That error, and the error for a box with no height whose vertices lie on one parallel other than the equator, say to transform boundary to a projected CRS in which a parallel is a curve, such as the one ensure_projected() picks for it (a polar one, such as EPSG:3413 or 3031, for a ring around a pole), where the region has an area and lies in its box.

sf draws the points in the bounding box and keeps those inside, so it draws the number asked for times the ratio of the box to the area. In any CRS, a boundary that would take more than 10^6 points drawn in its box, or 10 times the points asked for if more (small pieces far apart, a thin strip at a slant), is sampled piece by piece in the same way (or whole, in draws of at most 10^6 points in its box, where that takes less time), and a piece that would still take more is drawn in such draws. Where the points drawn in all would exceed 2e7 (or 10 times the points asked for, if more), the call stops before any draw with an error that gives the ratio and says to pass sample_points (method = "kmeans", whose cloud is max(2000, 50 * n) points) or to ask for fewer seeds.

See Also

Other cell building: build_tessellation(), clip_target_for(), create_grid_polygons(), create_grid_polygons_cached(), create_voronoi_polygons(), ensure_stable_poly_id(), plot_tessellation_map(), voronoi_seeds_kmeans(), voronoi_seeds_random()

Examples

library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
  c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
get_voronoi_seeds(bnd, method = "random", n = 5, set_seed = 1)

# Seeds from a cloud with one dense place: density-weighted k-means (the
# default, 3 starts) against plain k-means.  The fewest and most points a
# seed's cell holds under each kind, with more seeds than dense places:
set.seed(2)
cloud <- st_as_sf(data.frame(x = c(rnorm(150, 30, 5), runif(50, 0, 100)),
                             y = c(rnorm(150, 30, 5), runif(50, 0, 100))),
                  coords = c("x", "y"), crs = 32632)
dens <- get_voronoi_seeds(bnd, method = "kmeans", n = 20,
                          sample_points = cloud, set_seed = 1)
km   <- get_voronoi_seeds(bnd, method = "kmeans", n = 20,
                          sample_points = cloud, set_seed = 1,
                          partition = "kmeans")
sizes <- list(density = attr(dens, "kmeans")$size,
              kmeans  = attr(km, "kmeans")$size)
sapply(sizes, range)   # fewest and most points per seed

Compute length-scale bounds for a squared-exponential GP

Description

Computes lower and upper bounds for the length-scale \ell of a squared-exponential (exponentiated-quadratic) kernel, k(h) = \exp(-h^2 / (2\ell^2)), from the spread of the pairwise distances between the points. fit_bayesian_spatial_model() calibrates its length-scale prior over them. The effective range, where the correlation drops to 5 percent, is \ell \sqrt{2 \ln 20} \approx 2.45\,\ell.

Usage

gp_lengthscale_bounds(coords_xy, q_small = 0.25, max_n = 1000L)

Arguments

coords_xy

Numeric matrix or data.frame of coordinates with at least two columns; the first two are used, and replicated rows are collapsed before the distance quantiles are taken, because brms::gp() (gr = TRUE, its default) reduces its covariates to unique rows: a station sampled many times would otherwise weight the quantile by how often it was measured rather than by where the sites are. A row with a coordinate that is missing, not finite or beyond 1e150 has no location: it is left out, with a warning of class spatialkit_rows_dropped that gives the count.

q_small

Quantile of the pairwise distances for the lower bound, a single number in [0, 1]. Default 0.25. On clustered data a low quantile reflects the spacing within clusters.

max_n

Maximum number of distinct points to use in the distance computation. Default 1000. Set to Inf to use all of them. Above it, a subsample is drawn with a fixed seed from the distinct points in coordinate order, so the bounds do not depend on the row order of coords_xy, and the caller's random-number stream is left where it was.

Details

The lower bound is the q_small quantile of the pairwise distances (by default the 25th percentile) taken as an effective range, and the upper bound is the largest pairwise distance taken as an effective range. The inverse-gamma prior that fit_bayesian_spatial_model() calibrates on them puts 1 percent of its mass below the lower bound and 1 percent above the upper. Both are fixed fractions of the spread of pairwise distances, so they do not shrink as points are added to the same area: more points help the data identify a short range, but they make neither these bounds nor the basis derived from them finer.

These are the bounds a length-scale prior is calibrated over, not the scales a fitted model can resolve, which depend on the basis size (gp_k in fit_bayesian_spatial_model(), which reports it as $info$gp_ell_min, and in CRS units as $info$gp_resolution). A surface whose range is shorter than the lower bound needs a basis fine enough to represent it and a prior that allows it. A larger gp_k under the prior calibrated here changes almost nothing, because the prior still holds the length-scale above this bound. fit_bayesian_spatial_model() therefore moves the prior's lower tail down to the length-scale the basis resolves whenever gp_resolution or an explicit gp_k asks for a finer basis than the one derived from these bounds.

Large layers are subsampled (max_n) to bound the cost of the pairwise distances, which grows with the square of the points.

Value

Named numeric vector c(lower, upper): length-scales in the units of coords_xy. lower is the q_small quantile of the distinct pairwise distances divided by \sqrt{2 \ln 20} (about 2.45); upper is the largest pairwise distance divided by the same factor, and at least 1.2 times lower. c(lower = 0.001, upper = 1) when fewer than two distinct located rows or no positive distances remain. fit_bayesian_spatial_model() standardises the coordinates before it calls this function, so its bounds are in those standardised units.

See Also

Other model fitting: fit_bayesian_spatial_model(), fit_gwr_model(), fit_rf_model(), new_spatial_fit()

Examples

# 500 points spread evenly over a square of side 100 km, in metres.
set.seed(1)
xy <- cbind(runif(500, 0, 1e5), runif(500, 0, 1e5))
b <- gp_lengthscale_bounds(xy)
b
# The bounds as effective ranges: the 25th percentile of the pairwise
# distances, about a third of the side, and the largest distance.
b * sqrt(2 * log(20))

Select GWR predictors by forward selection on AICc

Description

Grows a GWR model one predictor at a time and scores every intermediate model with a corrected Akaike information criterion, the sweep GWmodel::gwr.model.selection() defines, and returns a ranked table with each model's distance from the best. The model without predictors is scored too. Every model is fitted by the package's own local solve (see "The local solve" in fit_gwr_model), so a candidate that is constant inside some windows, a regional indicator say, is scored on what those windows do estimate and neither stops the sweep nor scores as rounding error.

Usage

gwr_model_selection(
  data_sf,
  response_var,
  candidate_vars,
  bandwidth = NULL,
  adaptive = TRUE,
  kernel = c("bisquare", "gaussian", "tricube", "boxcar", "exponential"),
  bw_approach = c("AICc", "CV"),
  max_models = 200L,
  dmat_max_n = 2000L,
  quiet = TRUE,
  .engine = .gwr_ms_engine
)

## S3 method for class 'gwr_model_selection'
print(x, n = 10L, ...)

Arguments

data_sf

An sf object with response, predictors and geometry.

response_var

Response column name.

candidate_vars

Character vector naming at least two numeric predictors to choose among. Factor, character and logical candidates are refused: a factor is several model-matrix columns while this sweep counts it as one variable, so the criteria would not be comparable, and fit_gwr_model(), the documented next step, takes only numerics. Encode them as numeric indicators first.

bandwidth

Bandwidth held fixed across all candidate models. If NULL (default) it is searched for on the model containing every candidate, by the grid-then-refine search of fit_gwr_model() (see its Bandwidth selection); what the search scored is returned in bandwidth_search. Integer neighbour count when adaptive = TRUE; otherwise a distance in the units of the projected CRS the sweep runs in, which prep_model_data() may have chosen for you. Geographic input is projected before the bandwidth is used, so a value in degrees would be read as metres; a fixed bandwidth below a ten-thousandth of the data's extent raises a warning saying so, as in fit_gwr_model(). An adaptive count too small for the full model is raised, with a warning, to the number of candidates plus 3 for the bisquare and tricube kernels (which give the farthest neighbour in a window weight 0), plus 2 for the others. That floor is enough unless several neighbours tie at the kernel's edge (a regular grid), which leaves a window fewer weighted points; then use a larger bandwidth. An adaptive count below 1 or above R's largest integer is refused, as in fit_gwr_model(). One above the number of observations is capped at it, with a warning.

adaptive

Logical; adaptive (nearest-neighbour) bandwidth. Default TRUE.

kernel

Weighting kernel: one of "bisquare" (default), "gaussian", "tricube", "boxcar" or "exponential", as in fit_gwr_model().

bw_approach

Criterion for the bandwidth search on the full model: "AICc" (default, the criterion fit_gwr_model() uses) or "CV", the leave-one-out sum of squared prediction errors. fit_gwr_model() has no CV option, so with "CV" pass the selected bandwidth to it explicitly. When observations share a location the search leaves out whole locations whichever is asked for; see Observations that share a location.

max_models

Refuse the call if the sweep would exceed this many model fits. Default 200, which admits up to 19 candidates.

dmat_max_n

Not used. The sweep takes its distances window by window and builds no n x n distance matrix, so a fixed bandwidth works at any n. The argument is accepted so that calls written with it run.

quiet

Print no progress. Default TRUE, unlike select_features_forward(). With FALSE one line is written (with cat()) as each model is fitted, to watch a long sweep progress.

.engine

Internal; leave at the default.

x

A gwr_model_selection object.

n

Number of top-ranked models print() shows. Default 10.

...

Not used.

Value

An object of class gwr_model_selection, a list with:

best

Character vector of the selected predictors, the model with the lowest criterion; character(0) when that is the model without predictors.

table

Ranked data.frame of every model evaluated, with columns rank, n_vars, variables, criterion and delta, the criterion minus the best model's. The model without predictors is the row <none>. criterion is NA, and the model is ranked last, where it could not be evaluated or where AICc is undefined because the model's effective number of parameters tr(S) is not below n - 2 (with a warning).

within_2, smallest_within_2

The rows of table whose delta is at most 2, and the predictors of the smallest model among them.

criterion

"AICc".

criterion_by_name, criterion_column, criterion_verified

Where the criterion was read from the diagnostic table: TRUE, 3 and TRUE with the built-in engine.

response_var, candidate_vars

The response and the full candidate set the sweep ran over, both echoed by print().

bandwidth, bandwidth_source, adaptive, kernel

The smoothing held fixed across the sweep, and where it came from: "supplied", or the criterion's name followed by "search on the full model", the criterion being "leave-one-location-out CV" when observations share a location.

bandwidth_search

What the search scored, as fit_gwr_model keeps it; NULL when the bandwidth was supplied.

n_obs, n_models

The number of observations, and the number of rows of table.

used_dmat

Always FALSE.

raw

The forward sweep in the layout GWmodel::gwr.model.selection() returns: the two-element list of its model list and its diagnostic table, without the model that has no predictors.

Scope of the criterion

AICc penalises the effective number of parameters but is computed on the data the model was fitted to, and under spatial autocorrelation an in-sample criterion is optimistic in a way that a spatially blocked estimate is not. Use this function as a fast screen and confirm with select_features_forward(), which runs the same forward search on a spatially blocked cross-validated score at a higher cost.

Every model is fitted at one bandwidth, as Lu et al. (2014) define the method: comparing criteria across models needs the smoothing held fixed. The bandwidth chosen for the full model is not optimal for smaller ones, so refit the selected model with bandwidth = NULL once the set is settled.

The model without predictors, and the gaps

The forward sweep starts from one predictor, so by itself it always names at least one, whether or not any candidate helps. The model without predictors, a local mean at the sweep's bandwidth, is therefore scored as well and ranked with the others as <none>. When it ranks first, best is character(0): no candidate improves on it.

The delta column of table is each model's criterion minus the best one's. Differences of AICc below about 2 do not separate two models (Burnham and Anderson 2002), so within_2 lists the models that close to the best and smallest_within_2 names the one among them with the fewest predictors, which is the one to prefer when several are that close. best is still the model with the lowest criterion.

Observations that share a location

When rows of data_sf have the same coordinates, the bandwidth search leaves out whole locations, for either bw_approach (see fit_gwr_model, Observations that share a location); bandwidth_source then reads "leave-one-location-out CV search on the full model". The models are still ranked by AICc, which counts the rows at one location as independent, so the gaps overstate what a predictor adds when a location has an effect of its own; a warning of class "spatialkit_gwr_repeated_locations" says so with the counts. A model whose fit reproduces the mean of the observations at each location (every such model scores the same, whatever its predictors) has criterion NA and is listed last, as is one with a term that no local window can estimate; a warning names them.

Cost

The sweep fits p * (p + 1) / 2 GWR models for p candidates (55 at p = 10, 210 at p = 20), and the one without predictors, each over all n locations. max_models stops the call before it runs for hours.

Using $raw with GWmodel directly

raw has the layout of GWmodel's own list(model.list, GWR.df), so its two elements have to be unpacked before GWmodel's helpers will take them: GWmodel::gwr.model.view() takes (DeVar, InDeVars, model.list), so the call is

  GWmodel::gwr.model.view(sel$response_var, sel$candidate_vars, sel$raw[[1]])

Pass sel$raw[[1]], not sel$raw. The diagnostic table is sel$raw[[2]], a numeric matrix whose columns are bandwidth, AIC, AICc, RSS in that order (and are named so); the criterion column of $table is its third column.

Printing

print() shows the response, the candidate predictors, and the top-ranked models with their criterion values and, in the delta column, how far each is from the best. Below the table it lists the models within 2 of the best, which a difference in AICc does not separate (Burnham and Anderson 2002), and names the smallest of them. When several models are that close, treat the choice of predictors as unsettled; when the model without predictors (<none>) is among them, no candidate has been shown to help. print() returns x invisibly.

References

Burnham, K. P. and Anderson, D. R. (2002). Model Selection and Multimodel Inference: A Practical Information-Theoretic Approach, 2nd edition. Springer.

Lu, B., Harris, P., Charlton, M. and Brunsdon, C. (2014). The GWmodel R package: further topics for exploring spatial heterogeneity using geographically weighted models. Geo-spatial Information Science 17(2), 85–101. doi:10.1080/10095020.2014.917453

See Also

select_features_forward() for the blocked cross-validated counterpart, plot.gwr_model_selection() to draw the models, and fit_gwr_model() to fit the selected model.

Other predictor selection: plot.feature_selection(), plot.gwr_model_selection(), select_features_forward()

Examples


library(sf)
set.seed(1)
n <- 80
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             a = rnorm(n), b = rnorm(n), noise = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
# The slope on a rises from 1 in the west to 3 in the east.
east <- (st_coordinates(dat)[, 1] - 5e5) / 1000
dat$z <- (1 + 2 * east) * dat$a - dat$b + rnorm(n, 0, 0.3)
sel <- gwr_model_selection(dat, "z", c("a", "b", "noise"), bandwidth = 30)
sel                     # every model tried, by AICc, with the gaps
sel$best                # the winning predictor set
# Refit with the bandwidth chosen afresh for the selected set.
fit_gwr_model(dat, "z", sel$best)


Bring two spatial objects to one CRS

Description

Brings two sf or sfc objects to one CRS: the CRS of a or b, as prefer says, or target_crs when it is given. Without target_crs, two objects that both lack a CRS are returned unchanged.

Usage

harmonize_crs(
  a,
  b,
  prefer = c("a", "b"),
  target_crs = NULL,
  on_transform_error = c("stop", "set_crs")
)

Arguments

a, b

Objects of class sf or sfc.

prefer

Which object's CRS both are brought to when they differ: "a" (default) or "b". Ignored when target_crs is given.

target_crs

Optional target CRS to apply to both: anything sf::st_crs() accepts, including an sf or sfc object, whose CRS is used.

on_transform_error

What to do when sf::st_transform() fails: "stop" (default) raises an error; "set_crs" relabels the CRS with sf::st_set_crs() without moving the coordinates. Use "set_crs" only when the coordinates are already in the target CRS.

Details

When one input has no CRS, the lon/lat test that ensure_projected() uses decides what happens (see spatialkit-geometry, "Layers without a CRS"), so both functions place the same data in the same place: coordinates the test takes for degrees are read as EPSG:4326 and reprojected to the other object's CRS (or target_crs); other coordinates are stamped with that CRS by sf::st_set_crs(), which relabels them without moving them. Either way a warning says so. A CRS in longitude and latitude is not stamped on coordinates that cannot be in it: a layer with an x outside -180 to 360 or a y beyond 90 north or south, read on the coordinates that have a location, stops the call with an error that names a or b, its box and the target CRS.

A layer that is transformed is read as spatialkit-geometry describes: a layer that mixes XY and XYZ (or XYM) geometries comes back in XY, with a warning of class spatialkit_zm_dropped, and a row without a location comes back empty, in its own geometry type. So does a row of a projected layer moved to a CRS in degrees with a coordinate beyond 1e10 in its CRS's own unit, further out than any projected CRS places a point of the Earth. A row that has a location and that the target CRS cannot place in full, such as a point far outside a UTM zone or a ring with a vertex at a latitude beyond 90, comes back empty, or without the vertices the CRS cannot place, and a warning of class spatialkit_rows_unplaced names such rows of a or b (rows on the condition).

Value

A named list with components a and b, each of the class it came in. A layer that is not transformed is returned as it came.

See Also

spatialkit-geometry for how input geometry and CRSs are read.

Other data preparation: [.spatialkit_rows(), coerce_to_points(), ensure_projected(), prep_model_data(), spatialkit-geometry

Examples

library(sf)
a <- st_as_sf(data.frame(x = c(500000, 500100), y = c(4000000, 4000100)),
              coords = c("x", "y"), crs = 32632)
b <- st_transform(a, 4326)                 # same points, lon/lat
h <- harmonize_crs(a, b)                    # b is brought into a's CRS
c(a = st_crs(h$a)$epsg, b = st_crs(h$b)$epsg)
st_crs(h$a) == st_crs(h$b)

Check whether block kriging would improve cell means

Description

summarize_by_cell() aggregates by plain means inside cell boundaries. A block-kriging aggregator would instead weight observations by their spatial correlation with the cell, and would return an estimate and a variance for every cell, thin or empty. This function measures what block kriging would add on a given layer, without changing any cell value. For every cell it reports the block-kriging estimate and variance implied by a fitted variogram (kr_pred, kr_var), that variance as a share of the variance the cell's mean would have with no data at all (kr_ratio), and, where the cell has points, the error variance of its plain mean under the same variogram (plain_var) and the share of that variance kriging removes (kr_gain). It also scores the variogram itself by blocked cross-validation.

Usage

kriging_adequacy(
  assigned_points_sf,
  response_var,
  cells_sf,
  id_col = "poly_id",
  sac = NULL,
  folds = NULL,
  k = 5L,
  seed = 123L,
  nmax = 50L,
  max_neighbours = 2000L,
  max_box_ratio = 1000,
  quiet = TRUE
)

Arguments

assigned_points_sf

Points with a cell identifier column, as assign_features_to_polygons() returns. Any Z or M dimension is dropped, on every layer, because gstat::krige() uses every coordinate dimension of its locations and the variogram is fitted in x and y (estimate_sac_range() drops Z and M too): the points are kriged in x and y. Multipoints whose geometries carry M (XYM or XYZM) are reduced to points in x and y, since GEOS does not read M.

response_var

The response column: numeric or logical. A logical column is kriged as 0/1, so its cell mean is a share. Any other class (a factor, an ordered factor, character, a date) is an error naming the column and its class, and is never converted: a factor's level codes are an arbitrary relabelling, and kriging them gave a variogram, kriged estimates and plain means that all changed with the order of the levels. For a category, pass an indicator (x == "level").

cells_sf

The cell polygons, with the matching ID column. A layer with no CRS is taken to be in the points' CRS (and points with none in the cells'), with a warning. Cells that do not all have the same dimensions are read in x and y, without their Z and M. So are cells whose geometries carry M (XYM or XYZM), which GEOS does not read.

id_col

Name of the ID column, found as summarize_by_cell() finds it: on the points the first of id_col, "poly_id", "polygon_id" and "cell_id"; on the cells the first of that column, "poly_id", "polygon_id", "id", "cell_id" and "grid_id". IDs are matched as text, whole numbers written out in full, so a double 1e5 matches an integer 100000; a point whose ID matches no cell is counted in no cell, with a warning. NA and NaN are no ID: a cell without one holds no point (n 0, mean and se NA) and is kriged as any other, and a cells_sf in which no cell has an ID is an error. Two cells with one ID are an error too, since the points that carry it cannot be placed in one of them. Default "poly_id".

sac

Optional sac_range carrying a variogram model.

folds

Optional make_folds() result on assigned_points_sf for the cross-validation statistic, or a vector of fold labels, one per row of assigned_points_sf (the labels of rows dropped for a missing response or location are not used; one label per row kept is read as well); built here with block_kfold when NULL. As in cv_*(), folds whose recorded rows sit at other locations in assigned_points_sf (built on another layer, such as the points before assign_features_to_polygons() dropped some) are refused. So are folds whose test sets share a location: each location is kriged once, under one fold.

k, seed

The number of blocked folds built when folds is NULL, and the random seed for that construction and for the variogram estimated when sac is NULL. Defaults 5 and 123.

nmax

The number of neighbours each kriging system uses (gstat's nmax): the locations nearest the cell's centre, or, for a cell those leave some of its own locations out of, all of its own plus this many outside it (see "The kriging neighbourhood"). The cross-validation kriges each held-out point from its nmax nearest training locations. Default 50.

max_neighbours

The largest kriging system a cell is given when its neighbourhood has to grow to hold all its own locations; a cell that would need more is left out (kr_ columns NA) with a warning. Never below nmax. Default 2000.

max_box_ratio

A cell whose bounding box is more than this many times its area is left out (kr_ columns NA) with a warning, because gstat's discretisation of it costs memory in proportion. Default 1000.

quiet

Logical; suppress this function's progress message()s. It does not silence R warnings, nor the package's console log echo (see spatialkit_quiet for that). Default TRUE.

Value

An sf object of class "kriging_adequacy", one row per cell with the cell geometry and: the ID column, n (points in the cell), mean (the plain mean), se (its naive standard error), plain_var (the plain mean's error variance under the variogram), kr_pred, kr_var, kr_ratio, kr_gain, kr_shift and kr_n_used (how many locations the cell was kriged from; NA for a cell left out). Attributes: variogram (the model frame), sill, nugget, range, range_identified, rejected_reason (why the range was refused, from sac; NA when it was identified), cv (a list: zscore_var, zscore_mean, rmse, n_pred, k, method), nmax, n_points (the points used), n_locations (the distinct locations among them, which the kriging used), cells_left_out (counts of cells left out, named shape for max_box_ratio and size for max_neighbours) and replicates (NULL when no two points share a location; otherwise a list with n_points, the points that share one, within_var, their pooled within-location variance, df, its degrees of freedom, nugget, the variogram's, nugget_used, the larger of the two, which is the error variance a location seen once is kriged with, and above_nugget, TRUE when the replicate variance exceeds the variogram's nugget).

Reading the columns

kr_ratio

The block-kriging variance over the cell's prior variance, in [0, 1]. The prior variance is the variance the cell's mean would have with no data at all, \bar C(B,B): the covariance averaged over pairs of points in the cell, on the discretisation gstat block-kriges with, and without the nugget, which averages out over a block (gstat leaves it out of the block variance too). Each cell has its own: a cell's mean varies less than a single point does, and far less once the cell is wider than the range, so the point sill is not the scale. It is the coverage score, and it needs no hand-set threshold in metres or point counts: as it approaches 1 the estimate carries almost no information from the data about the cell and is reverting to the estimated mean. Ordinary kriging adds the variance of that estimated mean, so a cell the data do not reach comes out at or above its prior variance and reads 1. A cell at 0.05 is well determined; a cell at 0.8 is mostly prior. NA when the model is a pure nugget, where a cell mean has no prior variance to be a share of.

plain_var

The error variance of the cell's plain mean as an estimate of the cell's average, under the same variogram and the same discretisation of the cell as kr_var: a' C a - 2 a' \bar c(B) + \bar C(B,B), with a the plain mean's weights on the cell's observations, C their covariances (the nugget on the diagonal), \bar c(B) their covariances with the cell and \bar C(B,B) the covariance within it. It is the model's counterpart of se^2. s^2/n is the variance the plain mean would have if the cell's points were independent draws; under spatial correlation it understates the error, most where a cell's points sit close together, so se^2 / plain_var below 1 says the naive standard error is too small if the variogram is right. Defined from one point up. NA for a cell with no point and for a cell left out of the kriging.

kr_gain

1 - kr_var / plain_var: the share of the plain mean's error variance that kriging removes in the cell. Both variances come from the one variogram, so the gain does not move when sill and nugget are multiplied by a constant (unless locations are repeated, whose replicate variance is read off the data and does not scale with the model). It is at least 0: the kriging neighbourhood always holds the cell's own points, the plain mean is one unbiased combination of them, and kriging is the best such combination. The exception is a cell with rows at a location whose rows name more than one cell: that location is no cell's own (see "The kriging neighbourhood"), and the neighbourhood need not hold it. It is what the variogram expects, not what happened: read it beside attr(, "cv")$zscore_var, which says whether the variogram's variances are the right size. NA where plain_var is. kr_var is not compared with s^2/n. That comparison sets a variance from the model against one from the cell's own spread, so it moves with the fitted sill, and it does not mark the cells where kriging fails to pay.

kr_shift

The kriged estimate minus the plain mean, over the standard deviation the variogram gives that difference, sqrt(plain_var - kr_var) (the kriging error is uncorrelated with the difference, so the two variances subtract). Under the right variogram it has variance 1: about 32 percent of cells beyond 1 and 5 percent beyond 2. More than that says the plain means and the variogram disagree, so the counts print() gives are a check of the variogram on the cells themselves, beside the cross-validation statistic. In units of the naive standard error s/\sqrt{n} the same shift does not have variance 1 under the right variogram, so counts beyond 1 and 2 in that unit are not this check. NA for a cell with no point, and where the two variances agree to within a ten-thousandth, which is where kriging returns the plain mean.

The cross-validation statistic

The kriging variance is only as good as the variogram. With blocked folds, each held-out point is kriged from the training folds and the standardised error (z - \hat z) / \sqrt{kv} is recorded; the variance of those over all held-out points should be about 1. Its departure from 1 measures how badly the kriging variance is understated (or overstated): 1.4 means the variances are roughly 40 percent too small. Under blocked folds every held-out point is far from the training data, where the kriging variance is close to the sill whatever the nugget, so the blocked statistic checks the sill and range and says little about the nugget. To check the nugget, pass random folds (make_folds(method = "random_kfold")) as folds: the held-out points are then close to their neighbours, where the nugget decides the variance. The statistic is computed fold by fold with gstat::krige() on the splits make_folds() built, each held-out point kriged from that split's own training set, so the folds carry the same separation the package uses everywhere else: "buffered_loo" and "nndm" keep the points they exclude around each held-out one out of its kriging, and print() names the scheme that ran. A vector of fold labels is run as k-fold, each fold kriged from all the others.

What this needs

A variogram model. sac is a estimate_sac_range() result carrying one (attr(, "variogram_model")); when NULL it is estimated here from the response. The model families are the ones the package interprets elsewhere: exponential, spherical and Gaussian components with a nugget. Anything else is refused by name. A model whose range was not identified (an NA estimate with the model attached) is used with a warning that says why it was refused, and the reason is kept as attr(, "rejected_reason"): a range past the fitted lags means the sill was never reached and the ratios rest on an extrapolation; a variogram that falls with distance, or a range below the shortest lag, describes the data poorly at some lags; and a response in which estimate_sac_range() found no spatial structure comes with a pure-nugget model, which gives kriging no correlation to use.

The model has to be of the response itself. A variogram of residuals (estimate_sac_range(predictor_vars = ...), attr(, "detrended") TRUE) leaves out the variance the predictors explain, while the response is kriged here without them, so kr_var, kr_ratio and the cross-validation statistic come out too small; it is used with a warning. The points are put in the CRS the variogram was fitted in (attr(sac, "crs")), because its range is a length in that CRS's units. Requires gstat.

The kriging neighbourhood

gstat kriges a cell from the nmax locations nearest its centre. On gridded locations several of them are often the same distance away, and which of those the last bits of the coordinates make nearer moves with the unit and the origin. So the nmax are chosen by the package's tie rule: squared distances within one part in ten million of each other count as equal, and a tie goes to the location of lower first coordinate, then lower second, coordinates within that part of the distance counting as equal. Where the nmax-th nearest location ties with the next, the cell is kriged from the locations the rule picks; elsewhere the nmax nearest are one set and gstat's own search finds it. Each held-out location of the cross-validation is kriged from its nmax nearest training locations the same way. The kriged figures, and the cross-validation statistic on the same folds, are then the same in another unit or with another origin, to rounding, as long as no coordinate moves by more than about a two-hundred-millionth of the distance between neighbouring locations. The rows are put in order by their coordinates, then their cell ID, then their response before any of this, so the result does not depend on the order of the rows either.

A cell holding more locations than nmax would be estimated from its middle alone, which describes the middle rather than the cell. So wherever the nmax locations nearest a cell's centre leave out any of the cell's own locations (more than nmax locations are as near as its furthest own one, under the same tolerance), the cell is kriged from all of its own locations plus the nmax nearest outside it, chosen by the same rule; kr_n_used says how many locations each cell was kriged from. The cost of a kriging system grows with the cube of its size, so a cell that would need more than max_neighbours is left out with a warning, its kr_ columns NA. A cell's own locations are those whose rows name it. A location whose rows name more than one cell (rows at one place carrying different IDs) is no cell's own, with a warning that gives the count of such locations: it is kriged from as any other location, and each of its rows still counts in n, mean, se and plain_var of the cell it names.

gstat also discretises each cell into 500 points on a regular grid laid over the cell's whole bounding box, keeping those inside, so the memory a cell takes grows with the ratio of that box to its area. A cell whose bounding box exceeds its area more than max_box_ratio times (a sliver, parts far apart, a cell that is mostly hole) is left out the same way. attr(, "cells_left_out") counts both kinds, and print() says how many cells have no estimate and why. An empty cell, or one with a coordinate that is not finite or lies beyond 1e150 (read as given), has no location and is left out as well, with a warning of its own, and comes back with an empty geometry; it is counted with the cells of the second kind (shape).

Repeat measurements at one location

Two observations at the same coordinates (visits to a station, records geocoded to one address) make a kriging system singular, because gstat gives them the full sill, nugget included, as their covariance, as if they were one observation. The kriging and its cross-validation therefore use one observation per location, the mean of its replicates, with a warning; n and mean still count every point. How much of the nugget c_0 a mean of m replicates keeps is read off the replicates: their pooled within-location variance s_w^2 is the part that differs from visit to visit and averages down, and what the nugget holds beyond it is micro-scale variation the visits share, so the mean carries error variance \max(c_0 - s_w^2, 0) + s_w^2/m. That goes to gstat as a known measurement error (its weights) on the model with the nugget set to zero. For replicates that differ only by measurement error this is exactly the kriging of every observation, and for identical replicates it is the kriging of one. plain_var uses the same error variances: the observations a cell has at one location share the micro-scale part and average the rest.

When s_w^2 is above c_0 the replicates show more variation between visits than the model has room for (with a zero nugget, any at all). The replicate variance is then used as it is: a mean of m is kriged with error variance s_w^2/m, and a location seen once with s_w^2 where the model gives it c_0. Capping it at c_0 would krige the means as more exact than their replicates show them to be. The warning then carries the class "spatialkit_replicate_var_above_nugget" and both numbers, which attr(, "replicates") records and print() repeats. The replicate variance is an estimate (its degrees of freedom are in the warning and the record), and the variogram still says c_0: refit it with a nugget of at least s_w^2.

In the cross-validation a location is held out whole, under the fold of its first row, and its error variance is part of its standardised error. A cell or held-out location gstat still cannot krige is reported NA with a warning, and print() says how many.

References

Cressie, N. (1993). Statistics for Spatial Data, revised edition. Wiley. (Block kriging, chapter 3; cross-validation of the kriging variance, section 2.6.4.)

See Also

Other assign and summarise: assign_features_to_polygons(), cell_values_at(), summarize_by_cell()

Examples


library(sf)
set.seed(1)
n <- 200
x <- 5e5 + runif(n, 0, 1000); y <- 5e6 + runif(n, 0, 1000)
d <- as.matrix(dist(cbind(x, y)))
z <- as.numeric(t(chol(0.8 * exp(-d / 100) + diag(0.2, n))) %*% rnorm(n))
pts <- st_as_sf(data.frame(x = x, y = y, z = z), coords = c("x", "y"), crs = 32632)
bnd <- st_sf(geometry = st_as_sfc(st_bbox(pts)))
cells <- create_grid_polygons(bnd, target_cells = 16, type = "square")
asg <- assign_features_to_polygons(pts, cells)
ka <- kriging_adequacy(asg, "z", cells, k = 4)
print(ka)                   # the report
# Variance of the standardised errors: about 1 when the variogram is right
attr(ka, "cv")$zscore_var


Create spatial cross-validation folds

Description

Builds train and test splits of a layer for cross-validation, by one of six methods: random k-fold, spatial block k-fold, buffered leave-one-out, leave-location-out, nearest-neighbour distance matching (NNDM) leave-one-out, or its k-fold version (kNNDM). It returns the splits (folds), one row per observation naming the fold that holds it out (assignment), and the settings and diagnostics of the build (params). Pass the result as folds to cv_spatial() or another ⁠cv_*()⁠ function, map it with plot_folds(), and measure how far the held-out points sit from their training data with fold_separation().

Usage

make_folds(
  points_sf,
  k,
  method = c("random_kfold", "block_kfold", "buffered_loo", "leave_location_out", "nndm",
    "knndm"),
  seed = NULL,
  block_nx = NULL,
  block_ny = NULL,
  block_multiplier = 3,
  block_size = NULL,
  auto_range = FALSE,
  range_frac = 1,
  response_var = NULL,
  group_var = NULL,
  prediction_points = NULL,
  predictor_vars = NULL,
  boundary = NULL,
  buffer = NULL,
  min_train = 0.5,
  phi = NULL,
  drop_empty_blocks = TRUE,
  blocks = NULL,
  balance_tol = 3,
  max_test = NULL
)

Arguments

points_sf

An sf layer of the observations. Z and M are dropped before folding, since distances are measured in x and y. A layer without a CRS is aligned to a boundary, blocks or prediction_points that has one, by the rule in spatialkit-geometry. Rows without a location are dropped (see Value).

k

The number of folds, a single whole number of at least 1; required except for "buffered_loo" and "nndm", which build one fold per held-out point (k = n, or max_test of them when it is given) whatever k is. A fraction, NA or a vector is an error. "block_kfold" lowers k when fewer than k blocks hold points, "leave_location_out" when there are fewer than k groups, and "random_kfold" and "knndm" when the layer has fewer than k rows; those four raise k = 1 to 2, since one fold has no training set. Read the k element of the result rather than assume the value asked for, which params$k_requested keeps. Fewer folds than asked raise a warning of class "spatialkit_k_reduced", whose message gives both counts, the reason and, where there is one, a setting that works; the condition carries them as k_requested and k, so tryCatch(spatialkit_k_reduced = ) or withCallingHandlers() can act on it without reading the text.

method

One of the six methods in the section "Fold methods": "random_kfold" (default), "block_kfold", "buffered_loo", "leave_location_out", "nndm" or "knndm".

seed

Optional integer RNG seed; NULL (default) leaves the draws to the session's RNG state. It draws the partition of "random_kfold", the assignment of groups to folds of "leave_location_out", the packing ties of "block_kfold" and "knndm", the random candidate of "knndm" and, above 4,000 points, its k-means starts, and the max_test subset of "buffered_loo" and "nndm", which are otherwise deterministic. With auto_range = TRUE it is also the seed of estimate_sac_range(), which keeps its own default of 123 when seed is NULL.

block_nx, block_ny

Optional grid dimensions for "block_kfold", each a single whole number of at least 1. Give both, or give one and the other is derived from the extent's aspect ratio so that the blocks are about square. Ignored when block_size or auto_range set the grid.

block_multiplier

A single positive number, default 3. When neither block_size nor block_nx/block_ny is given, the grid aims for block_multiplier * k blocks over the extent, keeping its aspect, so each fold holds out about block_multiplier blocks; an extent more than about block_multiplier * k times as wide as it is tall (or as tall as it is wide) gets a single row (or column) of that many blocks. With 1, every fold is one contiguous area and the score depends on which area each fold gets; with many, the blocks shrink towards single points and the folds approach random k-fold. 3 is a compromise between the two, not a published constant.

block_size

Optional positive number, the minimum block edge length, in the units of the CRS the folds are built in (params$crs): your own CRS's units for projected input, and for lon/lat input those of the metre CRS ensure_projected() chooses, which varies with the data (project the data yourself to fix the units in advance). It takes precedence over block_nx/block_ny and block_multiplier. The blocks built are at least this long on an axis that can hold one, and up to just under twice as long; params$block_width and params$block_height record them. See the section "Block size and the autocorrelation range" for how the grid is laid and for a size that leaves too few blocks.

auto_range

Logical, default FALSE. TRUE estimates the autocorrelation range with estimate_sac_range() and uses it as the minimum block_size; it needs response_var, and an explicit block_size takes precedence. With supplied blocks the range is only compared with them. See the section "Block size and the autocorrelation range".

range_frac

Passed to estimate_sac_range() when auto_range = TRUE: a fitted range beyond the longest lag the empirical variogram was fitted over is refused as unidentified, and the grid falls back to geometry, with a warning. A range within that bound can still be too wide for two blocks. Default 1.

response_var

Name of the response column. Required when auto_range = TRUE. For "block_kfold" a name that is not a column of points_sf is an error whether or not auto_range is set, since the response also feeds the warning on blocks smaller than the range, which a misspelt name would switch off.

group_var

Name of a column of points_sf that identifies the location each observation belongs to. Required for method = "leave_location_out", which keeps every observation from a location in one fold. Repeated measurements at a site split across folds score the model partly on sites it has already seen.

prediction_points

Optional sf layer of the locations the model will predict at, such as the grid from predict_surface(); required for "nndm" and "knndm". A layer of cells or polygons is reduced to representative points first, so the target distances are point to point: a point-to-polygon distance is zero for every cell that holds a training point, which would pull the target towards zero and the folds towards plain leave-one-out. A layer that mixes dimensions or carries M is read in x and y, before and after it is reduced to points (spatialkit-geometry). A prediction point without a location, as given or once brought into the CRS of the folds, takes no part in the target and is not counted in params$n_prediction_points.

predictor_vars

Optional character vector of predictor column names, passed to estimate_sac_range() so that the range is that of the residuals on them.

boundary

Optional polygon layer (sf or sfc) that the block grid of "block_kfold" is clipped to. A cell the boundary only touches at a corner or along an edge is not a block, and a point on the boundary, to the margin in the section "Numerical tolerances", is inside it. See spatialkit-geometry for how a boundary without a CRS is read, and for the rows of a boundary that are left out or refused.

buffer

For "buffered_loo": a single positive number, the distance within which the held-out point's neighbours are excluded from its training set. Like block_size it is in the units of the CRS the folds are built in (params$crs), which for lon/lat input is the metre CRS ensure_projected() chooses: 0.1 means 0.1 m, not 0.1 degrees. A neighbour at the buffer distance is excluded. A buffer that excludes no neighbour from any fold makes the scheme plain leave-one-out, with a warning.

min_train

For "nndm": the smallest fraction of the data any fold's training set may be reduced to by neighbour exclusion; default 0.5, as in CAST::nndm(). Where it binds, the distance matching stops short and the held-out points stay closer to their training data than the prediction points are (see the section "NNDM"). For "knndm": the smallest fraction of the data a fold may leave for training, so a candidate whose largest fold holds more than 1 - min_train of the rows is set aside (the maxp = 0.5 of CAST::knndm() is min_train = 0.5). Equal folds leave 1 - 1/k of the data, so a value above that is an error.

phi

For "nndm": the distance up to which the two nearest-neighbour distance distributions are matched, in the CRS the folds are built in. Matching is attempted only while a held-out point's nearest-neighbour distance is at most phi; the exclusion that takes it past phi is the last one, so a realised distance can exceed phi by up to one neighbour step, as in CAST::nndm(). In Milà et al. (2022) and in CAST::nndm(), \phi is the autocorrelation range of the outcome: beyond it observations are close to independent, so matching adds nothing. estimate_sac_range() gives such a value. Default NULL: the largest prediction-to-training distance, which matches everywhere (phi = "max" in CAST).

drop_empty_blocks

Logical, default TRUE. With FALSE the blocks that hold no point are kept and packed into folds too, but k is still lowered to the number of blocks that hold points, so no fold is left without test points.

blocks

Optional polygon layer (sf or sfc, POLYGON or MULTIPOLYGON, at least two features) to use as the blocks of "block_kfold" in place of the grid: the ⁠$cells⁠ of a build_tessellation() result, hexagons, watersheds, administrative units, or the ⁠$blocks⁠ of blockCV::cv_spatial(). Each point takes the block that contains it, and the blocks are then assigned to folds as grid cells are. block_size, block_nx/block_ny, block_multiplier and boundary have nothing to act on and are ignored (logged); auto_range only compares the estimated range with the blocks. See the section "Supplied blocks". Blocks that mix dimensions or carry M are read in x and y, and params$blocks holds them in XY. An error for any other method.

balance_tol

A number of at least 1, default 3. For "block_kfold": the ratio of the largest fold's point count to the smallest's above which the folds are reported as imbalanced, with a warning (an R condition, also logged) that names both counts; Inf turns the check off. It is the tolerance of a check, not a target the packing aims for (see the section "Fold balance"), and params$balance_ratio carries the ratio achieved. For "knndm" it is a limit: a candidate whose largest fold holds more than balance_tol times the points of its smallest is set aside, so the folds returned are within it.

max_test

For "buffered_loo" and "nndm": optional whole number of at least 2. Folds are built for a random subset of that many held-out points (drawn under seed), and every row stays available for training, so each fold returned is the fold the full design has for that point. The model is then refitted max_test times and not n times, and the folds hold 4 * n * max_test bytes of row indices in place of 4 * n^2, which lets "buffered_loo" run on layers its storage limit otherwise refuses. It does not lift the 5,000-row limit of "nndm", whose cost is the matching itself; for that there is "knndm". For "nndm" the matching still runs over all n points and params describes all of them. area_of_applicability() needs every training row in a test fold and refuses a subset. Default NULL: every point is held out once. An error for the k-fold methods, whose number of folds is k.

Value

A list with:

method

The method used.

k

The number of folds built, which can differ from the k asked for (see k); length(folds) always equals it.

folds

A list with one element per fold, each a list of train and test row IDs: the values of the ..row_id column when the input has one, otherwise row positions.

assignment

A tibble with one row per observation kept: row_id (the same IDs) and fold, and for "block_kfold" a third column, block_id, the row of params$blocks the point fell in. With max_test, fold is NA for the rows not held out.

params

The settings and diagnostics of the build, below.

Every method's params carries seed, k_requested (the k asked for, NA when none was given) and row_probe, a small sample of row IDs and coordinates that every ⁠cv_*()⁠ function compares with the data it is handed, so folds built from a different layer of the same size are refused rather than applied. The methods that work in projected space add crs, the CRS the folds were built in (an "EPSG:code" string where there is one, otherwise the CRS's input definition). Every length in params (block_size, sac_range, buffer, median_buffer) is in that CRS's units, which for lon/lat input is a CRS ensure_projected() chose, not one you passed.

For "block_kfold" the block design comes with the folds:

For "nndm", params carries the diagnostics named in the section "NNDM". For "knndm" it carries chosen ("random" or "clusters"), n_clusters (the number of clusters packed into the folds; NA for the random partition), clustering ("ward" or "kmeans+ward"; NA when no cluster count was tried), candidates (a data frame with one row per candidate, the random partition first: candidate, n_clusters, largest_fold, balance_ratio, admissible and W, which is NA for a candidate set aside), wasserstein, wasserstein_random and wasserstein_loo (the Wasserstein distance to the target of the folds returned, of the random partition among the candidates and of plain leave-one-out, in distance units), fold_sizes, balance_ratio, target_distances and realised_distances (one per prediction point, and one per row: its distance to the nearest point of another fold) with their medians and means, and the diagnostics "nndm" reports under the same names: max_ecdf_excess, max_ecdf_deficit, loo_ecdf_deficit, ecdf_deficit_tol, target_separated and target_out_of_reach, with short_of_target for the opposite case (see the section "kNNDM"). With max_test, params$max_test records the value.

Rows without a location (an empty point, or a coordinate that is not finite or lies beyond 1e150) are dropped before folding, with a logged warning naming the count; they appear in no fold and in no assignment row. The bound is read on the coordinates as given, and again after the projection for the methods that measure distance.

Fold methods

Method Held out in each fold Needs Suits a map that
"random_kfold" a random 1/k of the rows k predicts among the samples, over an area they cover evenly
"block_kfold" whole blocks of a grid, or of blocks k; block_size or auto_range to size the grid predicts into unsampled gaps about as wide as the blocks
"buffered_loo" one point, with its neighbours within buffer left out of training buffer predicts at a known distance from the data
"leave_location_out" every row of one or more locations group_var predicts at sites with no measurements, from repeated measurements at others
"nndm" one point, with neighbours left out to match the prediction distances prediction_points; at most 5,000 rows predicts at known locations, with a model cheap enough to refit once per point
"knndm" k folds matched to the prediction distances prediction_points predicts at known locations, from a large layer or with a costly model

A cross-validated error is the error at the distances the folds put between the held-out points and their training data. It reads low for predictions made farther from the data than the held-out points sit, and high for predictions made closer, so which folds to use depends on where the model will predict. fold_separation() with prediction_points compares the two distances, and method = "nndm" and "knndm" build folds matched to them.

"random_kfold" ignores geography: a held-out point keeps most of its neighbours in the training data, so the score is the error of predicting among the samples. That is the error of a map over an area the samples cover evenly, and it reads low for predictions made farther from the data, such as a map of a whole region from clustered samples. "block_kfold" holds out whole blocks, so the held-out points sit farther from their training data the wider the blocks are, and the score is the error of predicting into unsampled gaps of that size; for a map of an area the samples cover, it reads high. "buffered_loo" holds out one point at a time and excludes everything within a fixed buffer from its training set. "leave_location_out" groups by group_var, so all observations from a location share a fold.

Block size and the autocorrelation range

With block_size, each axis of the extent gets as many blocks as leave every block at least that long, so on an axis at least as long as block_size the blocks are from one to just under two times this size. An axis shorter than block_size is spanned by one row or column of blocks as long as the extent there: a 39.8 km by 5 km extent with block_size = 10000 gets three blocks 13.3 km wide and 5 km tall. A size that leaves fewer than k blocks holding points returns that many folds, with a warning (see k); one that leaves a single block is an error. Both name the largest size that still gives k folds. A size in the wrong unit asks for an enormous grid, so a request above 1,000,000 blocks is refused with an error naming the grid dimensions, the extent and the CRS's units.

Without block_size or auto_range, the grid is sized from the extent and block_multiplier (or block_nx and block_ny) alone, with no regard to the autocorrelation range of the data. The wider the blocks, the farther the held-out points sit from their training data. When blocks are smaller than the autocorrelation range, each held-out point still has training data within the range. The score is then the error of predicting that close to the data. It reads low for a map whose locations lie farther from the samples, and is the error of a map whose locations lie as close.

block_size sets a minimum block edge length in CRS units, and auto_range = TRUE estimates the range with estimate_sac_range() and uses it as that minimum. When a response is given and the blocks are smaller than the estimated range, make_folds() warns and gives the block size of the range. When blocks of that size leave fewer than k folds on this layout, the warning also names the largest size that still gives k folds and a method that needs no block size ("nndm", or "knndm" above 5,000 rows).

Sizing blocks from the autocorrelation range is the recommendation of Roberts et al. (2017) and what blockCV (Valavi et al. 2019) automates. blockCV takes the fitted variogram's range parameter as the block size; auto_range takes the effective range that estimate_sac_range() returns, three times that parameter for an exponential fit, so its blocks are larger than blockCV's from the same variogram. The estimate is the omnidirectional range. On a field known to be anisotropic, pass block_size = max(attr(r, "directional_fitted"), na.rm = TRUE) yourself after checking attr(r, "directional_status") (see the section "Directional ranges and anisotropy" in estimate_sac_range()).

Range-sized blocks do not fit every layout. On a square extent at k = 5, a range up to a third of the side gives five folds; up to half, a 2 by 2 grid and four folds, returned with the "spatialkit_k_reduced" warning. Above half the extent in both directions there is room for a single block, and make_folds() stops with an error naming the size rather than return one fold with an empty training set. The warning and the error name the largest block size that still gives k folds on this layout and how far below the range it is. When no range is identified, the geometric grid is used instead, with a warning that gives the reason. When the range is used, a message states the grid and the block size built.

NNDM

"nndm" implements the distance-matching principle of Milà et al. (2022): it sizes the exclusion around each held-out point, with no fixed buffer, so that the distribution of distances from the held-out points to their training data approaches the distribution of distances from the prediction locations to the training data.

The procedure is the paper's, and it is deterministic. Let G_{ij} be the empirical distribution of prediction-to-nearest-training distances and G_j^* the distribution of each held-out point's distance to its nearest remaining training point. Starting from plain leave-one-out, the point with the smallest G_j^* at which the realised distribution exceeds the target (G_j^*(r) > G_{ij}(r)) has its nearest training neighbour removed, and this repeats until no such point remains, within two limits. A point is matched only while its nearest-neighbour distance is at most phi (default: the largest prediction distance, since a training point already farther than every prediction distance has nothing to match), so the exclusion that takes it past phi is its last and a realised distance can exceed phi by up to one neighbour step. And no fold's training set is stripped below min_train of the data.

It differs from CAST::nndm() in two details, so the folds agree closely with CAST's but not exactly. The removal rule is strict: a neighbour is removed whenever the realised distribution exceeds the target, where CAST removes one only while the realised distribution, less the point about to move, is still at or above the target. The rule here therefore removes up to one point more per distance value, erring towards held-out distances longer than the target. And ties in G_j^* are broken by the points' coordinates, not by their row index as in CAST, so the folds do not depend on the order of the rows (see the section "Numerical tolerances").

Where neither limit binds, the realised distribution of nearest-neighbour distances is never shorter than the target: G_j^*(r) \le G_{ij}(r) up to the granularity of the neighbour distances, which is the property the method exists to deliver. It is a statement about the distance to the one nearest training point. A learner that draws on several neighbours (a forest, a k-nearest-neighbour mean, a kriging neighbourhood) also depends on how far the second and later neighbours are, which NNDM does not match, so on clustered samples its cross-validated error can still read low for the prediction points with the nearest-neighbour distances matched exactly. Beyond phi no matching is attempted. min_train is different: when the prediction locations lie farther from the samples than a fold can be made to hold out (clustered samples and a prediction domain well beyond them, the layout NNDM is meant for), it stops the matching early and the realised distances stay too short. params$n_at_min_train counts the folds held at the floor while still closer than the target allows, and make_folds() warns when that leaves more than one point's worth of excess at or below phi. Lower min_train to match further, or read the cross-validated score as an upper bound on performance at the prediction locations. params$max_ecdf_excess reports the largest remaining excess; compare params$target_median with params$realised_median as well.

The match has a second side. params$max_ecdf_deficit is the largest amount by which the target distribution runs above the realised one, the mirror of params$max_ecdf_excess: the share of prediction points within some distance of the data that the folds do not reproduce. Part of it is the granularity of the matching. Excluding a neighbour moves a held-out point out to its next remaining neighbour, and on clustered samples that can be the next cluster, well past the prediction distances.

The other part no setting reaches. Excluding neighbours can only lengthen a held-out distance, so when the prediction points sit nearer to the data than the samples sit to each other (prediction points among the samples, or a regular sample predicted between its nodes) the folds returned are plain leave-one-out and are still farther from their training data than the prediction points are. The cross-validated error is then pessimistic for those prediction points: an upper bound on the error there. params$loo_ecdf_deficit is the largest amount by which the target distribution runs above that of plain leave-one-out. When it exceeds params$ecdf_deficit_tol, three times \sqrt{1/n + 1/m} for n folds and m prediction points (about three times the chance difference between two samples of one distribution), make_folds() raises a warning of class "spatialkit_nndm_out_of_reach" and sets params$target_out_of_reach to TRUE.

On small samples no deficit can exceed that tolerance. A deficit is a difference of two shares, so it is at most 1, and the tolerance is 1 or more whenever nm/(n+m) \le 9: for nine folds or fewer whatever the number of prediction points, and for up to eighteen folds with as many prediction points. There the same warning is raised in one case only, complete separation: every prediction point nearer to the data than any sample is to its nearest other sample, by more than one part in ten million (a deficit of 1), provided the two sets are large enough for that ordering to mean something, taken as choose(n + m, n) >= 1000 ways of interleaving them (17 prediction points for 3 folds, 7 for 6 folds, 4 for 12 folds). params$target_separated records the ordering whether or not it was enough to warn, and the warning's condition carries it as separated. With very few samples it can hold for a grid over the samples' own extent, because a few points hug the box they span; the folds are then farther than the grid all the same. A partial shortfall on such a sample (most prediction points nearer than leave-one-out reaches, not all) is not warned about, since no difference of shares exceeds a tolerance of 1 or more. Compare params$target_median with params$realised_median.

params$wasserstein is the Wasserstein distance between the target and realised distributions, in distance units, and params$wasserstein_loo the same for plain leave-one-out: equal when nothing was excluded, smaller when the matching helped.

kNNDM

"knndm" is the k-fold version of NNDM (Linnenbrink et al. 2024): k folds, and so k model fits, whose held-out distances are as close to the same target as a set of candidates allows. It has no row limit, and is the method to use above the 5,000 rows "nndm" takes or when a model is too costly to refit once per point. Below that it matches less closely than NNDM, since a fold design has far fewer degrees of freedom than one exclusion set per point.

The candidates are a random k-fold partition (the one "random_kfold" builds with the same seed) and, for each of up to 50 cluster counts spaced evenly on the log scale from k to one fewer than the number of distinct locations, the samples clustered on their coordinates and the clusters merged into k folds. Few large clusters give folds that are whole areas, far from their training data; many small ones approach the random partition. Up to 4,000 points the clustering is Ward's (stats::hclust(method = "ward.D2")), cut at each count. Above that, where the n by n distance matrix it needs is too large, k-means first reduces the samples to 4,000 groups (Lloyd's algorithm from random sample locations, at most ten passes) and Ward's method is continued from those groups; a count above 4,000 is a k-means run of its own. params$clustering says which ("ward" or "kmeans+ward"). Clusters are merged by the packing "block_kfold" uses for its blocks, largest first and each to the fold with the fewest points so far (see the section "Fold balance"). CAST::knndm() merges clusters by a rule of its own, which this was not checked against, so the folds are not expected to equal CAST's.

Each candidate is scored by the Wasserstein distance W between its held-out distances (each point's distance to the nearest point of another fold) and the target distances, in the unit of the layer, and the smallest W is returned; of the candidates within one part in ten million of the smallest, the earliest in params$candidates. A candidate is set aside without being scored when its largest fold leaves less than min_train of the rows for training or holds more than balance_tol times the points of its smallest; the random partition is always kept. So params$wasserstein is never above params$wasserstein_random, the W of that random partition, and params$candidates lists every candidate with its cluster count, fold sizes and W. params$chosen is "random" when no clustering came closer, as for samples spread evenly over the prediction area. Read W against the mean target distance; it has no sign, so it measures the mismatch in either direction. With few folds a random partition can itself be farther than the target, since each fold trains on 1 - 1/k of the points. Construction time grows with the number of points and of folds.

Two cases are warned about, each with a condition class. When the prediction points sit nearer to the data than a sample is to its nearest other sample, no fold design reaches them, since a held-out point is never nearer to its training data than that; the test is the one "nndm" applies, the warning has the same class, "spatialkit_nndm_out_of_reach", and what comes back is the random partition or a candidate as fine as one. In the other direction, the closest candidate can still be short of the target: prediction points well beyond the samples lie farther from the data than k folds of those samples can be held apart. When the mean held-out distance of the folds returned is below the mean target distance by more than a quarter of it and by at least half of W (the test fold_separation() words as "closer"), make_folds() raises a warning of class "spatialkit_knndm_short_of_target" and sets params$short_of_target: the cross-validated error then tends to read low for the prediction points. Fewer folds hold out larger areas. Short of either warning the folds can still differ from the target at some distances; params$max_ecdf_excess and params$max_ecdf_deficit give the largest difference each way, and fold_separation() reads the folds against the same prediction points fold by fold.

Supplied blocks

A polygon layer passed as blocks is aligned to the points the way boundary is, and then brought into the CRS the folds are built in (see spatialkit-geometry). A point inside more than one block is given the first (lowest row) that contains it, as for a point on the shared edge of two grid cells, and a point within the margin of a block's edge (see the section "Numerical tolerances") counts as inside it. When the blocks that caught such a point share area instead of an edge, the layer overlaps and is not a partition, and make_folds() warns. A point inside no block is assigned to the nearest one, by distance to the polygon itself; a point the same distance from two blocks, to one part in ten million or that margin, goes to the lower row. The count of such points is warned about, unless they sit within a millionth of the extent of a block, an edge that reprojection or clipping moved by a rounding error. Blocks that hold no point are dropped when drop_empty_blocks = TRUE, and k is lowered to the number of blocks that hold points when that is smaller.

params$n_blocks is the number of blocks before empties were dropped and params$blocks_used the number after (so with drop_empty_blocks = FALSE the two are equal, and sum(params$block_sizes > 0) is how many hold points); params$grid_nx and params$grid_ny are NA. params$block_scale is the median, over the blocks that hold points, of the side of the square with the block's area. A polygon has no single edge length, so that is the length compared with the autocorrelation range for the warning on blocks smaller than the range.

Every set of cells build_tessellation() builds can be a block design here, including Voronoi cells around get_voronoi_seeds(method = "kmeans") seeds, which adapt to the density of the points.

Fold balance

"block_kfold" and "knndm" balance the number of points per fold by packing: blocks (for "knndm", clusters of the samples) are taken largest first and each goes to the fold with the fewest points so far, ties broken at random. This is the longest-processing-time rule for multiway partitioning, and make_folds() offers no search over other packings. The remedy for an imbalance past balance_tol is the block design: smaller blocks, or blocks that adapt to the density of the points, passed through blocks. Density-adaptive blocks are smaller where points are dense, so check params$block_scale against the autocorrelation range as you would a grid.

"knndm" chooses its clusters, so for it balance_tol is a limit: a clustering whose packing exceeds it is not a candidate, and the folds returned are within it (params$fold_sizes, params$balance_ratio).

The other methods do not balance point counts. "random_kfold" is balanced by construction (fold sizes differ by at most one); "buffered_loo" and "nndm" hold out one point per fold; "leave_location_out" gives each fold the same number of locations (to within one), so folds differ by as much as the locations' sizes do.

Numerical tolerances

A point on the edge two grid cells share goes to the lower one, the cell with the lower index in the full grid (params$blocks$source_row; the grid is numbered along each row from the bottom left, so the cell to the left or below). A point is on an edge while it lies within one part in 1e10 of the largest coordinate of the points and the blocks from it (0.44 mm at a UTM northing of 4,400 km), at most a millionth of the diagonal of their bounding box and at least four times the spacing of doubles at that coordinate, so points on the grid lines of a lattice are blocked alike in any unit or origin. A point in no cell of a clipped grid goes to the cell with the nearest centroid, and to the lower of two whose centroids are as near to one part in ten million or that margin. The same margin decides whether a point lies on a boundary or inside a supplied block.

A block shorter than block_size by no more than one part in ten million counts as that long, so a size of exactly the axis over a whole number gives that number of blocks in any unit. A neighbour of a "buffered_loo" point at the buffer distance is excluded, and so is one over it by rounding: a squared distance within one part in ten million of the buffer's square (a distance about one part in twenty million over the buffer) counts as at it, so a lattice whose spacing divides the buffer gives the same folds in any unit or origin.

NNDM counts distances within one part in ten million of each other as equal, when the held-out distances are counted, compared with the target and phi, and put in order. Equal ones are taken by the column of the point (first coordinates within that part of the extent of the points count as one), then its second coordinate, counted the same way, then its row. Each point's neighbours are put in order by the same rule, so of neighbours that are equally far away the same one is excluded first. The folds are then the same in another unit or with another origin as long as no coordinate moves by more than about a two-hundred-millionth of the distance between neighbouring locations.

The clusterings of kNNDM read the coordinates centred on the middle of their bounding box, divided by its diagonal and rounded to 2^-30 of it (about a billionth), as the "kmeans" partition hands them to stats::kmeans(); on a lattice many merges and many assignments tie exactly, and the last bits of the coordinates, which move with the unit and the origin, would settle them. A point as near two k-means centres to one part in ten million goes to the lower-numbered one: a squared distance ties with the least when it is no more than the square of the least distance lengthened by a margin, plus one part in ten million of the least squared distance, the margin one part in 1e10 of the largest coordinate of the centres in that frame, at most a millionth of the diagonal of their bounding box and at least four times the spacing of doubles at that coordinate. The clusters are then the same in another unit or with another origin, but for a location within its own rounding noise of the middle of a step.

Points so far from the origin of their coordinates that doubles there are spaced more than a millionth of the points' extent apart are held to that spacing, and so are the edges of the blocks laid over them (see the section "Coordinates far from the origin" in spatialkit-geometry). With method = "block_kfold" or "buffered_loo" the folds are made, and a warning of class "spatialkit_xy_imprecise" gives the spacing and the extent.

References

Linnenbrink, J., Mila, C., Ludwig, M. and Meyer, H. (2024). kNNDM CV: k-fold nearest-neighbour distance matching cross-validation for map accuracy estimation. Geoscientific Model Development 17, 5897-5912. doi:10.5194/gmd-17-5897-2024

Mila, C., Mateu, J., Pebesma, E. and Meyer, H. (2022). Nearest neighbour distance matching Leave-One-Out Cross-Validation for map validation. Methods in Ecology and Evolution 13, 1304-1316. doi:10.1111/2041-210X.13851

Roberts, D. R., Bahn, V., Ciuti, S., Boyce, M. S., Elith, J., Guillera-Arroita, G., Hauenstein, S., Lahoz-Monfort, J. J., Schroder, B., Thuiller, W., Warton, D. I., Wintle, B. A., Hartig, F. and Dormann, C. F. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography 40, 913-929. doi:10.1111/ecog.02881

Valavi, R., Elith, J., Lahoz-Monfort, J. J. and Guillera-Arroita, G. (2019). blockCV: An R package for generating spatially or environmentally separated folds for k-fold cross-validation of species distribution models. Methods in Ecology and Evolution 10, 225-232. doi:10.1111/2041-210X.13107

See Also

plot_folds() to map the folds, fold_separation() to measure how far the held-out points sit from their training data, cv_spatial() to score a model on them, and cv_block_size_sweep() to cross-validate at a ladder of block sizes.

Other folds: cv_block_size_sweep(), fold_separation(), plot_folds()

Examples

library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(30, 0, 1000), y = 5e6 + runif(30, 0, 1000)),
  coords = c("x", "y"), crs = 32632
)
folds <- make_folds(pts, k = 3, method = "block_kfold", seed = 42)
folds$assignment          # fold and block of each row
lengths(folds$folds[[1]]) # the train and test row IDs of fold 1
folds$params$block_sizes  # points per block
folds$params$fold_blocks  # the blocks each fold holds

# Buffered leave-one-out: neighbours within 100 m left out of training.
loo <- make_folds(pts, method = "buffered_loo", buffer = 100)
loo$k                     # one fold per point

# Three folds matched to the distances from a prediction grid to
# clustered samples.
set.seed(2)
cx <- runif(6, 0, 1e4); cy <- runif(6, 0, 1e4)
xy <- do.call(rbind, lapply(1:6, function(i)
  cbind(cx[i] + rnorm(15, 0, 200), cy[i] + rnorm(15, 0, 200))))
cl <- st_as_sf(data.frame(x = 5e5 + xy[, 1], y = 5e6 + xy[, 2]),
               coords = c("x", "y"), crs = 32632)
grid <- st_make_grid(cl, n = c(20, 20), what = "centers")
km <- make_folds(cl, k = 3, method = "knndm", prediction_points = grid,
                 seed = 42)
km$params[c("chosen", "n_clusters", "wasserstein", "wasserstein_random")]

Compute goodness-of-fit metrics for a fitted model

Description

Reports RMSE, MAE, MAPE, SMAPE, R^2 and adjusted R^2 for any spatial_fit as a one-row data frame. With newdata it scores rows you held out yourself. Without it, it reads the fit's own fitted values: in-sample for a GWR or a Bayesian GP fit, out-of-bag for a random forest. Those numbers do not compare across backends, and the data frame carries no label saying which kind it holds.

Usage

model_metrics(object, ...)

## S3 method for class 'spatial_fit'
model_metrics(object, newdata = NULL, ...)

Arguments

object

A spatial_fit object.

...

Passed to predict() when newdata is given. Without newdata nothing reads them, so any argument here is an error, which catches a misspelt newdata. The metrics are computed from one predicted value per row, so draws = TRUE (a Bayesian GP fit) and se.fit = TRUE (a GWR fit), with which predict() returns a matrix or a list, are refused.

newdata

Optional sf object of held-out rows, carrying the response and the predictors. If NULL, the fitted values are used (in-sample, or out-of-bag for an rf_fit; see "What the metrics are computed on").

Details

Use this function for one fit. evaluate_insample() runs it over a list of fits and labels each row with its basis, and compare_models() adds information criteria and residual Moran's I to that table. None of the three refits a model. An in-sample score is not a cross-validation score: a GWR can reach a near-perfect in-sample R^2 at a small bandwidth without predicting anything. For a figure you can report, use cv_gwr(), cv_bayes(), cv_rf() or compare_models_cv().

Value

A one-row data.frame with n, RMSE, MAE, MAPE, SMAPE, R2, Adj_R2, n_MAPE and n_SMAPE (the last two are the rows each percentage error was averaged over). Adj_R2 is always NA: a GWR's effective number of parameters far exceeds the global predictor count and a GP model has no simple p. A character or factor response is an error; a logical response is scored as 0/1.

What the metrics are computed on

With newdata = NULL the metrics come from fitted(object). That is in-sample for a GWR or a Bayesian GP fit, and out-of-bag for a random forest, whose fitted() method returns out-of-bag predictions (see fit_rf_model()). Check object$info$fitted_are_oob before comparing numbers across backends; evaluate_insample() and compare_models() record it per model in a metric_basis column, and compare_models_cv() scores every backend the same way.

R^2 is 1 - RSS/TSS with the total sum of squares taken about the mean of the response the model was fitted to. In sample that is the ordinary R^2. With newdata it is the out-of-sample R^2 every cv_*() function uses: the model is measured against the training mean, the prediction it had to beat, and not against the new rows' own mean, which it could not have known. It is below 0 when the model predicts the new rows worse than the training mean does, and NA when the response does not vary about that mean beyond the rounding of its values, whatever its units and origin.

A GWR fit whose response fit_gwr_model() took about a centre (fit$engine$centres$response, a response at a large offset) is scored on the response and the fitted values or predictions less that centre, which keep digits that rounding at the response's size would lose: RMSE, MAE and R^2 are those of the same values at 0, and MAPE and SMAPE divide the same errors by the values in the response's units. fitted() and predict() still return values in the response's units.

Percentage errors on responses with zeros

MAPE divides by the observed value and SMAPE by |y| + |\hat{y}|, so neither is defined where its denominator is zero. Neither returns Inf or NaN. Both are averaged over the rows whose denominator is non-zero, and are NA when no row qualifies. Non-zero is judged at the scale of the data: a denominator no larger than 100 machine epsilons times the largest one counts as zero, so the rule does not depend on the units of the response. The n_MAPE and n_SMAPE columns record how many rows that was; the n column (n_pred in a cross-validation result) counts finite observation/prediction pairs. Read a percentage error next to that count: when n_MAPE is smaller, MAPE is an average over a subset of the data, whatever its value.

Any response taking exact zeros is affected: counts, rainfall, abundance, claim amounts. On a zero-inflated response with 62 zeros out of 120, MAPE averages the 58 non-zero rows and n_MAPE is 58. SMAPE drops the rows where observation and prediction are both near zero, which on a well-fitted zero-inflated model are the rows it got right, so it averages the harder rows only and reads worse than the fit deserves. n_SMAPE shows how many rows it kept; it does not correct the average.

RMSE, MAE and R^2 use every finite row; prefer them whenever the response can be zero. For a Bayesian GP fit, cv_bayes() also reports CRPS and interval coverage, which are proper scoring rules and are defined at zero.

Which metrics survive a non-Gaussian response

RMSE and MAE are defined for any numeric response and are what to read for a count, a rate or a bounded outcome. MAPE and SMAPE assume a response that is rarely zero (see "Percentage errors on responses with zeros"), and R^2 and adjusted R^2 compare residual variance to total variance, which suits a Gaussian response and fits loosely anything whose variance tracks its mean. On a Poisson or zero-inflated response read the four as a rough summary rather than a score.

For the Bayesian GP, cv_bayes() also reports CRPS and interval coverage at its coverage_levels (50, 80 and 95 percent by default). Both are proper scoring rules computed from posterior draws, so they are meaningful for any family that predicts one number per row (a count, a rate, a binary or bounded outcome), and they are the numbers to compare when the response is not Gaussian. A categorical or ordinal family predicts a probability per response category instead, so cv_bayes() refuses one before fitting anything. When every fold fails, the fold_metrics frame cv_bayes() returns carries the CRPS column but not the coverage_* columns, so code that reads those columns must allow for their absence.

See Also

Other in-sample checks: compare_models(), evaluate_insample(), print.morans_i(), residual_morans_i()

Examples


library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(60, 0, 1000), y = 5e6 + runif(60, 0, 1000),
             a = rnorm(60)),
  coords = c("x", "y"), crs = 32632
)
# An offset keeps the response away from zero, where MAPE is undefined.
pts$z <- 10 + 2 * pts$a + rnorm(60, 0, 0.3)
# Fit on 40 rows and keep 20 back, so the second call is out of sample.
fit <- fit_rf_model(pts[1:40, ], "z", "a", num_trees = 50, seed = 1)
model_metrics(fit)                           # out-of-bag for a forest
model_metrics(fit, newdata = pts[41:60, ])   # on the 20 held-out rows


Build a spatial_fit object for a backend of your own

Description

The constructor for the spatial_fit class, and the way to plug a model backend of your own into this package. The three built-in fitters (fit_rf_model(), fit_gwr_model() and fit_bayesian_spatial_model()) all end by calling it, and so should a custom fit_fn written for cv_spatial(). A model wrapped in a spatial_fit works with the package's folds, metrics, comparisons and area of applicability unchanged.

Usage

new_spatial_fit(
  subclass,
  engine,
  formula,
  response_var,
  predictor_vars,
  data_sf,
  info = list()
)

Arguments

subclass

Character scalar naming the class to stamp on the object: one of the built-ins "gwr_fit", "bayesian_fit" or "rf_fit", or any name of your own for a custom backend (say "lm_fit"). It is the S3 dispatch key: predict(), fitted(), residuals() and coef() on the result all dispatch on it, so a custom subclass needs a matching predict.<subclass>() method before cv_spatial() can use it.

engine

The raw model object your backend produced (an lm, a ranger object, a brmsfit, ...). Nothing inspects it except your own methods.

formula

A formula: the model, as print() and summary() show it. Its left side, when it has one, holds response_var (log(price) ~ elev for "price"). Its right side uses the columns predictor_vars names and no other attribute column of data_sf than these and the response, read by all.vars(), so log(elev) and elev * slope count as their columns, and so do the columns of an offset() or a grouping term; names that are not columns of data_sf and the reserved names ..x and ..y are not checked, and a right side with . is not read. A column a fit_fn derives itself and keeps out of predictor_vars, such as coordinates x and y for a trend surface, needs a name that is not a column of data_sf: on a layer that keeps its coordinates as columns x and y, derive them as cx and cy, or drop those columns first.

response_var

Character(1): the name of the response column of data_sf, an attribute column (not the geometry).

predictor_vars

Character vector of attribute column names of data_sf, not including response_var: the columns the right side of formula uses. character(0) for a model without predictors.

data_sf

An sf object with its geometry column: the rows the model was fitted on, with their geometry, in the order fitted() returns its values.

info

Named list of model-specific extras (list() for none). Set fitted_are_oob = TRUE when your fitted() values are held out instead of in-sample, so summary() labels them correctly.

Details

A custom backend needs three things:

  1. a fit_fn that returns an object built by new_spatial_fit();

  2. a predict.<subclass>() method for the subclass you chose. cv_spatial() scores each fold by calling the predict() generic on the fit, so without one every fold fails;

  3. a fitted.<subclass>() method that returns one value per row of the fit's data_sf, in the same order. summary() and model_metrics() need it, and without one they stop with an error that names the method to define.

residuals() and coef() methods are optional.

The constructor checks the fields the package's functions read from a fit, and stops with an error that names the argument: subclass must be one class name, data_sf an sf object with its geometry column, formula a formula whose left side, when it has one, holds the response, response_var the name of one attribute column of data_sf (a column other than its geometry), predictor_vars a character vector of its attribute columns other than the response, the columns the right side of formula uses, and info a list. It does not check the response's type (a Bayesian fit can have a factor or ordinal response); summary() and model_metrics() refuse a response that is not numeric or logical.

Value

An object of class c(subclass, "spatial_fit"): a list with engine, formula, response_var, predictor_vars and data_sf as given, n (the number of rows of data_sf) and info (the list given, with a private cache environment added as info$.cache, which methods should not modify).

The coef() contract

coef() on one of the three built-in backends either returns the coefficients or signals an error. It never returns NULL. A custom subclass inherits stats::coef.default(), which returns NULL, so define a coef.<subclass>() that errors when your backend has no coefficients. coef.rf_fit() always errors, because a forest has no coefficients; coef.gwr_fit() and coef.bayesian_fit() error when the backend cannot supply them (a missing package, an engine without the expected component). A NULL return could not be told from "this model has no fixed effects", and lapply(fits, coef) would return a shorter answer than the caller expected. Wrap the call in try() or tryCatch() when sweeping over a list of fits from different backends.

See Also

cv_spatial(), which takes a custom fit_fn; fit_rf_model() for a built-in fitter.

Other model fitting: fit_bayesian_spatial_model(), fit_gwr_model(), fit_rf_model(), gp_lengthscale_bounds()

Examples

library(sf)
set.seed(1)
n <- 80
site <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             elev = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
site$price <- 10 + 0.01 * (st_coordinates(site)[, 1] - 5e5) +
  2 * site$elev + rnorm(n)

# A custom backend: an ordinary linear model behind the spatial_fit interface.
lm_fit <- function(train_sf) {
  new_spatial_fit(
    subclass       = "lm_fit",
    engine         = lm(price ~ elev, st_drop_geometry(train_sf)),
    formula        = price ~ elev,
    response_var   = "price",
    predictor_vars = "elev",
    data_sf        = train_sf
  )
}

# Required: cv_spatial() scores each fold through the predict() generic,
# which dispatches on the subclass named above.
predict.lm_fit <- function(object, newdata = NULL, ...) {
  if (is.null(newdata)) newdata <- object$data_sf
  as.numeric(stats::predict(object$engine, st_drop_geometry(newdata)))
}
registerS3method("predict", "lm_fit", predict.lm_fit)

# Required by summary() and model_metrics(): one value per training row.
fitted.lm_fit <- function(object, ...) as.numeric(stats::fitted(object$engine))
registerS3method("fitted", "lm_fit", fitted.lm_fit)

summary(lm_fit(site))
cv <- cv_spatial(site, "price", "elev", fit_fn = lm_fit, k = 3, seed = 1)
cv$overall
# Check that these two agree before reading the metrics above.
c(attempted = cv$n_folds_attempted, succeeded = cv$n_folds_succeeded)

Plot the dissimilarity distribution behind an area of applicability

Description

Draws the dissimilarity index of the prediction locations against that of the training data, with the threshold marked, so you can see whether the prediction set sits well inside, near the threshold or outside. n_outside gives only how many prediction locations fall outside the area of applicability, not how close to the threshold the rest sit or how far outside the outsiders are. The training DI is cross-validated over the folds passed to area_of_applicability(), or without them is each training point's distance to its nearest other training point; the legend and the caption say which. The training curve is the reference the threshold was derived from: the threshold is the largest training DI inside an outlier fence, so the curve reaches it exactly when no training value was fenced off and runs past it, by the tail the fence removed, when some were. A prediction location outside on a predictor dropped for having no training variance, or under categorical = "indicator" on a level no training row has, has DI = Inf: it counts in the prediction curve, which then tops out below 1, and the caption says how many are off the axis. A location with a missing predictor (DI = NA) is neither inside nor outside; it is left out of the curve and the caption counts it.

Usage

## S3 method for class 'aoa'
plot(x, type = c("ecdf", "histogram"), ...)

Arguments

x

An aoa object from area_of_applicability().

type

"ecdf" (default), the two empirical distribution functions on one axis, or "histogram", the prediction DI as bars with the training DI as an outline.

...

Not used.

Details

When location has an index of its own (a gwr_fit, a bayesian_fit, a forest fitted with include_coords = TRUE, or coords = "yes"; see area_of_applicability()), the curves and the dashed line are the predictor index alone (for the forest, its ..x and ..y columns included). The subtitle then counts three things: the locations beyond the predictor threshold, those beyond the location threshold, and those outside the area of applicability, which is either.

Value

A ggplot object.

See Also

area_of_applicability(), which makes the object, and print.aoa().

Other prediction: area_of_applicability(), predict_surface(), print.aoa()

Examples


library(sf)
set.seed(2)
n <- 200
train <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             a = rnorm(n), b = rnorm(n)),
  coords = c("x", "y"), crs = 32632)
train$z <- train$a - train$b + rnorm(n, 0, 0.3)
# Prediction locations whose predictor `a` drifts beyond the training range.
new <- st_as_sf(
  data.frame(x = 5e5 + runif(100, 0, 1000), y = 5e6 + runif(100, 0, 1000),
             a = rnorm(100, mean = 2), b = rnorm(100)),
  coords = c("x", "y"), crs = 32632)
aoa <- area_of_applicability(new, train_sf = train, predictor_vars = c("a", "b"))
plot(aoa)                     # the two ECDFs
plot(aoa, type = "histogram")


Plot the path of a forward feature selection

Description

select_features_forward() scores every candidate at every step and keeps the best; its history holds all of them. This draws the accepted variable's score at each step as the path, every other candidate's score at that step as a faint point, and the step at which the selection stopped in red. When it stopped because no candidate passed the acceptance rule (rule in select_features_forward()), the path runs one step further to the best of the rejected candidates, drawn hollow and labelled "not added", so the stop reads as a flattening rather than a cut. The picture then shows whether the last variable was a clear gain or a marginal one, and whether the runner-up would have done as well. The scores are the selection's own cross-validated criterion, optimistically biased by the selection (see "Selection score" in select_features_forward()); when a hold-out score was computed (select_on = "split") it is drawn as a separate mark at the final step and named in the caption.

Usage

## S3 method for class 'feature_selection'
plot(x, ...)

Arguments

x

The list returned by select_features_forward().

...

Not used.

Details

With a learner that cannot fit an empty predictor set the first variable is added without a test and can be dropped at the end (baseline$first$dropped). The path drawn is then the one the sweep walked, with that variable hollow and labelled "dropped at the end", and the red mark is the selected set, scored without it.

Value

A ggplot object.

See Also

select_features_forward(), which makes the object.

Other predictor selection: gwr_model_selection(), plot.gwr_model_selection(), select_features_forward()

Examples


library(sf)
set.seed(4)
n <- 150
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             a = rnorm(n), b = rnorm(n), c = rnorm(n)),
  coords = c("x", "y"), crs = 32632)
dat$z <- 2 * dat$a - dat$b + rnorm(n, 0, 0.5)
fit_fn <- function(train_sf, vars)
  fit_rf_model(train_sf, "z", vars, num_trees = 80, seed = 1)
sel <- select_features_forward(dat, "z", c("a", "b", "c"), fit_fn = fit_fn,
                               k = 3, quiet = TRUE)
plot(sel)


Plot a GWR model selection

Description

gwr_model_selection() ranks every model it evaluated on AICc. This draws each model's criterion against its number of predictors, the winner in red, so the gap between the best model and the runners-up (which the ranked table shows only as numbers) is read as a shape. A winner well below the rest is preferred; one within 2 AICc units of others is not separated from them (see "Printing" in gwr_model_selection()). The criterion is in-sample, and the caption says so.

Usage

## S3 method for class 'gwr_model_selection'
plot(x, ...)

Arguments

x

A gwr_model_selection object.

...

Not used.

Value

A ggplot object.

See Also

gwr_model_selection(), which makes the object.

Other predictor selection: gwr_model_selection(), plot.feature_selection(), select_features_forward()

Examples


library(sf)
set.seed(1)
n <- 80
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             a = rnorm(n), b = rnorm(n), noise = rnorm(n)),
  coords = c("x", "y"), crs = 32632)
dat$z <- 2 * dat$a - dat$b + rnorm(n, 0, 0.5)
sel <- gwr_model_selection(dat, "z", c("a", "b", "noise"), bandwidth = 30)
# Every model tried, AICc against its size; the winner (a and b) marked.
plot(sel)


Plot a resolution profile

Description

The criteria of a resolution_profile() against the number of cells, one panel per criterion on a shared x axis, with the level each criterion selects marked and the region over which it is within tol of its optimum shaded. The shading marks the flat region select_resolution() reports. A criterion whose optimum sits at an end of the levels it was scored at is captioned with which bound that is (the support ceiling, the range floor, the ladder's own end, or the first level the criterion is computable at), because there the bound is choosing, not the criterion. A criterion that is NA at every level is left out with a log line rather than drawn empty.

Usage

## S3 method for class 'resolution_profile'
plot(x, criteria = NULL, tol = 0.02, ...)

Arguments

x

A resolution_profile.

criteria

Character vector of criteria to draw, any of "cp", "reliability", "elbow", "loo", "moran_z", "wss". Default: the first five, each where it is finite at some level. "cp", "reliability", "elbow" and "loo" (the leave-one-out error of the estimate the profile was built for; a profile built without estimate has no such column, and a column of that name added to one is drawn only when named here) are count criteria and get a selected level and a shaded band. "moran_z" is a diagnostic of the cell means and not a count rule (see select_resolution()), and "wss" is the raw curve behind "elbow": both are drawn as curves with no selected point.

tol

Passed to select_resolution() for the flat region.

...

Not used.

Details

A profile whose ladder is one size (obs_per_cell set to one number, or the default profile) has one level, set by the size. Each criterion that is finite there is drawn as one point in its panel, with no selected level and no band, and the caption says that the size set the count.

Value

A ggplot object.

See Also

resolution_profile(), which makes the object, and select_resolution().

Other resolution: determine_optimal_levels(), resolution_profile(), select_resolution(), summary.resolution_profile()

Examples


library(sf)
# The same field as ?resolution_profile: an exponential covariance with
# range parameter 200 and a nugget of 0.6 on a unit sill.
set.seed(4)
n <- 400
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 / 200) + diag(0.6, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
prof <- resolution_profile(pts, response_var = "z", n_levels = 12)
# Two of the criteria it scored (plot(prof) draws every one, a panel each)
plot(prof, criteria = c("cp", "reliability"))
plot(prof, criteria = c("cp", "wss")) # Cp beside the raw WSS curve


Plot an estimated spatial autocorrelation range

Description

Draws the empirical variogram that estimate_sac_range() attaches to its result, as a ggplot2 object, with the fitted model and the effective range overlaid where a range was identified, and a subtitle that gives the reason where it was not. A variogram that never reaches a sill, or that has no spatial structure at the lags resolved, is drawn as well, since the curve shows why the range came back NA.

Usage

## S3 method for class 'sac_range'
plot(x, ...)

Arguments

x

A sac_range object, as returned by estimate_sac_range().

...

Ignored.

Details

Nothing is recomputed: the plot reads the variogram, variogram_model, crs and rejected_reason attributes the estimate carries. The variogram is the one over all point pairs. The distance axis is in the units of the CRS the variogram was fitted in, which estimate_sac_range() chooses itself for lon/lat input.

Value

A ggplot object.

See Also

estimate_sac_range(), which makes the object, and plot.spatial_fit() with type = "variogram", which draws the same picture for a fitted model's residuals.

Other spatial autocorrelation: estimate_sac_range(), sac_nugget()

Examples


library(sf)
# An exponential field with range parameter 150 (effective range about
# 450 m) and a nugget of half the sill, so the fitted model, the nugget and
# the range line all have something to show.
set.seed(3)
n <- 250
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 / 150) + diag(0.5, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
r <- estimate_sac_range(pts, response_var = "z")
plot(r)

# A field whose variogram never reaches a sill: the plot still draws it,
# and the subtitle says why no range is marked.
xy$trend <- sin(xy$x / 400) + rnorm(n, sd = 0.2)
r2 <- estimate_sac_range(st_as_sf(xy, coords = c("x", "y"), crs = 32632),
                         response_var = "trend")
plot(r2)


Plot a fitted spatial model

Description

Draws one of four diagnostic plots of a spatial_fit, as a ggplot2 object: the residuals mapped at the training locations, observed against fitted values, the residual variogram beside the response's, or, for a GWR, the map of one local coefficient. Use it to see whether spatial structure is left in the residuals, and where.

Usage

## S3 method for class 'spatial_fit'
plot(
  x,
  type = c("residuals", "observed_predicted", "variogram", "coefficients"),
  response = TRUE,
  term = NULL,
  mask = TRUE,
  ...
)

Arguments

x

A spatial_fit. The residuals drawn are residuals(x); for a custom subclass with no residuals() method (optional, see new_spatial_fit()) they are the response minus fitted(x), which is what the built-in backends' methods return. The maps are drawn in x and y: a data_sf whose geometries mix XY with XYZ or XYM is drawn without its Z and M.

type

One of:

"residuals"

Residuals mapped at the training locations. Spatial structure here is the signal that the model has not captured the autocorrelation.

"observed_predicted"

Observed against fitted, with a 1:1 reference line.

"variogram"

Empirical variogram of the residuals with the fitted model overlaid, so the fit can be judged rather than trusted, and (unless response = FALSE) the variogram of the response itself on the same points and lags, drawn hollow with a dashed fit. The gap between the two curves is the spatial structure the model absorbed: a residual sill well below the response sill means most of it, two curves that coincide mean none. When both effective ranges were identified over the same point pairs the caption gives the residual sill as a share of the response sill and the two ranges; when either variogram has no identified range, or the two are not over the same pairs, the caption says so and compares nothing: a sill the data never reached is not a number to divide by, and one direction's sill is not comparable with all directions'. The residual range is expected to come out shorter and the residual sill lower even when the model is right, because residuals of a fitted trend understate the variogram (see estimate_sac_range(), "Detrending and the residual-variogram bias"). The distance axis is labelled in the units of the CRS the variogram was fitted in, which is not always the fit's own CRS (lon/lat data are projected first). Each curve is the variogram estimate_sac_range() returns for its variable, which is over all point pairs. A fit that identified no range says why in the subtitle, since the overlaid model line is then not a fit to believe. Requires gstat.

"coefficients"

For a GWR fit only: the local coefficient of one term mapped at the training locations, which is the reason to fit GWR at all. Locations where the local design is collinear for that term are drawn hollow and grey (mask = TRUE): for a slope, where the kernel-weighted window's slope condition index (cn_slopes, predictors centred in the window) is above 30 or the window is singular; a predictor far from zero is not masked, because the local solve centres each window and the index with the intercept (cn) does not enter; for the Intercept, where cn is above 30 (a predictor far from 0 against its local spread makes the local intercept an extrapolation). They are masked because the smooth surface a naive map draws over them is the picture of an unstable estimate, not of a relationship; the subtitle counts them. The condition indices are the fit's info$local_collinearity, computed for every location when the model was fitted. A diverging scale centred on zero is used when the coefficient changes sign, otherwise a sequential one.

response

Logical, default TRUE: for type = "variogram", overlay the response's own variogram. Ignored by the other types.

term

For type = "coefficients": which local coefficient to map, one of the names coef(x) returns. Default NULL: the first predictor. Ignored by the other types.

mask

For type = "coefficients": whether to draw locations whose local design is collinear for that term (see type = "coefficients") as hollow grey points instead of colouring them by a coefficient that is not to be believed there. Default TRUE. Locations whose coefficient is non-finite are masked either way.

...

Ignored.

Value

A ggplot object.

See Also

coef.gwr_fit() for the coefficients themselves.

Other fit methods: print.spatial_fit(), spatial_fit-coef, spatial_fit-fitted, spatial_fit-predict, spatial_fit-residuals, summary.spatial_fit()

Examples


# Works on any spatial_fit; a forest keeps the example free of the optional
# GWR and Stan backends.
library(sf)
# price depends on elevation, which the forest sees, and on a spatially
# correlated field it does not: that field is what the residual plots are
# there to find.
set.seed(2)
n <- 120
xy <- data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
                 elev = rnorm(n))
D  <- as.matrix(dist(xy[, c("x", "y")]))
xy$price <- 10 + 2 * xy$elev +
  as.numeric(t(chol(exp(-D / 100) + diag(0.3, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
fit <- fit_rf_model(pts, "price", "elev", num_trees = 100, seed = 1)
plot(fit, type = "residuals")            # structure left in the residuals
plot(fit, type = "observed_predicted")
if (requireNamespace("gstat", quietly = TRUE))
  plot(fit, type = "variogram")          # residual and response variograms


Plot the interval calibration of a Bayesian cross-validation

Description

cv_bayes() scores every fold's posterior predictive intervals at each of coverage_levels: the share of held-out observations the interval of that nominal level contained. This draws observed coverage against nominal with the diagonal, one point per level for the fold-weighted pooled value (from predictive_coverage) and one faint point per fold, so you can see systematic over-confidence (points below the line) or intervals wider than they need to be (above it). Three levels is a thin curve; pass coverage_levels = seq(0.1, 0.9, by = 0.1) to cv_bayes() for a full one. Each level is drawn at the nominal value cv_bayes() records in coverage_levels, so whatever was computed is drawn where it belongs (0.975 at 0.975, not rounded).

Usage

plot_calibration(cv, ...)

Arguments

cv

The list returned by cv_bayes(), or a compare_models_cv() result that ran the Bayesian backend (its $bayes_cv is used).

...

Not used.

Value

A ggplot object.

See Also

cv_bayes(), which makes the result.

Other cross-validation: compare_models_cv(), cv_bayes(), cv_gwr(), cv_rf(), cv_spatial(), plot_cv_metrics()

Examples

## Not run: 
# Needs brms and a Stan toolchain, and takes minutes: run it, do not check it.
library(sf)
set.seed(1)
n <- 80
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             a = rnorm(n)),
  coords = c("x", "y"), crs = 32632)
dat$z <- 2 * dat$a + rnorm(n)
# Nine coverage levels give a curve rather than three points; chains and
# iterations are kept small to keep this to a few minutes, so the intervals
# will be rough.
cv <- cv_bayes(dat, "z", "a", k = 3, coverage_levels = seq(0.1, 0.9, 0.1),
               fit_args = list(chains = 2, iter = 1000))
plot_calibration(cv)

## End(Not run)

Plot one cross-validation metric fold by fold

Description

One pooled RMSE can come from the same error in every fold or from small errors in most folds and a large one in a single fold (a model that works, and a model that fails in one block), and the pooled number cannot tell the two apart. This draws the metric of each fold as a point, sized by the number of held-out predictions the fold contributed, with the pooled value from overall as a horizontal line, so the spread behind the number is visible. A compare_models_cv() result draws one panel per model on a shared scale, folds aligned, which is the comparison the shared fold set was built for.

Usage

plot_cv_metrics(cv, metric = "RMSE", ...)

Arguments

cv

The list returned by cv_spatial(), cv_gwr(), cv_bayes(), cv_rf() or compare_models_cv().

metric

Character(1) naming a column of fold_metrics (or of by_fold). Default "RMSE".

...

Not used.

Details

Any column of fold_metrics can be drawn, including a backend's extras (bandwidth, CRPS, coverage_95) and columns a metrics function added. A column that is NA in every fold is refused with a message saying why rather than drawn as an empty panel: Adj_R2 is NA for every backend unless p was passed to cv_spatial(), by design. The pooled line is drawn from overall when it carries the metric, from predictive_coverage for cv_bayes()'s coverage and CRPS columns, and not at all for a per-fold extra that has no pooled counterpart (a bandwidth) or for a count (n_pred, n_MAPE, n_SMAPE), whose overall value is the total over the folds; the caption says which. A model with no finite per-fold value gets no panel and no pooled line, and the caption names it.

Value

A ggplot object.

See Also

cv_spatial() and compare_models_cv(), which make the results.

Other cross-validation: compare_models_cv(), cv_bayes(), cv_gwr(), cv_rf(), cv_spatial(), plot_calibration()

Examples


library(sf)
set.seed(1)
n <- 150
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             a = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
dat$z <- 2 * dat$a + 0.003 * (st_coordinates(dat)[, 1] - 5e5) +
  rnorm(n, 0, 0.5)
cv <- cv_rf(dat, "z", "a", k = 5, num_trees = 100)
plot_cv_metrics(cv, "RMSE")


Map a cross-validation fold scheme

Description

Maps the fold each observation belongs to, as a ggplot2 object. Use it to check that the blocks separate the data, and how wide they are beside the autocorrelation range when make_folds(auto_range = TRUE) estimated one. For "block_kfold" folds the block outlines are drawn too, from folds$params$blocks, so a fold can be seen to be one area or several and an empty block can be seen to be empty.

Usage

plot_folds(folds, points_sf, boundary = NULL, blocks = TRUE)

Arguments

folds

A list returned by make_folds().

points_sf

The sf layer the folds were built from. It is drawn in x and y (spatialkit-geometry), and so are boundary and the blocks. A row without a location (a coordinate that is not finite or lies beyond 1e150, or a point that make_folds() left out of every fold because it is empty or the CRS the folds were built in cannot place it) is not drawn, and neither is a row of boundary with such a coordinate; one warning says how many.

boundary

Optional polygon layer (sf or sfc) to draw underneath.

blocks

Logical; draw the block polygons when folds carries them. Default TRUE.

Details

The subtitle states the setting that decides how far the held-out points sit from their training data, read from folds$params: the size of the blocks built and the block_size asked for (with the estimated range when there is one), the buffer, the number of location groups, the median NNDM exclusion, or, for kNNDM folds, that they are matched to the prediction distances. Lengths are in the units of the CRS the folds were built in.

Value

A ggplot object.

See Also

make_folds(), which builds the folds, and fold_separation() to measure how far the held-out points sit from their training data.

Other folds: cv_block_size_sweep(), fold_separation(), make_folds()

Examples


library(sf)
set.seed(1)
n <- 80
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000)),
  coords = c("x", "y"), crs = 32632
)
f <- make_folds(pts, k = 5, method = "block_kfold", block_size = 300)
plot_folds(f, pts)


Plot a tessellation map with optional boundary, seeds, and features

Description

Builds a layered ggplot2 map of the cells, with optional overlays of a study boundary, seed points and other features. Requires the ggplot2 package.

Usage

plot_tessellation_map(
  tessellation_sf,
  boundary = NULL,
  seeds_sf = NULL,
  features_sf = NULL,
  fill_col = NULL,
  palette = "viridis",
  na_fill = "grey90",
  tile_alpha = 0.9,
  outline_col = "white",
  outline_size = 0.2,
  features_col = "#333333",
  features_size = 0.5,
  seeds_col = "#1f77b4",
  seeds_size = 1.5,
  boundary_col = "#111111",
  boundary_size = 0.6,
  labels = FALSE,
  label_col = NULL,
  label_size = 2.7,
  legend = TRUE,
  legend_title = NULL,
  theme = NULL,
  target_crs = NULL,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  xlim = NULL,
  ylim = NULL,
  expand = TRUE
)

Arguments

tessellation_sf

An sf POLYGON/MULTIPOLYGON layer. Required.

boundary

Optional sf/sfc polygon outline layer.

seeds_sf

Optional sf/sfc point layer of seed locations.

features_sf

Optional sf/sfc layer of additional features.

fill_col

Name of the COLUMN in tessellation_sf to map to fill; NULL for no fill. A numeric column gets a continuous scale, as does a Date or POSIXct column (on a date or time axis) and a units or difftime column (drawn as numbers, with the unit in the legend title); anything else a discrete one. fill_col and label_col name columns, while outline_col, features_col, seeds_col and boundary_col are colours.

palette

Viridis palette, passed as option to ggplot2::scale_fill_viridis_c() or ggplot2::scale_fill_viridis_d(): "viridis" (default), "magma", "inferno", "plasma", "cividis", "rocket", "mako" or "turbo".

na_fill

Fill for NA values. Default "grey90".

tile_alpha

Alpha for filled polygons. Default 0.9.

outline_col, outline_size

Colour and line width of the cell outlines. Defaults "white" and 0.2.

features_col, features_size

Colour and point size of the feature overlay. Defaults "#333333" and 0.5.

seeds_col, seeds_size

Colour and point size of the seed overlay. Defaults "#1f77b4" and 1.5.

boundary_col, boundary_size

Colour and line width of the boundary outline. Defaults "#111111" and 0.6.

labels

Logical; draw per-cell labels. Default FALSE. A cell is labelled when its label is not NA and it has a location; when no cell has both, the labels are skipped with a log line.

label_col

Name of the COLUMN holding the label text. Default NULL: the first of "poly_id", "polygon_id", "id", "cell_id" and "grid_id" the layer has, the order in which assign_features_to_polygons() reads a polygon layer's IDs, so the cells of build_tessellation() and the output of summarize_by_cell() are labelled without naming one, by the ID the summary is keyed on. A units or difftime column is drawn formatted, with its unit.

label_size

Label text size. Default 2.7.

legend

Logical; show fill legend. Default TRUE.

legend_title

Optional legend title.

theme

A ggplot2 theme. Default NULL, which uses ggplot2::theme_void().

target_crs

Optional CRS for plotting. When NULL (the default) the tessellation's own CRS is used, or (if the tessellation has none) a CRS borrowed from the first overlay that carries one, so a CRS-less grid drawn with located features still lines up. Any layer that arrives without a CRS is brought into the plot's CRS instead of being dropped: reprojected when its coordinates look like longitude/latitude, otherwise stamped with a warning, since a stamp assumes the coordinates were already in that CRS. A plot CRS in longitude and latitude is not stamped on coordinates that cannot be in it (an x outside -180 to 360, or a y beyond 90 north or south): the call stops and asks for the layer's CRS or a projected target_crs.

title, subtitle, caption

Plot annotations.

xlim, ylim

Optional numeric vectors of length 2 for coordinate limits (in the plot CRS). Default NULL (auto).

expand

Logical; expand plot area slightly beyond data limits. Default TRUE.

Details

Every layer is drawn in x and y: a layer whose geometries mix XY with XYZ or XYM (as rbind() of an XY and an XYZ layer gives) is drawn without its Z and M. The labels are placed in x and y, also on cells whose geometries carry M (XYM or XYZM).

A row of any layer with a coordinate that is not finite or lies beyond 1e150 has no location: it is left out of the map, with one warning that says how many rows of which argument were not drawn. A row the plot's CRS cannot place in full is drawn as the move leaves it (empty, or without the vertices it cannot place), with a warning of class spatialkit_rows_unplaced that names it.

Value

A ggplot2 object.

See Also

Other cell building: build_tessellation(), clip_target_for(), create_grid_polygons(), create_grid_polygons_cached(), create_voronoi_polygons(), ensure_stable_poly_id(), get_voronoi_seeds(), voronoi_seeds_kmeans(), voronoi_seeds_random()

Examples

if (requireNamespace("ggplot2", quietly = TRUE)) {
  library(sf)
  set.seed(1)
  n <- 60
  pts <- st_as_sf(
    data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
               z = rnorm(n)),
    coords = c("x", "y"), crs = 32632
  )
  # Cells from the points, the response aggregated onto them, and the map
  # shaded by the cell mean rather than by an arbitrary ID.  Each cell
  # holds one point, so there is nothing to pool: estimate = "mean".
  tess  <- build_tessellation(pts, method = "voronoi", quiet = TRUE)
  asg   <- assign_features_to_polygons(pts, tess$cells,
                                       polygon_id_col = "cell_id")
  cells <- summarize_by_cell(asg, response_var = "z", id_col = "cell_id",
                             cells_sf = tess$cells, estimate = "mean")
  plot_tessellation_map(cells, features_sf = pts, fill_col = "resp_mean_z",
                        legend_title = "mean z")
}

Predict a fitted model onto a regular grid

Description

Builds a prediction surface over the extent of the training data (or over a grid you supply), predicts in chunks, and returns an sf layer.

Usage

predict_surface(
  object,
  grid = NULL,
  cell_size = NULL,
  n_cells = 10000L,
  boundary = NULL,
  covariates = NULL,
  chunk_size = 5000L,
  se = FALSE,
  ...
)

Arguments

object

A spatial_fit (from fit_rf_model(), fit_gwr_model() or fit_bayesian_spatial_model()).

grid

Optional sf POINT layer to predict onto, with at least one row. When NULL, a regular grid is built over the training extent. A grid of polygons is reduced to points; see "Coordinate reference systems and geometry".

cell_size

Grid resolution in CRS units. Ignored when grid is supplied; when NULL, derived from n_cells. A value that would produce more than 5,000,000 cells is refused, naming the implied count and the CRS units. The usual cause is a value in the wrong unit. The grid is centred on the training bounding box and covers it: when the extent is not a whole number of cells, it overhangs the box by less than one cell, split evenly between the two sides. A cell_size wider than the extent yields a single centred cell.

n_cells

Approximate cell count used to derive cell_size. Default 10000. Must be a single positive finite number and at most 5,000,000; anything else is an error. Also ignored when grid is supplied. The grid you pass is used verbatim.

boundary

Optional polygonal sf/sfc; grid points outside it are dropped. Aligned to the fit's CRS as grid is.

covariates

Optional sf layer carrying the model's predictors. Required when the model has predictors and grid does not already contain them. Values are taken from the nearest feature (see "Ties between nearest covariate features"). Aligned to the fit's CRS as grid is, with the same warning when it has no CRS.

chunk_size

Rows per prediction call. Default 5000. A performance setting only: rows do not interact, and for a bayesian_fit the GP boundary is held at its fitted value whatever the chunk holds (see spatial_fit-predict). The two warnings in which predict() on a GWR fit counts locations (classes "spatialkit_gwr_extrapolation" and "spatialkit_gwr_not_estimable") are raised once for the grid, with its totals, whatever the number of chunks.

se

Logical; also return a standard error (or posterior SD) column where the backend supports it. Default FALSE. For a bayesian_fit this is the SD of the posterior draws predict() returns, and those are of the expected value by default (type = "epred"): the uncertainty of the mean surface, not of a new observation, which also carries the observation noise. For the predictive SD, the one that goes with prediction intervals and cv_bayes()'s calibration, pass type = "predict" as well.

...

Passed to predict(), e.g. type = "predict" for a bayesian_fit. Not draws, which this function sets itself and refuses here.

Details

predict_surface() builds the grid, joins the covariates, aligns the CRSs and calls predict() in chunks of chunk_size rows. Rows do not interact, so chunking changes memory use and not the predictions. For a bayesian_fit the draw matrix is n_draws by the number of rows, which on a fine grid outgrows memory long before the fit does.

Value

An sf POINT layer with a .pred column, and .pred_se when se = TRUE and the backend gives one. A .pred_se column that a supplied grid carries from an earlier surface is removed when this call adds none. For an auto-generated grid the resolution is attached as attribute "cell_size". For a user-supplied grid it is only whatever "cell_size" attribute that object already carried. That is usually NULL, and NULL for certain if the grid had to be re-projected, since st_transform() does not preserve custom attributes.

Coordinate reference systems and geometry

grid, boundary and covariates are brought into the fit's CRS first. A layer without a CRS is read the way the training data were (the assumption recorded on the fit), with a warning, and then reprojected; when that reading is longitude and latitude, a layer with an x outside -180 to 360 or a y beyond 90 north or south cannot be in it, and the call stops. Without this a CRS-less grid could land thousands of kilometres from the covariates, and every cell would take the same nearest feature. A layer still without a CRS after that is taken as EPSG:4326 and reprojected when its coordinates look like longitude and latitude, and otherwise stamped with the fit's CRS, with a warning either way; a fit's CRS in longitude and latitude is not stamped on coordinates outside longitude -180 to 360 and latitude -90 to 90, which is refused. See spatialkit-geometry for these rules in general.

A grid of polygons (create_grid_polygons() output, say) is reduced to one representative point per cell, as coerce_to_points() does, so covariates are taken at the location predicted for; boundary then keeps the cells whose point falls inside it. All three layers are read in x and y: one whose geometries mix XY with XYZ or XYM, or carry M (XYM or XYZM), is read without its Z and M, with no warning for a boundary or covariates. A POINT grid whose coordinates are not moved (one in the fit's CRS, or one without a CRS that is stamped with it) is returned with its rows as given, Z and M included; one that mixes dimensions and is reprojected into the fit's CRS comes back in XY with a warning of class "spatialkit_zm_dropped". The points a grid of polygons is reduced to are in XY when its geometries mix dimensions or carry M.

A grid row without a location (an empty geometry, or a coordinate that is not finite or lies beyond 1e150) gets an NA prediction; in a grid that is reprojected, or reduced from polygons, it comes back as an empty point. A covariate row without a location is never the nearest feature.

Ties between nearest covariate features

A grid point the same distance from several features of covariates takes one of them by a fixed rule, so a grid laid between the points of a lattice takes the same covariates in another unit or with another origin, and with or without the FNN package.

See Also

area_of_applicability() to mark where the surface applies, and spatial_fit-predict for the predictions of each backend.

Other prediction: area_of_applicability(), plot.aoa(), print.aoa()

Examples


# Any spatial_fit works here; a forest keeps the example free of the
# optional GWR and Stan backends.
library(sf)
set.seed(1)
n <- 120
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             elev = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
pts$price <- 10 + 0.01 * (st_coordinates(pts)[, 1] - 5e5) +
  2 * pts$elev + rnorm(n)
fit  <- fit_rf_model(pts, "price", "elev", num_trees = 100, seed = 1)
surf <- predict_surface(fit, n_cells = 500, covariates = pts)
surf[".pred"]               # one prediction per grid cell, as an sf layer
# Check where the surface extrapolates before mapping it.  The grid took
# its covariates from the nearest observation, so here nothing is
# outside; covariates from another source, such as a raster converted to
# sf points, are where this bites.
area_of_applicability(surf, model = fit)


Prepare an sf layer for model fitting

Description

Reduces the layer to 2-D points in a projected CRS and drops the rows a model cannot use: rows with a missing or non-finite value in the response or a predictor, and rows without a location. Every fitter and every cv_*() function prepares its data here.

Usage

prep_model_data(
  data_sf,
  response_var,
  predictor_vars,
  boundary = NULL,
  pointize = c("auto", "surface", "point_on_surface", "centroid", "line_midpoint",
    "bbox_center"),
  require_response = TRUE
)

Arguments

data_sf

An sf object. Rows without a location are dropped (see Details).

response_var

Name of the response column.

predictor_vars

Predictor column names. May be character(0) for an intercept-only model (fit_bayesian_spatial_model() supports one; the GWR and random-forest backends do not and reject it themselves).

boundary

Optional sf/sfc whose CRS the data are projected to. It is not a clip: rows that fall outside it are kept. Subset data_sf yourself (for example with sf::st_filter()) to restrict the rows. One that mixes XY and XYZ (or XYM) geometries is read in x and y.

pointize

How non-point geometries become points, passed to coerce_to_points() as its mode: "auto" (default), "centroid", "point_on_surface", "surface" (an alias for "point_on_surface"), "line_midpoint" or "bbox_center". Its errors, such as the one of class spatialkit_features_degenerate for a polygon s2 cannot take a centroid of, are raised in this function's name and give the rows of data_sf.

require_response

Logical; if FALSE the response column is not required to be present (useful for out-of-sample prediction where the response is unknown). Default TRUE.

Details

Non-POINT geometries (MULTIPOINT included) are reduced to representative points by coerce_to_points(), so that coordinates line up one row per observation. Any Z or M coordinate (POINT Z from a GPS, a GeoPackage or KML) is dropped, because every backend works in 2-D distance.

A row has no location when its geometry is empty, a coordinate is not finite or lies beyond 1e150, or, in a geographic CRS, a vertex lies at a latitude beyond 90 degrees (see spatialkit-geometry, "Rows without a location"). The 1e150 bound is read on the coordinates as given and again after the projection, because a move between CRSs can bring a coordinate beyond it back finite, and that point is not a place the caller gave.

The CRS is projected whenever one can be established (ensure_projected()). A layer without a CRS is read by the lon/lat test of spatialkit-geometry ("Layers without a CRS"): coordinates the test takes for degrees are read as EPSG:4326 and projected, with a warning, and others are passed through as they are. A small planar survey inside the lon/lat envelope is read as degrees, so set the CRS on data_sf if the data are planar.

The response may not appear in predictor_vars. Using it as its own predictor is leakage no backend catches (an out-of-bag R^2 near 1 in the random forest, a silently reduced design matrix in GWR, duplicated rows and a phantom <none> entry in the GWR selection table), so it is refused here.

Column names must be syntactically valid R names (make.names(x) == x). Every backend builds a model formula from these names, and a name R parses as an expression would fit another model than the one requested while the fit still recorded the name you asked for: "B5-B4" is B5 - B4, and "log(a)" is a function call. Rename the column (for example with make.names()) before fitting.

The "dropped" record describes the rows this call returned and does not survive subsetting: clean[i, ], like dplyr::filter(), slice() or arrange() of it, is a plain layer with no "dropped" attribute, and a fit given such a subset with .already_prepped = TRUE reports n_dropped = 0 even when the parent layer dropped rows. sf::st_drop_geometry() keeps the record, since the rows are the same; see [.spatialkit_rows for what binding such data frames does.

Value

An sf object with 2-D (XY) POINT geometry, without the rows that were dropped. The attribute "dropped" records what was removed and two marks on the rows that were kept, in a list with these fields:

n

Rows dropped. Every fit stores it as $info$n_dropped.

n_geometry

How many of them were dropped for having no location.

which

Their positions in data_sf.

row_id

Their ..row_id values when the layer carries that column, else NULL.

reason

One per dropped row: "geometry", "missing" or "non_finite", in that order of precedence when several apply.

by_column

For each modelling column, and for "(geometry)", how many of the dropped rows it is missing or non-finite in; a row can count under several.

response_std_diff

The mean response of the dropped rows minus that of the kept rows, in standard deviations of the response over both; NA when the response is not numeric, is itself missing in every dropped row, or takes one value up to the rounding of its values.

n_rows

The number of rows returned, which the record was made for.

constant_predictors

The predictors that take one value in every returned row (character(0) when none does).

n_duplicate_locations

The returned rows whose coordinates repeat those of an earlier row.

Warnings

When preparing data for a fit (require_response = TRUE) three conditions are raised as R warnings, each with a class so it can be caught by name with tryCatch() or withCallingHandlers():

spatialkit_rows_dropped

Rows were dropped. The message gives the number and share of rows, the count by reason and by column, and, for a numeric response, how far the mean response of the dropped rows sits from that of the kept rows. A fit on the rows that remain describes those rows only; when the difference is large the rows are not missing at random and the fit is biased towards the complete ones.

spatialkit_response_imprecise

The response lies so far from zero that doubles there are spaced more than a millionth of its standard deviation apart (a standard deviation of 1 at about 1e10, 2^{33}, or beyond). Its values are rounded to that spacing, and so is every mean and prediction computed at that size: the fit, its scores and any choice made on them read that rounding. The rows are kept; subtract a constant from the response first.

spatialkit_constant_predictor

A predictor takes a single value in every row that remains. Its coefficient cannot be told from the intercept: a GWR window is rank-deficient, a Bayesian slope is its prior, and a forest ignores it. The predictor is kept; drop it from predictor_vars.

The fitters and the cv_*() functions pass these warnings on. compare_models_cv(), cv_block_size_sweep() and select_features_forward() run several cross-validations of one layer, each of which prepares it, and raise spatialkit_rows_dropped and spatialkit_constant_predictor once per distinct text for the run and spatialkit_response_imprecise once per response column; cv_spatial() raises the last once as well when its fit_fn prepares each fold's rows again.

With require_response = FALSE (how every predict() method prepares newdata) none is raised: the dropped rows are written to the log and to the record, and the prediction for each comes back NA, so nothing is lost without a trace. Repeated locations are legitimate (repeat visits to one site) and are counted in the record and the log, never warned about.

See Also

Other data preparation: [.spatialkit_rows(), coerce_to_points(), ensure_projected(), harmonize_crs(), spatialkit-geometry

Examples

library(sf)
dat <- st_as_sf(
  data.frame(x = 1:5, y = 5:1,
             resp = c(1, 2, NA, 4, 5),
             pred = c(1, 2, 3, 4, Inf)),
  coords = c("x", "y"), crs = 32632
)
# Drops rows 3 (NA) and 5 (Inf), and warns that it did, with the counts.
clean <- suppressWarnings(prep_model_data(dat, "resp", "pred"))
attr(clean, "dropped")

Print an area-of-applicability result

Description

Prints how many prediction locations fall inside the area of applicability and how many outside, the dissimilarity threshold that separated them, and the predictors the index was computed over (naming any dropped for having no usable variance). It also says where the weights came from (the model's importance, a vector the caller supplied, or equal weights and why), whether location was measured and how, how categorical predictors were handled, and how many training rows repeat another's predictor values. With a location index the rows outside are split into those outside on the predictors and those outside on location. The share of locations outside is the number to report: a map that extrapolates over much of its extent rests on predictions the training data cannot support.

Usage

## S3 method for class 'aoa'
print(x, ...)

Arguments

x

An aoa object.

...

Not used.

Value

x, invisibly.

See Also

area_of_applicability(), which makes the object, and plot.aoa().

Other prediction: area_of_applicability(), plot.aoa(), predict_surface()

Examples

library(sf)
set.seed(1)
train <- st_as_sf(
  data.frame(x = 5e5 + runif(60, 0, 1000), y = 5e6 + runif(60, 0, 1000),
             a = rnorm(60)),
  coords = c("x", "y"), crs = 32632
)
# 15 new points take values of a seen in training; five lie far above
# its range, and print() counts those five outside.
newpts <- st_as_sf(
  data.frame(x = 5e5 + runif(20, 0, 1000), y = 5e6 + runif(20, 0, 1000),
             a = c(train$a[1:15], rnorm(5, 8))),
  coords = c("x", "y"), crs = 32632
)
res <- area_of_applicability(newpts, train_sf = train, predictor_vars = "a")
print(res)

Print a residual Moran's I result

Description

Prints the statistic, the null its moments come from and the evidence behind them. The weight matrix the result carries is described in one line instead of printed.

Usage

## S3 method for class 'morans_i'
print(x, ...)

Arguments

x

An object of class morans_i, from residual_morans_i().

...

Not used.

Value

x, invisibly.

See Also

residual_morans_i(), which makes the object.

Other in-sample checks: compare_models(), evaluate_insample(), model_metrics(), residual_morans_i()

Examples


library(sf)
set.seed(1)
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(80, 0, 1000), y = 5e6 + runif(80, 0, 1000),
             elev = rnorm(80)),
  coords = c("x", "y"), crs = 32632
)
dat$price <- 10 + 2 * dat$elev + rnorm(80)
fit <- fit_rf_model(dat, "price", "elev", num_trees = 100, seed = 1)
print(residual_morans_i(fit))


Print a fitted model

Description

Prints the backend, the formula, the number of observations and the CRS, then lines for the backend:

A custom subclass prints the common lines only. Typing the object's name calls this method; use it to confirm that a fit used the data, predictors and CRS you meant. For fit quality use model_metrics() or summary.spatial_fit(). Apart from a forest's out-of-bag error and a Bayesian GP's LOOIC, an approximate leave-one-out score of single rows, nothing printed here is an out-of-sample score, and neither of those is a spatial one.

Usage

## S3 method for class 'spatial_fit'
print(x, ...)

## S3 method for class 'rf_fit'
print(x, ...)

Arguments

x

A spatial_fit object.

...

Not used.

Value

x, invisibly.

See Also

fit_rf_model(), fit_gwr_model() and fit_bayesian_spatial_model(), which make the objects.

Other fit methods: plot.spatial_fit(), spatial_fit-coef, spatial_fit-fitted, spatial_fit-predict, spatial_fit-residuals, summary.spatial_fit()

Examples


library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(60, 0, 1000), y = 5e6 + runif(60, 0, 1000),
             a = rnorm(60)),
  coords = c("x", "y"), crs = 32632
)
pts$z <- 10 + 2 * pts$a + rnorm(60, 0, 0.3)
fit <- fit_rf_model(pts, "z", "a", num_trees = 50, seed = 1)
fit                     # print.rf_fit()
if (requireNamespace("sp", quietly = TRUE))
  print(fit_gwr_model(pts, "z", "a", bandwidth = 30))   # print.spatial_fit()


Test the residuals of a fitted model for spatial autocorrelation

Description

Takes the residuals and the observation coordinates of a spatial_fit, builds a spatial weight matrix, and computes Moran's I with its expectation and variance under a stated null. A z-score and a p-value say whether spatial autocorrelation remains after fitting. The default weights are the row-standardised k-nearest-neighbour matrix described under weights.

Usage

residual_morans_i(
  fit,
  alternative = c("two.sided", "greater", "less"),
  weights = NULL,
  k = 8L,
  null = c("auto", "randomisation", "residual"),
  keep_weights = FALSE
)

Arguments

fit

A spatial_fit object (from fit_gwr_model, fit_bayesian_spatial_model or fit_rf_model). The locations are read from its data_sf, a feature that is not a point reduced to one as coerce_to_points(, "auto") does. A layer whose geometries mix XY with XYZ or XYM, or carry M (XYM or XYZM), is read in x and y, with no warning (see spatialkit-geometry).

alternative

Character: "two.sided" (default), "greater" (positive autocorrelation), or "less".

weights

Optional user-supplied n x n weight matrix: a base matrix or a Matrix-package matrix (e.g. a sparse dgCMatrix). When NULL (the default), a row-standardised k-nearest-neighbour weight matrix (k = 8) is built from the observation coordinates. Ties at the k-th distance (every regular grid, every site with repeat visits) share that slot's weight equally, with no tie-break by row order or by which backend found them, so the matrix is a function of the geometry alone. A distance is tied with the k-th when their squares are within one part in ten million of each other, so the matrix is the same in any unit and at any origin where the doubles hold the coordinates to better than about one part in 1e8 of the distances between neighbours. Farther from the origin the doubles round the coordinates more coarsely, and a lattice whose coordinates are not on that rounding can lose its ties. Where a distance lies past a tie by less than that rounding, the call warns, with class "spatialkit_xy_imprecise", naming the rounding and the distance; the matrix is the one the coordinates as stored give. On distinct, untied coordinates it equals spdep's knearneigh() + nb2listw(style = "W") exactly. If a non-row-standardised matrix is supplied (i.e. rows do not all sum to 1), the Cliff & Ord variance formula is still valid for general W and the computation proceeds; a note is logged (not raised as an R warning) because the magnitude of I is not directly comparable to results obtained with row-standardised weights. A weights argument that is not an n x n matrix is an error.

k

Integer number of nearest neighbours used when building the default weight matrix (ignored when weights is supplied). Default 8. k >= n - 1 is a complete graph (n(n-1) weights however they are stored) and is refused above 20 million of them.

null

Which null distribution the expectation, variance and p-value are computed against. One of:

"auto" (default)

"residual" when the design matrix can be rebuilt and the fit's residuals are the OLS residuals on it, "randomisation" otherwise.

"randomisation"

Always the exchangeable moments.

"residual"

Always the Cliff & Ord residual moments. Falls back to "randomisation" with a logged warning if the design cannot be rebuilt, and logs a warning (but proceeds) if the residuals are not the OLS residuals on it, in which case the moments are approximate.

Both "auto" and "residual" also fall back to "randomisation" when the residual degrees of freedom n - p are below 4 (the residual variance divides by (n-p)(n-p+2) and the normal approximation means nothing there); "residual" logs a warning when it does, "auto" does not, and df in the result is then n - 1. Read null in the result to see which it was. See the section "Which null, and when it is approximate".

keep_weights

Logical. Return the n \times n weight matrix in the result? Defaults to FALSE: the matrix makes up most of the object's size, while most uses read only the statistic and its moments, and weights_summary says what it was. Set TRUE when you need the matrix itself.

Value

A list with components:

observed

Numeric scalar, Moran's I statistic.

expected

Expected I under the null named by null: -1/(n-1) for "randomisation", (n/S_0)\mathrm{tr}(MW)/(n-p) for "residual".

sd

Standard deviation of I under that same null.

z

Standardised z-score, (I - E[I]) / sd(I).

p_value

Two-sided (or one-sided) p-value from the normal approximation.

n

Number of observations used.

null

The null actually used, "randomisation" or "residual". Check it, since "auto" chooses per fit and "residual" can fall back.

df

Residual degrees of freedom behind the moments: n - p for "residual" (where p is the rank of the design matrix), n - 1 for "randomisation".

weights

The n \times n weight matrix the statistic was computed with, either the row-standardised k-nearest-neighbour matrix built here (sparse when Matrix is installed) or the supplied weights after the diagonal was zeroed. It is NULL unless keep_weights = TRUE.

kurtosis

The residual kurtosis m_4 / m_2^2, which the randomisation variance conditions on and which says how far the residuals sit from the Gaussian case the residual moments assume (3 for a normal sample).

p

The rank of the rebuilt design matrix behind the "residual" moments; NA under "randomisation".

exact

Logical: TRUE when the moments are exact for these residuals (the residual null on OLS residuals of the response on the rebuilt design), FALSE when they are an approximation (the residual null forced onto a non-OLS backend, or the randomisation null, whose exchangeable moments model residuals do not satisfy).

weights_summary

What the weight matrix was, present whether or not the matrix itself was kept: n, storage (its class), neighbours (the smallest and largest number of neighbours any row has, and NA for a dense matrix, where counting them would allocate a second one), kept (whether weights holds the matrix) and desc, the one line print() shows.

The list is classed "morans_i" and has a print() method, so the console shows the statistic and its null without printing the n \times n weights matrix; [ drops the class, and $, [[ and unlist() are unaffected. A custom fit whose class has no residuals() method (which new_spatial_fit calls optional) is scored on the observed response minus fitted(), as plot() does for it. Returns NULL with a warning if computation fails, saying why: residuals() raised an error (its message is quoted), or returned NULL and the response minus fitted() could not be formed either (the reason is quoted), fewer than 4 valid residuals, a residual vector whose length does not match the fit's data_sf, weights that sum to less than .Machine$double.eps, or residuals that leave I a ratio of rounding: they do not vary, or vary by no more than the rounding of the response (a standard deviation of 3 units in the last place of its largest value, or a root mean square of 10\epsilon times that of the response about its centre), or are the OLS residuals of an exact fit of the response on the predictors (a root mean square of 10\epsilon times that of the fit's terms). The test reads the residuals against the response, so residuals in any unit are scored or refused alike, and I, z and the p-value do not depend on the unit.

Which null, and when it is approximate

Two nulls are available, and the one used is reported in the null element of the return value.

"randomisation" is the classical exchangeable null: E[I] = -1/(n-1) with the Cliff and Ord randomisation variance, conditioning on the observed kurtosis. These are the moments of I for a vector whose elements are equally likely in any order.

Model residuals are not exchangeable. They are orthogonal to the design matrix, which pushes E[I] below -1/(n-1) whenever the covariates are spatially smooth, and further the more covariates there are. Under the exchangeable null the z-score of OLS residuals is then shifted below 0, and the test loses power.

"residual" therefore uses the Cliff and Ord (1981, section 8.3) moments for regression residuals, with M = I - X(X'X)^{-1}X' rebuilt from predictor_vars and data_sf:

E[I] = (n/S_0)\,\mathrm{tr}(MW)/(n-p)

Var[I] = (n/S_0)^2[\mathrm{tr}(MWMW') + \mathrm{tr}((MW)^2) + (\mathrm{tr}MW)^2]/[(n-p)(n-p+2)] - E[I]^2

These assume normal errors and do not condition on the observed kurtosis. They agree with spdep::lm.morantest() to machine precision.

The residual moments are exact for e = My and for nothing else, so null = "auto" does not guess from the fit's class: it rebuilds X, regresses the response on it, and uses the residual moments only when the supplied residuals are those OLS residuals to numerical tolerance. A GWR wide enough to have collapsed to global OLS passes that test; the same GWR at a working bandwidth does not. The response, and each predictor whose centre is more than 1000 times its spread, are taken about their centres before the regression, which leaves its residuals as they are, so a timestamp or a response at 1e10 gives the null, moments and rank p of the same columns at 0. The supplied residuals pass where none differs from the OLS residuals by more than 1e-7 of the response's standard deviation, or where the differences are no more than the rounding a regression of the raw columns leaves: a root mean square of 10\epsilon (\epsilon = .Machine$double.eps) times that of the fit's terms, among them the offset the fit regressed the response at (for a GWR that took the response about its centre, the offset left after that centre). They also pass where none differs by more than 1e-7 of the response's standard deviation from the residuals lm() gives on the raw columns, where the raw design keeps the rank of the centred one: that rounding grows with the number of rows.

For the flexible backends neither null is exact, and "auto" leaves them on "randomisation": forcing the OLS moments on them does not correct them, and for a forest it raises the false-positive rate. A random forest's residuals here are the out-of-bag ones (spatial_fit-residuals). The random forest is anticonservative under both: its residuals are not a linear projection of the response and they are spatially heteroscedastic, so neither set of moments describes their null distribution and the variance is understated whichever is used. GWR is conservative under both, because it removes far more structure than a rank-p projection does. Treat the p-value from those backends as a rough indicator, and prefer spatially blocked cross-validated residuals or an explicit spatial covariance model when the answer has to carry weight.

A permutation null does not help: permuting the residual vector destroys the orthogonality that causes the bias, so its mean is the exchangeable -1/(n-1) by construction and it reproduces the randomisation null.

Reading a large I

A large positive I with a small p-value means the residuals keep spatial structure the model did not capture (for a forest, read the p-value as rough; see above): a covariate it lacks, or a scale it cannot represent. Add the missing covariate if there is one, compare a backend that models space (fit_gwr_model() or fit_bayesian_spatial_model()), and score the model with blocked folds (cv_spatial()). A z near 0 with a large p-value means the test found no structure left.

References

Cliff, A. D. and Ord, J. K. (1981) Spatial Processes: Models and Applications. Pion, London. Section 8.3.

See Also

compare_models(), which adds the statistic to a comparison of fits.

Other in-sample checks: compare_models(), evaluate_insample(), model_metrics(), print.morans_i()

Examples


# Works on any spatial_fit; a forest keeps the example free of the
# optional GWR and Stan backends.
library(sf)
set.seed(1)
n <- 120
dat <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             elev = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
# An east-west trend the predictor cannot explain.
dat$price <- 10 + 0.02 * (st_coordinates(dat)[, 1] - 5e5) +
  2 * dat$elev + rnorm(n)
fit <- fit_rf_model(dat, "price", "elev", num_trees = 100, seed = 1)
# A large positive I and z: the residuals carry the east-west trend the
# forest could not see.  A z near 0 with a large p-value would mean no
# structure was left.
residual_morans_i(fit)


Score candidate cell counts on several criteria

Description

Scores candidate numbers of cells (levels) for a layer of points, so that the count chosen, by select_resolution() or by eye, can be defended with the whole profile in place of one criterion's optimum.

Usage

resolution_profile(
  data_sf,
  response_var = NULL,
  predictor_vars = NULL,
  levels = NULL,
  n_levels = 20L,
  min_cell_n = 9L,
  sample_n = 1500L,
  nstart = NULL,
  seed = 123L,
  sac = "auto",
  select_on = c("all", "split"),
  range_floor = FALSE,
  partition = c("density", "kmeans"),
  init = c("kmeans++", "random"),
  density_power = 1,
  density_k = 8L,
  iter_max = NULL,
  estimate = "auto",
  obs_per_cell = "auto"
)

## S3 method for class 'resolution_profile'
print(x, digits = 3L, ...)

Arguments

data_sf

An sf object of points (other geometries are reduced to representative points with coerce_to_points()). Features without a location, as given, once projected or in the CRS of sac, are dropped with a warning, and a layer that mixes XY and XYZ geometries or carries M is read in x and y (see spatialkit-geometry).

response_var

Name of the response column (numeric or logical), or NULL. Enables cp and moran_z, and, when it is numeric, the pooled estimate the default profile scores by loo. A variogram estimated from it also gives the range floor the bounds report and reliability; it is estimated on a ladder of counts or when sac asks for it, and not on the default ladder of one size, so cp and reliability are NA there. Rows where it, or a predictor, is missing or non-finite stay in the geometry and are left out of the OLS fit, the RSS, cp, moran_z and the count the support ceiling divides by min_cell_n; a logged warning gives their number, and an R warning says so when they lower the ceiling.

predictor_vars

Optional predictor column names (numeric or logical). With them, cp scores the OLS residuals of the response on the predictors, the variogram is estimated from those residuals, and moran_z regresses the cell means on the cell-mean predictors.

levels

Optional integer vector of level counts to score, replacing the ladder; values below 2, above the number of distinct locations, or at or above the number of points, are dropped (k-means cannot place more centres than there are distinct points, and stats::kmeans() refuses as many centres as points). When none is left the call stops with an error, before the variogram is estimated or read, so it raises no warning about the variogram.

n_levels

Number of levels on the ladder. Default 20. The ladder has fewer when rounding puts two of them on one count, and one more when the range floor is added as a level (see "The ladder and its bounds"). Supplying it, or min_cell_n, sample_n, levels or range_floor, gives that ladder in place of the ladder of sizes obs_per_cell = "auto" would set.

min_cell_n

Minimum average number of rows per cell that a level must keep (scored rows when response_var is given: those with a response and every predictor; points otherwise); sets the ceiling. Default 9. A layer that cannot give two cells that many is profiled at two cells, or at the levels asked for, with supported = FALSE and a warning. It is floored to a whole number, and it is not read on a ladder obs_per_cell sets (see "The ladder and its bounds").

sample_n

Points are subsampled to this many before the k-means fits, as in determine_optimal_levels(), on the ladder of "The ladder and its bounds"; on a ladder of sizes, the default, the centres are fitted to every row. Default 1500. The columns read off the fitted cells (wss, the cell_ and cells_ columns, rss, moran_i, moran_z) describe the subsample; the bounds, supported, the variance term of cp and reliability describe the whole layer, so the answer does not change with sample_n except through the fits. The fits are those of the subsample, which seed draws, so on a layer of more than sample_n points the count read off the profile can move with seed and with sample_n. The level select_resolution() chooses off such a profile without an estimate is refitted to every point before its seeds are handed on (see refit_rows under "Value"); a profile with an estimate scores it on every row in the cells of the centres fitted, and hands those centres on.

nstart

Starts per level; the best is kept. They are k-means++ starts unless init says otherwise. NULL (default) is the kind's own number: 3 for the kind "density" and 25 for the kind "kmeans". A number is run under either partition. attr(, "nstart") holds the number that was run.

seed

RNG seed for the subsample and the restarts; restored afterwards. Default 123. The rows are put in coordinate order before either, so the profile does not depend on the order they come in. Each level's restarts run on a stream of their own, seeded from seed and the level, so for one seed a level gets the same cells on any ladder that holds it and is fitted to the same rows, and with them the same wss, rss, moran_z and the other columns read off its cells. On a layer of more than sample_n rows a ladder of counts is fitted to a subsample and a ladder of sizes to every row, so there the two can give a level other cells. cp also reads its noise variance, which without a usable variogram comes from the ladder's finest level (attr(, "cp_noise")).

sac

Optional sac_range object from estimate_sac_range() to take the range, nugget and correlation function from. Pass one fitted with detrend = "reml", say. It must describe the variable the profile scores: the raw response without predictor_vars, the residuals on them with; a sac whose detrended attribute says otherwise is used with a warning. Its range is read in its own CRS (attr(sac, "crs")), to which the points are transformed first, so the area, the floor and cell_diam_median are then in that CRS's units. A sac whose range was rejected (NA with a rejected_reason) gives cp its nugget (held to the semivariance of nearest-neighbour pairs, and not at all when it is at the fit's lower bound), with a warning, and leaves reliability NA, since that needs the range; one whose model did not converge (its fit has no minimum inside the ranges searched, so its nugget and sill are not fitted values), or whose range is below the shortest lag fitted (a structure that cannot be told from a nugget, so the nugget is not identified either), gives neither, and cp takes its noise variance from the finest level (see cp above). Whether the model converged is read from the model (attr(attr(sac, "variogram_model"), "converged"), which estimate_sac_range() sets and describes), not from the reason: the reason names one ground for the refusal, and such a fit is refused as past the largest lag. The warning then names both. A sac that carries no such flag (one made by hand, or built from REML parameters) is judged by its reason. Under select_on = "split" the sac must come from the selection half alone: run the profile once without it, fit the sac on data_sf[attr(p, "split")$selection, ] and pass it to a second call with the same seed, which makes the same split. When NULL and a response is given, one is estimated on the subsample (its selection half under "split") with the same predictor_vars. A plain number is taken as the range alone, in the units of the CRS the profile is computed in (metres for lon/lat input): it gives the range floor, reliability, which needs a fitted model, is NA, and cp takes its noise variance from the finest level whose cells hold at least two scored rows on average (see cp above). A sac refused because the response shows no spatial structure (either of the two rejected_reason values of estimate_sac_range() that say so; the model it attaches is a pure nugget) gives cp no nugget either, and select_resolution() then returns structured = FALSE. A units object is refused rather than read as a number in whatever unit it was written in. The string "auto", the default, is NULL on every ladder but one that obs_per_cell sets. On that ladder no variogram is estimated or read: cp and reliability are NA at every level, cp takes no noise variance from the finest level in its place, attr(, "cp_noise") is a list whose source is "none" and whose reason says why, and the variogram and sac attributes are NULL. The other columns do not read the variogram and are the numbers sac = NULL gives. sac = NULL estimates the variogram on a ladder of sizes too, and gives cp and reliability there.

select_on

"all" (default) profiles every point; "split" reads the response on one spatially blocked half only (the OLS fit, the variogram, rss, cp and moran_z) and returns the other half as the set to estimate on, in the "split" attribute. The cells, wss, elbow, and the extent and point counts behind the bounds, cp's variance term and reliability still come from every point, because the tessellation the count is for is built on every point: the levels are cell counts for the whole layer, and the estimation half's response never touches them. See the "Post-selection inference" section of determine_optimal_levels; the profile reads the response whenever response_var is given.

range_floor

FALSE (default) starts the ladder at 2 whatever the range, and the range floor is reported in the bounds and the print without being applied. TRUE starts the ladder at the floor when the data support it and the floor is below the ceiling; an estimated range then sets the fewest cells any criterion can choose (see "The ladder and its bounds").

partition

What the centres of the cells minimise, at every level of the ladder. "density" (default): the sum of squared distances from the points to their nearest centre, each point weighted by its local density to the power density_power; compact cells that, at the default power, hold about the same number of points each once there are more cells than dense places, and counts about as uneven as "kmeans" gives below that. "kmeans": the same sum unweighted; compact cells whose counts are several times higher in dense places than in sparse ones, from 25 starts under nstart = NULL. See "The partition".

init

How each start is drawn. "kmeans++" (default): the centres one at a time, each in proportion to its squared distance from those already drawn, times its weight under partition = "density". "random": k distinct locations at random, as kmeans() draws them.

density_power

For partition = "density": the power the local density is raised to for a point's weight, a number from 0 to 2. Default 1, which evens out the cell counts once the cells outnumber the dense places (see "The partition"). 0 weights every point alike, the objective of "kmeans" (reached by Lloyd's iteration, so the centres are close to that kind's and not equal to them); values between give counts between the two; values above 1 give the cells of dense places fewer points than those of sparse places. Setting it under partition = "kmeans", which does not read it, is a warning.

density_k

For partition = "density": the number of nearest neighbours the local density is read from. Default 8. It is held to one fewer than the distinct locations. A small number follows the density closely and noisily; a large one smooths it. Setting it under partition = "kmeans" is a warning.

iter_max

The most iterations a start runs for: a single positive whole number, or NULL (default) for the kind's own limit, 50 for partition = "kmeans" from k-means++ starts and 100 for random starts and for partition = "density". A kept start that was cut off at the limit is a warning of class "spatialkit_not_converged", except for the kind "kmeans" from k-means++ starts under iter_max = NULL, which reports nothing.

estimate

The cell value the profile scores, which is the one summarize_by_cell() is to report: "auto" (default; see below), NULL for none, "mean" for the plain mean of a cell's rows, "pooled" for the mean pulled toward the mean of the 8 nearest cells. With an estimate the profile gains five columns and attr(, "estimate") (see "Value"), and every column and attribute it has without one is unchanged. loo is the leave-one-out mean squared error of that estimate: each row predicted by the value of its cell computed without it. Under "mean" a row in a cell of two or more is predicted by the mean of the others, and a row alone in its cell by the mean of the cell of its nearest other row. Under "pooled" the cell's mean and its own weight are computed again without the row, and the spread inside the cells, the spread between a cell and its target, and the targets are held. It is computed on every row of the layer with a finite response (of the selection half under select_on = "split"), not on the subsample the centres were fitted to, and each row is scored in the cell of its nearest centre, the cell get_voronoi_seeds() hands on. It needs no variogram. Rows at one location are left out one at a time. "auto" is "pooled" when there is a numeric response_var with a finite value and no predictor_vars, and NULL otherwise. NULL scores none and gives the profile without the five columns. "mean" and "pooled" are errors without a response_var, with predictor_vars (the profile would then score residuals, and the summary reports cell values of the response), with a logical response, and with a response that has no finite value. Under select_on = "split" a selection half with no finite response is not an error: the five columns are NA at every level, with a warning of class spatialkit_no_scored_rows.

obs_per_cell

Rows per cell: "auto" (default; see below); NULL for the ladder described under "The ladder and its bounds", whatever the other arguments are; or one number or several, each at least 1 (fractions are allowed), for a ladder of sizes. The level of a size s is max(2, round(n / s)) cells, with n the rows that have a response (and, with predictor_vars, every predictor), or every point when there is no response_var or no row has a response. Under select_on = "split" n counts the rows of both halves, since the cells are built on every point. On a ladder of sizes the centres are fitted to every row, no subsample is drawn, and n_levels, min_cell_n, sample_n and range_floor are not read: supplying n_levels, min_cell_n, sample_n or range_floor = TRUE beside a numeric obs_per_cell is a warning of class spatialkit_ladder_unused, and levels beside it is an error. A level is held to the most centres k-means can place (the distinct locations, and one short of the points). "auto" is NULL when levels is given or the caller supplies any of those four arguments; otherwise 4.5 when the estimate is "pooled", the seven sizes 18, 12, 9, 6, 4.5, 3 and 2 when it is "mean", and NULL without an estimate. The cost of a ladder of sizes is bounded before any fit (see "Conditions").

x

A resolution_profile, for print().

digits

For print(): significant digits for the table. Default 3.

...

Ignored.

Details

Called with a numeric response, no predictors and none of levels, n_levels, min_cell_n, sample_n or range_floor, the profile is one level: the count that gives 4.5 rows per cell (obs_per_cell = "auto"), scored for pooled values (estimate = "auto") by the leave-one-out error loo, with no variogram fitted (sac = "auto"), in cells of the density kind (partition = "density") kept from 3 k-means++ starts (nstart = NULL). cp and reliability need the variogram and elbow needs a curve, so the three are NA there; moran_z is computed. select_resolution() reads the count off it by the size.

Any of those five ladder arguments, obs_per_cell = NULL, or a call with no estimate (no response, predictor_vars, or a logical or wholly missing response) gives a ladder of counts (see "The ladder and its bounds"). At every level the profile then scores the within-cluster sum of squares of the coordinates and its elbow, Mallows' C_p of the piecewise-constant approximation of the response by cell means, Moran's z of the cell means and their reliability, and, with an estimate, the leave-one-out error of the cell value. Mallows (1973) presents C_p itself as a display of the bias-variance trade-off across candidates, and the profile is that display, with the other criteria alongside.

print() gives a header that states the ladder and its bounds, the variogram (or why none was fitted), what was scored and on how many starts, what one cell for the whole layer scores, the estimate, whether the WSS curve has an elbow and, under select_on = "split", the rows of each half; then the table, one row per level, at digits significant digits.

Value

A data.frame of class resolution_profile, one row per level. Columns a missing input leaves undefined are NA.

levels

The number of cells.

wss

The within-cell sum of squares of the coordinates, every point counted once, under either partition.

wss_spread

The relative spread of WSS across the restarts; under partition = "density", of the weighted sum the starts minimise.

elbow

The sag of the WSS curve below a power law (see "The criteria").

cell_n_min, cell_n_median

The fewest and the median points per cell.

cell_diam_median

Twice the median RMS radius of the cells, in coordinate units: about 0.8 of the side of a square cell of the same area, and less for finer cells, so a size to compare levels by rather than a width.

rss, cp

The residual sum of squares of the scored rows about their cell means, and Mallows' C_p.

moran_i, moran_z

Moran's I of the cell means and its standardised deviate.

reliability

The between-cell signal's share of the spread in the cell means.

cells_resp

The cells that hold at least one scored row.

cell_resp_mean

The scored rows per such cell; compare it with min_cell_n.

Like the other columns read off the fitted cells, cells_resp and cell_resp_mean count rows of the subsample when the layer is larger than sample_n: the cells of the layer then hold about n_response / n_scored times as many scored rows as cell_resp_mean shows (under select_on = "split", split$n_response / n_scored: both count the rows of the selection half).

With an estimate the frame has five more columns, after cell_resp_mean:

scored_per_cell

The rows loo read over the cells that hold one; the layer's counterpart of cell_resp_mean, which counts the subsample's rows.

loo

The leave-one-out mean squared error of the estimate; lower is better.

loo_se

The standard error over rows of that level's mean squared error. It is not the standard error of a difference between two levels, whose errors come from the same rows.

share_alone

The share of the scored rows that are the only scored row of their cell.

own_weight

The median over cells of the weight a pooled value gives the cell's own mean; NA under "mean".

loo, loo_se and own_weight are NA at a level where no cell holds two scored rows, at every level when the response is constant over the rows loo reads, and at every level when those rows' values lie beyond what the arithmetic of the estimate holds (spatialkit_pool_unavailable). All five are NA at every level when no row of the selection half has a response (select_on = "split"; spatialkit_no_scored_rows).

Attributes:

bounds

A list: floor, ceiling, ceiling_from ("min_cell_n", "min_cell_n (rows with a response)", "distinct locations", "sample_n", "fewer than two supported cells" or "fewer than two distinct locations", whichever bound it), supported, area, range, n (the points in the layer), n_sample (the points the k-means fits ran on), n_distinct, min_cell_n, range_floor (the argument), n_response (the rows of the layer that carry a response and, with predictor_vars, every predictor, which the support ceiling counts; NA without a response_var), n_scored (the rows of the subsample the response criteria read; NA without a response_var), levels_given (whether levels set the ladder), predictors (whether predictor_vars were given) and, where rows have a response and none of them every predictor, n_response_only (the rows with a finite response), and, where the range floor lies above the ceiling, floor_applied (FALSE: the floor is above every level and is not applied, whatever range_floor is). On a ladder that obs_per_cell sets, bounds describes that ladder: ceiling is the finest level; ceiling_from is "obs_per_cell", "distinct locations", "fewer than two cells of the size" or "fewer than two distinct locations"; supported is FALSE when the finest size gives fewer than two cells or the range floor is above the finest level; levels_given is TRUE; n_sample is every point; min_cell_n holds the argument, which is not read; and two fields are added, obs_per_cell (the sizes, largest first) and size_levels (the level of each, named by size; NA for a size of "auto" that gives fewer than two cells and was left out).

variogram

A list with nugget, psill, range (NA when rejected), model and detrended (whether the sac says it is a variogram of residuals; NA when it does not say); NULL when none was usable.

variable

"response", "residuals" or NA.

wss_bumps, nstart

The number of rising steps on the WSS curve, and the starts run per level.

sac

The range object used.

split

With select_on = "split": a spatialkit_split with selection and estimation (integer row positions in data_sf), the method and seed that made them, and with a response n_response, the rows of the selection half with a finite response and every predictor, counted on the layer before any subsample.

cp_noise

A list with source ("variogram nugget", "finest-level residual mean square" or "short-lag semivariance"), value (the \tau^2 used) and level (the level it was read at, or NA). Under the short-lag semivariance it also has cap, that semivariance, and uncapped, a list of the source, value and level it held. When the finest level whose cells hold two scored rows on average has a residual mean square of 0 to within rounding, source and value are NA, and the list has level (that level), rows_per_cell (its scored rows a cell), rms (its residual mean square: 0, or the rounding it was read as) and reason, which select_resolution() gives. On a ladder of sizes under sac = "auto" it is a list whose source is "none" and whose reason says why. NULL when cp has no noise variance for another reason; see cp under "The criteria".

one_cell

What one cell for the whole layer scores, the reference a level has to beat: a list with n (the scored rows), rss (their total sum of squares), cp (the same formula at one cell, or NA when cp has no noise variance), constant (whether the scored variable is constant to within rounding), cp_levels (the cp column it belongs to) and f_p (named by level, the p-value of the F test of that level's cell means against one mean, (TSS - RSS) / (L - 1) over RSS / (m - L) on the L cells that hold a scored row and the m scored rows). NULL without a response.

centres, centres_crs, hull

A list named by level of the two-column matrices of the scored partitions' centres, the CRS they are in, and the convex hull of the points profiled (an sfc in that CRS). A k-means partition is the Voronoi partition of its centres, so these seed the cells each level was scored on: select_resolution() returns the chosen level's as $seeds, and get_voronoi_seeds() and voronoi_seeds_kmeans() use them when given the selection or the profile. The centres carry the hull as their "cover" attribute, which those two functions hand on so that Voronoi cells built on the seeds reach the edge of the points.

refit_rows

When the centres were fitted to a subsample and the profile has no estimate: a list with xy, the coordinates of every point in the CRS of the centres, and iter_max, the iteration limit of the fits, from which select_resolution() refits the level it chooses to every point. The seeds are then the chosen level's centres refitted to every point, whose cells are not the cells scored (see select_resolution, "Value").

partition

On a profile built with partition = "density" or init = "random": a list with kind, init, density_power and density_k (both NA for kind = "kmeans"); for kind = "density", objective, the weighted sum the centres minimise, named by level; iter_max, the iteration limit; and iter and converged, the iterations each level's kept start took and whether it stopped before the limit, named by level. The selection carries the first four as $partition, its seeds and the seeds the seeding functions return as attr(, "partition"), and a Voronoi tessellation built on them as params$partition. A profile of the kind "kmeans" from k-means++ starts has no such attribute, and neither has anything made from it.

estimate

With an estimate: a list with value ("mean" or "pooled"), neighbours (8, or NA under "mean"), response (the column), n (the rows loo read), rows ("all" or "selection half"), features ("points", or "other" when the layer held features that were reduced to points), seed, constant, loo_one_cell and loo_one_cell_se (the same error with one mean for all those rows, the reference a level has to beat; NA for a constant response, for fewer than two rows and for values beyond the arithmetic of the estimate), loo_levels (the loo column those references belong to, named by level), and, named by level, sigma2 (the spread of the rows about their cell's mean), tau2 (the mean squared distance between a cell's level and its target; NA under "mean"), cells (the cells that hold a scored row) and f_p (the p-value of the F test of those cells' means against one mean). constant says whether the response is constant over those rows by the estimate's test, which reads the raw values and the values centred on their median and scaled, so that 1e15 plus a spread of 1 is not constant while values that differ only by their rounding, 0.1 beside 0.3 / 3, are; it is FALSE for fewer than two rows. one_cell$constant, the test for cp, reads the scored rows of the subsample the same way, and residuals against the rounding of the regression and of the response.

The partition

The cells at every level are the Voronoi cells of a set of centres: a point belongs to the centre nearest to it. partition says what the centres minimise, and every level of the ladder is built with the same kind.

"kmeans"

The sum, over the points, of the squared distance to the nearest centre. The centres follow the square root of the point density. The cells are compact, smaller where the points are dense and larger where they are sparse, and a cell in a dense place holds several times the points of a cell in a sparse place.

"density" (default)

The same sum with each point weighted by its local density to the power density_power. The local density at a point is the number of points in the disc that reaches its density_k-th nearest neighbour, over the area of that disc. With density_power = 1 the centres follow the point density itself. The cells are compact: many small ones where the points are dense, a few large ones where they are sparse. They hold about the same number of points each once there are more cells than dense places (clusters of points). With fewer cells than dense places a cell takes in whole clusters, large and small, and the counts are about as uneven as under "kmeans". density_power = 0 weights every point alike, which is the objective of "kmeans"; a power above 1 goes past equal counts and gives the cells of dense places fewer points than those of sparse places.

A ladder starts at 2 cells, so its low levels are usually below the number of dense places, and the columns cell_n_min and cell_n_median show where the two kinds part.

The density kind is the default. The default size, 4.5 rows per cell, puts the count above the number of dense places on a layer whose clusters hold more than a few observations each, so the default kind and the default count go together. A coarse ladder the caller sets (with levels, large sizes, or the low levels of the automatic ladder) may not, and at those levels the density kind does not even the counts. partition = "kmeans" gives plain k-means cells, from 25 k-means++ starts unless nstart says otherwise.

init says how each of the nstart starts is drawn before it is refined; the best start is kept. "kmeans++" draws the centres one at a time, each a point taken in proportion to its squared distance from the centres already drawn (times its weight, under "density"), which spreads the start over the points. "random" draws k distinct locations at random, as kmeans() does.

A start of the kind "kmeans" is refined by kmeans() (Hartigan and Wong), for at most 50 iterations from a k-means++ start and 100 from a random one. A start of the kind "density" is refined by Lloyd's iteration, for at most 100 steps: each point goes to its nearest centre, each centre moves to the weighted mean of its points, and a centre left without a point stays where it is. iter_max sets another limit. The start with the lowest sum is kept (under the density kind a later start replaces an earlier one only when its sum is lower by more than one part in ten million, so of starts whose sums agree to rounding the first is kept), and a kept start that was cut off at the limit is reported (see "Conditions"): its centres are those of the last step. A large layer can need more steps than the default limit.

The density kind depends on the points alone. It works on the distinct locations in coordinate order (see below for first coordinates equal but for their last bits), so the order of the rows does not matter. Its tolerances do not depend on the unit of the coordinates: the neighbour distance is not taken below a millionth of the extent of the points (the diagonal of their bounding box), the iteration stops when no centre moves by 10^{-12} of it, and the tie rules below are fractions of the extent or of the quantities they compare. On gridded locations many points are equally near two neighbours or two centres, and the last bits of the coordinates, which move with the unit and the origin, would settle those ties. So squared distances within one part in ten million of each other count as equal, a tie between neighbours goes to the lower first coordinate and then the lower second, a tie between centres goes to the lower-numbered one (between centres a squared distance ties with the least when it is no more than the square of the least distance lengthened by a margin, plus one part in ten million of the least squared distance; the margin is one part in 1e10 of the largest coordinate of the centres, at most a millionth of the diagonal of their bounding box and at least four times the spacing of doubles at that coordinate), first coordinates within that part of the extent count as equal when the rows and the locations are put in order, and so do weights within that part of each other when the first k-means++ centre is drawn. The cells are then the same in another unit or with another origin as long as no coordinate moves by more than about a two-hundred-millionth of the distance between neighbouring locations, but for one case: the margin of the centres grows with their largest coordinate (about 0.46 mm at a UTM northing near 4,550 km, about half a micrometre once the origin lies next to data 5 km across), and the rows are given to the centres in the layer's own coordinates, so a row whose distances to two centres differ by less than the margin with one origin and by more with another goes to the lower-numbered centre with the first and to the nearer with the second. The rounding PROJ leaves when it changes the unit or the false origin, about 10^{-9} m, is below that for locations more than about a quarter of a metre apart. Coordinates rounded more coarsely can give other cells: a lattice at 250 m with its coordinates stored in feet to four decimals does. Points at one location count as that many points at it and share a cell; the neighbour distance is measured to the density_k-th nearest other location, so it is not zero where locations repeat. The neighbour searches use FNN when it is installed. The result is the same without it; the search then takes time that grows with the square of the number of points.

The kind "kmeans" meets the same ties inside kmeans(), which settles them by the last bits of the coordinates and takes no tolerance. So it is handed the coordinates centred on the middle of their bounding box, divided by its diagonal and rounded to 2^{-30} of it (about a billionth); the starts are drawn from those coordinates and ranked by their sums, and the cells it returns are read back in the layer's own coordinates, so the centres, wss and every column are in its unit. The rows are put in order as for the density kind. The cells are then the same in another unit or with another origin unless the change moves a coordinate across the middle of a rounding step, which the rounding PROJ leaves (about 10^{-9} m) does more often the smaller the extent. Distinct locations that would round to one point keep their coordinates unrounded, so they stay distinct. stats::kmeans() also settles such ties by the last bits of its own compiled arithmetic, which differ between platforms, so on a layer where ties decide cells the kind "kmeans" can return other cells on another platform from the same coordinates and seed, and with them every column read off the cells.

The columns keep their meaning under "density", because each is read off the cells and not off the way they were drawn. wss is the within-cell sum of squares of the coordinates with every point counted once, taken about each cell's mean, so wss and elbow compare between kinds; the weighted sum the centres minimise is kept in attr(, "partition")$objective, and wss_spread is its spread over the starts. cp, moran_z and the test against one cell need cells drawn without the response, which both kinds give. reliability is computed for square cells of the level's average area and count and never reads the cells, so it is the same number under either kind. The elbow is found more readily under "density" where the points cluster: once each cluster has its centres, further centres go into the clusters, the sparse ground between them keeps its sum of squares, and the curve flattens.

A profile of the density kind, or of either kind from random starts, carries attr(, "partition"), and select_resolution(), the seeding functions and build_tessellation() hand that record on with the cells (see "Value"). A result with no such record was built by plain k-means: from k-means++ starts when it comes from a profile, and from random starts when a seeding function fitted it.

The ladder and its bounds

This is the ladder of a call that sets levels, n_levels, min_cell_n, sample_n or range_floor, or passes obs_per_cell = NULL, and of a call with no estimate: one without a response, with predictor_vars, or with a logical or wholly missing response. Cells are clusters of the (projected) coordinates of the kind partition names, fitted at each level as the best of nstart k-means++ starts (see determine_optimal_levels for why) unless init says otherwise (see "The partition"). Levels are spaced logarithmically, because cell diameter scales as L^{-1/2}: a unit step wastes fits at large L and starves resolution at small. The ladder runs from 2 to a ceiling the data impose. The ceiling is floor(n / min_cell_n): cells with fewer than min_cell_n rows on average have too little support. With a response_var, n is the number of rows of the layer (not of the subsample) that are scored: those with a response and, with predictor_vars, every predictor, since the cell means the criteria read are built from those rows alone. ceiling_from is then "min_cell_n (rows with a response)" when some rows are not scored (the label is the same when it is a predictor they lack), and a warning of class spatialkit_response_ceiling gives both counts and names the bound in force. Without a response_var, or when no row has a response, n is every point. The ceiling is also held to the number of distinct locations, one cell on each, and to one short of the number of points, which stats::kmeans() needs. The count n / L is the rows per cell only when the scored rows are spread over the whole extent. Where they sit in one part of it, the cells elsewhere hold none and the occupied cells hold more than n / L, so the ceiling is lower than those cells need: cells_resp and cell_resp_mean give the cells that hold a scored row and the scored rows per such cell at each level (of the subsample, when the cells are fitted to one), and profiling the scored rows alone bounds the ladder by the area they cover.

When fewer than two cells meet min_cell_n (floor(n / min_cell_n) < 2), or the layer has one distinct location, there is no ladder: the profile scores two cells so that level is still visible (or the levels asked for, as given), supported is FALSE, ceiling_from is "fewer than two supported cells" (or "fewer than two distinct locations") and a warning of class spatialkit_not_supported names both numbers.

min_cell_n sets the ceiling of this ladder. It is a mean number of rows per cell and not a minimum: a cell of a level at the ceiling can hold fewer (cell_n_min). It is floored to a whole number, so 4.5 is read as 4. With levels it does not choose the levels scored, and it still sets bounds$ceiling, supported and the spatialkit_not_supported warning.

The range floor is ceiling(area / range^2) when an autocorrelation range is available: cells wider than the range average over more than one patch of the field. It is reported in the bounds and the print, and by default it is not applied: the ladder starts at 2. When the layer supports the floor and it lies between the ladder's ends, the floor is one of the ladder's levels all the same (so the ladder can have one more level than n_levels): select_resolution(criterion = "reliability") reads from the floor up and returns the floor itself, not the next level the spacing happened to put above it. The range is an estimate, and a response with no spatial structure can still be given one, so a ladder started at the floor can leave out the coarse counts such a response supports. range_floor = TRUE starts the ladder at the floor when the layer supports it and it lies below the ceiling. When the floor exceeds the ceiling the data cannot support a tessellation that respects their own correlation structure; that is reported as a finding (a warning of class spatialkit_not_supported, and attr(x, "bounds")$supported is FALSE) and the ladder runs from 2 to the ceiling (or the levels asked for are scored, as given), so the profile still shows what each level costs. A floor equal to the ceiling would leave one level and nothing to compare it with, so that ladder starts at 2 as well. On a layer larger than sample_n the ceiling is also held to half the subsample's scored rows (two per cell, the least a fitted cell can be scored on; half the subsample without a response); ceiling_from is then "sample_n", a floor above that raises a warning of class spatialkit_floor_above_ceiling with a request to raise sample_n, and it does not make supported FALSE.

The floor moves with the range estimate, and the ceiling with n. To compare profiles of similar data (the folds of a cross-validation, say), pass the same levels to each. reliability is the one criterion that still reads the floor: select_resolution() holds it to the levels at or above the floor by default, so its pick can differ widely between two such profiles when the floor is supported on one and not on the other; pass range_floor = FALSE there to read the whole ladder.

A ladder that obs_per_cell sets is a ladder of sizes (see "Observations per cell"). It has one level per size s, max(2, round(n / s)) cells, held to the most centres k-means can place: the distinct locations, and one short of the points. Its centres are fitted to every row. No subsample is drawn, and n_levels, min_cell_n, sample_n and range_floor are not read. The finest size takes the part min_cell_n has on the ladder above: bounds$ceiling is the finest level, and supported is FALSE when the finest size gives fewer than two cells or the range floor is above the finest level. The range floor is reported and not applied.

A ladder of sizes under sac = "auto" fits no variogram, so cp and reliability are NA at every level there, and attr(, "cp_noise") says why. sac = NULL, or a sac of the caller's own, gives them. sac = "auto" and obs_per_cell = "auto" are the defaults, so the default profile has neither column.

Observations per cell

obs_per_cell sets the ladder by a size: the mean number of rows a cell is to hold. The level of a size s is max(2, round(n / s)) cells, with n the rows the size divides (see the argument). A size says how many observations a cell value is to stand on, and that is the caller's choice: no criterion makes it. Under a size neither the cells, which are fitted to the coordinates, nor their number, which is a count of rows, depend on the values of the response. Under select_resolution(criterion = "loo") the count does.

For pooled values the leave-one-out error tends to keep falling as the cells shrink, so its minimum tends to be the finest size offered, and the end of the ladder would then choose the count (see "How this was checked"). select_resolution(criterion = "size") therefore sets the count of pooled values from a size, 4.5 unless another is given, and criterion = "loo" reads the lowest error for plain means.

Two columns say what a size leaves a cell value to stand on. share_alone is the share of the scored rows that are the only scored row of their cell: the plain mean of such a cell is one observation, and its pooled value has the smallest own weight a cell can have. own_weight is the median weight a pooled value gives the cell's own mean: at 1 the pooled values are the plain means, and at 0 each is the mean of the cell's neighbours.

obs_per_cell = "auto", the default, is resolved against the other ladder arguments, in this order. Whether the caller supplied an argument is what counts, so a value a wrapper passes on counts as supplied.

  1. With levels, "auto" is NULL: the levels are scored as given. A numeric obs_per_cell beside levels is an error, since each sets the ladder.

  2. With n_levels, min_cell_n, sample_n or range_floor supplied, "auto" is NULL: those arguments describe the ladder of "The ladder and its bounds", and the caller gets it, with the estimate's columns when there is an estimate.

  3. Otherwise "auto" is 4.5 when the estimate is "pooled", the seven sizes 18, 12, 9, 6, 4.5, 3 and 2 when it is "mean", and NULL without an estimate.

  4. A numeric obs_per_cell beside n_levels, min_cell_n, sample_n or range_floor = TRUE sets the ladder, with a warning of class spatialkit_ladder_unused that names the arguments that are not read.

On a ladder of sizes the centres are fitted to every row and the count of cells grows with the rows, so a step that compares every point with every centre grows with the square of the rows. partition = "kmeans" has such a step in every pass and in a k-means++ start. partition = "density" has it in a k-means++ start and, without FNN, in every pass; with FNN and init = "random" it has none. The profile stops before any fit, with an error of class spatialkit_work_limit, when the points times the cells of the finest level times nstart (times iter_max for the density kind without FNN) is above getOption("spatialkit.fit_work_max", 1e10). The message names the ways on: fewer starts, which keep the best of fewer; a coarser size; partition = "density" with init = "random", which leaves a cell without a point more often (see spatialkit_empty_cells under "Conditions") and, where FNN could not be loaded, needs it reinstalled first; or a higher limit. The work and the limit are written in full, so that a work just above the limit does not print as the limit. The limit counts the finest level, and a ladder of several sizes fits every one of its levels. At the default size the work grows with the square of the rows, and a call just below the limit runs for a long time and prints nothing while it runs. spatialkit-options describes both limits.

Without FNN the density kind also finds its weights by comparing every pair of distinct locations. A profile on a ladder of sizes stops, with the same class, when the square of their number is above getOption("spatialkit.exact_pairs_max", 2e9), which is about 44,700 locations. The result of every search is the same with and without the package. moran_i and moran_z need FNN and Matrix at a level where more than 5,000 cells hold a scored row. Without them a ladder of sizes has NA in both columns there, with a warning of class spatialkit_moran_skipped, and so does a ladder set any other way (see "Conditions"). At a level of up to 5,000 such cells, when either package is missing, the neighbour weights of the cell means are held as a dense matrix of cells by cells.

The criteria

select_resolution() reads cp by default on a profile without an estimate; on one with an estimate it reads the size (pooled values) or loo (plain means). reliability needs a variogram range and is NA without one; elbow is NA unless the points cluster; and moran_z is a diagnostic of the cell means, which no function reads as a count rule by default. With an estimate the profile has a fifth column, loo, which is the last entry. Each entry below says what the column measures and what it returns.

elbow

How far the WSS curve sags below a power law: on log-log axes, \log WSS below the straight line from k = 1 (the total sum of squares) to the last level, in natural-log units (larger is better). Points with no cluster structure have a WSS close to c/k, which is straight on those axes, so the column is NA at every level unless the largest sag reaches \log 1.25, and the print says there is no elbow (the rule is given in determine_optimal_levels). The classical chord on linear axes found a "knee" on such a layer anyway, at about \sqrt{L_{first} L_{last}}, where the ladder's ends put it. A level whose WSS is 0 (to within 10^{-12} of the total), one cell on every distinct location, which the ladder reaches when locations repeat, is left out of the line; when the other levels have no elbow, that fall to zero is the elbow, and its sag is measured with the WSS floored at 10^{-12} of the total, which puts it far above any other level's. Geometry only; it knows nothing of the response. It is NA unless the points cluster, and where they do it names the number of clusters, which is usually the first level or two of the ladder.

cp

Mallows' C_p of the piecewise-constant approximation of the response (or of its OLS residuals on predictor_vars) by cell means: RSS(L)/n + 2 \tau^2 L / n, with \tau^2 the nugget of the fitted variogram (lower is better). It estimates the error of re-measuring the sampled sites: each scored row observed again at its own location, with fresh noise of variance \tau^2, and predicted by the mean of its cell. For an observation at a new location the penalty needs the spread of the field inside a cell as well, which the nugget leaves out. This \tau^2 is the nugget, the noise of one measurement; it is not the tau2 of a pooled value, which is the mean squared distance between a cell's level and its target. When the cells are fitted to a subsample of m of the N points with a response, the penalty is split between the two: RSS(L)/m + \tau^2 L_m / m + \tau^2 L / N, where the first two terms estimate the approximation error from the subsample (adding back the optimism of its own cell means, over the L_m cells its scored points fall in) and the last is the variance of cell means built from all N, which is what the tessellation will carry. With no subsample it is the formula above. On a smooth field with little noise the approximation keeps improving as cells shrink and the penalty is too small to stop it, so the minimum of C_p is the support ceiling and min_cell_n is what is choosing; select_resolution() says so when that happens. C_p has an interior minimum when the nugget is a large share of the sill. A nugget of 0, or of at most 10^{-4} of the sill, which estimate_sac_range() marks as nugget_at_bound, is the fit's lower bound and not an estimate, and as \tau^2 it would leave no penalty, so that C_p would descend to the ceiling whatever the field: C_p does not take it. When the variogram gives no nugget (none was fitted, its nugget is at that bound, its fit has no minimum inside the ranges searched, its range is below the shortest lag, it found no spatial structure, or sac is a range alone), \tau^2 is Mallows' own choice instead: the residual mean square RSS / (m - L_m) of the finest level whose cells hold at least two scored rows on average. It counts the structure within those cells as noise too, so on average it is no smaller than the nugget and errs towards fewer cells. When no level's cells hold that many, or the finest that does has a residual mean square of 0 to within the rounding of the values scored (as when each of its cells holds one location whose rows carry one value), cp is NA at every level, as it is for a constant response, which the profile warns about. Whatever its source, \tau^2 is held to the semivariance of nearest-neighbour pairs the variogram carries (attr(sac, "short_lag_semivariance"), see sac_nugget): a semivariance does not fall as the lag shrinks, so it bounds the nugget from above, and a larger \tau^2 is contradicted by the closest pairs and stops C_p early. A semivariance of 0 holds nothing. When \tau^2 is not the nugget as it stands, a warning of class spatialkit_cp_noise says where it came from, and attr(, "cp_noise") records the source and, when the semivariance held it, the number it replaced. Its minimum is often a bound, the support ceiling when the nugget is a small share of the sill, and select_resolution() then names the bound in edge. The same formula at one cell, with the total sum of squares as its RSS, is kept in attr(, "one_cell"), with the p-value at every level of the F test of that level's cell means against one mean. A level has to beat one cell: select_resolution() returns structured = FALSE when C_p at one cell is within tol of the optimum, or when the cell means at the optimum differ from one mean by no more than chance allows, because one mean for the whole layer then predicts as well as the cells and the count is not identified (see select_resolution for the rule).

moran_z

A diagnostic of the cell means: the standardised deviate of Moran's I on the cell means, or with predictor_vars on the residuals of the cell means regressed on the cell-mean predictors, over the 8 nearest neighbours of each cell. It tests whether neighbouring cell means are independent. It does not measure what the cells leave unexplained, and it does not say how well they represent the response. On any autocorrelated response it grows as the cells get finer than the range, because neighbouring cells then resemble each other, and it has almost no power below about 20 cells, where the 8-neighbour graph between cells is close to complete and Moran's I sits near -1/(L - 1) whatever the data. The level with the smallest |z| is therefore among the coarsest it is computed at on a structured response, whatever the layer and its ceiling, and arbitrary on a response with no structure, where z is calibrated and flat in L. select_resolution() refuses to read it as a criterion unless asked with diagnostic = TRUE, and neither summary() nor the functions that take a profile as a cell count read it by default. NA at nine cells or fewer.

reliability

The between-cell signal's share of the spread in the cell means, from the fitted variogram alone via Krige's additivity relation (Cressie 1996), for square cells of the level's average area holding the level's average share of the layer's points with a response (larger is better). This is the shrinkage factor of Fay and Herriot (1979). The curve has an interior optimum, a broad one, which can lie below the range floor. select_resolution() reads it at the levels at or above the floor (its range_floor argument), and what it returns is then often the floor, which is a level of every ladder the profile builds: the coarsest count the range allows, with the range choosing rather than the curve. Report the flat region with the count. The domain term is taken over the convex hull the area is measured on, so rotating the layer does not move it. NA without a usable variogram, and when the variogram's range was rejected (see sac).

loo

With an estimate: the leave-one-out mean squared error of that cell value (lower is better). It estimates the squared error of predicting one further observation, at a location drawn the way the data's locations were, by the value of the cell it falls in. That error depends on the cell value, so the column is computed for the estimate the profile is given and for no other. Each scored row of the layer is predicted by the value of its cell computed without it, in the cell of its nearest centre, which is the cell the seeds will build. Under "mean" a row in a cell of two or more is predicted by the mean of the others, and a row alone in its cell by the mean of the cell of its nearest other scored row. Under "pooled" the cell's mean and its own weight are computed again without the row; the spread inside the cells, the spread between a cell and its target and the targets are held; and a cell left empty takes its target. It needs no variogram. It describes locations among the observations and says nothing of a location away from them: it is a criterion for comparing levels where data are near, not an estimate of the error of a map. loo_se is the standard error, over rows, of that level's mean squared error. It is not the standard error of a difference between two levels, whose errors come from the same rows. scored_per_cell counts the rows loo read, every scored row of the layer, over the cells that hold one; cell_resp_mean counts the rows the other response criteria read, which are the subsample's when the cells are fitted to one. For pooled values its minimum tends to be the finest size offered (see "How this was checked"), so a size sets the count, and select_resolution(criterion = "size") reads it.

cp and reliability answer different questions: how well the cells represent the field, and whether the cell values are distinguishable from noise. They can disagree, and the profile shows both.

Conditions

What changes the meaning of a result is raised as an R warning with a class, so tryCatch(), withCallingHandlers() and options(warn = 2) see it without matching message text; the rest is logged (see spatialkit_quiet). These are the classes this function raises; spatialkit-conditions lists every class the package raises.

spatialkit_not_supported

supported is FALSE, because the range floor exceeds the ceiling or because fewer than two cells meet min_cell_n.

spatialkit_floor_above_ceiling

The range floor lies above the ceiling that sample_n sets on a layer that supports it, so the floor is above every level and is not applied; supported stays TRUE. The condition carries reason ("sample_n"), floor, ceiling, n and n_sample. Raise sample_n.

spatialkit_response_ceiling

Rows that are not scored (no response, or with predictor_vars a predictor missing) lowered the ceiling. The message names the bound in force, min_cell_n or, on a subsample, sample_n; the condition carries n, n_response, ceiling, ceiling_from, n_sample and n_scored.

spatialkit_constant_response

The scored variable is constant to within rounding (a response the predictors fit exactly leaves such residuals), so cp, moran_i and moran_z are NA at every level. On a profile with an estimate whose rows are constant too, so are loo and loo_se, and for pooled values own_weight; the message names them. summary() of such a profile stops with an error that says the response is constant. Both tests read the raw values and, where those show no spread, the values centred on their median and scaled, so 1e15 plus a spread of 1 is not constant while values that differ only by their rounding (0.1 beside 0.3 / 3) are; residuals are read against the rounding of the regression and of the response, and where the residuals of the raw values show no spread, they are those of a fit to the response less its median. The test for cp reads the scored rows of the subsample and the estimate's every row of the layer (of its selection half under select_on = "split") with a value: where the first finds the response constant and the second does not, the message says that loo is scored, and the print does not call the response a constant.

spatialkit_empty_cells

Under partition = "density": a centre holds no point, so there are fewer occupied cells than the count. A centre that loses its points stays where it is, and the start that is kept is the one with the lowest sum, whether or not all its centres hold points. It happens at high counts, mostly from init = "random". The condition carries level, the count, and empty.

spatialkit_not_converged

The start that was kept was cut off at the iteration limit, so its centres are those of the last step and a longer run can still move points between cells. Not raised for the kind "kmeans" from k-means++ starts under iter_max = NULL. The condition carries level (every level it happened at), iter and iter_max. Raise iter_max.

spatialkit_ladder_unused

A numeric obs_per_cell sets the ladder, and the caller also supplied n_levels, min_cell_n, sample_n or range_floor = TRUE, which are then not read. The condition carries unused (the argument names) and obs_per_cell.

spatialkit_size_not_reached

On a ladder of sizes: a size does not give the count it asks for. Either a size given as a number gives fewer than two cells while a finer one does not, and its level is 2 (reason is "fewer than two cells"); or a size asks for more cells than k-means can place, and its level is the most that can (reason is "more cells than can be placed"). It is raised once for each reason, naming every size held for it. The condition carries obs_per_cell and wanted (one element for each such size, in the order of the ladder), used and reason. When the finest size gives fewer than two cells the warning is spatialkit_not_supported, with obs_per_cell among its fields and min_cell_n NA; and spatialkit_response_ceiling is not raised on such a ladder, since a size already counts the rows with a response.

spatialkit_repeated_locations

With an estimate: scored rows share a location. Each row is left out alone and the others at its location stay, so loo then describes a further observation at a place already observed. Raised once, after the levels are scored, and not when loo is NA at every level. The condition carries n (the rows that share a location), total (the rows loo read) and column.

spatialkit_no_scored_rows

Under select_on = "split": no row of the selection half has a response, and the rows of the layer with one are all in the estimation half. rss, cp, moran_i and moran_z, which read the selection half, are NA at every level. With an estimate, whose check that it has rows to read is made on the layer, loo and the estimate's other columns read no row and are NA at every level too. With predictor_vars a row counts when it has a response and every predictor. Not raised when no row of the layer has a response. Raised once, after the levels are scored. The condition carries reason ("no response in the selection half"), n (0, the rows of the selection half scored), selection (the rows of the selection half), n_response (the rows of the layer with a response) and column. Raised too, with or without the split, when rows of the layer have a response and none of them every predictor: then reason is "no row with a response and every predictor", n_response the rows with a finite response, and selection NA without the split.

spatialkit_pool_unavailable

With an estimate: the values of the response lie beyond what the arithmetic of the estimate holds, values so large, or so close to their median, that the squares of many such values can overflow or lose their precision, so loo, loo_se and own_weight are NA at every level. Where the test for cp finds such a response constant, cp, moran_i and moran_z are NA for the same reason, and this message names them in place of spatialkit_constant_response. The message gives the bounds; the response rescaled by a power of ten is scored. Raised once, after the levels are scored. The condition carries reason ("values out of range") and columns, the response, as summarize_by_cell(estimate = "pooled") raises the class for its pooled columns.

spatialkit_moran_skipped

With a level of more than 5,000 cells, on any ladder, when FNN cannot be loaded or Matrix is not installed: moran_i and moran_z are NA at a level where more than 5,000 cells hold a scored row, and every other column is computed. Raised once, before the first fit, when such a level can occur: the cells that hold a scored row are counted after a level's fit, so where rows without a response leave fewer of them the two columns are computed after all. The condition carries limit, levels (the levels above the limit) and missing.

spatialkit_variogram_unusable

The variogram, the one estimated or sac, gives no usable range (rejected_reason of estimate_sac_range()), so reliability is NA, and the message says whether cp may still take its nugget. The condition carries reason, converged (whether the variogram model converged; NA when it does not say), nugget and nugget_used.

spatialkit_cp_noise

cp does not take the variogram's nugget as it stands. Its noise variance is the residual mean square of the finest level (the variogram gives no nugget, or its nugget is at the fit's lower bound), or the semivariance of nearest-neighbour pairs, which holds the nugget or that residual mean square where they are larger; or there is none and cp is NA at every level: the finest level whose cells hold two scored rows on average has a residual mean square of 0 to within rounding, or, with the nugget at its bound, no level's cells hold that many. The condition carries source, value and level (as attr(, "cp_noise") holds them; with no noise variance source and value are NA, and level is the level whose residual mean square is 0 to within rounding, or NA), cap (the semivariance, NA when the variogram carries none), uncapped_source and uncapped_value (what cp would take without the hold, and with no noise variance what it refused: the nugget at its bound, or that residual mean square).

The other warnings of this function (points dropped, a variogram of another variable) are R warnings without a class; rows left out for a missing response, a rising WSS curve and a subsample too small to reach the floor are logged only.

One refusal is an error with a class, spatialkit_work_limit: resolution_profile() stops before a step whose count of comparisons is above a limit. The condition carries work (the count), limit and what (the step). On a ladder that obs_per_cell sets, the count of cells grows with the rows, so two costs are bounded before the variogram is estimated and before any fit. The fits: the points times the cells of the finest level times nstart may not pass getOption("spatialkit.fit_work_max", 1e10) (what = "partition fit"; the condition also carries kind, init, nstart and fnn). That product counts the step in which every point is compared with every centre, which partition = "kmeans" has in every pass and in a k-means++ start, and partition = "density" has in a k-means++ start. Without FNN the density kind compares every point with every centre in every pass, and the product is multiplied by iter_max; with FNN and init = "random" it has no such step and nothing is counted. The density kind's weights: without FNN they come from a search that compares every pair of distinct locations, and the square of their number may not pass getOption("spatialkit.exact_pairs_max", 2e9) (what = "density weights"); density_power = 0 has no weights and no such search. With an estimate and without FNN, on any ladder, the same limit bounds the three exact searches the estimate's columns make: each scored row's nearest centre, each cell's nearest cells, and, under "mean", the nearest other location of a row alone in its cell. The result of every search is the same with and without FNN.

The warnings of the pooled values and of the count record, which summarize_by_cell() raises, are listed on its page.

How this was checked

The sizes for pooled values were compared in a simulation of 200 layers, each 1,500 clustered observations of a field with covariance exp(-d / 100) plus noise on a square of side 1,000 (dev/sim-pooled-values.R in the package's GitHub repository; summarize_by_cell describes it), profiled at the sizes 18, 12, 9, 6, 4.5, 3 and 2 with partition = "density". The lowest loo of the pooled value was at the size 2 on 176 layers, at 3 on 22 and at 4.5 on 2. That of the plain mean was at 2 on none: it was at 6 on 86 layers, at 4.5 on 51, at 9 on 49, at 12 on 12, and at 18 and at 3 on one each. These figures are of those seven sizes and say nothing of another ladder.

References

Cressie, N. (1996). Change of support and the modifiable areal unit problem. Geographical Systems, 3(2–3), 159–180.

Fay, R. E. and Herriot, R. A. (1979). Estimates of income for small places: an application of James-Stein procedures to census data. Journal of the American Statistical Association, 74(366), 269–277. doi:10.1080/01621459.1979.10482505

Mallows, C. L. (1973). Some comments on C_p. Technometrics, 15(4), 661–675. doi:10.1080/00401706.1973.10489103

See Also

select_resolution() to read a level and its flat region off the profile; summary.resolution_profile() for every criterion's pick side by side; determine_optimal_levels() for a count from the coordinates alone; build_tessellation() and get_voronoi_seeds(), which accept the profile or a select_resolution() result directly as approx_n_cells and n.

Other resolution: determine_optimal_levels(), plot.resolution_profile(), select_resolution(), summary.resolution_profile()

Examples


library(sf)
# An exponential field with range parameter 200 (true effective range
# 600 m) on a 1 km square, with a nugget of 0.6 on a unit sill.
set.seed(4)
n <- 400
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 / 200) + diag(0.6, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)

# The default profile: one level at 4.5 rows per cell, scored for
# pooled values, in density-weighted cells, with no variogram.
prof1 <- resolution_profile(pts, response_var = "z")
prof1
select_resolution(prof1)   # the count the size gives

# A ladder of counts for plain means: n_levels asks for the ladder and
# estimate = NULL scores no cell value, so cp is the rule that goes
# with it.
prof <- resolution_profile(pts, response_var = "z", n_levels = 12,
                           estimate = NULL)
prof
# Three of the criteria, one row per level.
as.data.frame(prof)[, c("levels", "cp", "reliability", "moran_z")]
attr(prof, "bounds")$floor   # the range floor: reported, not applied
select_resolution(prof, criterion = "cp")


Extract the nugget of an estimated autocorrelation range

Description

The nugget variance of the variogram model behind an estimate_sac_range() result: the model's semivariance as the separation shrinks to zero, which is measurement error plus variation at scales shorter than the first lag of the empirical variogram.

Usage

sac_nugget(x)

Arguments

x

A sac_range object, or any other value.

Details

The nugget is extrapolated to zero from the first lag, not observed, so it is only as good as that lag is short; attr(x, "first_lag") says where the extrapolation starts. With lags = "adaptive" (the default) the first lag is the separation of the closest pairs of points. With lags = "equal" it is the middle of a bin cutoff * max_dist / n_lags wide, which on a dense layer can be many times the spacing of close pairs, and structure shorter than that bin is then counted as nugget. When attr(x, "lag_fallback") is TRUE the result is the equal-lag one although adaptive lags were asked for (see the section "The lags" in estimate_sac_range()), and its nugget is extrapolated from the first equal bin.

Every classed result, identified or rejected, carries the nugget as its nugget attribute, since a resolution criterion for a tessellation needs it: it is the short-lag variance that no cell can average away. On a result refused for want of spatial structure it is the variance of the modelled variable, the nugget of the pure-nugget model that the refusal supports.

Value

A single number, the nugget in the units of the response's variance, or NA_real_ when x carries no fitted model: a bare NA from a run that could not fit anything, a rejected result with too few lag bins to fit, or an object that is not a sac_range.

How far to trust it

Four more attributes of the result bear on the nugget.

See Also

estimate_sac_range(), which produces the object.

Other spatial autocorrelation: estimate_sac_range(), plot.sac_range()

Examples


library(sf)
# A field with a nugget: half a unit of white noise on a unit sill.
set.seed(3)
n <- 250
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 / 150) + diag(0.5, n))) %*% rnorm(n))
r <- estimate_sac_range(st_as_sf(xy, coords = c("x", "y"), crs = 32632), "z")
sac_nugget(r)                      # the fitted nugget, on the sill's scale
attr(r, "nugget_at_bound")         # FALSE: an estimate, not the bound
attr(r, "short_lag_semivariance")  # what the closest pairs say, no model
attr(r, "zero_lag_pairs")          # 0: no location was visited twice
sac_nugget(NA)                     # nothing fitted: NA


Select predictors by forward selection on spatial folds

Description

Selects predictors by repeatedly adding whichever candidate most improves a cross-validated score, stopping when the best candidate's improvement is no larger than the fold-to-fold noise in it (rule = "se", the default) or no larger than tol (rule = "tol"). The first variable has a baseline to beat with every learner, so the selection can be empty.

Usage

select_features_forward(
  train_sf,
  response_var,
  candidate_vars,
  fit_fn,
  k = 5,
  method = c("block_kfold", "random_kfold"),
  block_size = NULL,
  metric = c("RMSE", "MAE", "R2"),
  tol = 0,
  max_vars = NULL,
  max_fits = 5000L,
  seed = 123,
  quiet = FALSE,
  auto_range = FALSE,
  select_on = c("all", "split"),
  rule = c("se", "tol"),
  se_mult = 1,
  null_fn = NULL
)

Arguments

train_sf

Training data (sf). With select_on = "split" a feature that is not a point is reduced to one, and the layer is read in x and y (see spatialkit-geometry).

response_var

Character(1).

candidate_vars

Character vector of predictors to choose among.

fit_fn

A function (train_sf, predictor_vars) returning a spatial_fit. The signature takes two arguments because selection has to refit with different predictor sets.

k

Inner fold count. Default 5.

method

Inner fold method: "block_kfold" (default) or "random_kfold".

block_size

Minimum inner block edge, passed to make_folds(); NULL (default) for the geometric grid. Pass the outer block size so inner and outer blocks are on the same scale.

metric

Score to optimise: "RMSE", "MAE" (minimised) or "R2" (maximised). Default "RMSE".

tol

Minimum improvement of the pooled score required to accept a variable, in the units of metric. Default 0. It is a floor under both rules: with rule = "tol" it is the whole test, and with rule = "se" the per-fold test applies as well. The first variable is judged against a baseline with every learner; see "The baseline for the first variable". Any single number is accepted: Inf leaves nothing selected, and -Inf puts no floor under a step.

max_vars

Optional cap on how many predictors to select; NULL (default) for no cap.

max_fits

Abort if the sweep would exceed this many model fits. Default 5000.

seed

RNG seed, default 123. It governs both the inner fold construction and the cross-validation itself: it is forwarded to cv_spatial(seed = ), which draws one RNG stream per fold from it, so it also seeds the learner inside every fold. A stochastic fit_fn is therefore reproducible from this one value.

quiet

Logical; suppress this function's progress message()s. It does not silence R warnings, nor the package's console log echo (see spatialkit_quiet for that). Default FALSE.

auto_range

Logical. If TRUE and method is "block_kfold", the autocorrelation range is estimated from the response (detrended on the candidates) and used as the minimum block size of the inner folds, exactly as in make_folds(): a block_size given takes precedence, and the range is then only compared with it. Default FALSE, which keeps the geometric blocks. With inner blocks smaller than the range a candidate can be chosen for tracking nearby values of the response, the case the random_kfold caution above is about, so the warning make_folds() raises on blocks smaller than the range applies to the inner folds too.

select_on

"all" (default) runs the sweep on every row of train_sf. "split" runs it on one spatially blocked half, then fits the selected set on that half and scores it on the other: score_holdout is then the selected model's metric on rows whose response the sweep never read (the sweep's own score is not; see "Selection score"). It is one estimate from one half of the area: the halves share a border with no buffer, so rows near it are still correlated with the selection half. Both halves come back in $split. See the "Post-selection inference" section of determine_optimal_levels for the trade: coverage for half the sample.

rule

How a step is judged. "se" (default) accepts the best candidate when its pooled gain exceeds tol and its mean per-fold gain exceeds se_mult standard errors of that mean; "tol" accepts any pooled gain above tol. See "When a variable is accepted".

se_mult

Number of standard errors the mean per-fold gain must exceed under rule = "se". Default 1; 0 asks only that the mean per-fold gain be positive.

null_fn

Optional function (train_sf) returning a fitted model with no predictors, used as the baseline for the first variable when fit_fn cannot fit an empty predictor set. Default NULL: fit_fn(train_sf, character(0)) is tried, and the training-fold mean is used when that fails. The example builds one.

Details

To get a performance estimate for the selected model, call this function inside the fit_fn you pass to cv_spatial(). cv_spatial() calls fit_fn(train_sf) on each fold's training rows only, so a selection run inside fit_fn sees no held-out data. The cost grows fast: a sweep over p candidates costs roughly p^2 / 2 * k model fits, and nesting it inside n outer folds multiplies that by n. max_fits guards against it.

Value

A list of class "feature_selection" (so that plot.feature_selection() draws the selection path) with these elements:

selected

The chosen predictors, in the order they were added; possibly none.

score

The winning set's cross-validated metric at the final step: the optimum inside the selection, optimistically biased because it was chosen as the best of many (see "Selection score"), and NA when nothing was selected.

score_holdout

NA unless select_on = "split", and then the selected set's metric when fitted on the selection half and predicted on the estimation half (R^2 against the selection half's mean, the out-of-sample convention); NA when nothing was selected or the prediction failed.

history

A data.frame with step, variable, score, n_pred, gain, fold_gain and fold_gain_se, holding every candidate evaluated at every step, and a step = 0 row named "<none>" giving the baseline, so the first variable's gain can be read off directly. gain is the candidate set's improvement in the pooled score over the set it was added to (the baseline at step 1), fold_gain the mean of the per-fold improvements and fold_gain_se its standard error: the three numbers the rule reads. n_pred is how many rows the set's cross-validation predicted.

fold_scores

A data.frame with step, variable, fold and score: the metric of every set in every fold.

baseline

A list with type ("null model", "null_fn" or "fold mean"), score, path (the set the sweep reached), gain, fold_gain and fold_gain_se (that set against the baseline), kept (FALSE when the path did not beat a fold-mean baseline and selected is empty for that reason; NA when the path is empty) and first. first is NULL unless the baseline is the fold mean and a path of two or more variables was kept. It is then the test of the first variable, a list with:

  • variable;

  • gain, fold_gain and fold_gain_se: the path against the path without that variable;

  • rest, a list with vars, score, gain, fold_gain and fold_gain_se: the path without it, and that set against the baseline;

  • dropped: TRUE when the variable was taken out (selected is then path[-1] and score is rest$score);

  • note, the verdict in words.

The set scored for that test is not a step of the sweep, so it is not in history or fold_scores.

split

NULL, or a list with selection and estimation, integer row positions in train_sf as passed; rows the completeness filter above dropped are in neither.

params

The settings: metric, method, k, tol, seed, auto_range, select_on, n_candidates, estimated_fits, n_scored, rule, se_mult and baseline (its type).

Every set is scored on the same rows: those the null model's cross-validation predicted or, when the baseline is the fold mean, those any step-1 set predicted; params$n_scored counts them (a warning says so when that is fewer than all). A set that left some of the scored rows unpredicted, because a fold failed for it, has score NA, with a warning naming it: scored on the rows it did predict it would be compared on fewer, usually easier, rows than its rivals. A factor with a level found in one spatial block only is the usual case, and cannot be selected.

Inner and outer folds

The inner folds should hold points out as the outer ones do. A cross-validated score is the error at the distance the folds put between the held-out points and their training data, so nested selection chooses the variables that predict best at the inner folds' distance. Random inner folds inside blocked outer folds choose for predicting among the samples, where a variable that only tracks nearby values of the response can win, and the outer loop then scores the chosen set at the blocks' distance, for which it was not chosen. method therefore defaults to "block_kfold", as the folds of the cv_*() functions do, and logs a caution (not an R warning) when set to "random_kfold".

When a variable is accepted

Each candidate set is scored by cross-validation on the same inner folds, and the candidate with the best pooled score is the one considered. Under rule = "se" it is accepted when two things hold: the pooled score improves by more than tol, and the mean of the per-fold improvements (the metric computed in each fold for the set with and without the candidate, and differenced) exceeds se_mult times the standard error of that mean across the folds. This is the one-standard-error idea of Breiman et al. (1984) applied to a step: a gain the folds do not agree on is not evidence that the variable predicts. The fold is the unit because under spatially blocked folds the errors within a block are correlated, so a standard error over rows would understate the noise. Against rule = "tol", which accepts any pooled gain above tol, the rule adds fewer noise variables and costs power on weak predictors. With few folds the standard error is itself noisy, so raise k before lowering se_mult. history records each candidate's pooled gain, mean per-fold gain and its standard error, and fold_scores the per-fold scores themselves, so every decision can be checked.

The baseline for the first variable

The first variable is compared with a model that has no predictors, recorded as step 0 of history. Which model that is depends on the learner, and baseline$type says which was used:

baseline$type The baseline How the first variable is tested
"null model" fit_fn(train_sf, character(0)), when the learner can fit it at step 1, like any other step
"null_fn" the model null_fn(train_sf) returns, for a learner that cannot fit an empty set at step 1
"fold mean" the mean response of each fold's training rows, when neither is available (fit_rf_model() refuses an empty predictor set) the whole set at the end of the path, then the set without its first variable

Under a fold-mean baseline the first variable is provisional: it is added without a test, the sweep continues by the rule, and the finished set is kept only if it beats the fold mean by the same rule; otherwise nothing is selected, and baseline$path holds the set that was reached. The test is at the end of the path because a forest on a single variable can lose to the mean when two variables together beat it clearly. A kept path of two or more variables is then scored once more without its first variable (one more set, k more fits), and that variable is dropped from selected when the set is no better with it by the rule and the rest of the path still beats the fold mean by the rule. baseline$first records the test, and selected is baseline$path[-1] after a drop. When the set is no better with the first variable but the rest of the path does not beat the fold mean either, the two cannot be told apart: the set is kept whole, a caution is logged, and baseline$first$note says the variable is unproven. So in a selection of two or more variables from a learner that falls back to the fold mean, selected[1] has been shown to improve the set, not to predict on its own.

For a GWR the fold mean is a weak baseline: every GWR carries a local intercept and beats a global mean on any smooth response, whatever its predictors are. The baseline that matters is the kernel-weighted local mean at the same bandwidth, a GWR with a local intercept and no predictors, which fit_gwr_model() fits when its predictor_vars is character(0). A fit_fn that hands its variables to fit_gwr_model() therefore gets it as the null model. Give such a fit_fn a fixed bandwidth, so that every set is fitted under the kernel the baseline has; with bandwidth = NULL each set, the empty one included, searches for its own. A GWR fit_fn that refuses an empty set falls back to the fold mean, and the sweep logs a caution: read a selection of one variable made that way as unproven, or supply the local mean as null_fn, as the second half of the example does.

predict() on a GWR warns about held-out locations it cannot estimate and about those beyond the reach of a fold's fit (classes "spatialkit_gwr_not_estimable" and "spatialkit_gwr_extrapolation"; see spatial_fit-predict). The sweep raises each once, under this function's name, with the totals over the candidate sets it scored; every set is predicted on the same rows, so a location can be counted once per set.

Selection with a random forest

A forest confounds selection with tuning: a predictor that carries no signal still changes how the trees split, and with ranger's default node size that can regularise the forest and lower the cross-validated error. No acceptance rule refuses that gain, so a variable in a forest selection may be there as a tuning effect, wherever in the order it was added. Setting the node size in fit_fn reduces this without removing it, and comparing the selected set with a tuned forest on the variables you have other reasons to believe in shows how much of the gain is tuning:

fit_fn <- function(train_sf, vars)
  fit_rf_model(train_sf, "z", vars, min_node_size = 20)

Selection score

$score is the cross-validated metric of the winning set at the final step: the best of every candidate set the sweep scored. A number optimised over many candidates is optimistically biased by construction, and Cawley and Talbot (2010) show the bias can exceed the differences between the models being compared. Quote it as the selection criterion, not as the performance of the selected model. A performance estimate needs data the selection never saw. Two ways to get one: run this function inside the fit_fn of cv_spatial(), so the outer folds score a model whose predictors were chosen on the inner ones alone; or pass select_on = "split", which selects on one spatial half of train_sf and returns the selected set's score on the other as score_holdout.

References

Breiman, L., Friedman, J. H., Olshen, R. A. and Stone, C. J. (1984). Classification and Regression Trees. Wadsworth.

Cawley, G. C. and Talbot, N. L. C. (2010). On over-fitting in model selection and subsequent selection bias in performance evaluation. Journal of Machine Learning Research, 11, 2079–2107. https://jmlr.org/papers/v11/cawley10a.html

See Also

plot.feature_selection() to draw the selection path, gwr_model_selection() for a fast in-sample screen for GWR, and cv_spatial() to nest the selection in outer folds.

Other predictor selection: gwr_model_selection(), plot.feature_selection(), plot.gwr_model_selection()

Examples


library(sf)
set.seed(1)
n <- 120
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             a = rnorm(n), b = rnorm(n), noise = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
pts$resp <- 3 * pts$a + 2 * pts$b + rnorm(n, 0, 0.3)

# The learner: a GWR with an adaptive bisquare kernel reaching the 30th
# nearest training point.  With no variables it is the kernel-weighted
# local mean, which is the baseline: a GWR's local intercept beats a
# global mean on any smooth response, so the first variable has to beat
# the local mean under the same kernel.
fit_fn <- function(tr, vars) fit_gwr_model(tr, "resp", vars, bandwidth = 30)
sel <- select_features_forward(pts, "resp", c("a", "b", "noise"), fit_fn,
                               k = 3, quiet = TRUE)
sel$selected
sel$baseline$type        # "null model": step 1 was tested against it
sel$history[sel$history$step <= 1, c("step", "variable", "score", "gain")]

# A learner that cannot fit an empty set takes its no-predictor model
# through `null_fn`.  Here the same local mean, written as a spatial_fit
# of its own with a predict() method, for a learner that insists on a
# variable.  Without `null_fn` that sweep would start from the mean of
# each training fold.
needs_one <- function(tr, vars) {
  if (!length(vars)) stop("this learner needs a predictor")
  fit_gwr_model(tr, "resp", vars, bandwidth = 30)
}
local_mean <- function(tr, bandwidth = 30) {
  new_spatial_fit("local_mean_fit",
                  engine = list(xy = st_coordinates(tr), y = tr$resp,
                                bandwidth = bandwidth),
                  formula = resp ~ 1, response_var = "resp",
                  predictor_vars = character(0), data_sf = tr)
}
predict.local_mean_fit <- function(object, newdata = NULL, ...) {
  e  <- object$engine
  at <- if (is.null(newdata)) e$xy else st_coordinates(newdata)
  vapply(seq_len(nrow(at)), function(i) {
    d <- sqrt((e$xy[, 1] - at[i, 1])^2 + (e$xy[, 2] - at[i, 2])^2)
    h <- sort(d)[min(e$bandwidth, length(d))]  # the kernel's reach here
    w <- ifelse(d > h, 0, (1 - d^2 / h^2)^2)   # bisquare weights
    sum(w * e$y) / sum(w)
  }, numeric(1))
}
registerS3method("predict", "local_mean_fit", predict.local_mean_fit)
sel2 <- select_features_forward(pts, "resp", c("a", "b", "noise"), needs_one,
                                k = 3, quiet = TRUE, null_fn = local_mean)
sel2$baseline$type       # "null_fn"
all.equal(sel2$baseline$score, sel$baseline$score)  # the same baseline


Choose a cell count from a resolution profile

Description

Picks the level a criterion prefers, together with the flat region: every level whose criterion value is within tol of the optimum. Report the flat region with the count. On the default profile, one size scored for pooled values, the default criterion is that size: it returns the count the size gives, with no optimum and no flat region (see "A profile built with an estimate"); what follows is about the criteria read on a ladder of counts. When the optimum sits at an end of the levels the criterion was scored at, the result says so and names the bound, because a bound is then doing the choosing rather than the criterion (see resolution_profile for what each criterion measures and what it returns in practice). The functions that take the result as a cell count raise that as a warning of class spatialkit_bound_chosen.

Usage

select_resolution(
  profile,
  criterion = c("auto", "cp", "reliability", "elbow", "moran_z", "loo", "size"),
  tol = 0.02,
  range_floor = TRUE,
  diagnostic = FALSE,
  obs_per_cell = NULL
)

Arguments

profile

A resolution_profile.

criterion

Which rule sets the count: "cp" (minimised), "reliability" (maximised at or above the range floor), "elbow" (maximised), "loo" (the leave-one-out error of the profile's estimate, minimised), "size" (the count obs_per_cell gives), "auto" ("size" for a profile of pooled values, "loo" for one of plain means, "cp" for a profile without an estimate) or, with diagnostic = TRUE, "moran_z" (|z| minimised). Default "auto".

tol

Width of the flat region. For cp, reliability and loo it is relative to the optimum's value (0.02 keeps levels within 2 percent of it); for elbow and moran_z, whose optimum can be zero, it is relative to the criterion's range over the ladder. Under "size" there is no flat region, and tol is the margin by which the cells have to beat one mean for structured and nothing else.

range_floor

For criterion = "reliability" only. TRUE (default) reads the criterion at the levels at or above the range floor in attr(profile, "bounds"). It applies when the layer supports the floor, some scored level reaches it, and the profile built its own ladder (a ladder set with levels is read as given). A floor above every level scored (above the ceiling, say) is not held: every level is read, range_floor in the result is NA, and note says so in an element named floor. FALSE reads every level.

diagnostic

criterion = "moran_z" is refused, with an error of class spatialkit_diagnostic_criterion that says what the column measures, unless this is TRUE: moran_z is a diagnostic of the cell means, not a count rule. Default FALSE.

obs_per_cell

For criterion = "size": the mean number of rows per cell wanted, a single number of at least 1 (fractions are allowed). NULL (default) is the profile's own size when it was built at exactly one (resolution_profile(obs_per_cell = )), and 4.5 otherwise. Given with a criterion that is not "size" it is an error.

Value

A list of class resolution_selection with these elements:

best

The level.

flat

The levels in the flat region, ascending: a set, which can skip a rung.

criterion

The criterion applied, never "auto".

value

The optimum.

at_ceiling, at_floor

Whether the optimum is the last or first of the levels this criterion was read at, which for moran_z starts above nine cells and for reliability at the range floor; both NA under "size", which searches for no optimum.

edge

Which bound that is, in words: the support ceiling, the subsample's ceiling, the range floor, the ladder's own end, the finest or the coarsest size offered on a ladder obs_per_cell set, the only level scored, or the first or last level the criterion is computable at; NA for an interior optimum and under "size".

n_levels

The levels on the profile.

values

The criterion at every level, NA where it could not be computed.

structured

For cp: FALSE when cp at one cell is not above the optimum by more than tol (below it included), when the cell means at the optimum differ from one mean by no more than chance allows, or when the variogram found no spatial structure; TRUE when the optimum beats one cell on both counts (see "What each criterion returns"). For loo and size on a profile built with estimate: FALSE when the leave-one-out error of one mean for all scored rows is within tol of the error at best, or below it, or when the cell means at best differ from one mean by no more than chance allows; TRUE when the cells beat one mean on both counts. TRUE for an elbow; NA for reliability and moran_z, and for a profile that carries no one-cell value.

one_cell

cp at one cell under cp; the leave-one-out error of one mean for all scored rows under loo and size; NA otherwise.

structure_p

The p-value of the F test of the cells at best against one mean, multiplied by the number of levels searched and capped at 1 (a size searches one level); NA where structured is not read off cp or the leave-one-out error.

range_floor

The floor reliability was held to, or NA.

note

What the flags mean, in words: a character vector, one note an element; NULL when there is nothing to say. The notes written under "loo" and "size", for a profile built with estimate or with one size, and about the range floor, carry names: size (the size that set the count), held (a size the profile held to the most cells k-means can place), structure (why the count is not identified), finest (the lowest error of pooled values is at the finest level scored), estimate (cp scores plain means, on a profile of pooled values), ladder (the ladder is one size) and floor (under reliability with range_floor = TRUE: the range floor lies above every level scored, so it was not held; structured is NA there). A note of cp or moran_z about the criterion itself has no name. The warning of class spatialkit_no_structure that the functions taking the selection as a count raise carries every note but those named size, held, finest, estimate and ladder.

seeds

An sf POINT layer, with seed_id, of the centres of the partition the profile scored at best, in the CRS it was computed in; NULL for a profile that does not carry them. See "Seeds" below.

partition

For a profile built with partition = "density" or init = "random": kind, init, density_power and density_k. The seeds carry it as attr(, "partition"); the cells are those the profile built, whatever kind built them. It stays the last element.

For "loo" and "size", and for any criterion on a profile built with estimate, the list has these elements after seeds:

estimate

The profile's, "mean" or "pooled"; NA for a profile without one.

obs_per_cell

Rows per cell at best: the rows a size divides over best; NA for an object that keeps no row count.

obs_per_cell_asked

The size asked for; NA unless the criterion is "size".

scored_per_cell

The profile's column at best: the rows the leave-one-out error read over the cells that hold one. It is not obs_per_cell: it leaves out rows the error did not read and cells that hold none of them, as under select_on = "split".

loo, loo_one_cell

The leave-one-out error at best and that of one mean for all scored rows.

share_alone, own_weight

The profile's columns at best.

count_rule

A list of class spatialkit_count_rule that records how the count was set: rule (the criterion applied), estimate (the estimate the rule was computed for: the profile's for "size" and "loo", "mean" for "cp", NA otherwise), cells, obs_per_cell, obs_per_cell_asked, response, n (the rows the size divides), n_points, n_fit (the rows the centres were fitted to; fewer than n_points for a subsample), seed, features, scored (what the profile scored at best for its estimate: estimate, n, cells, loo, loo_se, loo_one_cell, share_alone, own_weight, structured, rows and centres, the matrix of the centres the rows were scored in, in crs and in the profile's order; NULL without an estimate), partition, crs and scored_cells (NA: the record stands for a count).

A "cp" selection off a profile without an estimate has count_rule as well, after seeds, and nothing else of this list: its estimate is "mean", since C_p scores plain means, and scored is NULL. Under "loo" and "size" one_cell holds the leave-one-out error of one mean and range_floor is NA.

seeds carries the same record as attr(, "count_rule") with scored_cells = TRUE, since they are the centres that were scored, or FALSE when they were refitted to every point, since they are then other cells built from the count. The record travels on with the seeds, the cells and the assigned layer to summarize_by_cell(), which warns when it reports another cell value than the count was chosen for (class spatialkit_estimate_mismatch) and when the cells or rows it is given are not the ones the count was scored on (spatialkit_cells_differ).

Seeds: the Voronoi cells of the seeds are the cells that were scored; get_voronoi_seeds(method = "kmeans", n = <this>) and voronoi_seeds_kmeans(k = <this>) return them. On a profile without an estimate whose centres were fitted to a subsample (n_sample below n in attr(profile, "bounds")) the seeds are those centres refitted to every point: the kind's own iteration (Hartigan and Wong's for "kmeans", Lloyd's on every point's density weights for "density") run from the centres scored, with the profile's iteration limit and no random draw. Where Hartigan and Wong's algorithm refuses the centres, Lloyd's iteration with every weight one runs in its place, and a log line says so. Such seeds carry attr(, "refit"): rows (the points), subsample (the points the profile fitted to), kind, iter, iter_max, converged, wss_scored (the within-cell sum of squares of every point in the cells of the centres scored, each cell about its own mean) and wss (the same of the refitted cells). Their cells are then not the cells scored, and the count is still the one the subsample gave; the centres scored are attr(profile, "centres")[[as.character(best)]]. The refit reads every point's coordinates from attr(profile, "refit_rows"); on a profile without that attribute the centres scored are the seeds, and a log line says so. The refit is not run either, and the centres scored are the seeds, when it would pass the work limits of a profile's own fits (see "Conditions" in resolution_profile); a log line says so. A profile with an estimate scores it on every row of the layer in the cells of the centres fitted to the subsample, so its seeds are those centres, whose cells are the cells scored. summary() and plot() of a profile read no seeds and refit nothing.

What each criterion returns

cp

The level that minimises Mallows' C_p: the count at which re-measuring the sampled sites, each predicted by its cell's mean, has the least estimated error (resolution_profile says what that leaves out for a new location). On a smooth response with little noise that is the support ceiling. The result also says whether the optimum beats one cell for the whole layer (attr(profile, "one_cell")), in structured. It is TRUE when two things hold: C_p at one cell is above the optimum by more than tol, and the cell means at the optimum differ from one mean by more than chance allows. The second is the F test of the cells against one mean, (TSS - RSS) / (L - 1) over RSS / (m - L), at 5 percent after a Bonferroni adjustment for the levels the optimum was searched over (structure_p is the adjusted p-value). The cells are fitted to the coordinates alone, so the test holds its level on a response with no spatial structure whatever C_p's noise variance is, and it is what decides when that variance is 0: C_p is then RSS / n, which falls with every finer level by chance alone, and the first comparison says nothing. When either fails, structured is FALSE: one mean for the whole layer predicts as well as any level scored, so the response shows no spatial structure the cells can use and the count is not identified. structured is also FALSE when the profile's variogram was refused for showing no spatial structure. best is still the argmin. The F distribution is exact for a Gaussian response. The test has little power on a small layer, so a FALSE there is weak evidence that there is no structure.

reliability

The level of highest reliability at or above the range floor the profile reports (when the layer supports the floor and the profile built its own ladder). The reliability curve often peaks below the floor, and the floor is a level of every such ladder, so the result is often the floor, the coarsest count the range allows, with edge naming it (on a profile whose k-means failed at that level, the first level above it). range_floor = FALSE reads every level and returns the curve's own maximum, which can be a count below the floor.

elbow

The number of clusters of the points, when they cluster; an error otherwise, because the column is NA at every level unless the WSS curve bends.

moran_z

Refused unless diagnostic = TRUE. It is the level at which neighbouring cell means (or, with predictors, their regression residuals) are least autocorrelated. |z| is near 0 at 10 to 20 cells whatever the data and grows as cells get finer than the range, so its minimum is usually the first level it can be computed at, or one near it, and it says nothing about how well the cells represent the response.

loo

The level with the lowest leave-one-out error of the estimate the profile was built for (resolution_profile(estimate = )); of levels with the same error, the one with the fewest cells. The flat region is every level whose error is within tol of the lowest. The column needs no variogram. structured is read as for cp, with the leave-one-out error in place of C_p: it is TRUE when the error of one mean for all scored rows is above the optimum by more than tol and the F test of the cells at the optimum against one mean, adjusted for the levels searched, has p < 0.05; one_cell then holds the error of one mean. Under this criterion the count depends on the values of the response. When the profile's estimate is the pooled value and the lowest error is at the finest level scored, a note says that the end of the ladder chose the count. For pooled values the error tends to keep falling to the finest level (see "How this was checked" in resolution_profile). On a ladder obs_per_cell set, an optimum at an end has the edge "the finest size offered (obs_per_cell)" or "the coarsest size offered (obs_per_cell)"; a finest level the profile held to the most cells k-means can place keeps the label of the support ceiling.

size

The count a size gives, max(2, round(n / obs_per_cell)), with n the rows the size divides: the rows with a response, or every point for a profile without one. No optimum is searched for. The level returned is the first of three that applies: the level the profile built for that size; the count itself, when the profile has a partition at it; otherwise the built level nearest to the count on the log scale (of two as near, the one with fewer cells), with a warning of class spatialkit_size_not_reached, which says so when the count is more than k-means can place on the layer. It reads any profile, one built without a response or without an estimate included, but not a column subset, which has lost the row count. flat is the level, value the rows per cell it leaves (n / best), and at_ceiling, at_floor and edge are NA: no bound chose anything, so the functions that take the selection as a count raise no spatialkit_bound_chosen. Under this rule neither the cells, which are fitted to the coordinates, nor their number, which is a count of rows, depend on the values of the response. A size does not ask whether the response has structure the cells can use, so structured asks it separately, on a profile built with an estimate. It is FALSE when the leave-one-out error of one mean for all scored rows is within tol of the error at the level, or below it, or when the F test of the cells at the level against one mean has p \ge 0.05. The count stands either way, since a size set it and no criterion: structured = FALSE says that the cell values will say little that one mean for the layer does not. The functions that take the selection as a count then raise spatialkit_no_structure. On a profile without an estimate structured is NA.

auto

The rule that goes with the profile's estimate: "size" for a profile built with estimate = "pooled", "loo" for estimate = "mean", and "cp" for a profile without an estimate. A column subset of a profile has lost the record of its estimate and is read by "cp". criterion in the result is the criterion applied, never "auto".

A profile built with an estimate

This function's default criterion is "auto": "size" for a profile of pooled values, "loo" for one of plain means and "cp" for a profile without an estimate. A profile built with estimate that is passed straight to get_voronoi_seeds(), voronoi_seeds_kmeans() or build_tessellation() as the count is read the same way, so select_resolution(profile) and the profile itself give the same count. A profile of pooled values built with a ladder argument (n_levels and the others) is read by the size as well: the default returns the level nearest the count the size gives, on the automatic ladder its top level, with spatialkit_size_not_reached. criterion = "cp" reads C_p on a profile that has it. cp is computed on such a profile as on any other and scores plain means; when the profile's estimate is the pooled value the result's note says so.

"cp" and "reliability" cannot be read off a profile whose ladder obs_per_cell set under sac = "auto". Such a profile fits no variogram, both columns are NA at every level, and the call is an error that names the ways to get them: build the profile with sac = NULL, with a sac of your own, or with obs_per_cell = NULL. The default profile is such a profile. On a ladder of one size that has a variogram either criterion returns the one level, with edge "the only level scored".

For a ladder of one size, summary() of the profile lists each criterion that is finite at the level and says that the size set the count, and plot() draws each as one point, with no selected level and no flat region. When none is finite, as on a constant response, where loo is NA too, or when no row of the selection half has a response (select_on = "split"), summary() stops with an error that says so. In that last case "cp" and "moran_z", and "loo" with an estimate, are errors that give the same reason, except "cp" on a size ladder that fitted no variogram, which gives the size ladder's reason, as above.

See Also

Other resolution: determine_optimal_levels(), plot.resolution_profile(), resolution_profile(), summary.resolution_profile()

Examples


library(sf)
# An exponential field with range parameter 200 (true effective range
# 600 m) on a 1 km square, with a nugget of 0.6 on a unit sill.
set.seed(4)
n <- 400
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 / 200) + diag(0.6, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)

# The default profile is one size scored for pooled values, and the
# default criterion, "auto", reads it by that size.
select_resolution(resolution_profile(pts, response_var = "z"))

# A ladder of counts for plain means, read by Mallows' Cp.
prof <- resolution_profile(pts, response_var = "z", n_levels = 12,
                           estimate = NULL)
sel <- select_resolution(prof, criterion = "cp")
sel               # the level, and the flat region around it
sel$flat          # every level within `tol` of the optimum
sel$edge          # the bound the optimum sits on; NA when interior
sel$structured    # FALSE when one cell for the layer does as well

# Reliability prefers coarse cells: it is read at or above the floor the
# autocorrelation range sets, and the result says in words when the
# floor is choosing.
rel <- select_resolution(prof, criterion = "reliability")
rel
rel$at_floor
rel$edge


Extract the coefficients of a fitted model

Description

coef() on a GWR returns the local coefficients, one row per observation and one column per term. On a Bayesian GP fit it returns the posterior summary of the global regression terms. A random forest has no coefficients, so coef() on an rf_fit always stops with an error rather than returning NULL; a forest's variable importance is in fit$info$importance (see fit_rf_model()). None of the three returns NULL (see "The coef() contract" in new_spatial_fit()).

Usage

## S3 method for class 'gwr_fit'
coef(object, se = FALSE, ...)

## S3 method for class 'bayesian_fit'
coef(object, ...)

## S3 method for class 'rf_fit'
coef(object, ...)

Arguments

object

A fitted gwr_fit, bayesian_fit or rf_fit.

se

GWR only. Logical; also return the standard errors and t values. Default FALSE.

...

Not used.

Details

The GWR table shows where, and by how much, a predictor's relationship with the response changes across the study area: read the spread of its column, or join the table back to object$data_sf to map it. plot.spatial_fit() draws that map.

The Bayesian GP summary gives the estimate, error and credible interval of each predictor, as brms::fixef() reports them. The Gaussian-process term has already taken up the spatially structured part of the signal, so these are effects net of location (see "Spatial confounding" in fit_bayesian_spatial_model()).

Value

For a GWR with se = FALSE, a data.frame of local coefficient estimates: one row per observation, one column per model term. With se = TRUE, a list of three such data.frames: estimate, se and t. An engine without an SDF component is an error.

For a Bayesian GP fit, a matrix of fixed-effect posterior summaries, as brms::fixef() returns them, on the fitted scale (per standard deviation of each predictor under standardize_predictors = TRUE), in the units of the response: where the response was handed to brms less a centre or divided by a scale, the intercept has the centre added back and every column is multiplied by the scale (see "The response's centre and scale" in fit_bayesian_spatial_model()). brms::fixef() on object$engine answers on the scale brms was given. A missing brms or a failing fixef() call is an error.

For a random forest, nothing: the call is an error.

GWR columns

Only the model terms are returned: the intercept and one column per predictor. The engine's SDF data slot holds more beside them (standard errors, t values, the observed response, the fitted values, the residuals, Local_R2); read object$engine$SDF for those, and ask for the standard errors and t values with se = TRUE.

A coefficient is NA at a location whose local window cannot estimate it: a predictor that does not vary among the observations that carry weight there has no slope, and the intercept is then not identified either unless the predictor is 0 there. object$info$nonfinite_coef is the mask, and fit_gwr_model() raises a warning that counts them.

If the model terms cannot be located in the SDF (an engine that names its coefficient columns differently), the whole slot is returned, with a WARN line in the log saying so (a log record, not an R warning; see spatialkit_quiet()). With se = TRUE the call stops instead. It never returns a silently short table.

GWR standard errors

With se = TRUE the local standard errors and t values come with the estimates. A standard error is \hat\sigma\sqrt{(C C^\top)_{jj}}, with C = (X^\top W X)^{-1} X^\top W the weights the local regression puts on the responses and \hat\sigma^2 the residual sum of squares over the fit's effective degrees of freedom: the definition GWmodel::gwr.basic() uses, computed from the QR decomposition that gave the estimate. They treat the bandwidth as known. The t values are one test per term and location, tens to thousands of them and strongly dependent, so a map of |t| > 2 overstates what is significant; no p-value, adjusted or not, is returned. An adjustment for the number of tests can use the t values here, the effective number of parameters object$info$enp and the residual degrees of freedom object$info$edf. When observations share a location the standard errors are too small as well (see "Observations that share a location" in fit_gwr_model()).

Bayesian GP standardised predictors

The summaries are on the scale the model was fitted on. A fit made with standardize_predictors = TRUE was fitted on centred and scaled numeric predictors, so each slope is the change in the linear predictor per standard deviation of its predictor and the intercept is its value at the predictor means, not the raw-unit numbers stats::lm() reports on the same formula. The returned matrix does not say so; print() on the fit does, and the centre and scale of each predictor are in object$info$predictor_scaling. To put a slope back in raw units divide its Estimate, Est.Error and interval bounds by that predictor's scale. The intercept's Estimate follows by linearity (subtract each raw-unit slope times its predictor's center), but its Est.Error and interval depend on the posterior covariance of the coefficients: transform the draws from brms::as_draws_df(object$engine) for those, or refit without standardising.

See Also

Other fit methods: plot.spatial_fit(), print.spatial_fit(), spatial_fit-fitted, spatial_fit-predict, spatial_fit-residuals, summary.spatial_fit()

Examples


library(sf)
set.seed(1)
n <- 80
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
             a = rnorm(n)),
  coords = c("x", "y"), crs = 32632
)
# The slope on a rises from west to east.
east <- (st_coordinates(pts)[, 1] - 5e5) / 1000
pts$z <- 10 + (1 + 2 * east) * pts$a + rnorm(n, 0, 0.3)
gw <- fit_gwr_model(pts, "z", "a", bandwidth = 30)
str(coef(gw, se = TRUE))
summary(coef(gw)$a)     # the local slopes span the west-east change


Extract the fitted values of a fitted model

Description

fitted() on a random forest, a GWR or a Bayesian GP fit returns one value per training row, in the order of object$data_sf. What the value is depends on the backend, and so does what summary() and model_metrics() without newdata report:

Usage

## S3 method for class 'gwr_fit'
fitted(object, ...)

## S3 method for class 'bayesian_fit'
fitted(object, ...)

## S3 method for class 'rf_fit'
fitted(object, ...)

Arguments

object

A fitted rf_fit, gwr_fit or bayesian_fit.

...

Not used.

Value

A numeric vector of length object$n. For a GWR, NA where the values cannot be read from the engine. For a Bayesian GP, a posterior that cannot be drawn is an error, as is a family with a probability per response category (ordinal, categorical), which has no single fitted value per row.

The Bayesian GP cache

brms::posterior_epred() takes time in proportion to the number of draws times the number of rows, and summary(), residuals(), model_metrics() and compare_models() each call fitted(), so the values are kept in an environment carried in object$info$.cache. The cache holds the expected values only, so predict(object, summary = "median") and predict(object, type = "predict") recompute from the posterior.

The entry records the n and a digest of the training data it was computed from, and is recomputed when either differs, so a copy given other data does not read the original's values. It is also tied to the sampling run: a refit or update() of the brmsfit recomputes. A brmsfit edited in place is what clear_fitted_cache() is for. A copy made with fit2 <- fit shares the environment, so clear_fitted_cache() on one empties the cache of both (the other recomputes), and identical() cannot tell two fits apart by their caches. The entry holds the values and a small identifier of the sampling run, so a fit saved with saveRDS() after fitted() is no larger for it.

See Also

residuals() on the same fits (spatial_fit-residuals), and model_metrics().

Other fit methods: plot.spatial_fit(), print.spatial_fit(), spatial_fit-coef, spatial_fit-predict, spatial_fit-residuals, summary.spatial_fit()

Examples


library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(60, 0, 1000), y = 5e6 + runif(60, 0, 1000),
             a = rnorm(60)),
  coords = c("x", "y"), crs = 32632
)
pts$z <- 10 + 2 * pts$a + rnorm(60, 0, 0.3)
rf <- fit_rf_model(pts, "z", "a", num_trees = 50, seed = 1)
gw <- fit_gwr_model(pts, "z", "a", bandwidth = 30)
# Out-of-bag for the forest, in-sample for the GWR.
head(cbind(z = pts$z, rf = fitted(rf), gwr = fitted(gw)))


Predict from a fitted model

Description

predict() has a method for each backend: a random forest (rf_fit), a GWR (gwr_fit) and a Bayesian GP (bayesian_fit) fit. Every method reads newdata the same way: a layer without a CRS is read the way the training data were (see "Layers without a CRS" in spatialkit-geometry), the layer is transformed to the CRS used at fitting time, a feature that is not a point is reduced to one, and a row with a missing or non-finite predictor or no location gets NA. A layer that mixes XY with XYZ or XYM geometries is read in x and y. The response need not be present. With newdata = NULL each method returns the fit's own fitted values: out-of-bag predictions for a random forest, in-sample values for the others.

Usage

## S3 method for class 'gwr_fit'
predict(object, newdata = NULL, se.fit = FALSE, ...)

## S3 method for class 'bayesian_fit'
predict(
  object,
  newdata = NULL,
  summary = c("mean", "median"),
  type = c("epred", "predict"),
  draws = FALSE,
  ...
)

## S3 method for class 'rf_fit'
predict(object, newdata = NULL, ...)

Arguments

object

A fitted rf_fit, gwr_fit or bayesian_fit.

newdata

An sf object carrying the predictors, or NULL for the fitted values.

se.fit

GWR only. Logical; also return standard errors. Default FALSE.

...

For a random forest, passed to ranger's predict method; any other name is an error. Arguments that make ranger return a matrix (predict.all = TRUE, type = "quantiles", type = "se" with predict.all) are refused, because the method returns one number per row; call predict(fit$engine, data = ...) for those. What ranger itself refuses, such as type = "quantiles" on a forest grown without quantreg = TRUE, is an error that gives ranger's reason. seed defaults to a constant, so the number of predict() calls a script makes (through predict_surface()'s chunk_size, say) does not shift later random draws; it does not change a regression forest's predictions. num.threads defaults to getOption("mc.cores", 1L). For a GWR or a Bayesian GP fit, not used: any argument here is an error, so a misspelt newdata cannot slip through.

summary

Bayesian GP only. "mean" (default) or "median" over the posterior draws.

type

Bayesian GP only. "epred" (default) for the expected value, without observation noise, or "predict" for posterior predictive draws, with it.

draws

Bayesian GP only. TRUE returns the full matrix of posterior draws instead of a summary. Default FALSE.

Details

A random forest predicts with ranger's predict method. A GWR solves one local regression at each new location, with the fit's kernel and bandwidth (an adaptive bandwidth counts neighbours among the training points), and returns x^\top\hat\beta(u). The local regressions are weighted least squares solved by the pivoted QR fit_gwr_model() uses: on a window of full rank the values equal those of GWmodel::gwr.predict() to rounding error, and at a training location with that row's own predictors they equal fitted(). Each location stands alone, so one that cannot be estimated does not affect the others. A Bayesian GP fit applies the coordinate scaling and predictor standardisation stored at fit time and then calls brms::posterior_epred() or brms::posterior_predict().

Value

For a random forest, a numeric vector aligned to nrow(newdata), with NA for rows dropped as incomplete (all NA, with a WARN line in the log, when every row is). The forest in fit$engine predicts (y - fit$info$response_centre) / fit$info$response_scale (see the Value section of fit_rf_model()); this method puts the centre and scale back. A failure inside ranger's predict method is an error.

For a GWR with se.fit = FALSE, a numeric vector aligned to nrow(newdata), with NA for rows dropped as missing or non-finite and for locations whose local regression cannot be estimated (see "When a GWR prediction is NA"). If the design matrix for newdata cannot be built, every value is NA and a warning says why. When the training data were read as longitude and latitude, a CRS-less newdata with an x outside -180 to 360 or a y beyond 90 north or south stops the call. With se.fit = TRUE, a list: fit (that vector), se.fit (the standard error of the fitted value, \hat\sigma\sqrt{s^\top s} with s the weights the local regression puts on the training responses), se.pred (the standard error of a new observation there, \hat\sigma\sqrt{1 + s^\top s}, the square root of GWmodel::gwr.predict()'s prediction variance), residual.scale (\hat\sigma, from the fit's residual sum of squares over its effective degrees of freedom) and df (those degrees of freedom). The standard errors treat the bandwidth as known and the local model as true at each location; they do not measure the bias of a local fit and are NA where the prediction is.

For a Bayesian GP fit, a numeric vector of length nrow(newdata), or an n_draws by nrow(newdata) matrix with draws = TRUE, in the units of the response (see "The response's centre and scale" in fit_bayesian_spatial_model()). Rows with a missing or non-finite predictor or coordinate, and rows carrying a level the model was not fitted with, are NA (an NA column with draws = TRUE). If the posterior draw fails the result is all NA (a one-row matrix for draws = TRUE) with a warning of class spatialkit_predict_failed that gives the cause. An ordinal or categorical family is an error under type = "epred": its expected value is a probability per response category. Use type = "predict", draws = TRUE for posterior draws of the predicted category, as category indices; the share of draws in each category estimates its probability. Without draws = TRUE, type = "predict" returns the mean (or median) category index, an expected rank for an ordinal family and an error for brms::categorical(), whose categories have no order. With newdata = NULL the cached fitted() values are returned only for the default summary = "mean", type = "epred", draws = FALSE; any other combination is recomputed against the training data, because the cache holds the expected values only.

Random forest predictors

A categorical predictor must not carry a level the forest was grown without, meaning a level with no training rows, not only one absent from levels(): an ordinary subset, or a spatial fold that holds out a whole class, keeps the unused level while the forest has no split for it. An unseen level is an error. A predictor that was numeric or logical when the forest was grown must arrive numeric or logical: ranger would otherwise code a character column as a factor and apply the numeric split thresholds to the codes, so a character column is refused. (ranger reads a logical as 0/1, so either form is accepted for one.)

When a GWR prediction is NA

A prediction is returned when it is estimable from the training points that carry weight at the new location, and is NA otherwise:

Where a predictor is constant in the window at the new row's own value, its coefficient is not needed and the prediction is returned. The decision uses the rule and the tolerance of the fit (see "The local solve" in fit_gwr_model()). A warning of class "spatialkit_gwr_not_estimable" counts the NA predictions; it carries n_na, n and n_empty.

GWR locations beyond the reach of the fit

An adaptive bandwidth always finds its neighbours, and a Gaussian or an exponential kernel weights every training point, so a location far from the data still gets a number: the local regression of training points that are all far away, extrapolated. When a new location's nearest training point is farther than the widest kernel used at any training location reaches, the prediction is returned and a warning of class "spatialkit_gwr_extrapolation" counts those locations and gives the range of their distances. The widest kernel is the largest distance from a training point to its bandwidth-th nearest neighbour (object$info$max_kernel_width), or the bandwidth itself when it is fixed. A bisquare, tricube or boxcar kernel reaches as far as its width; a Gaussian or exponential kernel has no edge, and its reach is taken as three widths. The check is on distance alone and is lenient: a location just outside the data is not flagged. The warning carries n_far, n, reach and nearest (the smallest and largest distance to a nearest training point).

Each call raises the warning once, with its own counts. predict_surface(), cv_gwr(), cv_spatial(), cv_block_size_sweep() and select_features_forward() predict in pieces and raise one warning per call with the totals. A cross-validation gives the smallest and the largest reach among its folds, and a sweep counts a location once for each fit that put it out of reach. A loop of your own over predict() gets one warning per call; the example below totals them with a handler. To drop the warning where extrapolation is intended, use suppressWarnings(predict(fit, newdata), classes = "spatialkit_gwr_extrapolation").

Bayesian GP boundary

brms 2.17 to 2.22 do not store the Hilbert-space boundary L in a fitted GP basis, and recompute it from whatever rows predict() is handed. This method therefore appends two rows at the training coordinate extrema before the posterior draw and drops them from the result, and when newdata reaches past the training range it scales down the c of the gp() term by as much as the range grew, so brms rebuilds the boundary the model was fitted with. A prediction does not depend on which other rows share the call: chunked, fold-wise and single-call predictions agree, and predict_surface() does not depend on chunk_size. brms 2.23.0 and later store L and reuse it; there c is left alone and the two extra rows change nothing.

Predictions outside the training coordinate envelope are extrapolation, and a line in the log says so. A row further than L from the centre of the training coordinates on either axis is past the edge of the basis, where the approximate GP is an odd reflection of the fitted surface, so it is returned as NA (a column of NA with draws = TRUE) with a warning. The default boundary factor puts that edge well outside the training data.

Bayesian GP categorical predictors

A factor or character predictor is handed to brms with the levels the model was fitted with: the values that occur in the training rows (object$info$predictor_levels). A newdata factor that only lists an extra level, or a model fitted on a subset whose factor kept an unused level, is predicted as usual. A row whose value is not among the fitted levels has no prediction: it is returned as NA, the other rows are predicted, and one warning of class spatialkit_new_levels names the predictor, the levels and the number of rows. The result does not depend on which other rows share the call.

See Also

predict_surface() to predict onto a grid, and area_of_applicability() to mark where the predictions apply.

Other fit methods: plot.spatial_fit(), print.spatial_fit(), spatial_fit-coef, spatial_fit-fitted, spatial_fit-residuals, summary.spatial_fit()

Examples


library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(60, 0, 1000), y = 5e6 + runif(60, 0, 1000),
             a = rnorm(60)),
  coords = c("x", "y"), crs = 32632
)
pts$z <- 10 + 2 * pts$a + rnorm(60, 0, 0.3)
new <- pts[1:5, ]
new$z <- NULL                          # the response is not needed

rf <- fit_rf_model(pts, "z", "a", num_trees = 50, seed = 1)
predict(rf, newdata = new)

gw <- fit_gwr_model(pts, "z", "a", bandwidth = 30)
str(predict(gw, newdata = new, se.fit = TRUE))

# A point 4 km east of the data is beyond the reach of every kernel.  A
# handler totals the extrapolation warnings of several calls; the log
# lines still print (spatialkit_quiet() turns them off).
far <- st_as_sf(data.frame(x = 5.05e5, y = 5e6 + 500, a = 0),
                coords = c("x", "y"), crs = 32632)
total <- 0
withCallingHandlers(
  for (i in 1:2) predict(gw, newdata = far),
  spatialkit_gwr_extrapolation = function(w) {
    total <<- total + w$n_far
    invokeRestart("muffleWarning")
  })
total


Extract the residuals of a fitted model

Description

residuals() on a random forest, a GWR or a Bayesian GP fit returns the observed response minus fitted(), one value per training row:

residual_morans_i() tests them for spatial structure the model did not capture.

Usage

## S3 method for class 'gwr_fit'
residuals(object, ...)

## S3 method for class 'bayesian_fit'
residuals(object, ...)

## S3 method for class 'rf_fit'
residuals(object, ...)

Arguments

object

A fitted rf_fit, gwr_fit or bayesian_fit.

...

Not used.

Value

A numeric vector of length object$n.

See Also

residual_morans_i().

Other fit methods: plot.spatial_fit(), print.spatial_fit(), spatial_fit-coef, spatial_fit-fitted, spatial_fit-predict, summary.spatial_fit()

Examples


library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(60, 0, 1000), y = 5e6 + runif(60, 0, 1000),
             a = rnorm(60)),
  coords = c("x", "y"), crs = 32632
)
pts$z <- 10 + 2 * pts$a + rnorm(60, 0, 0.3)
rf <- fit_rf_model(pts, "z", "a", num_trees = 50, seed = 1)
summary(residuals(rf))   # out-of-bag residuals


Warnings and errors the package raises

Description

Every condition class the package raises, with the functions that raise it, what it means, what to do and the fields it carries. Each class can be caught by name.

Catching a condition by class

Each condition below is an R warning or error whose class vector starts with the class named, followed by "warning" or "error" and "condition". A handler named after the class catches it without matching the message, and reads its fields with $:

w <- tryCatch(determine_optimal_levels(pts),
              spatialkit_no_elbow = function(w) w)
w$k

withCallingHandlers() with invokeRestart("muffleWarning"), or suppressWarnings(expr, classes = ), lets the call finish and drops the warning. options(warn = 2) turns every warning into an error.

Some warnings and errors carry no class of the package's own, such as the refusal of an argument of the wrong type. Catch those with ⁠warning =⁠ or ⁠error =⁠.

Warnings and log lines

The package also writes a log through logger: a trace in a temporary file, and a console echo of every line at the WARN level and above. A log line is not an R condition. tryCatch(warning = ) does not catch it, and suppressWarnings() does not silence it. Where a help page says a function raises a warning, it means an R warning; where it says the function logs one, it means a log line. spatialkit_quiet() turns the console echo off.

The package writes a classed warning to the log as well as raising it, so a warning muffled by a handler still prints its log line until the echo is turned off.

Condition classes

Each entry gives the class, the functions that raise it, what it means and what to do, and then the fields a handler reads with $. Each is a warning unless marked as an error. An entry without fields is a condition that carries only its message.

See Also

spatialkit_quiet() for the console log, spatialkit-options for the work limits, spatialkit-geometry for the rules behind the geometry classes, and vignette("troubleshooting", package = "spatialkit") for the messages met most often.

Other options and caches: clear_fitted_cache(), clear_grid_cache(), spatialkit-options, spatialkit_quiet()

Examples

library(sf)
set.seed(1)
# Points spread evenly have no elbow.
pts <- st_as_sf(data.frame(x = 5e5 + runif(200, 0, 100),
                           y = 5e6 + runif(200, 0, 100)),
                coords = c("x", "y"), crs = 32632)

# Catch the warning by its class and read its fields.
w <- tryCatch(determine_optimal_levels(pts, max_levels = 6),
              spatialkit_no_elbow = function(w) w)
class(w)
w$k

# Let the call finish without the warning; the log line still prints
# until the console echo is off.
old <- spatialkit_quiet()
k <- suppressWarnings(determine_optimal_levels(pts, max_levels = 6),
                      classes = "spatialkit_no_elbow")
spatialkit_quiet(old)
k

How input geometry is read

Description

The rules the package applies to the spatial layers it is given: how two layers are brought into one CRS, how a layer without a CRS is read, how mixed dimensions and rows without a location are handled, what a boundary needs, and what s2 refuses in longitude and latitude. A function's own page says how it applies them: which of its arguments they cover, and whether a row it leaves out is reported by a warning or in the log.

Coordinate reference systems

A function that takes two layers, such as points and a boundary or features and cells, brings them into one CRS before it reads either. harmonize_crs() is the rule in its plain form: when both layers have a CRS, one is transformed into the other's; a layer without one is read by the test in "Layers without a CRS" and then reprojected or stamped, with a warning.

A function that measures distances moves a lon/lat layer into the projected CRS ensure_projected() chooses from the layer's extent: the UTM zone for a local extent, otherwise the candidate that distorts distances least (its page gives the cases). A layer that already has a projected CRS is used as it is. Distances, and arguments given as distances, are in the units of the CRS the function works in, which its page names. For a lon/lat layer the function projects, that is the CRS ensure_projected() chose, whose unit is the metre.

Layers without a CRS

A layer without a CRS is read by a test of its coordinates. When their bounding box lies within longitude -180 to 180 and latitude -90 to 90, and they either span more than one unit on some axis or carry the decimal places of degrees, they are taken as EPSG:4326, with a warning. Otherwise they are left as they are. A small planar survey inside that box is read as degrees, so set the CRS of such a layer with sf::st_crs(x) <- ... before passing it.

Given a CRS to read the layer in (target_crs, or the CRS of a second layer), coordinates the test takes for degrees are reprojected from EPSG:4326, and the others are stamped with that CRS and not moved. A stamp is a relabel: check that the coordinates are in that CRS. A CRS in longitude and latitude is never stamped on coordinates that cannot be in it. An x outside -180 to 360, or a y beyond 90 north or south, stops the call with an error that gives the bounding box of the coordinates.

Mixed dimensions, Z and M

sf reads a layer in the dimension of its first geometry, and GEOS refuses M. A function that moves a layer into another CRS and returns it, or reduces it to points, reads a layer that mixes XY and XYZ (or XYM) geometries, as rbind() of an XY and an XYZ layer gives, in x and y. It returns that layer in XY, with a warning of class spatialkit_zm_dropped (its page names any exception). A layer in one dimension, XYM and XYZM included, is moved with its Z and M, and so is a layer whose only geometries of another dimension than the first are empty and not points.

A layer a function only reads for its x and y, such as a boundary or the points and cover of a builder, is read in x and y when it mixes dimensions or its geometries carry M (XYM or XYZM). coerce_to_points() reduces a geometry that carries M in x and y as well, with the same warning; its page gives the exceptions.

Rows without a location

A row has no location when its geometry is empty, or one of its coordinates is not finite or lies beyond 1e150. Such a row takes no part in the choice of a projection, and its coordinates none in the lon/lat test. Moved into another CRS, it comes back empty, in its own geometry type. sf::st_transform() alone would drop the vertex it cannot move, or put a coordinate beyond 1e150 at a finite place, and return the rest of the feature.

In a geographic CRS a vertex at a latitude beyond 90 is no place on the Earth. A row with one takes no part in the choice of a projection either. coerce_to_points(), prep_model_data() and the fits, the points of the k-means seeders, the features of assign_features_to_polygons(), the pooled columns of summarize_by_cell() and cell_values_at(), and ensure_stable_poly_id() read such a row as a row without a location. coerce_to_points() and ensure_stable_poly_id() say so with a warning of class spatialkit_lat_beyond_90 that names the rows.

A row that has a location and that the target CRS cannot place in full comes back empty, or without the vertices that CRS cannot place, with a warning of class spatialkit_rows_unplaced that names the rows.

What a function does with such a row (drops it, keeps it with NA, or leaves it out of one step) is on its page.

Boundaries

A boundary is a polygonal sf or sfc layer: the study area that cells are clipped to, that seeds are drawn in, or that fold blocks are cut from.

get_voronoi_seeds() adds the rules for drawing points inside a boundary, and make_folds() the rule for a block the boundary only touches.

Polygons in degrees

With s2 on (sf::sf_use_s2(), sf's default), sf reads polygons in longitude and latitude on the sphere, and s2 refuses a polygon that is not valid there: one whose edges cross, or with two corners it reads as one point. Cells returned in lon/lat can hold two such corners. This happens where four Voronoi seeds stand the same distance from one point, and the transform to degrees puts two corners that differ only by rounding at one point (see crs in create_voronoi_polygons()).

A function that joins, measures or unions such a polygon in degrees stops with an error that names its rows, quotes s2's reason and says to transform the layer to a projected CRS, such as the one ensure_projected() picks for it. The class is spatialkit_cells_degenerate for cells and boundaries, and spatialkit_features_degenerate for features being assigned or reduced to points. Some steps repair the polygons first, such as the largest-overlap join of assign_features_to_polygons() and the union of a boundary in get_voronoi_seeds(), and stop only when s2 refuses a repaired polygon.

A hex or square grid built with a geographic crs is laid in degrees (create_grid_polygons()). Voronoi cells asked for in a geographic crs are built in a projected CRS and then transformed.

Coordinates far from the origin

Far from the origin of a CRS, doubles are spaced more widely: 0.125 apart at 1e15. Where they are spaced more than a millionth of a layer's extent apart, edges and points are held to that spacing, and a point within it of an edge can fall on the other side. The functions that build cells, blocks and joins still run, with a warning of class spatialkit_xy_imprecise that gives the spacing and the extent; clip_target_for() stops with an error of class spatialkit_xy_imprecise_error where its buffer comes back empty or with no area. Those that search for neighbours (estimate_sac_range(), fit_gwr_model(), residual_morans_i()) give the same warning where a distance lies past a tie by less than the rounding. Subtract a constant from the coordinates to bring them nearer the origin.

See Also

spatialkit-conditions for every condition class named here, ensure_projected() for the choice of a projected CRS, and harmonize_crs() for aligning two layers.

Other data preparation: [.spatialkit_rows(), coerce_to_points(), ensure_projected(), harmonize_crs(), prep_model_data()


Options that bound the work of a search or a fit

Description

The package reads two options. Each bounds a step whose cost grows with the square of the rows or of the cells, so that such a step stops, or is skipped, before it starts. Set them with options().

The options

spatialkit.exact_pairs_max

Default 2e9 pairs. The most pairs a search made without the FNN package may compare. Without FNN, a nearest-neighbour search (each cell's neighbours, each row's nearest centre, each location's nearest other location) compares every pair, and a search over the pairs of about 44,700 cells or locations reaches the default. With FNN, which installs with spatialkit, these searches use a kd-tree and the limit is not read. The result of every search is the same with and without FNN. Above the limit:

  • resolution_profile() stops with an error of class spatialkit_work_limit before the search: on a ladder of sizes, for the weights of partition = "density"; with an estimate, on any ladder, for the estimate's searches.

  • cell_values_at() stops with the same error before the search.

  • summarize_by_cell() returns NA pooled columns with a warning of class spatialkit_pool_unavailable (reason = "work limit"), and does not run the check of the count record ("not checked: work limit").

  • select_resolution() hands on the centres fitted to the subsample without refitting them to every point, with a logged warning.

spatialkit.fit_work_max

Default 1e10 point-to-centre comparisons. The most work the partition fits of a ladder of sizes may do: the points times the cells of the finest level times nstart, times iter_max for partition = "density" without FNN. With FNN and init = "random" the density kind has no step that compares every point with every centre, and nothing is counted. Above the limit, resolution_profile() stops with an error of class spatialkit_work_limit before any fit. At the default size the work grows with the square of the rows. select_resolution() refits the centres of a profile fitted to a subsample to every point, and counts the points times the cells of the count it selects, times iter_max for the density kind without FNN, whatever the start. Above the limit it hands on the centres fitted to the subsample, with a logged warning.

Setting a limit

Each option takes a single number, 0 or more; Inf removes the limit. Any other value is an error when the option is read. The error of class spatialkit_work_limit carries work (the count), limit and what (the step), and its message says what to change: for a fit, fewer starts, a coarser obs_per_cell, random starts of the density kind or a higher limit; for a search, reinstalling FNN. A profile just below spatialkit.fit_work_max prints nothing while its fits run.

The console log is set with spatialkit_quiet(), not with an option.

See Also

spatialkit-conditions for the classes named here, and resolution_profile() for the work its fits do.

Other options and caches: clear_fitted_cache(), clear_grid_cache(), spatialkit-conditions, spatialkit_quiet()

Examples

getOption("spatialkit.exact_pairs_max", 2e9)
getOption("spatialkit.fit_work_max", 1e10)

# Raise one limit for a session, then put it back.
old <- options(spatialkit.fit_work_max = 2e10)
getOption("spatialkit.fit_work_max")
options(old)

Turn the console log off or on

Description

Turns the package's console log off (quiet = TRUE) or back on. The package writes a trace of INFO lines and above to file.path(tempdir(), "spatialkit_model_log.log"), a file that lasts as long as the R session, and echoes WARN lines and above to the console; this function changes only the console echo. logger::log_threshold() changes the log file's threshold by default (index = 1), not the console echo's, so use this function for the echo.

Usage

spatialkit_quiet(quiet = TRUE)

Arguments

quiet

TRUE (default) silences the console echo; FALSE restores the package default, WARN+. A logger threshold (logger::ERROR, or the value a previous call returned) sets that level instead, which is how to put back exactly what was in force rather than the default: old <- spatialkit_quiet(); spatialkit_quiet(old).

Details

These are log records, not R conditions: suppressWarnings() and tryCatch(warning = ) do not see them. Conditions the package raises as R warnings are unaffected by this function (see "Warnings and log lines" in spatialkit-conditions).

While a document is being knitted (R Markdown, Quarto, a pkgdown article) the console echo is also sent as an R message, because knitr does not capture what is written to the console's error stream and the cautions would otherwise be missing from the output. They appear as ## WARN [...] lines, and the chunk option message = FALSE, like suppressMessages(), keeps them out of the document. A line the package also raises as an R warning is not repeated, since the document shows the warning. Outside knitr nothing changes.

Value

Invisibly, the threshold that was in force before the change, a logger level that can be passed back as quiet.

See Also

Other options and caches: clear_fitted_cache(), clear_grid_cache(), spatialkit-conditions, spatialkit-options

Examples

old <- spatialkit_quiet()      # console echo off
spatialkit_quiet(old)          # back to whatever it was
spatialkit_quiet(FALSE)        # or back to the WARN+ default

Summarise assigned points by cell, with standard errors and pooled values

Description

Aggregates an sf point dataset into one row per cell. Each cell gets a count, the mean of each response and predictor column (or the functions in agg_funs), and that column's within-cell standard deviation and standard error. By default each numeric column also gets a pooled value, the cell's mean pulled toward the mean of the cells around it (estimate = "pooled"; estimate = "mean" leaves it out). On request the frame adds an interval for each mean (conf_level) and an interval for one further observation (obs_level).

Usage

summarize_by_cell(
  assigned_points_sf,
  response_var = NULL,
  predictor_vars = NULL,
  id_col = "poly_id",
  agg_funs = list(mean = function(x) mean(x, na.rm = TRUE)),
  cells_sf = NULL,
  deff = 1,
  sac = NULL,
  deff_max_n = 500L,
  quiet = TRUE,
  conf_level = NULL,
  area = FALSE,
  estimate = c("pooled", "mean"),
  obs_level = NULL
)

Arguments

assigned_points_sf

An sf object with a cell identifier column.

response_var

Optional response column name for per-cell aggregation: a single character string. A name that is not a column, or a column that is not numeric, is skipped with a warning.

predictor_vars

Optional predictor column names for per-cell aggregation. Names that are not columns, and columns that are not numeric, are skipped with a warning.

id_col

Name of the cell ID column. Default "poly_id". When assigned_points_sf has no column of that name, the first of "poly_id", "polygon_id" and "cell_id" it carries is used; the message that names the column shows only with quiet = FALSE. The column of cells_sf is found as cells_sf says.

agg_funs

Named list of aggregation functions. Default list(mean = \(x) mean(x, na.rm = TRUE)). Additional common options: median, sum, sd. A single function (agg_funs = median) or a character vector of function names (c("median", "sum")) is also accepted. A single function is named after the expression passed: a name gives that name (median, or f for a variable f holding a function), stats::median gives median, and any other expression gives agg1; pass a named list to choose the name. Anything else falls back to the default mean with a warning. The functions receive each column with its infinite values already set to NA (see "Output columns"), so they need na.rm = TRUE as they do for missing values.

cells_sf

Optional polygon sf layer to join cell geometries onto the output. When supplied, the return value is an sf object with the polygon geometry from cells_sf, with one row per cell in cells_sf. Cells that no feature fell in are kept, with NA summaries. Duplicate ID values in cells_sf would multiply those rows, so they are reported with a warning. Its ID column is the first of id_col, "poly_id", "polygon_id", "id", "cell_id" and "grid_id" it carries, the list and order assign_features_to_polygons() reads the polygons' IDs from. A summarised ID that matches no cell is reported with a warning, since the join drops it with its points; a cells_sf with none of those columns, or one that is not an sf object, gives a warning and a plain data frame (an error with area = TRUE). When NULL (default), a plain data.frame/tibble is returned.

deff

Design-effect adjustment for standard errors. One of:

1 (default)

No adjustment; the classic IID standard error sd / sqrt(n), which assumes the observations within a cell are independent. No "deff_applied" attribute is attached, so a result carrying none was computed this way.

"variogram"

Compute a per-cell design effect from a fitted variogram: for n points in a cell with correlation matrix R, the effective sample size of the mean is n^2 / sum(R), so deff = sum(R) / n. This generalises Kish (substituting a constant off-diagonal correlation recovers 1 + (n - 1) * rho exactly) but lets correlation decay with distance, which matters increasingly as cells get larger and Kish's single-rho assumption degrades. Supply the fit via sac, or it is estimated when response_var is given and gstat is available. The distances are taken in x and y: a layer whose features, or the points taken from them, do not all have the same dimensions (some with a Z or M coordinate) is read without its Z and M. Exponential, spherical and Gaussian models are supported, with a nugget and with several structured components (each weighted by its partial sill) and with gstat's 2-D geometric anisotropy (vgm(..., anis = c(angle, ratio))), applied as gstat applies it. A request that cannot be met falls back to "kish", with a warning of class "spatialkit_deff_fallback" that gives the reason and the ICCs: a model of any other family (named in the warning), or no usable model (none supplied and none could be estimated, or a rejected fit that could not be replaced by an estimate). The standard errors, intervals and cell_weight are then Kish's, the uncorrected ones where Kish's own ICC is 0 and NA where it cannot be estimated; the deff_method column says which on every row (see "Value"). The variogram route needs an identified range, which a layer does not always have, so read deff_method for the fallback. A layer whose geometries carry M (XYM or XYZM), which GEOS does not read, is read in x and y too. A model with no structured component (a pure nugget) implies that distinct observations are uncorrelated, so it is applied as a design effect of 1 in every cell, not treated as a fallback. That includes the model estimate_sac_range() returns when it finds no spatial structure (an NA range whose rejected_reason says so): the answer is then a design effect of 1, deff_method reads "variogram", and no fallback warning is raised. Predictor columns summarised under that verdict get the same design effect of 1, and a warning of class "spatialkit_deff_no_structure" names them (fields columns and reason). Points with empty geometry count towards their cells' values but not towards the correlation, with a warning.

"kish"

Estimate an intra-class correlation (ICC) for each summarised column from the grouped data using a one-way random-effects ANOVA decomposition (one ICC for the response and one for each predictor), then apply Kish's formula per cell: deff_i = 1 + (n_i - 1) * rho. The ICC is the ANOVA (method-of-moments) estimator with Donner's n0 for unequal cell sizes, not the REML estimate a mixed model returns, so on cells of unequal sizes the two estimates can differ. Each column's ICC is used for that column's SEs and for no other: the response's ICC is never applied to a predictor, nor one predictor's to another. It is the response's ICC that sets cell_weight whenever a response was given, and the first predictor's own ICC otherwise. An ICC needs at least 2 cells with 2+ observations of the column and at least 2 residual degrees of freedom (N - k >= 2). Where a column has fewer (all its values in one cell, say), its ICC cannot be estimated: it is NA, attr(, "icc")$reason says why, and the column's standard errors, ⁠..neff_*⁠ and ⁠..ci_*⁠ are NA in every cell of two or more observations (⁠..df_*⁠ stays n - 1), as is cell_weight when that column sets it, with a warning of class "spatialkit_icc_unavailable" (fields columns and reason). Rows with no cell id (kept by keep_unassigned = TRUE in assign_features_to_polygons()) give a summary row of their own but no cell to the ICC, so a column whose values all fall in them, or differ only there, has an ICC that cannot be estimated. An estimate at or below 0 is another case: the ICC is 0 and the column's standard errors are the uncorrected ones. A column that does not vary (all its values equal, those of rows with no cell id included) has an ICC of NA and standard errors of 0, with no warning: its mean has no error whatever the correlation. A column whose values differ only by their rounding (0.1 beside 0.3 / 3) is read the same way, as one that does not vary, at any size of its values; its standard errors are 0 in a cell whose values are equal and of the size of that rounding in one whose values differ. The "deff_applied" attribute is attached when any ICC is positive, so when all are 0 or NA there is none.

A positive number

Applied as a uniform design effect to every cell, as sd * sqrt(deff / n), exactly sqrt(deff) times the naive SE. Use when you have an external estimate of the design effect. Anything that is not a single finite number ⁠>= 1⁠ (including a value below 1, which would shrink the standard errors, and NA or Inf) is refused with a warning and replaced by 1.

sac

Optional sac_range object from estimate_sac_range(), used when deff = "variogram". Supplying one avoids re-fitting the variogram and lets you inspect the fit the design effect is based on. A sac_range whose fit was rejected (its value is NA and it carries a rejected_reason attribute) carries no usable correlation function, so it is set aside rather than correcting by a shape that was not trusted enough to report a range: the variogram is then estimated as if no sac had been given, with a plain warning saying so, or, where that is not possible, deff falls back to "kish" with the fallback warning, which names the rejection. The exception is a sac refused because no spatial structure was found, whose model is a pure nugget: it is used, and gives a design effect of 1. A sac with no variogram_model attribute, such as a plain number or a units object, is a range without a correlation function, and is set aside the same way. A sac fitted to residuals (attr(sac, "detrended") TRUE) is used as given, with a warning when it corrects response columns (see "Standard errors and design effects").

deff_max_n

Cells with more than this many points are subsampled before forming the ⁠n x n⁠ correlation matrix used by deff = "variogram". Default 500. It must be a single number of at least 2 when deff = "variogram"; anything else is an error. The subsample is drawn with a fixed seed from the cell's points in coordinate order, so it does not depend on the row order of assigned_points_sf, and the caller's random-number stream is left where it was.

quiet

Logical; suppress this function's progress message()s. It does not silence R warnings, nor the package's console log echo (see spatialkit_quiet for that). Default TRUE.

conf_level

Optional confidence level in (0, 1), such as 0.95. When given, every numeric response and predictor column also gets ⁠..neff_*⁠, ⁠..df_*⁠, ⁠..ci_lo_*⁠ and ⁠..ci_hi_*⁠ (see "Confidence intervals"). Default NULL: no such columns.

area

Logical, default FALSE. With TRUE, and cells_sf supplied, the result gains cell_area (each cell's planar area in the squared units of cells_sf's CRS) and n_per_area (the count of rows in the cell over that area, a point density; a rate of anything else is that thing's agg_funs sum over cell_area). The request is refused with an error, not answered with a number, when the cells' CRS distorts areas across them by more than 1 percent, measured as the spread of planar-to-geodesic area ratios over the cells (over 200 of them when there are more, taken at even spacing along the cells sorted by their bounding boxes in that CRS and then by the means of their vertices, together with the cells that reach furthest along x and y either way, so the order of the rows does not matter): a density is a comparison between cells and is meaningless where the map scale differs from one cell to the next. Inside a UTM zone the spread is under 0.3 percent and the request goes through; the conterminous United States forced into one zone (14 percent), or a few degrees of latitude in Web Mercator (4 percent at 48N), does not. Exact copies of one cell count once. A layer of one distinct cell gives one ratio and no spread, so its distortion is measured on a 6 by 6 grid over the cell's bounding box. Projected cells are first checked with sf::st_is_valid() in their CRS, every non-empty cell before any summary: a cell GEOS calls invalid (edges that cross, a spike, parts that overlap) has no planar area to vouch for, and the request is refused with an error that names the first such cells and GEOS's reason and says to repair the cells with sf::st_make_valid(). A valid projected cell with two vertices that fall on one point once in degrees, where s2 refuses it, is measured there without the repeat, which moves no area; when s2 refuses a valid cell it measures for another reason, the spread cannot be measured and the request is refused. ensure_projected() with purpose = "area" chooses an equal-area CRS for lon/lat input; build the cells in it. Lon/lat cells are measured geodesically instead: their cell_area is sf::st_area()'s area in square metres (on the sphere with s2, sf's default), not a planar area in squared degrees, and on the cells s2 measures the distortion check passes by construction. Every cell's area is taken before any summary, and when s2 refuses a cell that is not valid on the sphere, such as one with two corners it reads as one point (cells returned in lon/lat can hold them; see crs in create_voronoi_polygons()), the request stops with an error of class "spatialkit_cells_degenerate" that gives the rows of cells_sf s2 refuses (rows on the condition) and says to transform the cells to a projected CRS, such as the one they were built in or the equal-area one ensure_projected(purpose = "area") picks. With s2 switched off, sf needs lwgeom for that area and the request is refused without it. The measured spread is attached as attr(, "area_error"). Cells that mix XY and XYZ (or XYM) geometries are measured, and their spread taken, without Z and M, since sf reads a layer in the dimension of its first geometry; so are cells that carry M throughout, which GEOS does not read. The cells are returned with their own geometry. In a projected CRS whose unit sf has no name for (a +to_meter such as 1e6), sf::st_area() gives square metres; cell_area is the planar area in that CRS's unit squared all the same.

estimate

Which value of a cell the frame reports: "pooled" (default) or "mean". With "mean" the frame holds the plain columns only. With "pooled" every numeric response and predictor column also gets a pooled value, w * m + (1 - w) * t: the cell's own mean m and a target t, the mean of the rows of the 8 cells whose observations' centroids are nearest (all the other cells when there are fewer than 10; the polygons are not read). The own weight is w = tau2 / (tau2 + sigma2 / n), where n is the cell's count, sigma2 the spread of the observations about their cell's mean and tau2 the mean squared distance between a cell's true mean and its target. Each column is pooled on its own rows: those with a value, a cell and a location. agg_funs, deff, sac and conf_level do not enter the pooled columns, and every other column is computed as with "mean". Lon/lat coordinates, and coordinates without a CRS that look like degrees, are projected for the distances between centroids, as resolution_profile() projects them. The projection is chosen from every row of the layer, those without a value or a cell included, so on such input the rows a column does not use can still decide the CRS its distances are measured in; a layer projected beforehand is used in its own CRS. When the input carries the record of its cells' count (see "Value") and that record names a projected CRS, the one the profile worked in, the distances are measured in it, whatever CRS the layer is in. The distances are taken in x and y: a layer whose features, or the points taken from them, do not all have the same dimensions (some with a Z or M coordinate) is read without its Z and M. So is a layer whose geometries carry M (XYM or XYZM), which GEOS does not read. An abbreviation such as "m" is accepted. See "Pooled values" for what the pooled value estimates and what its numbers rest on, "Value" for the columns and the attributes, and "Conditions" for the warnings.

obs_level

Optional level in (0, 1), such as 0.90, of an interval for one further observation in a cell, located like the data. It needs estimate = "pooled": the interval is the pooled value plus the (1 - obs_level) / 2 and (1 + obs_level) / 2 quantiles of the leave-one-out residuals of the pooled values, so its two offsets are the same in every cell. It is a statement about observations on average, not about each cell. It is a separate argument from conf_level, whose interval is for a mean and is not a range for an observation. Any level strictly between 0 and 1 is computed the same way; only 0.90 has been checked (see "Intervals: which one answers which question"). Default NULL: no such interval.

Details

This is the step after assign_features_to_polygons(), which labels each observation with its cell. Beside every mean the frame keeps the count and the standard error, so a cell mean over 2 observations and one over 200 stay distinguishable in a map or a model, and deff can widen the standard error for correlation inside a cell.

Value

A tibble/data.frame (or sf if cells_sf given) with per-cell summaries: the ID column, n (rows in the cell), one column per agg_funs entry per variable (⁠resp_<name>_<var>⁠ for the response and ⁠pred_<name>_<var>⁠ for each predictor), ⁠..sd_*⁠ / ⁠..se_*⁠ for every numeric response and predictor, ⁠..neff_*⁠ / ⁠..df_*⁠ / ⁠..ci_lo_*⁠ / ⁠..ci_hi_*⁠ for the same columns when conf_level is given, cell_weight (always), deff_applied and deff_method when a design effect was requested (any deff other than 1), and cell_area / n_per_area when area = TRUE ("Output columns" gives the order). An input column also called n is not allowed to shadow the count.

deff_applied is TRUE on every row when a design-effect correction was applied (exactly when the "deff_applied" attribute below is attached; under "kish", when any standard-error column was corrected) and FALSE when none was: a refused deff, or "kish" ICCs of 0 or NA for every column (the standard errors are then the uncorrected ones, or NA where an ICC cannot be estimated). It is NA on a cells_sf row no point fell in. deff_method names the correction the standard errors carry, since their column names do not change with it: "variogram", "kish" or "fixed" when the one requested was applied, "none" when none was, and "kish (variogram fallback)" or "none (variogram fallback)" when a "variogram" request could not be met and Kish stood in for it (the second when Kish's ICCs were 0 or NA too). So deff_applied is TRUE on a Kish fallback row: test deff_method == "variogram" to keep only rows the variogram corrected. Unlike the attribute, both columns survive rbind() and dplyr::bind_rows() of many results. A fallback is also signalled by a warning of class "spatialkit_deff_fallback" (a Kish ICC of 0 under a "kish" request is reported on attr(, "icc") instead), which tryCatch(spatialkit_deff_fallback = ) catches without matching the message. It is raised when the correction requested was not the one applied: a refused number (the standard errors are then the uncorrected ones) or a "variogram" request that fell back to Kish; the condition of the second carries requested and used. Two more classes say what a design effect could not do: "spatialkit_icc_unavailable" names the columns whose Kish ICC cannot be estimated, and "spatialkit_deff_no_structure" the predictor columns given a design effect of 1 by a variogram that found no spatial structure.

When a correction was actually applied, an attribute "deff_applied" is attached recording it: method plus icc_resp/icc_pred and deff for "kish" (icc_pred is a vector named by predictor column, one ICC each; deff is the primary variable's per-cell design effect, all 1 when only a predictor's ICC was positive, except that it is NA in each cell of two or more of the primary variable's values when that variable's ICC cannot be estimated, and its entry in icc_resp or icc_pred is then NA too; requested and fallback_reason are added when a "variogram" request fell back to it), deff/deff_rows/rbar/crs/max_n for "variogram" (deff is the design effect at the primary variable's non-missing count per cell, deff_rows at the cell's row count, which is the vector the log line summarises as a median and a max), and deff alone for a fixed number. When cells_sf is supplied, every per-cell vector in that attribute (deff, deff_rows and rbar alike) is realigned to the joined row order, so deff[i] and rbar[i] still describe row i; cells with no observations carry NA. No attribute is attached when no correction was applied: deff = 1, or a deff = "kish" request (or Kish fallback) whose ICCs are all 0 or NA. A deff = "kish" request, and a "variogram" request that fell back to it, always records the ICCs it estimated on an attribute "icc" (resp, and pred, a vector named by predictor column; NA for a variable type with no numeric column and for a column whose ICC cannot be estimated; reason, a character vector named by column, is then added and says why), whether or not they were positive enough to apply, so a result with no "deff_applied" still says what the ICCs came out as.

The ID column keeps its input type when cells_sf's ID column and the summarised IDs already have the same class. When the classes differ, both are coerced to character in order to join (logged as a warning), and the returned ID column is therefore character. Whole numbers are written out in full for that ("100000", never "1e+05"), so an integer and a double ID of the same cell still match.

With estimate = "pooled", each numeric column v with its prefix (resp_ or pred_) gains ⁠..pooled_<prefix><v>⁠ (the pooled value), ⁠..pooled_w_<prefix><v>⁠ (the own weight, 0 to 1; it is not a regression weight) and ⁠..pooled_target_<prefix><v>⁠ (the target), and with obs_level also ⁠..obs_lo_<prefix><v>⁠ and ⁠..obs_hi_<prefix><v>⁠. They follow every column listed above and precede cell_area and n_per_area, the response's first, then each predictor's. A cell with no row that has a value, a cell and a location gets NA, never a value made from its neighbours. Two attributes are attached. attr(, "pooled"), of class "spatialkit_pooled", records what was fitted: toward, neighbours, crs (the CRS the centroid distances were measured in), obs_level, conf_level, intervals and columns, a list with one entry per pooled column holding column, role ("response" or "predictor"), n (rows used), cells, df (values beyond one per cell, which sigma2 rests on), neighbours (the cells in each target), sigma2, tau2, own_weight (the median weight), share_alone (the share of rows that are the only one in their cell), loo and loo_se (the leave-one-out mean squared error of the pooled value, and its standard error over rows), loo_one_cell (the same error with one mean for all rows), structured and structure_p (whether the cells predict a left-out observation better than one mean, and the p-value of the F test of the cell means against one mean, which has to be below 0.05 as well), offsets (the two offsets of the interval), repeated, skipped, constant and status. attr(, "intervals") is the same data frame as attr(, "pooled")$intervals: one row per family of interval columns in the frame, saying what it covers, what it is centred on, its level and its method. Away from the observations no interval here is calibrated.

Where the pooled columns of a column cannot be computed they are NA, with a warning of class "spatialkit_pool_unavailable" and not an error, and the plain columns are returned. "Conditions" lists that class and the other warnings of the pooled columns, with what each condition carries.

When assigned_points_sf carries attr(, "count_rule"), or cells_sf does (the assigned layer's is read first), the result carries that record with one more element, check, whatever estimate is. The record is the one select_resolution() wrote: rule, estimate (the cell value the count was chosen for), cells, obs_per_cell, response, scored (what the profile scored at the count: the rows, the cells that hold one, the leave-one-out error among them, and the centres the rows were given to), partition, crs and scored_cells. It has class "spatialkit_count_rule" and a print method. check$estimate is "match" or "mismatch": whether the summary reports the estimate the count was chosen for (NA for a count chosen for neither). A mismatch is a warning of class "spatialkit_estimate_mismatch" (fields chosen_for, reported, rule, cells), and the summary is returned as asked. check$cells is "match", "differ" or "not checked: <reason>": the response is fitted again on the rows and cells given, with the estimate the profile scored, and its scored rows, its occupied cells and its leave-one-out error are compared with the record's, the error to a relative tolerance of 1e-8. The first that differs is a warning of class "spatialkit_cells_differ" (fields what: "n", "cells" or "loo"; scored; found): rows were dropped or moved between cells, or the layer is another one. The same class with what = "record" (fields field, scored, found) is raised when the assigned layer and cells_sf carry different records, so the rows were assigned to other cells than the cells_sf given: the cells of another selection, or the scored cells of a selection beside other cells built from its count, such as a lattice sized by it. check$cells is then "differ", whatever the comparison of the rows finds. The comparison is not made, and check$cells says why, when the response is another column or was not summarised, the profile read the selection half (select_on = "split"), the cells are not the ones the profile scored (scored_cells is FALSE or NA), the profile scored no estimate, the input has no coordinates, the features are not points (see assign_features_to_polygons()), or the fit was stopped by the limit on an exact search without the FNN package. Cells and rows without a record, such as polygons the caller brings, are not checked and raise neither warning.

A row that is the same distance from two centres lies on the boundary between their cells, which happens on gridded locations. resolution_profile() scores such a row in the cell of the lower-numbered centre (a distance counts as the same as the least when its square is no more than the square of the least distance lengthened by a margin, plus one part in ten million of the least squared distance; the margin is one part in 1e10 of the largest coordinate of the centres, at most a millionth of the diagonal of their bounding box and at least four times the spacing of doubles at that coordinate), and assign_features_to_polygons(), on cells built from the centres the profile scored, gives a point on that boundary the same cell, measured in the CRS the record names, so the comparison reads "match" on gridded locations too. It does so on cells that carry the record, for rows that have a CRS exactly when the record names one. Rows without a CRS beside a record that names one, rows with a CRS beside a record that names none, rows assigned to the cells after they lost the record (written to a file and read back, say) and summarised with cells_sf set to the cells that carry it, and rows given their cells by another join are placed by the polygons alone, so a row on a boundary can sit in either cell. build_tessellation() draws those cells in the CRS the record names, whatever CRS the seeds arrive in, unless its crs names another projected CRS. Cells built in another projected CRS are the nearest-centre cells of that CRS, and cells transformed to another projected CRS are joined there, so a row near a boundary, on it or not, can sit in another cell than the profile put it in. So can a row joined in longitude and latitude, as rows and cells in degrees are when the cells do not carry the record or carry one in degrees (the Voronoi cells of the scored centres that build_tessellation() returns in a geographic crs are joined in the record's CRS while they carry it), a row in cells that carry the record but are not the Voronoi cells of its centres (seeds moved, or cells edited, after the selection), and a row that reached the record's CRS by another transformation than the profile's, which can settle a tie the other way. Cells returned in a geographic crs are moved back to the record's CRS for that join, and for a layer wider than a UTM zone the round trip can move a corner by more than the margin of assign_features_to_polygons(), so a row on an edge there can sit in another cell too. The comparison then reports "differ", with what = "loo" when it finds the same rows in the same number of cells with another leave-one-out error, and the warning names these cases. The summary's own numbers describe the cells as assigned.

The comparison uses the fit of the pooled columns when that is a fit of the estimate the profile scored, and fits the response once more otherwise. Without the FNN package that fit compares every pair of cell centroids (pooled values) or, for each row alone in its cell, every other location (plain means), and above options(spatialkit.exact_pairs_max = ) pairs it is not made ("not checked: work limit"). A summary is not compared when neither layer carries the record: attr(x, "count_rule") <- NULL on the assigned layer and on cells_sf removes it.

Output columns

One row per cell, with these columns in this order:

cell_weight is the effective sample size of the primary variable: the response when one was supplied, otherwise the first predictor. It counts that variable's non-missing rows, not all rows (a cell of 10 rows with 3 finite responses carries 3 observations' worth of information about the response), and it is divided by that cell's design effect when deff applied one. With deff = 1 and no missing values it equals n. Pass it as the weights argument of a downstream regression.

An infinite value (Inf, -Inf) in a response or predictor column is treated as missing, as NA and NaN are, in every statistic of that column: the agg_funs results, ⁠..sd_*⁠, ⁠..se_*⁠, the interval columns, ⁠..neff_*⁠, cell_weight and the design effect. n still counts the row. A warning of class "spatialkit_nonfinite" names the columns and gives the number of rows and cells affected (the condition carries n and columns). kriging_adequacy(), resolution_profile(), estimate_sac_range() and prep_model_data() leave such rows out too, so the steps of one pipeline agree on a cell's mean. A function in agg_funs therefore never sees an infinite value: max returns the largest finite value, and infinities cannot be counted through agg_funs.

⁠..sd_*⁠ is the standard deviation of the cell's values in the units of the column, at any size. Where the raw squares overflow or lose their bits (a standard deviation that is not finite or is below 1e-150), it is taken on the values centred on their median and divided by powers of two, which keeps their spread. A cell whose standard deviation is beyond the largest double (about 1.8e308) has ⁠..sd_*⁠ of Inf and standard errors and interval of NA, with a warning of class "spatialkit_sd_overflow" (the condition carries columns and cells, the number of such cells of each column).

Pooled values

With estimate = "pooled" every numeric column also gets a pooled value. That is the default; estimate = "mean" leaves the pooled columns out. A cell's value, plain or pooled, estimates the cell's true mean: the expected value of one further observation located in the cell the way its observations were. It is not the average of a surface over the cell's area, which would give weight to ground that holds no observation.

For one column, write n, S and m = S / n for the count, the sum and the mean of a cell's rows, N for the rows in all and K for the cells that hold one. Then

The own weight is the share of the pooled value that is the cell's own mean. It grows with the cell's count and with tau2. At 1 the pooled value is the plain mean; at 0 it is the target and holds none of the cell's own values. Pooled values are for maps and for predicting observations. ⁠..pooled_w_*⁠ is not a regression weight. The plain columns are the same under either estimate, and they are the ones to use, with cell_weight, in a regression on cell values: each column is pulled toward its neighbours by its own amount, so a regression of pooled responses on pooled predictors is not a regression of the true means.

The cells can be any polygons the rows were assigned to, the package's own or ones the caller brings, with IDs of any type: only each row's cell and location are read. Each column is pooled on its own rows, those with a value, a cell and a location, with its own centroids, neighbours, sigma2 and tau2; a missing value in one column changes nothing in another. A cell with one such row gets a value. A cell with none gets NA, never a value made from its neighbours. The pooled columns do not read agg_funs or deff: the mean that is pooled is the arithmetic mean whatever agg_funs computes, and no design effect enters sigma2, tau2, the weights or the interval of obs_level.

Three cases change what the numbers rest on, and each is a warning (see "Conditions"). With 2 to 9 cells the neighbours of a cell are all the others, so its target is the mean of every row outside it, and the overall mean lies between that target and the cell's own mean. A cell whose own weight is below its share of the rows, n / N, then gets a pooled value on the far side of the overall mean from its plain mean, and two cells can change order. When few cells hold two rows, sigma2 is estimated from few values and every weight rests on it: df in attr(, "pooled") is the number of values beyond one per cell. And when tau2 comes out at 0, every own weight is 0 and each pooled value is its target; with two cells that is the other cell's mean, so the two values change places.

Two candidate neighbours are a tie when their squared distances differ by no more than one part in ten million. A tie goes to the centroid with the lower x, then the lower y, coordinates within that part of the distance counting as equal, and then to the cell whose ID sorts first. The centroids are summed with the rows in coordinate order, so a cell's neighbours do not depend on the order of the rows, and on gridded locations they do not depend on the unit or the origin of the coordinates either. The values agree to rounding under another order of the rows, since a cell's sums are taken in the order of its rows, and under another unit or origin where three to eight cells' centroids coincide, since the rounding then sets the order in which a cell's neighbours on that point are summed. A cell whose centroid shares its point with as many other cells as it has neighbours, or more, takes its neighbours from them, the first by ID, without a search. Centroids count as one point there when they are equal, or when they lie within a ten-millionth of the largest coordinate of one another, in x and in y. Where other centroids that close to them chain on further than that, the chain is taken again at half that reach, and so on, until its parts span no more than the reach they were taken at. So those cells keep their neighbours and their values in another unit, and with the origin moved by little against the coordinates. On such a point, cells whose centroids lie that close without coinciding take each other by ID as well, not by distance. The reach follows the largest coordinate, so with the origin moved far, to the corner of the data say, such centroids can lie beyond it, and their cells then take the nearest. Distances are measured in the CRS named under estimate, so the same layer in another projection can still give a cell other neighbours, and so can a lattice whose spacing is below about a ten-millionth of its coordinates.

structured in attr(, "pooled") says whether these cells predict a left-out observation better than one mean for all rows. It is FALSE when the leave-one-out error of one mean (loo_one_cell) is within 2 percent of that of the pooled values (loo) or below it, or when the F test of the cell means against one mean has p >= 0.05 (structure_p). FALSE raises a warning of class "spatialkit_no_structure", and the values are returned. On a response without spatial structure they still make a smooth map: the own weights are small, so each pooled value lies close to the mean of its neighbours ("How this was checked" gives the figures).

The pooling model implies an error variance for a pooled value as an estimate of the cell's true mean, (1 - w) * tau2. It is not returned, and neither is an interval for the true mean, because no check has confirmed an interval built from it; sigma2, tau2 and ⁠..pooled_w_*⁠ are in the result for a reader who wants to form it. Away from the observations that variance is too small ("How this was checked").

Beside a sharp boundary the pooled value can be further from a cell's true mean than the plain mean, because its target takes in cells across the boundary.

Intervals: which one answers which question

Two families of interval columns can be in the frame. Each has its own argument, and neither changes the other.

Family Columns Target Centre Asked for by
observation ⁠..obs_lo_*⁠, ⁠..obs_hi_*⁠ one further observation in the cell pooled value obs_level
mean ⁠..ci_lo_*⁠, ⁠..ci_hi_*⁠ a mean, never one observation plain mean conf_level

The observation of the first is one located in the cell the way the data's were. obs_level needs estimate = "pooled": without it the call is an error, not an interval round the plain mean. The mean the second covers follows deff: at deff = 1 the cell's own mean, when its observations are spread through the cell; under deff = "kish", "variogram" or a number other than 1 the cell mean as an estimate of the population mean (see "Confidence intervals", which also describes ⁠..neff_*⁠ and ⁠..df_*⁠). No interval and no standard error is returned for a cell's true mean as the pooled value estimates it. attr(, "intervals") says the same of the frame in hand, one row per family present.

The interval for one observation is the pooled value plus two quantiles of the leave-one-out residuals of the pooled values. The residual e of a row is its value minus the pooled value of its cell computed without it: the cell's mean and own weight are computed again without the row, and sigma2, tau2 and the targets are held. With p = (1 - obs_level) / 2, ..obs_lo = pooled + quantile(e, p) and ..obs_hi = pooled + quantile(e, 1 - p).

cell_values_at() returns each location's distance from the nearest observation, and its help gives the coverage by that distance.

Away from the observations no interval here is calibrated.

Standard errors and design effects

What the ⁠..se_*⁠ columns estimate follows deff. At the default, deff = 1, sd / sqrt(n) is the standard error of the cell's own mean, the mean of the units the cell holds, and it is the right one when the cell's observations are spread through the cell. Under deff = "kish", "variogram" or a number other than 1 the columns are the standard error of the cell mean as an estimate of the population (grand) mean: the unconditional quantity, in which the cell's own realised deviation is part of the error, widened for the correlation inside the cell. That is the right quantity when cells are treated as samples from a common population.

Spatially autocorrelated observations in one cell are positively correlated: they share the cell's departure from the population mean. As an estimate of the population mean, a cell mean then has an effective sample size smaller than n, and the naive standard error is too small. A downstream weighted regression that uses cell_weight or the ⁠..se_*⁠ columns for population-level inference then gives overconfident standard errors for cells with strong within-cell correlation.

The corrected standard error is not that of the cell's own mean (the block average over that cell), which is what a cell-level map or a regression on cell values usually wants. For that quantity the naive sd / sqrt(n) is the better of the two on offer. Under exchangeable within-cell correlation it is exact, and the design-effect-corrected SE is too wide by the factor sqrt(deff / (1 - rho)) (4.6 at 20 points a cell and rho = 0.5). Under a spatial covariance model it holds only when the cell's points are spread through the cell; with clustered sampling inside a cell it is too small for the block average too, and the right quantity there is the plain mean's error variance under a variogram, plain_var in kriging_adequacy(). Use deff when the cell means feed a population-level inference; leave it at 1 when they are measurements of the cells themselves and the sampling within cells is close to uniform.

deff = "kish" applies Kish's design effect. An intra-class correlation (ICC) is estimated for every summarised column on its own, the response and each predictor, by a one-way random-effects decomposition across all cells, and each column's ICC is used for that column alone: listing or removing a predictor leaves every other column's standard error, effective n and interval as they were. Each cell's effective sample size is n_i / (1 + (n_i - 1) * rho). This first-order correction needs no spatial covariance model, but it needs enough cells and observations for a stable ICC. A column whose ICC cannot be estimated at all gets NA standard errors (see deff).

deff = "variogram" fits or accepts one correlation function and applies it to every numeric column, because a variogram is a property of the field being modelled rather than of a variable type; a predictor whose spatial structure differs from the response's has its SE corrected by the response's correlation. When that variogram finds no spatial structure (the pure nugget estimate_sac_range() returns with that verdict), every column gets a design effect of 1, the predictors included, and a warning of class "spatialkit_deff_no_structure" names the predictor columns: the verdict is about the variable the variogram was fitted to, not about them. The internally estimated variogram is fitted to the response itself, never to OLS residuals, whatever predictor_vars holds: the ⁠..se_resp_*⁠ columns estimate the grand mean of the response, so the correlation to correct for is the response's own. A residual variogram holds only the correlation of the part the predictors do not explain, which is weaker. Pass sac explicitly for a different variogram, such as a residual one from estimate_sac_range(..., predictor_vars = ). A sac whose attr(sac, "detrended") is TRUE is used as given, but when it corrects response columns a warning says that their standard errors are understated, as kriging_adequacy() warns about the same mismatch.

A design effect estimated from the data ("kish" or "variogram") comes with a second, small-sample correction. The within-cell correlation that inflates the variance of the mean to sigma^2 * deff / n also biases the within-cell sample variance downward: under exchangeable correlation rho (Kish's own assumption), with deff = 1 + (n - 1) * rho, E[s^2] = sigma^2 * (n - deff) / (n - 1), so s^2 understates sigma^2 by very nearly the factor by which deff inflates the mean's variance, and the two errors compound. The standard error is therefore s * sqrt(deff / n) * sqrt((n - 1) / (n - deff)), and NA where deff >= n (the cell then holds one observation's worth of information and s carries none about sigma). This is the package's own derivation, not taken from a reference.

A fixed numeric design effect (deff = 2, say) inflates the standard errors uniformly: it is applied as sd * sqrt(deff / n), exactly sqrt(deff) times the naive SE in every cell. The E[s^2] correction of the estimated design effects is derived from within-cell correlation, and is not applied to a number the caller chose.

Even with these corrections the adjusted SE is an approximation. For inference under spatial dependence, fit an explicit spatial covariance model, such as fit_bayesian_spatial_model().

Confidence intervals

With conf_level set, every numeric response and predictor column gains four more columns: ⁠..neff_*⁠, that column's effective sample size in the cell (its non-missing count over its design effect, the per-column version of cell_weight); ⁠..df_*⁠, the degrees of freedom the interval uses; and ⁠..ci_lo_*⁠ / ⁠..ci_hi_*⁠, a t interval for a mean. Which mean follows deff, as for ⁠..se_*⁠: at the default, deff = 1, the cell's own mean, when its observations are spread through the cell; under deff = "kish", "variogram" or a number other than 1, the cell mean as an estimate of the population (grand) mean. "Standard errors and design effects" applies to it, including that the corrected interval is not one for the cell's own block average. The interval is ⁠mean +/- qt((1 + conf_level) / 2, df) * se⁠, centred on the plain mean of the column's non-missing values whatever agg_funs computes, and is NA wherever the standard error is (a single observation; complete redundancy under deff). ⁠..neff_*⁠ and ⁠..df_*⁠ are NA where the column has one non-missing value or none, like the standard error; cell_weight still counts such a cell (1, or 1 / deff for a numeric deff), so the two differ there.

At no setting is ⁠..ci_*⁠ a range for one observation: it is an interval for a mean, and it narrows as a cell's count grows where the spread of single observations does not. The interval for one further observation in a cell has its own argument and columns, obs_level with estimate = "pooled" and ⁠..obs_lo_*⁠ / ⁠..obs_hi_*⁠ (see "Intervals: which one answers which question"). Away from the observations no interval here is calibrated.

The degrees of freedom are not neff - 1. The interval's spread comes from the within-cell sample variance, and under exchangeable correlation (deff = "kish") that variance keeps its n - 1 degrees of freedom whatever the design effect. The design effect inflates the mean's variance and biases s^2, both of which the standard error already corrects, and the resulting pivot is exactly t on n - 1 df. The effective-sample-size degrees of freedom of Faes et al. (2009) belong to a mean estimated across many correlated units whose variance is estimated from the spread between them; they do not transfer to a single cell's mean with a variance estimated from inside it. ⁠..df_*⁠ is therefore n - 1 at deff = 1, for a numeric deff and for "kish". Under deff = "variogram" correlation decays with distance and the within-cell variance loses degrees of freedom to it; ⁠..df_*⁠ is then the Satterthwaite (1946) moment-matched df of s^2 under the fitted correlation matrix, a fraction of n - 1 that shrinks as the range grows. The interval is only as good as the design effect under it: a mis-specified variogram, or an ICC estimated from too few cells, moves the coverage with it.

Conditions

What the pooled columns and the count record have to say is raised as R warnings with a class, so ⁠tryCatch(<class> = )⁠ and withCallingHandlers() catch each without matching its text. A warning of the pooled columns is raised once per call and reason, for all the columns it applies to: its text names them and the condition carries them in columns, in the order of the pooled columns. A field said to be by column is a vector named by those columns, and the numbers of each column are in attr(, "pooled").

The two about few cells and few values are raised for columns whose weights were estimated, and the two of obs_level for columns whose interval is read from residuals, so a constant column raises "spatialkit_pool_degenerate" and no other.

How this was checked

The figures on this page that describe pooled values and the two intervals come from one simulation, dev/sim-pooled-values.R in the package's GitHub repository, whose header holds its settings and seeds. It draws 200 layers on a square of side 1,000. Each has 2,100 clustered locations (four fifths of them round 25 parent points with a standard deviation of 40, the rest uniform) and a response that is a field with covariance exp(-d / 100) plus noise of variance 0.3. The 300 locations nearest a random centre are held out as a block, 300 of the others are held out at random, and the 1,500 left are the layer: 333 cells at 4.5 observations a cell from resolution_profile() with partition = "density", select_resolution(criterion = "size"), get_voronoi_seeds(), build_tessellation() and assign_features_to_polygons(), summarised with estimate = "pooled". A held-out observation is given the value of its cell by cell_values_at().

At the observations held out at random the root mean squared error of the pooled value was 0.96 of the plain mean's: 0.84 in cells that hold one of the layer's observations, 0.95 in cells of 2 to 4, 0.98 in cells of 5 to 9 and 0.99 in cells of 10 or more. In the held-out block it was 0.95.

The interval at obs_level = 0.90 held 89.6 percent of the observations held out at random among the others (83.7 to 94.0 percent in single layers) and 75.1 percent of those in the held-out block. ⁠..ci_*⁠ at conf_level = 0.90, read as a range for one observation, held 58.9 and 49.2 percent of them, over the held-out observations whose cell has that interval.

With a cell's true mean taken as the mean of the noise-free field over further locations drawn in it like the data's, the squared error of the pooled value was 0.98 of (1 - w) * tau2 among the observations and 6.9 times it in the held-out block.

With white noise as the response on the simulation's 200 layers the median own weight was 0.11, tau2 was 0 on 20 layers, the warning of class "spatialkit_no_structure" was raised on all 200, and a cell's pooled value had a correlation of 0.79 with the mean of the pooled values of its 8 nearest cells, where the plain means had one of -0.02.

References

Faes, C., Molenberghs, G., Aerts, M., Verbeke, G. and Kenward, M. G. (2009). The effective sample size and an alternative small-sample degrees-of-freedom method. The American Statistician, 63(4), 389–399. doi:10.1198/tast.2009.08196

Satterthwaite, F. E. (1946). An approximate distribution of estimates of variance components. Biometrics Bulletin, 2(6), 110–114. doi:10.2307/3002019

See Also

assign_features_to_polygons(), which produces the input layer; build_tessellation() for the cells themselves.

Other assign and summarise: assign_features_to_polygons(), cell_values_at(), kriging_adequacy()

Examples

library(sf)
set.seed(1)
n <- 200
east  <- runif(n, 0, 100)
north <- runif(n, 0, 100)
# A response with spatial structure, so the within-cell ICC is not zero.
pts <- st_as_sf(
  data.frame(x = 5e5 + east, y = 5e6 + north,
             val = 5 + 0.02 * east + 0.02 * north + rnorm(n, sd = 0.5)),
  coords = c("x", "y"), crs = 32632
)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
  c(5e5, 5e6), c(5e5 + 100, 5e6), c(5e5 + 100, 5e6 + 100),
  c(5e5, 5e6 + 100), c(5e5, 5e6)
))), crs = 32632))
grid <- create_grid_polygons(bnd, target_cells = 9, type = "square")
assigned <- assign_features_to_polygons(pts, grid)

# Nine cells are too few for pooled values (each would be pulled toward
# all the other cells), so these summaries report plain means alone:
# estimate = "mean".
# IID standard errors (default) against the Kish design effect.  The Kish
# correction is large here: about 22 points per cell that share the cell's
# part of the trend carry far fewer than 22 independent pieces of
# information about the cell mean.
naive <- summarize_by_cell(assigned, response_var = "val", estimate = "mean")
kish  <- summarize_by_cell(assigned, response_var = "val", deff = "kish",
                           estimate = "mean")
data.frame(n = naive$n,
           se_naive = naive$..se_resp_val,
           se_kish  = kish$..se_resp_val)
attr(kish, "deff_applied")   # method, icc_resp, icc_pred, per-cell deff

# A 95% interval for each cell mean as an estimate of the grand mean, on
# the Kish-corrected standard error and n - 1 degrees of freedom.
ci <- summarize_by_cell(assigned, response_var = "val", deff = "kish",
                        conf_level = 0.95, estimate = "mean")
ci[, c("poly_id", "n", "resp_mean_val", "..neff_resp_val", "..df_resp_val",
       "..ci_lo_resp_val", "..ci_hi_resp_val")]

# Pooled values, and a range for one observation: a smooth field plus
# noise at 400 points, on an 8 x 8 grid, so that a cell holds about six.
set.seed(2)
east  <- runif(400, 0, 8000)
north <- runif(400, 0, 8000)
pts2 <- st_as_sf(
  data.frame(x = 5e5 + east, y = 5e6 + north,
             val = 10 + 3 * sin(east / 1500) + 3 * cos(north / 1200) +
               rnorm(400)),
  coords = c("x", "y"), crs = 32632
)
bnd2 <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
  c(5e5, 5e6), c(5e5 + 8000, 5e6), c(5e5 + 8000, 5e6 + 8000),
  c(5e5, 5e6 + 8000), c(5e5, 5e6)
))), crs = 32632))
grid2 <- create_grid_polygons(bnd2, target_cells = 64, type = "square")
assigned2 <- assign_features_to_polygons(pts2, grid2)
# estimate = "pooled" is the default.
pooled <- summarize_by_cell(assigned2, response_var = "val", obs_level = 0.90)
# The plain mean, the pooled value and the weight on the cell's own mean.
head(pooled[, c("poly_id", "n", "resp_mean_val", "..pooled_resp_val",
                "..pooled_w_resp_val")])
# The range for one further observation in a cell.
head(pooled[, c("poly_id", "..obs_lo_resp_val", "..obs_hi_resp_val")])
attr(pooled, "pooled")   # what was fitted, and what the interval covers

Compare every criterion's pick on a resolution profile

Description

select_resolution() reads one criterion at a time. This puts the count criteria in one table: the level each prefers, the flat region around it, and whether a ladder bound is doing the choosing rather than the criterion. The closing line gives the levels that lie in every flat region, the cell counts no criterion objects to.

Usage

## S3 method for class 'resolution_profile'
summary(object, criteria = NULL, tol = 0.02, ...)

Arguments

object

A resolution_profile().

criteria

Character vector, any of "cp", "reliability", "elbow", "moran_z", "loo". Default: every one of "cp", "reliability", "elbow" and "loo" that is finite at some level (loo is a column of a profile built with estimate; a column of that name on a profile built without one is read only when named here). "moran_z", a diagnostic, is read only when named here. "size" and "auto" are not criteria of the table: a size sets the count and has no flat region to compare.

tol

Passed to select_resolution() for the flat region. Default 0.02.

...

Ignored.

Details

Read the table with what each criterion returns in mind (see resolution_profile()): reliability is read at or above the range floor and often returns it, elbow is absent unless the points cluster, and cp's optimum is often the support ceiling. moran_z is a diagnostic of the cell means and not a count rule, so it is not in the default set; named in criteria it gets a row, and it is left out of the closing comparison.

The criterion curves are not monotone, so a flat region can skip rungs of the ladder, and the table lists the levels it accepts ("26, 31") rather than a range ("26 to 31") that would include the levels it rejected.

The levels common to every flat region are often none. The criteria answer different questions: how well the cells represent the field (C_p), whether the cell values are distinguishable from noise (reliability), and where the within-cluster sum of squares bends (elbow). An empty set means the criteria favour different counts, and the print gives the spread between the picks.

A flat region can be wide, and the choice within it is the analyst's; plot.resolution_profile() draws the curves the regions were read from.

A profile whose ladder is one size (obs_per_cell set to one number, or the default profile) has one level, and the size set it. The table then has one row per criterion that is finite at that level, and the line under it says that the count is set by the size and that no criterion chooses among levels. The result carries the size as attr(, "obs_per_cell").

Value

A data.frame of class resolution_summary, one row per criterion in the order given, with columns criterion, best, flat_min, flat_max, n_flat, value (the optimum itself, on that criterion's own scale and so not comparable across rows, which is why the print method leaves it out), at_floor, at_ceiling, edge (which bound an edge optimum sits on, as select_resolution() reports it; NA when interior) and structured (as select_resolution() reports it: FALSE for a cp that one cell matches, and where the cells beat one cell but the F test does not tell their means from one mean or, for cp, the profile's variogram found no spatial structure). Attributes: bands (a named list holding each criterion's flat region in full, since flat_min and flat_max are only its ends and the region can have holes in it), common (the levels in every flat region of the count criteria, moran_z left out; an integer vector that is empty when the regions do not overlap), scored (the levels each criterion returned a finite value at, which is what decides whether a gap in a flat region is a rejection or a level nothing was computed at), ladder (every level on the profile), n_levels, tol and variable (what the criteria were scored on), and, only when some row has structured FALSE although its cells beat one cell by more than tol, not_identified (a character vector named by criterion that says why: the F test, or for cp the profile's variogram). The print method recomputes the closing comparison from bands, so a row subset of the result prints its own comparison.

See Also

select_resolution() for one criterion, with the per-level values attached; plot.resolution_profile() for the curves behind these flat regions.

Other resolution: determine_optimal_levels(), plot.resolution_profile(), resolution_profile(), select_resolution()

Examples


library(sf)
# An exponential field with range parameter 200 (true effective range
# 600 m) on a 1 km square, with a nugget of 0.6 on a unit sill.
set.seed(4)
n <- 400
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 / 200) + diag(0.6, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
prof <- resolution_profile(pts, response_var = "z", n_levels = 12,
                           estimate = NULL)

s <- summary(prof)
s
attr(s, "common")   # the levels every flat region accepts, if any
attr(s, "bands")    # each criterion's flat region in full


Summarise a fitted model

Description

Computes goodness-of-fit metrics from fitted(object) against the observed response, and prints them with what they are to be read against. A character or factor response is an error; a logical response is scored as 0/1.

Usage

## S3 method for class 'spatial_fit'
summary(object, ...)

Arguments

object

A spatial_fit object.

...

Not used.

Value

An object of class summary.spatial_fit: a list with class, formula, n, response_var, predictor_vars, info and in_sample (the metric data.frame, out-of-bag for an rf_fit).

What the metrics are computed on

For a GWR or a Bayesian GP fit these are in-sample metrics: fitted() returns values computed at the training locations from the model that saw them. For a random forest they are out-of-bag, because fitted() on an rf_fit returns out-of-bag predictions (see fit_rf_model()). The two are not comparable, and print() on the result says which one it holds, from $info$fitted_are_oob. Use compare_models_cv() to compare backends.

Adjusted R^2 is not computed: a GWR's effective number of parameters far exceeds the global predictor count, and a GP model has no simple p.

For a GWR, print() on the result adds what the in-sample metrics are to be read against: the effective number of parameters and residual degrees of freedom, the number of local windows of deficient rank, the number of locations when observations share one, and the AICc and RMSE of one global least-squares regression on the same rows beside the fit's own AICc ($info$global_ols; see fit_gwr_model()).

MAPE and SMAPE skip rows whose denominator is zero; n_MAPE and n_SMAPE count the rows they used (see "Percentage errors on responses with zeros" in model_metrics()).

See Also

model_metrics() for the metrics alone, and on new data.

Other fit methods: plot.spatial_fit(), print.spatial_fit(), spatial_fit-coef, spatial_fit-fitted, spatial_fit-predict, spatial_fit-residuals

Examples


library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(60, 0, 1000), y = 5e6 + runif(60, 0, 1000),
             a = rnorm(60)),
  coords = c("x", "y"), crs = 32632
)
pts$z <- 10 + 2 * pts$a + rnorm(60, 0, 0.3)
fit <- fit_rf_model(pts, "z", "a", num_trees = 50, seed = 1)
summary(fit)            # out-of-bag metrics for a forest


Place seeds at k-means cluster centres

Description

Places k seed points at k-means cluster centres of the observed coordinates, so seeds (and the Voronoi cells built from them) follow the sampling density: clusters of observations attract seeds, empty ground gets none. Use it when the cells should follow the data. With the default density kind the cells hold similar numbers of observations once there are more cells than clusters of points, which keeps per-cell aggregates in summarize_by_cell() from resting on one or two observations. Plain k-means (partition = "kmeans") minimises the spread of points around each centre and does not even out the counts. Use voronoi_seeds_random() instead when you want coverage of the study area rather than of the data, and get_voronoi_seeds() to pick between them by name.

Usage

voronoi_seeds_kmeans(
  points_sf,
  k,
  set_seed = 456,
  nstart = NULL,
  partition = c("density", "kmeans"),
  init = NULL,
  density_power = 1,
  density_k = 8,
  iter_max = NULL
)

Arguments

points_sf

An sf object with POINT geometries. Points that mix XY and XYZ (or XYM) are read without Z and M before they are projected or clustered, since sf reads a layer in the dimension of its first geometry.

k

Integer; requested number of clusters, treated as an upper bound only. It is clamped, with a warning, to whichever is smaller of the number of distinct point positions and one fewer than the number of points with a location (rows without one are dropped first), and not below 1, because k-means can produce neither more centres than there are distinct points nor as many centres as there are rows. Check nrow() on the result. A select_resolution() result or a resolution_profile() is also accepted: its scored centres are returned when it carries them, whatever partition, init and density settings the call names (see n in get_voronoi_seeds() for which arguments a call is taken to name), and otherwise its count is used. A profile is read as get_voronoi_seeds() reads one passed as n: by cp when it was built without an estimate, and by select_resolution(criterion = "auto") when it was built with one (a size for pooled values, the lowest leave-one-out error for plain means). Such a count raises the warnings and the error described under n in get_voronoi_seeds() (classes "spatialkit_bound_chosen", "spatialkit_no_structure" and "spatialkit_no_default_criterion").

set_seed

Optional integer RNG seed. Default 456, so a call gives the same seeds every time whatever the session's random-number state; an outer set.seed() does not change them, and the caller's random-number stream is left as it was. Pass NULL to draw the k-means starts from the session's stream instead (the default of get_voronoi_seeds()).

nstart

The number of starts, of which the best is kept. NULL (default) uses 3 starts for partition = "density" and 10 for partition = "kmeans". A number is run under either kind and either init.

partition

What the seeds minimise. "density" (default): the sum of squared distances from the points to their nearest seed, each point weighted by its local density to the power density_power; compact cells that, at the default power, hold about the same number of points each once k is above the number of dense places, and counts about as uneven as "kmeans" gives below that. "kmeans": the same sum unweighted; compact cells whose counts are several times higher in dense places than in sparse ones. It is stats::kmeans() from 10 random starts on the rows as they come, with the coordinates centred, divided by the diagonal of their bounding box and rounded to 2^-30 of it, so that the seeds do not move with the unit or the origin; where the locations span less than a kilometre a change of unit or origin can still move them (see "The partition" in resolution_profile()). Without the FNN package the density kind finds its weights by comparing every pair of distinct locations, so its time grows with the square of their number; the seeds are the same, and nothing stops the call. See "Details".

init

How each start is drawn: "random" (k distinct locations at random, as stats::kmeans() draws them) or "kmeans++" (the seeds one at a time, each in proportion to its squared distance from those already drawn, times its weight under partition = "density"). NULL (default) is each kind's own rule: "random" for partition = "kmeans" and "kmeans++" for partition = "density". Under partition = "kmeans" from random starts the points are clustered in the order their rows come in; with init = "kmeans++", and under partition = "density", the rows are put in coordinate order first, so the seeds do not depend on their order.

density_power

For partition = "density": the power the local density is raised to for a point's weight, from 0 to 2. Default 1, which evens out the cell counts once the cells outnumber the dense places; 0 weights every point alike, and values above 1 give the cells of dense places fewer points than those of sparse places. Setting it under partition = "kmeans" is a warning.

density_k

For partition = "density": the number of nearest neighbours the local density is read from. Default 8.

iter_max

The most iterations a start runs for: a single positive whole number, or NULL (default) for the kind's own limit, 50 for partition = "kmeans" and 100 steps of Lloyd's iteration for partition = "density". Under partition = "density", and with init = "kmeans++", a kept start that was cut off at the limit is a warning of class "spatialkit_not_converged"; partition = "kmeans" from random starts keeps the warning stats::kmeans() gives.

Details

Lon/lat input is projected first so the k-means distances are metric and not degrees; so is input with no CRS whose coordinates look like lon/lat (the heuristic ensure_projected() applies, with its warning), and the seeds come back in the input's own coordinates. Rows without a location (an empty point, a coordinate that is not finite or lies beyond 1e150, or in a geographic CRS a latitude beyond 90 degrees, read as given before the projection) are dropped with a warning, and k is clamped to the number of distinct positions or one fewer than the number of points, whichever is smaller, and not below 1.

A count given as a number gets a fresh partition, which is not the partition resolution_profile() or determine_optimal_levels() scored that count on: those fit their own run, the profile to every row or to a subsample, and keep the best of their own starts. Pass the select_resolution() result or the profile itself as k to get the scored one: the centres of the scored partition are then returned (in the CRS of points_sf, with attr(, "n_from")), and no k-means is run. On a profile without an estimate whose centres were fitted to a subsample, they are those centres refitted to every point by select_resolution(), with attr(, "refit").

partition says what the seeds minimise. "kmeans" is the sum of squared distances from the points to their nearest seed, from nstart random starts by stats::kmeans() (Hartigan-Wong) unless init says otherwise. The seeds follow the square root of the point density, so the cells are compact, smaller where the points are dense, and a cell in a dense place still holds several times the points of a cell in a sparse place. "density" weights each point by its local density (the number of points in the disc that reaches its density_k-th nearest neighbour, over the disc's area) to the power density_power, and is the default. At the default power of 1 the seeds follow the point density itself, and the cells are compact: many small cells where the points are dense, a few large ones where they are sparse. They hold about the same number of points each once k is above the number of dense places (clusters of points). With fewer cells than that a cell takes in whole clusters, large and small, and the counts are about as uneven as under "kmeans". The density kind is the best of nstart starts, each refined by at most 100 steps of Lloyd's iteration (iter_max sets another limit, and a kept start that was cut off at the limit is a warning of class "spatialkit_not_converged"); it does not depend on the order of the rows or on the unit of the coordinates, and points at one location share a cell. A seed can end with no point at counts from about a fifth of the points up, mostly from init = "random"; that is a warning of class "spatialkit_empty_cells". "The partition" in resolution_profile() gives the details and a comparison of the two kinds.

The centres lie inside the points, so their own hull is smaller than the data's. The result carries the convex hull of points_sf as attr(, "cover"), and build_tessellation() clips the cells to that hull (grown by 2 percent of its diagonal) when no boundary is passed, so every point of points_sf falls in a cell.

Value

An sf object of at most k cluster-centre POINTs (fewer when k is clamped, see k), with seed_id and method = "kmeans" columns matching get_voronoi_seeds(), and attr(, "cover"), the convex hull of the coordinates of points_sf (an sfc in its CRS): for lon/lat points, the hull in degrees, with the longitudes of points on both sides of 180 degrees taken from 0 to 360 (-170 as 190). Seeds placed with partition = "density" or init = "kmeans++", and the scored centres of a profile of the density kind or from random starts, also carry attr(, "partition"): a list with kind, init, density_power and density_k, and for seeds this call placed iter, iter_max and converged (the iterations the kept start took, the limit, and whether it stopped before the limit). build_tessellation() returns the list as params$partition. Seeds with no such record are plain k-means: from random starts when this call placed them, or the scored centres of a k-means profile from k-means++ starts. When k is a select_resolution() result that carries count_rule, or a profile built with an estimate or read by cp, the seeds carry that record as attr(, "count_rule"), with scored_cells TRUE for the scored centres and FALSE for refitted centres and for centres this call fits itself at that count (see get_voronoi_seeds()).

See Also

Other cell building: build_tessellation(), clip_target_for(), create_grid_polygons(), create_grid_polygons_cached(), create_voronoi_polygons(), ensure_stable_poly_id(), get_voronoi_seeds(), plot_tessellation_map(), voronoi_seeds_random()

Examples

library(sf)
set.seed(1)
pts <- st_as_sf(
  data.frame(x = 5e5 + runif(100, 0, 1000), y = 5e6 + runif(100, 0, 1000)),
  coords = c("x", "y"), crs = 32632
)
seeds <- voronoi_seeds_kmeans(pts, k = 8)   # density-weighted, 3 starts
nrow(seeds)   # at most 8: one seed per non-empty cluster
seeds         # the cluster centres, as an sf POINT layer in the points' CRS
# Plain k-means from 10 random starts.
voronoi_seeds_kmeans(pts, k = 8, partition = "kmeans")

Place seeds at random inside a boundary

Description

Draws k seed points uniformly at random inside boundary, ignoring where the observations are. Reach for this when the cells should cover the study area evenly (so that sparsely sampled ground still gets its own cells and is visibly under-sampled in the results) instead of concentrating resolution where the data already are, which is what voronoi_seeds_kmeans() does. It also suits a null or sensitivity comparison: rerunning an analysis over several random seedings shows how much of a result depends on one tessellation.

Usage

voronoi_seeds_random(boundary, k, set_seed = NULL)

Arguments

boundary

An sf or sfc polygonal object, the area the seeds are drawn in. Rows without a location, rows the repair leaves without a polygon, vertices at a latitude beyond 90 and mixed dimensions are handled as "Boundaries" in spatialkit-geometry says. The seeds are drawn as "Sampling inside the boundary" in get_voronoi_seeds() describes, with k as the number of points asked for; the error for a boundary that would take too many draws says to ask for fewer seeds.

k

Integer; number of random seeds.

set_seed

Optional integer RNG seed. Default NULL: the seeds are drawn from the session's random-number stream, so consecutive calls give different seedings and set.seed() before a call makes it reproducible. Pass a number to get the same seeds whatever that stream holds; the caller's stream is then left as it was.

Details

Seeds are drawn uniformly inside the polygon. When a draw falls short of k it is topped up with further uniform draws from the same polygon, so the result has exactly k seeds; only a geometry that still yields too few after ten top-ups returns fewer, and that shortfall is logged.

Value

An sf object of k random POINTs (fewer only in the degenerate case above), with seed_id and method = "random" columns matching get_voronoi_seeds(), and attr(, "cover"), the polygons of boundary: build_tessellation() clips the cells to it (grown by 2 percent of its diagonal) when no boundary is passed there, so the cells fill the area the seeds were drawn in and not only the seeds' own hull.

See Also

Other cell building: build_tessellation(), clip_target_for(), create_grid_polygons(), create_grid_polygons_cached(), create_voronoi_polygons(), ensure_stable_poly_id(), get_voronoi_seeds(), plot_tessellation_map(), voronoi_seeds_kmeans()

Examples

library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
  c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
set.seed(1)
seeds <- voronoi_seeds_random(bnd, k = 10)
nrow(seeds)   # 10
seeds
# Another call is another seeding; set_seed pins one.
identical(st_coordinates(voronoi_seeds_random(bnd, k = 10, set_seed = 7)),
          st_coordinates(voronoi_seeds_random(bnd, k = 10, set_seed = 7)))

These binaries (installable software) and packages are in development.
They may not be fully stable and should be used with caution. We make no claims about them.