###Pollinator contribution to plant sexual reproduction after fire: evidence from a widespread herb in Chaco ecosystems
###Carbone, LM., Cugini A., Chiapero A.L.

####################
###1. Pollinators

##1.1. Pollinator assemblage composition among time-since-fire Conditions

#File: "Pollinators per site.txt"
library(vegan)
comp<- read.table(file.choose(), header = TRUE)
head(comp)

#Analysis of Similarities
comp.num <- comp[, sapply(comp, is.numeric)]
data.dist <- vegdist(comp.num, method = "bray")
data.dist

#File: "Sites.txt"
site<- read.table(file.choose(), header = TRUE)
attach(site)

data.ano <- anosim(data.dist, Condition)
summary(data.ano)



##1.2. Pollinator visitation frequency among time-since-fire Conditions

#File: "Pollinator_visits.txt"
fre<- read.table(file.choose(), header = TRUE)
head(fre)
str(fre)
library(lme4)
library(nlme)
library(pscl)
library(glmmADMB)
library (ggplot2)
library(DHARMa)
library(glmmTMB)
library(multcompView)
library(emmeans)

fre$Condition<-as.factor(fre$Condition)
fre$Site<-as.factor(fre$Site)
fre$Round<-as.factor(fre$Round)
fre$Plant<-as.factor(fre$Plant)
fre$n_visits<-as.numeric(fre$n_visits)
fre$Inflo<-as.numeric(fre$Inflo)
fre$Pollinator<-as.factor(fre$Pollinator)
fre$Method<-as.factor(fre$Method)

# Order time-since-fire Conditions
orden_Conditions <- c("Recently1", "Recently2", "Intermediate", "Unburned")
fre$Condition <- factor(fre$Condition, levels = orden_Conditions)

# Subset by pollinator group

#APIS
apis <- subset(fre, Pollinator == "Apis")

apis_nb <- glmmTMB(n_visits ~ Condition * Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = nbinom2,  data = apis)

summary(apis_nb)

res2 <- simulateResiduals(apis_nb)
plot(res2) #Check assumptions

performance::check_zeroinflation(apis_nb) #Check for zero-inflation

#Model selection:
apis_nb.1 <- glmmTMB(n_visits ~ Condition + Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = nbinom2,  data = apis)

anova(apis_nb,  apis_nb.1) #Chisq= 2.7251; p= 0.436. Non-significant interaction 

apis_nb.2 <- glmmTMB(n_visits ~ Condition + offset(log(Time)) + (1 | Site) + (1 | Method),  
                     family = nbinom2,  data = apis)

anova(apis_nb.2, apis_nb.1) # Chisq=6.6509; p=0.009911   ** Available inflorescence are significant

apis_nb.3 <- glmmTMB(n_visits ~ Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method),family = nbinom2,  data = apis)

anova(apis_nb.3, apis_nb.1) #Chisq=1.8393; p=0.6064. Time-since-fire Condition not affected Apis visits.


#Appropriate minimum model
apis_nb.3 <- glmmTMB(n_visits ~ Inflo + offset(log(Time)) + 
                       (1 | Site) + (1 | Method),family = nbinom2,  data = apis) #Minimum adequate model
summary(apis_nb.3)

#Check significance of random factors:
apis_nb.3.1 <- glmmTMB(n_visits ~ Inflo + offset(log(Time)) + 
                         (1 | Site),family = nbinom2,  data = apis)

anova(apis_nb.3, apis_nb.3.1) # Chisq=10.575, p= 0.001146 **. Method is significant.

apis_nb.3.2 <- glmmTMB(n_visits ~ Inflo + offset(log(Time)) + 
                         (1 | Method),family = nbinom2,  data = apis) 

anova(apis_nb.3, apis_nb.3.2) #Chisq=18.827      p=1.431e-05 ***. Site is significant.


#Graph the raw data and the values stimated by the models
library(ggeffects)
library(effects)

ef_apis <- allEffects(apis_nb.1)
ef_df.apis <- as.data.frame(ef_apis$Condition)

