## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 8,
  fig.height = 5,
  warning = FALSE,
  message = FALSE
)

## ----libraries----------------------------------------------------------------
library(letsR)
library(terra)

## ----create-attribute-spaces, fig.width=9, fig.height=3.4---------------------
set.seed(1)
sample_sizes <- c(100L, 500L, 2000L)

simulate_traits <- function(n) {
  trait_a <- rnorm(n)
  trait_b <- 0.2 * trait_a + rnorm(n)
  data.frame(
    Species = paste0("sp", seq_len(n)),
    trait_a = trait_a,
    trait_b = trait_b
  )
}

trait_samples <- lapply(sample_sizes, simulate_traits)
attr_spaces <- lapply(trait_samples, lets.attrpam, n_bins = 30)
richness_rasters <- lapply(attr_spaces, function(z) z$Attr_Richness_Raster)

op <- par(mfrow = c(1, 3), mar = c(3, 3, 3, 2))
for (i in seq_along(richness_rasters)) {
  plot(richness_rasters[[i]],
       main = paste("Observed: n =", sample_sizes[i]))
}
par(op)

## ----attribute-occupancy------------------------------------------------------
attribute_coverage <- data.frame(
  n_species = sample_sizes,
  occupied_bins = vapply(
    richness_rasters,
    function(r) sum(!is.na(terra::values(r, mat = FALSE))),
    integer(1)
  )
)
attribute_coverage$proportion_occupied <-
  attribute_coverage$occupied_bins / 30^2
print(attribute_coverage, row.names = FALSE)

## ----smooth-attribute-spaces, fig.width=9, fig.height=6.7, message=TRUE-------
smoothed_rasters <- lapply(richness_rasters, function(r) {
  lets.smooth(
    x = r,
    k_sigma = "auto",
    restrict = TRUE,
    type_hull = "convex"
  )
})

op <- par(mfrow = c(2, 3), mar = c(3, 3, 3, 2))
for (i in seq_along(richness_rasters)) {
  plot(richness_rasters[[i]],
       main = paste("Observed: n =", sample_sizes[i]))
}
for (i in seq_along(smoothed_rasters)) {
  plot(smoothed_rasters[[i]],
       main = paste("Smoothed: n =", sample_sizes[i]))
}
par(op)

## ----side-by-side-plot, eval=FALSE--------------------------------------------
# lets.smooth(
#   richness_rasters[[2]],
#   k_sigma = "auto",
#   type_hull = "convex",
#   plot_raster = TRUE
# )

## ----bandwidth-comparison, fig.width=10, fig.height=3.5-----------------------
r_sparse <- richness_rasters[[1]]
bandwidths <- c(0.75, 1.5, 3)

estimates <- lapply(bandwidths, function(k) {
  lets.smooth(
    x = r_sparse,
    k_sigma = k,
    restrict = TRUE,
    type_hull = "convex"
  )
})

op <- par(mfrow = c(1, 4), mar = c(3, 3, 3, 2))
plot(smoothed_rasters[[1]], main = "Automatic (LOOCV)")
for (i in seq_along(estimates)) {
  plot(estimates[[i]], main = paste("k_sigma =", bandwidths[i]))
}
par(op)

## ----alternative-hulls--------------------------------------------------------
# Keep the bandwidth fixed to isolate the effect of hull geometry
r_convex <- lets.smooth(
  x = r_sparse,
  k_sigma = 1.5,
  restrict = TRUE,
  type_hull = "convex"
)
r_concave <- lets.smooth(
  x = r_sparse,
  k_sigma = 1.5,
  restrict = TRUE,
  type_hull = "concave_ratio",
  param = 0.5
)

op <- par(mfrow = c(1, 2))
plot(r_convex, main = "Convex hull")
plot(r_concave, main = "Concave hull")
par(op)

## ----theoretical-environmental-space------------------------------------------
r_template <- rast(
  nrows = 31, ncols = 31,
  xmin = -3, xmax = 3,
  ymin = -3, ymax = 3,
  crs = ""
)

xy <- terra::xyFromCell(r_template, seq_len(terra::ncell(r_template)))

# Hypothetical conditional richness as a continuous environmental response
richness_true <- 2 +
  16 * exp(-((xy[, 1] + 0.65)^2 / (2 * 0.65^2) +
             (xy[, 2] - 0.25)^2 / (2 * 0.55^2))) +
  8 * exp(-((xy[, 1] - 0.8)^2 / (2 * 0.5^2) +
            (xy[, 2] + 0.6)^2 / (2 * 0.6^2)))

r_truth <- rast(r_template)
terra::values(r_truth) <- richness_true
plot(r_truth, main = "Underlying conditional richness")

## ----simulate-environmental-samples, fig.width=9, fig.height=6.7, message=TRUE----
set.seed(123)

simulate_sites <- function(n) {
  a <- rnorm(n)
  b <- 0.35 * a + sqrt(1 - 0.35^2) * rnorm(n)
  cbind(a, b)
}

survey_samples <- lapply(sample_sizes, simulate_sites)

# Each sampled environmental combination reveals its true response
observed_environmental <- lapply(survey_samples, function(sites) {
  ids <- unique(terra::cellFromXY(r_template, sites))
  ids <- ids[!is.na(ids)]
  v <- rep(NA_real_, terra::ncell(r_template))
  v[ids] <- richness_true[ids]
  out <- rast(r_template)
  terra::values(out) <- v
  out
})

estimated_environmental <- lapply(observed_environmental, function(r) {
  lets.smooth(
    x = r,
    k_sigma = "auto",
    restrict = TRUE,
    type_hull = "convex"
  )
})

op <- par(mfrow = c(2, 3), mar = c(3, 3, 3, 2))
for (i in seq_along(sample_sizes)) {
  plot(observed_environmental[[i]],
       main = paste("Observed: n =", sample_sizes[i]))
}
for (i in seq_along(sample_sizes)) {
  plot(estimated_environmental[[i]],
       main = paste("Estimated: n =", sample_sizes[i]))
}
par(op)

## ----assess-sample-size-------------------------------------------------------
assess_estimate <- function(observed, predicted, truth) {
  v_obs <- terra::values(observed, mat = FALSE)
  v_pred <- terra::values(predicted, mat = FALSE)
  v_true <- terra::values(truth, mat = FALSE)

  unsurveyed <- is.na(v_obs)
  evaluated <- unsurveyed & is.finite(v_pred)

  data.frame(
    surveyed_cells = sum(!unsurveyed),
    prediction_coverage = mean(is.finite(v_pred[unsurveyed])),
    RMSE = if (any(evaluated)) {
      sqrt(mean((v_pred[evaluated] - v_true[evaluated])^2))
    } else NA_real_,
    MAE = if (any(evaluated)) {
      mean(abs(v_pred[evaluated] - v_true[evaluated]))
    } else NA_real_
  )
}

assessment <- do.call(rbind, Map(
  assess_estimate, observed_environmental,
  estimated_environmental,
  MoreArgs = list(truth = r_truth)
))
assessment <- cbind(n_surveys = sample_sizes, assessment)
print(assessment, row.names = FALSE, digits = 3)

