## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  warning = FALSE,
  message = FALSE,
  fig.width = 10,
  fig.height = 5.5
)

## ----data_simulation----------------------------------------------------------
library(ascent)

# 1. Functional Trait Space
set.seed(42)
aves_traits <- data.frame(
  Body_Mass   = c(15, 20, 30, 45, 60, 90, 150, 250, 400, 600),
  Beak_Length = c(10, 12, 15, 22, 28, 35,  45,  60,  85, 120),
  Frugivore   = factor(c(0, 0, 1, 1, 1, 0,  1,  1,  1,  0)),
  Forest_Dep  = factor(c(0, 0, 0, 0, 1, 1,  1,  1,  1,  1))
)
rownames(aves_traits) <- paste0("Av_sp", 1:10)

# 2a. Temporal Matrix (Deforestation)
abund_time <- rbind(
  Site1_Ref = c( 0,  0, 10, 15, 25, 20, 10, 8, 4, 2), # Mature forest
  Site1_Imp = c(40, 35, 15,  5,  0,  0,  0, 0, 0, 0)  # Logged area
)

# 2b. Spatial Matrix (Landscape Gradient)
abund_space <- rbind(
  Primary   = c( 0,  0,  5, 10, 20, 25, 15, 10, 5, 2),
  Secondary = c( 0,  5, 10, 20, 35, 20, 10,  0, 0, 0),
  Agri      = c( 0,  0,  0,  5, 45, 45,  5,  0, 0, 0)
)

## ----temporal_shift-----------------------------------------------------------
res_paired <- asc_paired(
  traits = aves_traits, abund = abund_time, 
  sites = c("Site1", "Site1"), time = c("Reference", "Impacted"),
  ref_time = "Reference", dist_method = "gower"
)
res_paired <- asc_null(res_paired, n_perm = 99, seed = 123)
summary(res_paired)

## ----leverage-----------------------------------------------------------------
# Extract the specific topological drivers
drivers_time <- asc_transitions(res_paired)
head(drivers_time$Site1$species_leverage, 4)

# Plot the PCoA trajectory and the leverage divergence
plot(res_paired, contrast = "Site1", type = "both", n_sp = 5)

## ----spatial_network----------------------------------------------------------
res_pw <- asc_pairwise(traits = aves_traits, abund = abund_space, dist_method = "gower")
res_pw <- asc_null(res_pw, n_perm = 99, seed = 42)
summary(res_pw)

# Visualize the functional gap between Primary and Secondary Forest
plot(res_pw, contrast = "Primary_vs_Secondary", type = "both", n_sp = 5)

# Visualize the severe functional gap between Secondary Forest and Agriculture
plot(res_pw, contrast = "Secondary_vs_Agri", type = "both", n_sp = 5)

## ----baseline-----------------------------------------------------------------
base_topo <- asc_baseline(traits = aves_traits, abund = abund_space, dist_method = "gower")
summary(base_topo)

## ----entities, fig.width=7, fig.height=5--------------------------------------
# Cluster the species into 3 functional entities using Gower distance
func_ent <- asc_entities(traits = aves_traits, dist_method = "gower", k = 3)
summary(func_ent)

# Visualize the functional dendrogram
plot(func_ent)