a1 <- ggplot() +
  geom_jitter(data = apis, aes(x = Condition, y = n_visits), width = 0.2, alpha = 0.5, size = 3, color = "#2b8a3e") +  # 
  geom_line(data = ef_df.apis, aes(x = Condition, y = fit, group = 1), color = "#a23b72", linewidth = 0.8) +  
  geom_point(data = ef_df.apis, aes(x = Condition, y = fit, group = 1), color = "#a23b72", size = 0.8) +
  geom_ribbon(data = ef_df.apis, aes(x = Condition, ymin = lower, ymax = upper, group = 1), alpha = 0.2, fill = "#a23b72") +
  labs(title = "Honeybees", x = "", y = "") +
  theme_minimal() +
  theme(axis.text = element_text(size = 9))
a1



#WASPS
Wasps <- subset(fre, Pollinator == "Wasps")

avi_zinf <- glmmTMB(n_visits ~ Condition * Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = poisson, ziformula = ~1, data = Wasps)

resAv <- simulateResiduals(avi_zinf)#Check assumptions
plot(resAv) 

#Model selection:
avi_zinf1 <- glmmTMB(n_visits ~ Condition + Inflo + offset(log(Time)) + 
                      (1 | Site) + (1 | Method), family = poisson, ziformula = ~1, data = Wasps)

anova(avi_zinf, avi_zinf1) #Chisq=4.91; p=  0.1785. Interaction not significant.

avi_zinf2 <- glmmTMB(n_visits ~ Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = poisson, ziformula = ~1, data = Wasps)

anova(avi_zinf1, avi_zinf2)## Chisq=  9.0854 ;P=0.02818 * Time-since-fire affected wasps visits.

avi_zinf3 <- glmmTMB(n_visits ~ Condition + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = poisson, ziformula = ~1, data = Wasps)

anova(avi_zinf1, avi_zinf3) ##Chisq= 10.441       P= 0.001232 ** Available inflorescences affected wasps visits.

#Appropriate minimum model
avi_zinf1 <- glmmTMB(n_visits ~ Condition + Inflo + offset(log(Time)) + 
                       (1 | Site) + (1 | Method), family = poisson, ziformula = ~1, data = Wasps)

#Pairwise comparisons to see differences between time-since-fire Conditions:
emmeans_obj <- emmeans(avi_zinf1, ~ Condition)  
letters <- contrast(emmeans_obj, adjust = "tukey")
print(letters)

em_Condition <- emmeans(avi_zinf1, ~ Condition)
contrast(em_Condition, method = "pairwise", adjust = "tukey")

#Check significance of random factors:
avi_zinf1.met <- glmmTMB(n_visits ~ Condition + Inflo + offset(log(Time)) + 
                           (1 | Site) ,family = poisson, ziformula = ~1, data = Wasps)

anova(avi_zinf1, avi_zinf1.met) #Chisq= 146.02, p  < 2.2e-16 *** . Method is significant.

avi_zinf1.site <- glmmTMB(n_visits ~ Condition + Inflo + offset(log(Time)) + 
                            (1 | Method),family = poisson, ziformula = ~1, data = Wasps)

anova(avi_zinf1, avi_zinf1.site) #Chisq=6.5045 , p= 0.01076 * . Site is significant.


#Graph the raw data and the values stimated by the models
ef_avis <- allEffects(avi_zinf1)
ef_df.avis <- as.data.frame(ef_avis$Condition)

a2<- ggplot() +
  geom_jitter(data = Wasps, aes(x = Condition, y = n_visits), width = 0.2, alpha = 0.5, size = 3, color = "#2b8a3e") +  
  geom_line(data = ef_df.avis, aes(x = Condition, y = fit, group = 1), color = "#a23b72", linewidth = 0.8) +  
  geom_point(data = ef_df.avis, aes(x = Condition, y = fit, group = 1), color = "#a23b72", size = 0.8) +
  geom_ribbon(data = ef_df.avis, aes(x = Condition, ymin = lower, ymax = upper, group = 1), alpha = 0.2, fill = "#a23b72") +
  labs(title = "Wasps", x = "", y = "") +
  theme_minimal() +
  theme(axis.text = element_text(size = 9))
a2




##BEETLES
coleop <- subset(fre, Pollinator == "Beetles")

coleo_nb <- glmmTMB(n_visits ~ Condition * Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = nbinom2,  data = coleop)

resCOL <- simulateResiduals(coleo_nb)#Check assumptions
plot(resCOL) 

performance::check_zeroinflation(coleo_nb) # Check for zero-inflation

