## ----setup, include=FALSE-----------------------------------------------------
# Everything in this article runs on the hard dependencies. Messages and
# warnings are shown, since they are what the article is about; the log lines
# reach the document as messages while knitr runs.
knitr::opts_chunk$set(
  echo     = TRUE,
  collapse = TRUE,
  comment  = "#>",
  message  = TRUE,
  warning  = TRUE
)

## ----layer--------------------------------------------------------------------
suppressPackageStartupMessages(library(sf))
library(spatialkit)

set.seed(1)
n   <- 300
pts <- st_as_sf(data.frame(x = 5e5 + runif(n, 0, 20000),
                           y = 5e6 + runif(n, 0, 20000)),
                coords = c("x", "y"), crs = 32632)
pts$w <- rnorm(n)
pts$z <- 2 * pts$w + rnorm(n)
st_crs(pts)$units_gdal

## ----block-units--------------------------------------------------------------
# A block size of 10, meant in kilometres, on a layer in metres.
# The message is wrapped to fit the page.
tryCatch(
  make_folds(pts, k = 5, method = "block_kfold", block_size = 10),
  error = function(e) writeLines(strwrap(conditionMessage(e), 76))
)

## ----all-failed---------------------------------------------------------------
folds <- make_folds(pts, k = 5, method = "block_kfold", seed = 1)
cv <- cv_spatial(pts, "z", "w", folds = folds,
                 fit_fn = function(train) stop("the backend is not installed"))
c(attempted = cv$n_folds_attempted, succeeded = cv$n_folds_succeeded)
cv$overall

## ----parallel, eval=FALSE-----------------------------------------------------
# cv <- cv_rf(pts, "z", "w", k = 5, parallel = 4L)       # four workers
# cv <- cv_bayes(pts, "z", "w", k = 5, parallel = TRUE)  # detects the cores

## ----log-file-----------------------------------------------------------------
log_file <- file.path(tempdir(), "spatialkit_model_log.log")
# The line is wrapped to fit the page.
writeLines(strwrap(tail(readLines(log_file), 1), 76))

## ----quiet--------------------------------------------------------------------
old <- spatialkit_quiet()
spatialkit_quiet(old)

## ----appender, eval=FALSE-----------------------------------------------------
# # Write the log file to my_analysis.log (index 1)
# logger::log_appender(logger::appender_file("my_analysis.log"),
#                      namespace = "spatialkit")
# # Send the console lines to a file instead of the console (index 2)
# logger::log_appender(logger::appender_file("my_console.log"),
#                      namespace = "spatialkit", index = 2)
# # Or print only FATAL lines on the console (index 2)
# logger::log_threshold(logger::FATAL, namespace = "spatialkit", index = 2)

