### Script: Morphometric and Landscape Analyses - Trypoxylon lactitarse
# Purpose: Perform MANOVA, GLMMs, and visualize effects of landscape metrics on wing shape and size

# --- Load required packages ---
library(openxlsx)    # For reading .xlsx files
library(tidyverse)   # For data manipulation and plotting
library(lme4)        # For generalized linear mixed models (GLMMs)
library(car)         # For ANOVA tests
library(MuMIn)       # For calculating R² for GLMMs

# --- Read dataset ---
Dataset <- read.xlsx("Trypoxylon_morphometrics_landscape.xlsx", colNames = TRUE, detectDates = TRUE)

# --- MANOVA: Effect of landscape variables and wing size on wing shape (PCs) ---
model.manova <- manova(cbind(PC1, PC2, PC3, PC4, PC5, PC6, PC7, PC8, PC9, PC10, PC11, PC12) ~ 
                         Log_Centroid_Size + Forest_Cover + Connectivity + Edge + Shdi,
                       data = Dataset)

summary(model.manova, test = "Wilks")

# --- GLMMs: Effect of individual landscape variables on wing shape ---
# Assumes 'Wing_shape' is a CVA- or PCA-derived axis (e.g., CV1)

model1 <- glmer(Wing_shape ~ Edge + (1 | Landscape), data = Dataset, family = gaussian)
model2 <- glmer(Wing_shape ~ Shdi + (1 | Landscape), data = Dataset, family = gaussian)
model3 <- glmer(Wing_shape ~ Connectivity + (1 | Landscape), data = Dataset, family = gaussian)
model4 <- glmer(Wing_shape ~ Forest_Cover + (1 | Landscape), data = Dataset, family = gaussian)
model5 <- glmer(Wing_shape ~ Log_Centroid_Size + (1 | Landscape), data = Dataset, family = gaussian)

# The same models (model1 to model4) were also fitted using Centroid_Size as the response variable instead of Wing_shape,
# to evaluate how landscape variables influence overall wing size.
# Example:
# model1_size <- glmer(Centroid_Size ~ Edge + (1 | Landscape), data = Dataset, family = gaussian)

# --- Model summaries ---
summary(model1)
summary(model2)
summary(model3)
summary(model4)
summary(model5)

# --- Extract p-values and conditional R² for each model ---
extract_p_r2 <- function(model) {
  r_p <- car::Anova(model)
  r_p <- data.frame(p_value = round(r_p$'Pr(>Chisq)', 3))
  conditional_r2 <- r.squaredGLMM(model, which = "conditional")
  r_p$r2 <- round(conditional_r2[2], 3)
  return(r_p)
}

r_p1 <- extract_p_r2(model1)
r_p2 <- extract_p_r2(model2)
r_p3 <- extract_p_r2(model3)
r_p4 <- extract_p_r2(model4)
r_p5 <- extract_p_r2(model5)

# --- View results ---
r_p1
r_p2
r_p3
r_p4
r_p5

# --- Visualization: Boxplot of wing shape by landscape, ordered by forest cover ---
# Assumes 'dadonovo1' is a cleaned or transformed version of Dataset with Wing_Shape and Forest_Cover

p1 <- Dataset %>%
  ggplot(aes(x = reorder(Landscape, Forest_cover), y = wing_shape)) + 
  geom_boxplot(color = "black") +
  theme_classic()

# Save plot as PNG (high resolution)
ggsave("boxplot_4.png", plot = p1, units = "px", dpi = 300, height = 800, width = 1400)