#Model selection
coleo_nb1 <- glmmTMB(n_visits ~ Condition + Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = nbinom2,  data = coleop)

anova(coleo_nb, coleo_nb1) # Chisq=0.3681,  p=0.9467. Interaction non significant.

coleo_nb2 <- glmmTMB(n_visits ~ Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method),family = nbinom2,  data = coleop)

anova(coleo_nb1, coleo_nb2) #Chisq=13.021 , p=0.004592 **. Time-since-fire is significant.

coleo_nb3 <- glmmTMB(n_visits ~ Condition  + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = nbinom2,  data = coleop)

anova(coleo_nb1, coleo_nb3) ## Chisq= 0.0567, p=0.8119 . Inflorescences available is not significant.


#Appropriate minimum model
coleo_nb3 <- glmmTMB(n_visits ~ Condition  + offset(log(Time)) + 
                       (1 | Site) + (1 | Method), family = nbinom2,  data = coleop)

#Pairwise comparisons to see differences between time-since-fire Conditions:
col_Condition <- emmeans(coleo_nb3, ~ Condition)
contrast(col_Condition, method = "pairwise", adjust = "tukey")

#Check significance of random factors:
coleo_nb3.metod <- glmmTMB(n_visits ~ Condition  + offset(log(Time)) + 
                             (1 | Site),family = nbinom2,  data = coleop)

anova(coleo_nb3, coleo_nb3.metod) #Chisq= 2.7935      p=0.09465 . Method is not significant.

coleo_nb3.Site <- glmmTMB(n_visits ~ Condition  + offset(log(Time)) + 
                             (1 | Method),family = nbinom2,  data = coleop)

anova(coleo_nb3, coleo_nb3.Site) #Chisq=  0      p= 1. Site is not significant.


#Graph the raw data and the values stimated by the models
ef_coleop <- allEffects(coleo_nb1)
ef_df.coleop <- as.data.frame(ef_coleop$Condition)

a3 <- ggplot() +
  geom_jitter(data = coleop, aes(x = Condition, y = n_visits), width = 0.2, alpha = 0.5, size = 3, color = "#2b8a3e") +  # 
  geom_line(data = ef_df.coleop, aes(x = Condition, y = fit, group = 1), color = "#a23b72", linewidth = 0.8) +  
  geom_point(data = ef_df.coleop, aes(x = Condition, y = fit, group = 1), color = "#a23b72", size = 0.8) +
  geom_ribbon(data = ef_df.coleop, aes(x = Condition, ymin = lower, ymax = upper, group = 1), alpha = 0.2, fill = "#a23b72") +
  labs(title = "Beetles", x = "", y = "") +
  theme_minimal() +
  theme(axis.text = element_text(size = 9))
a3



##HOVERFLIES (Syrphidae and Bombyliidae)
moscasF <- subset(fre, Pollinator == "Hoverflies")

moscaf_zinf <- glmmTMB(n_visits ~ Condition *Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = poisson, ziformula = ~1, data = moscasF)

resmosF1_z <- simulateResiduals(moscaf_zinf)#Check assumptions
plot(resmosF1_z)

#Model selection
moscaf_zinf.int <- glmmTMB(n_visits ~ Condition +Inflo + offset(log(Time)) + 
                         (1 | Site) + (1 | Method), family = poisson, ziformula = ~1, data = moscasF)

anova(moscaf_zinf, moscaf_zinf.int) #Chisq=4.8288, p=    0.1848. Interaction is not significant.

moscaf_zinf1 <- glmmTMB(n_visits ~ Condition + offset(log(Time)) + 
    (1 | Site) + (1 | Method),family = poisson, ziformula = ~1, data = moscasF)

anova(moscaf_zinf.int, moscaf_zinf1) ## Chisq=3.2893     P=  0.06973 .Available inflorescences are not significant.


moscaf_zinf4 <- glmmTMB(n_visits ~ Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = poisson, ziformula = ~1, data = moscasF)

anova(moscaf_zinf4, moscaf_zinf.int) #Chisq= 1.7356         P=0.6291. Time since fire is not significant.

#Check significance of random factors:
moscaf_zinf3.Method <- glmmTMB(n_visits ~ Condition+Inflo + offset(log(Time)) + 
                                 (1 | Site),family = poisson, ziformula = ~1, data = moscasF)

