## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 4.5,
  fig.align = "center"
)

## ----brazil-sites, fig.width=8, fig.height=5.5--------------------------------
library(letsR)
library(sf)

data("temp", package = "letsR")
data("prec", package = "letsR")
temperature_raster <- terra::unwrap(temp)
precipitation_raster <- terra::unwrap(prec)

brazil <- rnaturalearth::ne_countries(
  country = "Brazil",
  scale = "medium",
  returnclass = "sf"
)

candidate_sites <- expand.grid(
  longitude = seq(-74, -34, by = 2),
  latitude = seq(-33, 5, by = 2)
)

candidate_sf <- st_as_sf(
  candidate_sites,
  coords = c("longitude", "latitude"),
  crs = 4326
)
inside <- lengths(st_within(candidate_sf, brazil)) > 0L
candidate_sites <- candidate_sites[inside, , drop = FALSE]

# Extract the bundled WorldClim-based layers at the retained sites.
# With a SpatVector of points, the first extract() column is an ID.
candidate_points <- terra::vect(st_as_sf(
  candidate_sites,
  coords = c("longitude", "latitude"),
  crs = 4326
))
candidate_sites$temperature_raw <- terra::extract(
  temperature_raster, candidate_points
)[[2]]
candidate_sites$precipitation_mm <- terra::extract(
  precipitation_raster, candidate_points
)[[2]]

# Retain sites with valid temperature and precipitation observations.
candidate_sites <- candidate_sites[
  is.finite(candidate_sites$temperature_raw) &
    is.finite(candidate_sites$precipitation_mm),
  , drop = FALSE
]

set.seed(42)
sites <- candidate_sites[
  sample.int(nrow(candidate_sites), min(130L, nrow(candidate_sites))),
  , drop = FALSE
]
rownames(sites) <- NULL

plot(st_geometry(brazil), col = "gray96", border = "gray55",
     main = "Climate sampling locations in Brazil")
points(sites$longitude, sites$latitude,
       pch = 16, cex = 0.65, col = "steelblue4")

## ----temperature-map, fig.width=8, fig.height=5.5-----------------------------
sites$temperature_c <- sites$temperature_raw / 10

palette_temp <- grDevices::colorRampPalette(
  c("#2166AC", "#F7F7F7", "#B2182B")
)(100)
color_id <- cut(sites$temperature_c,
                breaks = 100, labels = FALSE, include.lowest = TRUE)

plot(st_geometry(brazil), col = "gray96", border = "gray55",
     main = "Mean annual temperature at sampled locations")
points(sites$longitude, sites$latitude,
       pch = 21, bg = palette_temp[color_id],
       col = "gray35", cex = 1.2)
legend("bottomleft", bty = "n", pch = 21,
       pt.bg = palette_temp[c(1, 50, 100)],
       legend = sprintf("%.1f °C", c(min(sites$temperature_c),
                                      median(sites$temperature_c),
                                      max(sites$temperature_c))),
       title = "Temperature")
summary(sites$temperature_c)

## ----distances----------------------------------------------------------------
xy <- as.matrix(sites[, c("longitude", "latitude")])

distance_m <- lets.distmat(xy, asdist = FALSE)
distance_km <- distance_m / 1000

summary(distance_km[upper.tri(distance_km)])

## ----correlogram, fig.width=7, fig.height=4.5---------------------------------
moran <- lets.correl(
  x = sites$temperature_c,
  y = distance_km,
  z = 8,
  equidistant = FALSE,
  plot = TRUE
)

round(moran, 3)

## ----uncertainty-intervals----------------------------------------------------
intervals <- data.frame(
  Distance_km = moran[, "Mean_Distance"],
  Moran_I = moran[, "Observed"],
  Lower = moran[, "Observed"] - moran[, "Confidence_Interval_(95%)"],
  Upper = moran[, "Observed"] + moran[, "Confidence_Interval_(95%)"]
)
round(intervals, 3)

## ----class-definitions, fig.width=7, fig.height=4.5---------------------------
moran_equalwidth <- lets.correl(
  x = sites$temperature_c,
  y = distance_km,
  z = 8,
  equidistant = TRUE,
  plot = FALSE
)

