## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 4.5,
  fig.align = "center"
)

# st_concave_hull() needs GEOS >= 3.11.0. If this requirement is not met,
# show the example code without running spatial operations during rendering.
geos_version <- unname(sf::sf_extSoftVersion()["GEOS"])
geos_format_ok <- length(geos_version) == 1L && !is.na(geos_version) &&
  grepl("^[0-9]+\\.[0-9]+\\.[0-9]+", geos_version)
geos_ok <- geos_format_ok &&
  utils::compareVersion(
    sub("^([0-9]+\\.[0-9]+\\.[0-9]+).*", "\\1", geos_version),
    "3.11.0"
  ) >= 0L
knitr::opts_chunk$set(eval = geos_ok)

## ----occurrences--------------------------------------------------------------
library(letsR)
library(sf)

occs <- rbind(
  # Species A: an Amazonian cluster (inland Amazonas)
  data.frame(
    scientificName = "Example_species_A",
    decimalLongitude = c(-60.4, -60.0, -59.7, -60.6, -60.2, -59.9),
    decimalLatitude  = c(-3.4, -3.2, -3.6, -3.8, -4.0, -3.9),
    region = "Amazon"
  ),
  # Species A: a second cluster in the Atlantic Forest (inland Espirito Santo)
  data.frame(
    scientificName = "Example_species_A",
    decimalLongitude = c(-41.7, -41.5, -41.3, -41.8, -41.4, -41.1),
    decimalLatitude  = c(-19.3, -19.6, -19.9, -19.8, -20.1, -19.5),
    region = "Atlantic Forest"
  ),
  # Species A: one geographically isolated Cerrado record
  data.frame(
    scientificName = "Example_species_A",
    decimalLongitude = -47.6,
    decimalLatitude  = -15.5,
    region = "Cerrado"
  ),
  # Species B: records exclusively in the Atlantic Forest
  data.frame(
    scientificName = "Example_species_B",
    decimalLongitude = c(-40.35, -40.0, -39.9, -40.2, -40.5, -40.15),
    decimalLatitude  = c(-17.5, -17.7, -17.9, -17.15, -17.9, -17.35),
    region = "Atlantic Forest"
  )
)

table(occs$scientificName, occs$region)

## ----mask, fig.width=9, fig.height=4.5----------------------------------------
study_area <- rnaturalearth::ne_countries(
  country = "Brazil",
  scale = "medium",
  returnclass = "sf"
)
study_area <- study_area["admin"]

occ_points <- st_as_sf(
  occs, coords = c("decimalLongitude", "decimalLatitude"), crs = 4326
)
inside_brazil <- lengths(st_within(occ_points, study_area)) > 0L
stopifnot(all(inside_brazil))

# A national view and a closer view of the three example regions.
regional_xlim <- c(-65, -38)
regional_ylim <- c(-23, -1)
atlantic_xlim <- c(-42.7, -39.5)
atlantic_ylim <- c(-21.3, -18.1)

op <- par(mfrow = c(1, 2), mar = c(2, 2, 3, 1))
plot(st_geometry(study_area), col = "gray95", border = "gray45",
     main = "Brazil")
points(occs$decimalLongitude, occs$decimalLatitude,
       pch = ifelse(occs$scientificName == "Example_species_A", 16, 17),
       col = ifelse(occs$scientificName == "Example_species_A",
                    "steelblue4", "darkorange3"), cex = 0.7)
plot(st_geometry(study_area), xlim = regional_xlim, ylim = regional_ylim,
     col = "gray95", border = "gray45",
     main = "Synthetic occurrence records")
points(occs$decimalLongitude, occs$decimalLatitude,
       pch = ifelse(occs$scientificName == "Example_species_A", 16, 17),
       col = ifelse(occs$scientificName == "Example_species_A",
                    "steelblue4", "darkorange3"))
legend("bottomleft", legend = c("Species A", "Species B"),
       pch = c(16, 17), col = c("steelblue4", "darkorange3"), bty = "n")
par(op)

## ----basic-range--------------------------------------------------------------
ranges <- lets.range(
  occs = occs,
  crop_shp = study_area,
  eps_m = 95000,       # 95 km neighborhood threshold for DBSCAN
  min_pts = 1,         # Retain even isolated occurrences
  ratio = 0.5,         # Intermediate concavity
  buf = 50000,         # 50 km buffer, applied before and after hull construction
  intersection = TRUE, # Retain only the area inside study_area
  plot_map = FALSE
)

ranges[, c("binomial", "cluster")]
st_geometry_type(ranges)
st_crs(ranges)$epsg