anova(moscaf_zinf.int, moscaf_zinf3.Method) #Chisq= 101.23       p < 2.2e-16 ***.Methods is significant.

moscaf_zinf3.site <- glmmTMB(n_visits ~ Condition+Inflo + offset(log(Time)) + 
                               + (1 | Method), family = poisson,    ziformula = ~1, data = moscasF)

anova(moscaf_zinf.int, moscaf_zinf3.site) #Chisq= 20.049      p = 7.547e-06 *** . Site is significant.

#Graph the raw data and the values stimated by the models
ef_mosF <- allEffects(moscaf_zinf.int)
ef_df.mosF <- as.data.frame(ef_mosF$Condition)

a4 <- ggplot() +
  geom_jitter(data = moscasF, aes(x = Condition, y = n_visits), width = 0.2, alpha = 0.5, size = 3, color = "#2b8a3e") +  # 
  geom_line(data = ef_df.mosF, aes(x = Condition, y = fit, group = 1), color = "#a23b72", linewidth = 0.8) +  
  geom_point(data = ef_df.mosF, aes(x = Condition, y = fit, group = 1), color = "#a23b72", size = 0.8) +
  geom_ribbon(data = ef_df.mosF, aes(x = Condition, ymin = lower, ymax = upper, group = 1), alpha = 0.2, fill = "#a23b72") +
  labs(title = "Hoverflies", x = "", y = "") +
  theme_minimal() +
  theme(axis.text = element_text(size = 9))
a4



##OTHERS BEES (non- Apis Apoidea)
abejas <- subset(fre, Pollinator == "OtherBees")

abejas_nb2 <- glmmTMB(n_visits ~ Condition*Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method),  family = nbinom2,  data = abejas)

resab2 <- simulateResiduals(abejas_nb2)#Check assumptions
plot(resab2)

performance::check_zeroinflation(abejas_nb2) #Check for zero-inflation

abejas_nb3 <- glmmTMB(  n_visits ~ Condition+Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = nbinom2,  data = abejas)

anova(abejas_nb2, abejas_nb3) ##Chisq= 1.0983      p=0.7775. Interaction in not significant

abejas_nb4 <- glmmTMB( n_visits ~ Condition + offset(log(Time)) + 
    (1 | Site) + (1 | Method),family = nbinom2,  data = abejas)

anova(abejas_nb4, abejas_nb3) # Chisq=  0.0561 p=0.8128. I can remove available flowers from the model

abejas_nb5 <- glmmTMB( n_visits ~ Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method),family = nbinom2,  data = abejas)

anova(abejas_nb5, abejas_nb3) #Chisq=10.528      p=0.01457 * . Time since fire is important.

#Pairwise comparisons to see differences between time-since-fire Conditions:
Abej_Condition <- emmeans(abejas_nb4, ~ Condition)
contrast(Abej_Condition, method = "pairwise", adjust = "tukey")

#Check significance of random factors:
abejas_nb4.metod <- glmmTMB(n_visits ~ Condition + offset(log(Time)) +  (1 | Site) ,
                            family = nbinom2,  data = abejas)

anova(abejas_nb4, abejas_nb4.metod) #Chisq=0      p=0.9999 . Method is not significant.

abejas_nb4.site <- glmmTMB(n_visits ~ Condition + offset(log(Time)) + 
                             + (1 | Method),   family = nbinom2,  data = abejas)

anova(abejas_nb4, abejas_nb4.site) #Chisq=0      p=0.9999. Site is not significant.

#Graph the raw data and the values estimated by the models

ef_abejas <- allEffects(abejas_nb3)
ef_df.abejas <- as.data.frame(ef_abejas$Condition)

a5 <- ggplot() +
  geom_jitter(data = abejas, aes(x = Condition, y = n_visits), width = 0.2, alpha = 0.5, size = 3, color = "#2b8a3e") +  # 
  geom_line(data = ef_df.abejas, aes(x = Condition, y = fit, group = 1), color = "#a23b72", linewidth = 0.8) +  
  geom_point(data = ef_df.abejas, aes(x = Condition, y = fit, group = 1), color = "#a23b72", size = 0.8) + 
  geom_ribbon(data = ef_df.abejas, aes(x = Condition, ymin = lower, ymax = upper, group = 1), alpha = 0.2, fill = "#a23b72") +
  labs(title = "Other bees", x = "", y = "") +
  theme_minimal() +
  theme(axis.text = element_text(size = 9))