plot(moran[, "Mean_Distance"], moran[, "Observed"],
     type = "b", pch = 16, col = "steelblue4",
     xlab = "Distance class midpoint (km)",
     ylab = "Moran's I", bty = "l",
     ylim = range(c(moran[, "Observed"],
                    moran_equalwidth[, "Observed"])),
     main = "Alternative distance-class definitions")
lines(moran_equalwidth[, "Mean_Distance"],
      moran_equalwidth[, "Observed"],
      type = "b", pch = 17, lty = 2, col = "darkorange3")
legend("topright", bty = "n", pch = c(16, 17), lty = c(1, 2),
       col = c("steelblue4", "darkorange3"),
       legend = c("Equal pair counts (approximately)",
                  "Equal distance widths"))

## ----compare-random, fig.width=8, fig.height=4--------------------------------
set.seed(123)
sites$random_temperature_c <- sample(sites$temperature_c)

moran_random <- lets.correl(
  x = sites$random_temperature_c,
  y = distance_km,
  z = 8,
  equidistant = FALSE,
  plot = FALSE
)

op <- par(mfrow = c(1, 2), mar = c(4, 4, 3, 1))
common_ylim <- range(c(moran[, "Observed"], moran_random[, "Observed"]))

plot(moran[, "Mean_Distance"], moran[, "Observed"],
     type = "b", pch = 16, col = "steelblue4", ylim = common_ylim,
     xlab = "Distance (km)", ylab = "Moran's I", bty = "l",
     main = "Observed temperature")
abline(h = 0, lty = 2, col = "gray55")

plot(moran_random[, "Mean_Distance"], moran_random[, "Observed"],
     type = "b", pch = 16, col = "darkorange3", ylim = common_ylim,
     xlab = "Distance (km)", ylab = "Moran's I", bty = "l",
     main = "Permuted temperature")
abline(h = 0, lty = 2, col = "gray55")
par(op)

## ----multiple-variables, fig.width=7, fig.height=4.5--------------------------
climate_variables <- scale(cbind(
  Temperature = sites$temperature_c,
  Precipitation = sites$precipitation_mm
))

moran_multi <- lets.correl(
  x = climate_variables,
  y = distance_km,
  z = 8,
  plot = TRUE
)

round(moran_multi, 3)

## ----separate-variables-------------------------------------------------------
individual_correlograms <- lapply(seq_len(ncol(climate_variables)), function(i) {
  lets.correl(
    x = climate_variables[, i],
    y = distance_km,
    z = 8,
    equidistant = TRUE,
    plot = FALSE
  )
})
names(individual_correlograms) <- colnames(climate_variables)

lapply(individual_correlograms, function(x) {
  round(x[, c("Observed", "Mean_Distance"), drop = FALSE], 3)
})

## ----phylogenetic-example, eval=FALSE-----------------------------------------
# # Load the package ape
# library(ape)
# 
# set.seed(123)
# 
# # Generate a random phylogenetic tree with 60 species
# tree <- ape::rtree(n = 60)
# 
# # Simulate a continuous trait evolving under Brownian motion
# trait <- ape::rTraitCont(
#   tree,
#   model = "BM",
#   sigma = 1
# )
# 
# # Visualize the phylogenetic tree
# plot(tree, cex = 0.5, main = "Simulated phylogeny")
# 
# # Calculate pairwise phylogenetic distances
# phylo_distance <- ape::cophenetic.phylo(tree)
# 
# # Align trait values with the distance matrix
# trait_aligned <- trait[rownames(phylo_distance)]
# 
# # Calculate phylogenetic autocorrelation
# phylo_correl <- lets.correl(
#   x = trait_aligned,
#   y = phylo_distance,
#   z = 8,
#   equidistant = FALSE,
#   plot = TRUE
# )
# 
# # Inspect the results
# print(phylo_correl)

## ----environmental-distance---------------------------------------------------
precipitation_distance <- as.matrix(
  stats::dist(matrix(sites$precipitation_mm, ncol = 1))
)

environmental_correl <- lets.correl(
  x = sites$temperature_c,
  y = precipitation_distance,
  z = 8,
  plot = TRUE
)