## ----plot-ranges, fig.height=5------------------------------------------------
plot(st_geometry(study_area), xlim = regional_xlim, ylim = regional_ylim,
     col = "gray95", border = "gray70",
     main = "Amazon, Cerrado and Atlantic Forest ranges")
plot(st_geometry(ranges[ranges$binomial == "Example_species_A", ]),
     col = grDevices::adjustcolor("steelblue3", alpha.f = 0.4),
     border = "steelblue4", add = TRUE)
plot(st_geometry(ranges[ranges$binomial == "Example_species_B", ]),
     col = grDevices::adjustcolor("darkorange2", alpha.f = 0.35),
     border = "darkorange3", add = TRUE)
points(occs$decimalLongitude, occs$decimalLatitude,
       pch = ifelse(occs$scientificName == "Example_species_A", 16, 17),
       col = ifelse(occs$scientificName == "Example_species_A",
                    "steelblue4", "darkorange3"))
legend("bottomleft", legend = c("Species A", "Species B"),
       pch = c(16, 17), col = c("steelblue4", "darkorange3"), bty = "n")

## ----clustering---------------------------------------------------------------
occ_A <- subset(occs, scientificName == "Example_species_A")

with_singletons <- lets.range(
  occ_A, crop_shp = study_area,
  eps_m = 95000, min_pts = 1,
  buf = 50000, ratio = 0.5,
  plot_map = FALSE
)

without_singletons <- lets.range(
  occ_A, crop_shp = study_area,
  eps_m = 95000, min_pts = 3,
  buf = 50000, ratio = 0.5,
  plot_map = FALSE
)

c(
  clusters_with_singletons = nrow(with_singletons),
  clusters_without_singletons = nrow(without_singletons)
)

## ----compare-clustering, fig.width=8, fig.height=4----------------------------
op <- par(mfrow = c(1, 2), mar = c(2, 2, 3, 1))
for (i in seq_along(list(with_singletons, without_singletons))) {
  x <- list(with_singletons, without_singletons)[[i]]
  plot(st_geometry(study_area), xlim = regional_xlim, ylim = regional_ylim,
       col = "gray97", border = "gray75",
       main = if (i == 1) "min_pts = 1" else "min_pts = 3")
  if (nrow(x)) {
    plot(st_geometry(x), add = TRUE,
         col = grDevices::adjustcolor("steelblue3", alpha.f = 0.4),
         border = "steelblue4")
  }
  points(occ_A$decimalLongitude, occ_A$decimalLatitude, pch = 16, cex = 0.7)
}
par(op)

## ----sensitivity--------------------------------------------------------------
small_buffer <- lets.range(
  occ_A, crop_shp = study_area,
  eps_m = 95000, min_pts = 3,
  ratio = 0.5, buf = 15000, plot_map = FALSE
)

large_buffer <- lets.range(
  occ_A, crop_shp = study_area,
  eps_m = 95000, min_pts = 3,
  ratio = 0.5, buf = 75000, plot_map = FALSE
)

concave_range <- lets.range(
  occ_A, crop_shp = study_area,
  eps_m = 95000, min_pts = 3,
  ratio = 0.2, buf = 30000, plot_map = FALSE
)

convex_range <- lets.range(
  occ_A, crop_shp = study_area,
  eps_m = 95000, min_pts = 3,
  ratio = 1, buf = 30000, plot_map = FALSE
)

## ----compare-sensitivity, fig.width=8, fig.height=7---------------------------
options_to_plot <- list(small_buffer, large_buffer,
                        concave_range, convex_range)
plot_titles <- c("buf = 15 km", "buf = 75 km",
                 "ratio = 0.2", "ratio = 1.0")
op <- par(mfrow = c(2, 2), mar = c(2, 2, 3, 1))
for (i in seq_along(options_to_plot)) {
  plot(st_geometry(study_area), xlim = atlantic_xlim, ylim = atlantic_ylim,
       col = "gray97", border = "gray75",
       main = plot_titles[i])
  plot(st_geometry(options_to_plot[[i]]), add = TRUE,
       col = grDevices::adjustcolor("steelblue3", alpha.f = 0.4),
       border = "steelblue4")
  points(occ_A$decimalLongitude, occ_A$decimalLatitude, pch = 16, cex = 0.6)
}
par(op)

## ----land-mask, fig.width=8, fig.height=4-------------------------------------
occ_B <- subset(occs, scientificName == "Example_species_B")

inside_land <- lets.range(
  occ_B, crop_shp = study_area,
  intersection = TRUE,
  eps_m = 95000, min_pts = 1, ratio = 0.5,
  buf = 60000, plot_map = FALSE
)