a5 



#OTHER FLIES
OMOscas <- subset(fre, Pollinator == "OtherFlies")

OMoscas_nb2 <- glmmTMB(n_visits ~ Condition*Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method),family = nbinom2,  data = OMOscas)

resOMoscas1 <- simulateResiduals(OMoscas_nb2) #Check assumptions
plot(resOMoscas1)

performance::check_zeroinflation(OMoscas_nb2) #Check for zero-inflation

#Model selection
OMoscas_nb2.1 <- glmmTMB(n_visits ~ Condition+Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method),family = nbinom2,  data = OMOscas)

anova(OMoscas_nb2, OMoscas_nb2.1) #Chisq=3.293 p=0.3486. Can remove the interaction of the model.

OMoscas_nb2.2 <- glmmTMB(n_visits ~ Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = nbinom2,  data = OMOscas)

anova(OMoscas_nb2.1, OMoscas_nb2.2) #Chisq=2.7223      p=0.4365. Post-fire Condition is not important.

OMoscas_nb2.3 <- glmmTMB(n_visits ~ Condition + offset(log(Time)) + 
    (1 | Site) + (1 | Method),family = nbinom2,  data = OMOscas)

anova(OMoscas_nb2.1, OMoscas_nb2.3) #chisq=2.9188  p=  0.08755. I can remove available flowers from the model

OMoscas_nb2.null <- glmmTMB(n_visits ~ 1 + offset(log(Time)) + 
    (1 | Site) + (1 | Method),family = nbinom2,  data = OMOscas)

anova(OMoscas_nb2.null, OMoscas_nb2.3) #chisq=4.3237      p=0.2286. Null model is the Appropriate minimal.


#Check significance of random factors:
OMoscas_nb2.null.metod <- glmmTMB(n_visits ~ 1 + offset(log(Time)) + (1 | Site),
                                  family = nbinom2,  data = OMOscas)

anova(OMoscas_nb2.null, OMoscas_nb2.null.metod) #Chisq= 0.7689      p=0.3806. Methods is not important.

OMoscas_nb2.null.site <- glmmTMB(n_visits ~ 1 + offset(log(Time)) + (1 | Method),
                                 family = nbinom2,  data = OMOscas)

anova(OMoscas_nb2.null, OMoscas_nb2.null.site) #x2=13.34      p=0.0002598 *** . Site is significant.

#Graph the raw data and the values stimated by the models
ef_OM <- allEffects(OMoscas_nb2.1)
ef_df.OM <- as.data.frame(ef_OM$Condition)

a6 <- ggplot() +
  geom_jitter(data = OMOscas, aes(x = Condition, y = n_visits), width = 0.2, alpha = 0.5, size = 3, color = "#2b8a3e") +  # 
  geom_line(data = ef_df.OM, aes(x = Condition, y = fit, group = 1), color = "#a23b72", linewidth = 0.8) +  
  geom_point(data = ef_df.OM, aes(x = Condition, y = fit, group = 1), color = "#a23b72", size = 0.8) + 
  geom_ribbon(data = ef_df.OM, aes(x = Condition, ymin = lower, ymax = upper, group = 1), alpha = 0.2, fill = "#a23b72") +
  labs(title = "Other flies", x = "Time since fire", y = "") +
  theme_minimal() +
  theme(axis.text = element_text(size = 9))
a6


#ANTS
Ant <- subset(fre, Pollinator == "Ants")

Ant_nb <- glmmTMB(n_visits ~ Condition*Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method),family = nbinom2,  data = Ant)

resAnt1.1 <- simulateResiduals(Ant_nb) #Check assumptions
plot(resAnt1.1)

#Model selection
Ant_nb.1 <- glmmTMB(n_visits ~ Condition+Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = nbinom2,  data = Ant)

anova(Ant_nb, Ant_nb.1) #Chisq=1.7366     p=0.6288. I can remove the interaction.

Ant_nb.2 <- glmmTMB(n_visits ~ Inflo + offset(log(Time)) + 
    (1 | Site) + (1 | Method), family = nbinom2,  data = Ant)

anova(Ant_nb.1, Ant_nb.2) # =4.4308      P=0.2185. Time since fire is not important.

Ant_nb.3 <- glmmTMB( n_visits ~ Condition + offset(log(Time)) + 
    (1 | Site) + (1 | Method),family = nbinom2,  data = Ant)

anova(Ant_nb.1, Ant_nb.3) #Chisq=0.1633      p=0.6861. Inflorescences in not significant.





####################
###2.Floral display

#File:"Inflorescences.txt"
InfloT<- read.table(file.choose(), header = TRUE) 

InfloT$Condition<-as.factor(InfloT$Condition)
InfloT$Site<-as.factor(InfloT$Site)
InfloT$Inflo<-as.numeric(InfloT$Inflo)
InfloT$PlantHeigh<-as.numeric(InfloT$PlantHeigh)

#Orden time-since-fire Conditions
orden_Conditions <- c("Recently1", "Recently2", "Intermediate", "Unburned")
InfloT$Condition <- factor(InfloT$Condition, levels = orden_Conditions)

I1_nb <- glmmTMB(Inflo ~ Condition +  (1|Site),family = nbinom2,  data = InfloT)

resI1_nb <- simulateResiduals(I1_nb)#Check assumptions
plot(resI1_nb)

#Model selection
I1_nulo <- glmmTMB(Inflo ~ 1 +  (1|Site),family = nbinom2,  data = InfloT)

anova(I1_nb, I1_nulo) #Chisq= 9.3406    , p valor = 0.02509 * . Floral display is affected by time-since-fire

#Pairwise comparisons to see differences between time-since-fire Conditions:
emmeans_obj <- emmeans(I1_nb, ~ Condition)  
letters <- contrast(emmeans_obj, adjust = "tukey")  
print(letters)

em_Condition <- emmeans(I1_nb, ~ Condition) 
contrast(em_Condition, method = "pairwise", adjust = "tukey")

#Plot
ef_inflo <- allEffects(I1_nb)
ef_df.inflo <- as.data.frame(ef_inflo$Condition)

ggplot() +
  geom_jitter(data = InfloT, aes(x = Condition, y = Inflo), width = 0.2, alpha = 0.5, size = 3, color = "#2b8a3e") +  # 
  geom_line(data = ef_df.inflo, aes(x = Condition, y = fit, group = 1), color = "#a23b72", linewidth = 0.8) +  
  geom_point(data = ef_df.inflo, aes(x = Condition, y = fit, group = 1), color = "#a23b72", size = 0.8) + 
  geom_ribbon(data = ef_df.inflo, aes(x = Condition, ymin = lower, ymax = upper, group = 1), alpha = 0.2, fill = "#a23b72") +
  labs(title = "", x = "Time since fire", y = "Number of inflorescences per plant") +
  theme_minimal() +
  theme(axis.text = element_text(size = 9))





####################
###3. Pollinator contribution

#3.1. Seed production of pollinator exclusion treatment and open pollination 
#File ""Seed production by treatments.txt"

fru<- read.table(file.choose(), header = TRUE)

fru$Condition<-as.factor(fru$Condition)
fru$Site<-as.factor(fru$Site)
fru$Plant<-as.factor(fru$Plant)
fru$Treatment<-as.factor(fru$Treatment)
fru$SeededFruit<-as.numeric(fru$SeededFruit)
fru$SeedlessFruit<-as.numeric(fru$SeedlessFruit)

##Response variable: successes/failures
fru$y<-cbind(fru$SeededFruit,fru$SeedlessFruit)

#new variable: viable seed production per plant per Condition
fru$fllenas<-fru$SeededFruit / fru$TotalSeeds

# Order time-since-fire Conditions
orden_Conditions <- c("Recently", "Intermediate", "Unburned")
fru$Condition <- factor(fru$Condition, levels = orden_Conditions)

# Delete NAs
fru_clean <- fru[!is.na(fru$PlantHeigh), ]

frulla <- glmmTMB(y ~ Condition * Treatment + (1 | Site), data = fru, family = betabinomial())

res_1 <- simulateResiduals(frulla)#Check assumptions
plot(res_1)

#Model selection
frulla.1 <- glmmTMB(y ~ Condition + Treatment + (1 | Site), data = fru, family = betabinomial())

anova(frulla.1, frulla) ##chisq= 4.2134   p= 0.1216. Fire * Treatment in not significant 