outside_land <- lets.range(
  occ_B, crop_shp = study_area,
  intersection = FALSE,
  eps_m = 95000, min_pts = 1, ratio = 0.5,
  buf = 60000, plot_map = FALSE
)

op <- par(mfrow = c(1, 2), mar = c(2, 2, 3, 1))
for (i in 1:2) {
  plot(st_geometry(study_area), xlim = atlantic_xlim, ylim = atlantic_ylim,
       col = "gray95", border = "gray50",
       main = if (i == 1) "Retained inside Brazil" else "Discarded outside Brazil")
  x <- if (i == 1) inside_land else outside_land
  if (nrow(x) > 0L) {
    plot(st_geometry(x), add = TRUE,
         col = grDevices::adjustcolor("steelblue3", alpha.f = 0.4),
         border = "steelblue4")
  }
  points(occ_B$decimalLongitude, occ_B$decimalLatitude,
         pch = 17, cex = 0.7, col = "darkorange3")
}
par(op)

## ----output-------------------------------------------------------------------
ranges$area_km2 <- as.numeric(st_area(ranges)) / 1e6

ranges_summary <- st_drop_geometry(ranges)[,
  c("binomial", "cluster", "area_km2")
]
print(ranges_summary)

# Combine all retained clusters of each species into a single geometry.
species_ranges <- do.call(
  rbind,
  lapply(split(ranges, ranges$binomial), function(x) {
    st_sf(
      binomial = x$binomial[1],
      geometry = st_union(st_geometry(x))
    )
  })
)

# There should now be one feature per species.
stopifnot(nrow(species_ranges) == length(unique(occs$scientificName)))
species_ranges

## ----presence-absence, fig.width=8, fig.height=5------------------------------
pam <- lets.presab(
  shapes = species_ranges,
  xmn = -65, xmx = -38,
  ymn = -23, ymx = -1,
  resol = 1,
  remove.cells = TRUE,
  remove.sp = TRUE,
  cover = 0
)

# Matrix: cell centroids followed by one 0/1 column per species.
head(pam$Presence_and_Absence_Matrix)

# Frequency of cells containing one or two species.
cell_richness <- rowSums(
  pam$Presence_and_Absence_Matrix[, -(1:2), drop = FALSE]
)
print(table(cell_richness))

# Spatial richness is stored as a terra raster.
terra::plot(pam$Richness_Raster,
            col = c("gray95", "lightskyblue3", "steelblue4"),
            main = "Illustrative richness from estimated ranges")
plot(st_geometry(study_area), border = "gray45", col = NA, add = TRUE)

## ----iucn-eoo, fig.width=8, fig.height=4.5------------------------------------
occ_A_sf <- st_as_sf(
  occ_A,
  coords = c("decimalLongitude", "decimalLatitude"),
  crs = 4326
)

# An illustrative equal-area projection covering the Brazilian example.
brazil_equal_area <- paste(
  "+proj=aea +lat_1=-5 +lat_2=-25 +lat_0=-15",
  "+lon_0=-48 +datum=WGS84 +units=m +no_defs"
)

projected_points <- st_transform(occ_A_sf, brazil_equal_area)
eoo_hull <- st_convex_hull(st_union(st_geometry(projected_points)))
eoo_km2 <- as.numeric(st_area(eoo_hull)) / 1e6

# lets.range() retains disconnected clusters after the Brazil land mask.
range_area_km2 <- as.numeric(st_area(st_union(st_geometry(with_singletons)))) / 1e6
comparison <- data.frame(
  estimate = c("Illustrative MCP-based EOO", "lets.range() polygon area"),
  area_km2 = round(c(eoo_km2, range_area_km2))
)
print(comparison)

op <- par(mfrow = c(1, 2), mar = c(2, 2, 3, 1))
plot(st_geometry(study_area), xlim = regional_xlim, ylim = regional_ylim,
     col = "gray95", border = "gray70", main = "Convex hull (EOO approach)")
plot(st_transform(eoo_hull, 4326), add = TRUE,
     col = grDevices::adjustcolor("darkorange2", alpha.f = 0.3),
     border = "darkorange3")
points(occ_A$decimalLongitude, occ_A$decimalLatitude, pch = 16, cex = 0.7)

plot(st_geometry(study_area), xlim = regional_xlim, ylim = regional_ylim,
     col = "gray95", border = "gray70", main = "lets.range() clusters")
plot(st_geometry(with_singletons), add = TRUE,
     col = grDevices::adjustcolor("steelblue3", alpha.f = 0.4),
     border = "steelblue4")
points(occ_A$decimalLongitude, occ_A$decimalLatitude, pch = 16, cex = 0.7)
par(op)