frulla.1_red <- glmmTMB(y ~ Condition + (1 | Site), data = fru, family = betabinomial())

anova(frulla.1_red, frulla.1) #Chisq=110.14  , p< 2.2e-16 ***. Pollination treatment is significant

frulla.1_redu <- glmmTMB(y ~ Treatment + (1 | Site), data = fru, family = betabinomial())

anova(frulla.1_redu, frulla.1) #Chisq=20.411      2  p=3.696e-05 *** Time-since-fire is significant.

#Appropriate minimal model
frulla.1 <- glmmTMB(y ~ Condition + Treatment + (1 | Site), data = fru, family = betabinomial())
summary(frulla.1)

#Pairwise comparisons to see differences between time-since-fire Conditions and pollination treatment:
em_Condition.1 <- emmeans(frulla.1, ~ Condition+Treatment) 
contrast(em_Condition.1, method = "pairwise", adjust = "tukey")

#Plot
ggplot(fru_clean, aes(x = Condition, y = fllenas, fill = Treatment)) +
  geom_boxplot(position = position_dodge(width = 0.8), 
               outlier.shape = NA, alpha = 0.5, color = "black", width = 0.6) +
  geom_jitter(aes(color = Treatment),
              position = position_jitterdodge(jitter.width = 0.15, dodge.width = 0.8),
              size = 2, alpha = 0.7) +
  labs(x = "Time-since-fire Condition",
       y = "Seed set") +
  scale_fill_manual(values = c("#2b8a3e", "#a23b72")) +
  scale_color_manual(values = c("#2b8a3e", "#a23b72")) +
  theme_minimal() +
  theme(axis.text.x = element_text(hjust = 1),
        axis.text = element_text(size = 9),
        legend.title = element_blank())




#3.2. Pollination contribution index
#File: "PollinatorContribution.txt"
pc<- read.table(file.choose(), header = TRUE)

pc$Condition<-as.factor(pc$Condition)
pc$Site<-as.factor(pc$Site)
pc$Plant<-as.factor(pc$Plant)

#Order Conditions
orden_Conditions <- c("Recently", "Intermediate", "Unburned")
pc$Condition <- factor(pc$Condition, levels = orden_Conditions)


#Test a Gaussian distribution, but first transforming the data.
n <- nrow(pc)
pc$PC2 <- (pc$PC * (n - 1) + 0.5) / n 
pc$PC_logit <- qlogis(pc$PC2) 

mod_gauss <- glmmTMB( PC_logit ~ Condition + (1 | Site),data = pc,family = gaussian())

summary(mod_gauss)

res.gauss <- simulateResiduals(mod_gauss) #Check assumptions
plot(res.gauss) 

#Plot
ggplot(pc, aes(x = Condition, y = PC)) +
  geom_boxplot(fill = "#a23b72",
               color = "black",
               outlier.shape = NA,
               alpha = 0.5,
               width = 0.6) +
  geom_jitter(color = "#a23b72",
              width = 0.15,
              size = 2,
              alpha = 0.7) +
  labs(x = "Time-since-fire",
       y = "PC") +
  theme_minimal() +
  theme(axis.text.x = element_text(hjust = 1),
        axis.text = element_text(size = 9),
        legend.position = "none")


emm <- emmeans(mod_gauss, ~ Condition)
emm_df <- as.data.frame(emm)
emm_df$prob   <- plogis(emm_df$emmean)
emm_df$lower  <- plogis(emm_df$lower.CL)
emm_df$upper  <- plogis(emm_df$upper.CL)

ggplot(emm_df, aes(x = Condition, y = prob)) +
  geom_point(size = 3) +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2) +
  ylab("PC") +
  xlab("Condition") +
  theme_minimal()

#Model selection
mod_gauss.1 <- glmmTMB( PC_logit ~ 1 + (1 | Site),data = pc,family = gaussian())

anova(mod_gauss, mod_gauss.1) #Chisq=3.3029 ,  p=0.1918. Fire not affect pollinator contribution



#Analise Coef. of variation (CV) of pollinator contribution
cv_fun <- function(x, indices) {
  d <- x[indices]
  return(sd(d) / mean(d))}

#Bootstrap by Condition
library(dplyr)
library(boot)

resultados <- pc %>%
  group_by(Condition) %>%
  summarise(
    boot_obj = list(boot(PC, cv_fun, R = 2000)),
    .groups = "drop")

#Extract IC
resultados <- resultados %>%
  rowwise() %>%
  mutate(
    ci = list(boot.ci(boot_obj, type = "perc")),
    CI_low = ci$percent[4],
    CI_high = ci$percent[5],
    CV = mean(boot_obj$t)
  ) %>%
  ungroup()

#Plot
ggplot(resultados, aes(x = Condition, y = CV)) +
  geom_point(size = 3, color = "#2b8a3e") +
  geom_errorbar(aes(ymin = CI_low, ymax = CI_high),
                width = 0,   # ??? sin pesta?as
                color = "#2b8a3e") +
  labs(x = "Time-since-fire condition",
       y = "CV") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = , hjust = 1),
    axis.text = element_text(size = 9),
    legend.title = element_blank())


#Integrated plot:

# scale CV to the inverted 0-0.5 range
sf <- 0.5 / max(resultados$CV, na.rm = TRUE)

ggplot() +
  geom_boxplot(data = pc,
               aes(x = Condition, y = PC),
               fill = "#a23b72",
               color = "black",
               outlier.shape = NA,
               alpha = 0.5,
               width = 0.6) +
  geom_jitter(data = pc,
              aes(x = Condition, y = PC),
              color = "#a23b72",
              width = 0.15,
              size = 2,
              alpha = 0.7) +
  geom_linerange(data = resultados,
                 aes(x = as.numeric(factor(Condition)) + 0.40,
                     ymin = 1 - (CI_high * sf),
                     ymax = 1 - (CI_low * sf)),
                 color = "#2b8a3e",
                 linewidth = 0.8) +
  geom_point(data = resultados,
             aes(x = as.numeric(factor(Condition)) + 0.40,
                 y = 1 - (CV * sf)),
             color = "#2b8a3e",
             size = 3) +
  scale_y_continuous(
    name = "Polliniator contribution (mean)",
    sec.axis = sec_axis(
      trans = ~ (1 - .) / sf,
      name = "CV",
      breaks = seq(0, 0.5, by = 0.1) ),
    limits = c(0, 1)) +
  labs(x = "Time-since-fire condition") +
  theme_minimal() +
  theme(axis.text = element_text(size = 9))





####################
###4. Temporal variation in Seed production

#File: SeedSet_InteranualVariation.txt
seed<- read.table(file.choose(), header = TRUE)

seed$Condition<-as.factor(seed$Condition)
seed$Site<-as.factor(seed$Site)
seed$Period<-as.factor(seed$Period)

##Responde variable: successes/failures
seed$y<-cbind(seed$SeededFruit ,seed$SeedlessFruit)

#Orde Condition
orden_Conditions <- c("Recently", "Intermediate", "Unburned")
seed$Condition <- factor(seed$Condition, levels = orden_Conditions)

#Model
seed1 <- glmmTMB(y ~ Condition*Period + (1 | Site), data = seed, family = betabinomial())

res <- simulateResiduals(seed1)#Check assumptions
plot(res) 

#Model selection
seed2 <- glmmTMB(y ~ Condition+Period + (1 | Site), data = seed, family = betabinomial())

anova(seed1,seed2)# Chisq=47.579 , p=4.659e-11 ***Time-since-fire Condition interacted with sampling year

#Pairwise comparisons to see differences between time-since-fire Conditions and samplig year:
em_Condition <- emmeans(seed1, ~ Condition*Period) 
contrast(em_Condition, method = "pairwise", adjust = "tukey")

#Plot
ggplot(seed, aes(x = Condition, y = SeedSet, fill = Period)) +
  geom_boxplot(position = position_dodge(width = 0.8), 
               outlier.shape = NA, alpha = 0.5, color = "black", width = 0.6) +
  geom_jitter(aes(color = Period),
              position = position_jitterdodge(jitter.width = 0.15, dodge.width = 0.8),
              size = 2, alpha = 0.7) +
  labs(title = "",
       x = "Time-since-fire condition",
       y = "Seed set") +
  scale_fill_manual(values = c("#2b8a3e", "darkolivegreen2")) +
  scale_color_manual(values = c("#2b8a3e", "darkolivegreen2")) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = , hjust = 1),
        axis.text = element_text(size = 9),
        legend.title = element_blank())
