#Analysis
# 1. Loading required packages --------------------------------------------
require(here)
require(lme4)
require(bbmle) #AIC tab
require(MuMIn)
require(ggplot2)
require(glmmADMB)#negative binomial
require(cowplot) # To put plots together (plot_grid)
require(blmeco) # for overdispersion of GLMMS using the function dispersion_glmer - it shouldn't be over 1.4 
require(arm)
require(coefplot)

# 2. Load data ------------------------------------------------------------
##Data for Analysis
IndInfoSharedFood<-read.csv(file="IndInfoSharedFood1.csv",header=T)
BegDataJuv<-read.csv(file="Opportunities and Attempts of FT with Juv Receivers2.csv",header=T)
LearningData<-read.csv(file="Learning_GLMM_Data_Final.csv", header=T)

##Data for Plots
Fig2Data<-read.csv(file="TableFig1_Modif.csv",header=T)



# 3. Analysis: Qualitative analysis of food transfers ---------------------
Shareddata<-IndInfoSharedFood[IndInfoSharedFood$FoodShare==1,] #Extract only data that are food transfers
dim(Shareddata)
levels(Shareddata$Ind)
unique(Shareddata$Ind)
#233 food transfers attempts by 32 ind from the 42 ind present

dim(IndInfoSharedFood)
levels(IndInfoSharedFood$Action)
#3506 events (eat, explore, FT, scrounging, social eating)

##Proportion of food transfers in food related events
233/3506*100#FT related events make up 6.64575 % of all foraging related events

##Proportion of transfers that are successfull
SuccesfulFT<-Shareddata[Shareddata$Success==1,]
dim(SuccesfulFT)
111/233*100

##Proportion of food transfers made from non-juveniles to juveniles
#Ad-Juv Trans
Juv_AdFT<-Shareddata[Shareddata$ReceiverState.JM=="JU",]
Juv_AdFT<-Juv_AdFT[Juv_AdFT$DonorState.JM!="JU",]

dim(Juv_AdFT)#119 food transfers attempts by 10 juv
119/233*100 #51% of transfers made from ad to ju
unique(Juv_AdFT$Ind)#10 juvenile receives
unique(Juv_AdFT$FoodShare.Who) #25 adult/subadult donors

##Proportion of food transfers ade from non-juveniles to juveniles that are successful
JuvAd_SuccessfulFT<-Juv_AdFT[Juv_AdFT$Success==1,]
dim(JuvAd_SuccessfulFT)#63
63/119*100 ##53% of food transfer from non-juveniles to juveniles are successful

##Proportion of food obtained by all tamarins that were obtained from transfers
Injestion<-IndInfoSharedFood[IndInfoSharedFood$Success==1,]
dim(Injestion)#1243
111/1243*100

##Proportion of succesful food tranfers made with novel food
table(Shareddata$Success, Shareddata$Option)
38+33+40#total succesful ft =111
38+40#total successful ft with novel food=78
78/111*100

##Proportion of succesful food tranfers made with novel food, when non-juveniles are donors and juveniles are receivers
table(Juv_AdFT$Success,Juv_AdFT$Option)
26+21+16#total succesful food tranfer = 63
26+16#total successful food transfer with novel food = 42
42/63*100


##Proportion of donor-initiated transfer
DonorInitiate<-Shareddata[as.character(Shareddata$FoodShare.Who)==as.character(Shareddata$Initiate),]
dim(DonorInitiate)#12
12/233*100

##Proportion of donor-initiated transfers that were successful
DonorInitiateSuccess<-DonorInitiate[DonorInitiate$Success==1,]
dim(DonorInitiateSuccess)#12 - all donor initiated transsfers were successful

##Identify of donors and receviers of donor-initiated transfers
DonorInitiate$Ind
DonorInitiate$ReceiverSex
DonorInitiate$ReceiverState.JM
DonorInitiate$FoodShare.Who
DonorInitiate$DonorSex
DonorInitiate$DonorState.JM



# 4. Analysis: Probability of success in a food transfer ------------------
hist(Shareddata$Success)#approx similar number os 0s and 1s

# 4.1. Analysis with receiver and donor option specific success as --------

Success1<-glmer(Success~I(DonorState.JM=="JU")+I(ReceiverState.JM=="JU")+I(DonorSex=="F")+I(ReceiverSex=="F")+I(as.numeric(Option)==2)+ReceiverSuccess+DonorSuccess+(1|IndName)+(1|DonorName), na.action="na.fail", data=Shareddata, family=binomial,glmerControl(optimizer="bobyqa", optCtrl = list(maxfun = 100000)))
#singular fit - overfitting, so need to drop some random effects
summary(Success1)

Success2<-glmer(Success~I(DonorState.JM=="JU")+I(ReceiverState.JM=="JU")+I(DonorSex=="F")+I(ReceiverSex=="F")+I(as.numeric(Option)==2)+ReceiverSuccess+DonorSuccess+(1|IndName), na.action="na.fail", data=Shareddata, family=binomial,glmerControl(optimizer="bobyqa", optCtrl = list(maxfun = 100000)))
#singular fit
summary(Success2)
Success3<-glmer(Success~I(DonorState.JM=="JU")+I(ReceiverState.JM=="JU")+I(DonorSex=="F")+I(ReceiverSex=="F")+I(as.numeric(Option)==2)+ReceiverSuccess+DonorSuccess+(1|DonorName), na.action="na.fail", data=Shareddata, family=binomial,glmerControl(optimizer="bobyqa", optCtrl = list(maxfun = 100000)))
summary(Success3)
##try without RE, to see if it gives similar results
Success4<-glm(Success~I(DonorState.JM=="JU")+I(ReceiverState.JM=="JU")+I(DonorSex=="F")+I(ReceiverSex=="F")+I(as.numeric(Option)==2)+ReceiverSuccess+DonorSuccess, na.action="na.fail",data=Shareddata, family=binomial)
summary(Success4)
###Fairly similar results to when DonorID is a RE

#model validation
#deviance residuals
devresid<-resid(Success1,type="deviance")
hist(devresid)#none are >2, so model fits
#overdispersion
dispersion_glmer(Success1)#1.153464
#resid
sresid<-resid(Success1,type="pearson")
hist(sresid)
#residuals vs fitted
fits<-fitted(Success1)
plot(sresid~fits)
#residuals vs each variable
plot(sresid~I(Shareddata$DonorState.JM=="JU"))
plot(sresid~I(Shareddata$ReceiverState.JM=="JU"))
plot(sresid~I(Shareddata$DonorSex=="F"))
plot(sresid~I(Shareddata$ReceiverSex=="F"))
plot(sresid~I(as.numeric(Shareddata$Option==2)))
plot(sresid~Shareddata$ReceiverSuccess)
plot(sresid~Shareddata$DonorSuccess)

model.set1<-dredge(Success1)
#boundary (singular) fit: see ?isSingular
top.models1<-get.models(model.set1, subset=delta<2)
a1<-model.avg(top.models1)
summary(a1)


# 4.2. Analysis of Random effects -----------------------------------------
#Get top model
TopSuccess1<-glmer(Success~I(DonorState.JM == "JU")+(1|IndName)+(1|DonorName), na.action="na.fail", data=Shareddata, family=binomial)
summary(TopSuccess1)
#Get 95% CI
confint(TopSuccess1)
#Get Odds
exp(0.3339)
exp(0)
exp(0.8592917)

##Compare with model without donnor success as REto get significance of effect
TopSuccess_WoutRE<-glmer(Success~I(DonorState.JM == "JU")+(1|IndName), na.action="na.fail", data=Shareddata, family=binomial)
anova(TopSuccess_WoutRE,TopSuccess1)  




# 4.3. Analysis with receiver and donor option specific success as --------
Success_Binom1<-glmer(Success~I(DonorState.JM=="JU")+I(ReceiverState.JM=="JU")+I(DonorSex=="F")+I(ReceiverSex=="F")+I(as.numeric(Option)==2)+I(ReceiverSuccess>0)+I(DonorSuccess>0)+(1|IndName)+(1|DonorName), na.action="na.fail", data=Shareddata, family=binomial,glmerControl(optimizer="bobyqa", optCtrl = list(maxfun = 100000)))
#singular fit
summary(Success_Binom1)

Success_Binom2<-glmer(Success~I(DonorState.JM=="JU")+I(ReceiverState.JM=="JU")+I(DonorSex=="F")+I(ReceiverSex=="F")+I(as.numeric(Option)==2)+I(ReceiverSuccess>0)+I(DonorSuccess>0)+(1|IndName), na.action="na.fail", data=Shareddata, family=binomial,glmerControl(optimizer="bobyqa", optCtrl = list(maxfun = 100000)))
#singular fit
summary(Success_Binom2)
Success_Binom3<-glmer(Success~I(DonorState.JM=="JU")+I(ReceiverState.JM=="JU")+I(DonorSex=="F")+I(ReceiverSex=="F")+I(as.numeric(Option)==2)+I(ReceiverSuccess>0)+I(DonorSuccess>0)+(1|DonorName), na.action="na.fail", data=Shareddata, family=binomial,glmerControl(optimizer="bobyqa", optCtrl = list(maxfun = 100000)))
summary(Success_Binom3)
Success_Binom4<-glm(Success~I(DonorState.JM=="JU")+I(ReceiverState.JM=="JU")+I(DonorSex=="F")+I(ReceiverSex=="F")+I(as.numeric(Option)==2)+I(ReceiverSuccess>0)+I(DonorSuccess>0), na.action="na.fail",data=Shareddata, family=binomial)
summary(Success_Binom4)
#they  give similar results

#model validation
#deviance residuals
devresid<-resid(Success_Binom1,type="deviance")
hist(devresid)#none are >2, so model fits
#overdispersion
dispersion_glmer(Success_Binom1)#1.137521
#resid
sresid<-resid(Success_Binom1,type="pearson")
hist(sresid)
#residuals vs fittes
fits<-fitted(Success_Binom1)
plot(sresid~fits)
#residuals vs each variable
plot(sresid~I(Shareddata$DonorState.JM=="JU"))
plot(sresid~I(Shareddata$ReceiverState.JM=="JU"))
plot(sresid~I(Shareddata$DonorSex=="F"))
plot(sresid~I(Shareddata$ReceiverSex=="F"))
plot(sresid~I(as.numeric(Shareddata$Option==2)))
plot(sresid~I(Shareddata$ReceiverSuccess>0))
plot(sresid~I(Shareddata$DonorSuccess>0))



model.set_binom1<-dredge(Success_Binom1)
#boundary (singular) fit: see ?isSingular
top.models_binom1 <-get.models(model.set_binom1, subset=delta<2)
a_binom1<-model.avg(top.models_binom1)
summary(a_binom1)


###Plot
bar3<-ggplot(Fig2Data, aes(DonorSuccess, cbind(Success/(Success+Failure)),fill=DonorSuccess))
ProbaSuccess<-bar3+geom_boxplot()+
  labs(x="Donor Success", y="Proportion of successful food transfers")+
  theme_classic()+
  theme(legend.position="none")+
  #theme(legend.position="none",panel.background = element_rect(fill = 'white'))+
  theme(text = element_text(size=12),
        axis.text.x = element_text(size=10),
        axis.text.y = element_text(size=10))+
  scale_x_discrete(labels=c("FALSE" = "Donor Success = 0", "TRUE" = "Donor Success >0"))+
  scale_fill_manual(values = c("#E69F00","#0072B2"))+
  annotate(geom="text",x=1,y=0.15,label="3/17",size=6)+ #the label doesn't match the value on the graph because the label shows the total nb of success/total number of success+failure, whereas the graph shows the average per ind (to account for some ind having more or less weight)
  annotate(geom="text",x=2,y=0.40,label="108/216",size=6)
ProbaSuccess

# 4.4. Analysis of Random effects -----------------------------------------
#Get top model
TopSuccessBinom1<-glmer(Success~I(as.numeric(Option) == 2)+ I(DonorState.JM == "JU")+I(DonorSuccess > 0)+I(ReceiverSuccess > 0)+(1|IndName)+(1|DonorName), na.action="na.fail", data=Shareddata, family=binomial)
summary(TopSuccessBinom1)
#Get 95% CI
confint(TopSuccessBinom1)
#Get Odds
exp(0.3029)
exp(0)
exp(0.850396553)

##Compare with model without donnor success as REto get significance of effect
TopSuccessBinom_WoutRE<-glmer(Success~I(as.numeric(Option) == 2)+ I(DonorState.JM == "JU")+I(DonorSuccess > 0)+I(ReceiverSuccess > 0)+(1|IndName), na.action="na.fail", data=Shareddata, family=binomial)
anova(TopSuccessBinom_WoutRE,TopSuccessBinom1)  

# 5.1. Analysis: Probability of attempting a food transfer ------------------
BegDataJuv2<-BegDataJuv[BegDataJuv$Option!="Cricket",]#get rid of cricket option because so few events - 7 opportunities, 0 attempts
BegDataJuv3<-BegDataJuv2[BegDataJuv2$JuvenileDonor=="FALSE",]#only transfers between juv receivers, and non-juv donors
BegMod1<-glmer(cbind(Attempts, Opportunities -Attempts)~ Option+ RecPrevOSS+ FemaleDonor+FemaleReceiver+(1| PotRec)+(1| PotDonor), data=BegDataJuv3,family="binomial",na.action="na.fail")

##model validation
#check ofr normal distribution of residuals
sresid<-resid(BegMod1,type="pearson")
hist(sresid) # not very normal
#plot residuals vs fitted values
fits<-fitted(BegMod1)
plot(sresid~fits)
#plot residuals vs each varaible
plot(sresid~BegDataJuv3$Option)
plot(sresid~BegDataJuv3$RecPrevOSS)
plot(sresid~BegDataJuv3$FemaleDonor)
plot(sresid~BegDataJuv3$FemaleReceiver)
#overdispersion
dispersion_glmer(BegMod1)#0.9989371


model.set<-dredge(BegMod1)#convergence pb with dredge when newBegDataJuv2, but not with newBegDataJuv3
top.models <-get.models(model.set, subset=delta<2)
a<-model.avg(top.models)#,method="NA") # conditional average averages only on models that contain the parameter. I will use the full average for Thesis
summary(a)


###Plot
table(BegDataJuv3$Attempts, BegDataJuv3$RecPrevOSS)
5+1*2#=nb attempts when no previous exp=7
24+12*2+7*3+4*4+2*6+2*7#=nb attempts when previous exp=111
table(BegDataJuv3$Opportunities, BegDataJuv3$RecPrevOSS)
27+9*2+8*3+6*4+5+6#=nb opportunities when no previous exp=7=104
25+9*2+11*3+7*4+9*5+11*6+4*7+7*8+2*9+10+5*11+5*12+13+14+3*15+16+18+19+20+23+26+31#=nb opportunities when previous exp=667

#7 attempts where ind had not previously had that type of food, within 104 opportunities = 6.730769 %
#111 attempts where ind had previously had that type of food, within 667 opportunities = 16.64168 %
sum(BegDataJuv3$Opportunities)
#771 opportunities
sum(BegDataJuv3$Attempts)
#118 attempts

bar4<-ggplot(BegDataJuv3, aes(RecPrevOSS, cbind(Attempts/Opportunities),fill=RecPrevOSS))
ProbaAttempt<-bar4+geom_boxplot()+
  labs(x="Receiver Success", y="Proportion of attempted food transfers")+#, given opportunity")+
  theme_classic()+
  theme(legend.position="none")+
  #theme(legend.position="none",panel.background = element_rect(fill = 'white'))+
  theme(text = element_text(size=12),
        axis.text.x = element_text(size=10),
        axis.text.y = element_text(size=10))+
  scale_x_discrete(labels=c("FALSE" = "Receiver Success = 0", "TRUE" = "Receiver Success >0"))+
  scale_fill_manual(values = c("#E69F00","#0072B2"))+
  annotate(geom="text",x=1,y=0.05,label="7/104",size=6)+ #the label doesn't mathc the value on the graph because the label shows the total nb of success/total number of success+failure, whereas the graph shows the average per ind (to account for some ind having more or less weight)
  annotate(geom="text",x=2,y=0.15,label="111/667",size=6)
ProbaAttempt



##Putting Figure 2 together
plot_grid(ProbaSuccess,ProbaAttempt, labels = c("A","B"))


# 5.2. Analysis of Random effects -----------------------------------------
#Get top model
TopBeg1<-glmer(cbind(Attempts, Opportunities -Attempts)~RecPrevOSS+(1| PotRec)+(1| PotDonor), data=BegDataJuv3,family="binomial",na.action="na.fail")
summary(TopBeg1)
#Get 95% CI
confint(TopBeg1)
#Get Odds
exp(0.3719 )
exp(0)
exp(0.7811319)

##Compare with model without donnor success as REto get significance of effect
TopBeg_WoutRE<-glmer(cbind(Attempts, Opportunities -Attempts)~RecPrevOSS+(1| PotRec), data=BegDataJuv3,family="binomial",na.action="na.fail")
anova(TopBeg_WoutRE,TopBeg1)  


# 6.1. Analysis: Probability of resistance during a food transfer -----------
Shareddata_Sel_Res<-Shareddata[Shareddata$Resistance!=2,]#get rid of 3 cases where resistance is unknown - now based on 230 FT
###Only juv as receipient and nonjuv as adults
Res_Juv_AdFT<-Shareddata_Sel_Res[Shareddata_Sel_Res$ReceiverState.JM=="JU",]
Res_Juv_AdFT<-Res_Juv_AdFT[Res_Juv_AdFT$DonorState.JM!="JU",]#select food transfers where juv were receivers, and non juv were donors
table(Res_Juv_AdFT$Resistance, Res_Juv_AdFT$Success)
sum(Res_Juv_AdFT$Resistance)#72
dim(Res_Juv_AdFT)#116

####Analysis
ModelRes1<-glmer(Resistance~I(DonorSex=="F")+I(ReceiverSex=="F")+Option+I(ReceiverSuccess>0)+I(DonorSuccess>0)+(1|IndName)+(1|DonorName), na.action="na.fail", data=Res_Juv_AdFT, family=binomial,glmerControl(optimizer="bobyqa", optCtrl = list(maxfun = 10000000)))
#singular fit- overfitting, so need to drop some random effects
summary(ModelRes1)

ModelRes2<-glmer(Resistance~I(DonorSex=="F")+I(ReceiverSex=="F")+Option+I(ReceiverSuccess>0)+I(DonorSuccess>0)+(1|IndName), na.action="na.fail", data=Res_Juv_AdFT, family=binomial,glmerControl(optimizer="bobyqa", optCtrl = list(maxfun = 10000000)))
summary(ModelRes2)

ModelRes3<-glmer(Resistance~I(DonorSex=="F")+I(ReceiverSex=="F")+Option+I(ReceiverSuccess>0)+I(DonorSuccess>0)+(1|DonorName), na.action="na.fail", data=Res_Juv_AdFT, family=binomial,glmerControl(optimizer="bobyqa", optCtrl = list(maxfun = 10000000)))
summary(ModelRes3)
##try without RE, to see if it gives similar results
ModelRes4<-glm(Resistance~I(DonorSex=="F")+I(ReceiverSex=="F")+Option+I(ReceiverSuccess>0)+I(DonorSuccess>0), na.action="na.fail", data=Res_Juv_AdFT, family=binomial)
summary(ModelRes4)
###Fairly similar results to when DonorID is a RE

#model validation
#deviance residuals
devresid<-resid(ModelRes1,type="deviance")
hist(devresid)#none are >2, so model fits
#overdispersion
dispersion_glmer(ModelRes1)#1.00122
#resid
sresid<-resid(ModelRes1,type="pearson")
hist(sresid)
#residuals vs fittes
fits<-fitted(ModelRes1)
plot(sresid~fits)
#residuals vs each variable
plot(sresid~I(Res_Juv_AdFT$DonorSex=="F"))
plot(sresid~I(Res_Juv_AdFT$ReceiverSex=="F"))
plot(sresid~Res_Juv_AdFT$Option)
plot(sresid~I(Res_Juv_AdFT$ReceiverSuccess>0))
plot(sresid~I(Res_Juv_AdFT$DonorSuccess>0))



model.set.Res1<-dredge(ModelRes1)
#boundary (singular) fit: see ?isSingular
top.models.res1<-get.models(model.set.Res1, subset=delta<2)
ares1<-model.avg(top.models.res1)
summary(ares1)

# 6.2. Analysis of Random effects -----------------------------------------
#Get top model
TopRes1<-glmer(Resistance~(1|IndName)+(1|DonorName), na.action="na.fail", data=Res_Juv_AdFT, family=binomial)
summary(TopRes1)
#Get 95% CI
confint(TopRes1)
#Get Odds
exp(1.135)
exp(0.5081871)
exp(2.179613)

##Compare with model without donnor success as REto get significance of effect
TopRes_WoutRE<-glmer(Resistance~(1|IndName), na.action="na.fail", data=Res_Juv_AdFT, family=binomial)
anova(TopRes_WoutRE,TopRes1)  


# 7. Analysis: Learning - does previous experience affect current  --------
head(LearningData)

hist(LearningData$Eat_Phase2)
sum(LearningData$Eat_Phase2==0)#30
dim(LearningData)#49 lines in totals
30/49#61% of lines are 0 - potential for 0 inflated data


modpoiss<-glmmadmb(Eat_Phase2~Individual_Eating+Explore+Social_Eating+(1|Ind),
                   family="poisson", link="log",
                   zeroInflation=TRUE,
                   data=LearningData)
summary(modpoiss)
E1<-residuals(modpoiss)
p<-length(fixef(modpoiss))+1#+1 due to random intercept of variance
Over<-sum(E1^2)/(nrow(LearningData)-p)
Over#454.7068

modpoissNOZIP<-glmmadmb(Eat_Phase2~Individual_Eating+Explore+Social_Eating+(1|Ind),
                        family="poisson", link="log",
                        #zeroInflation=TRUE,
                        data=LearningData)
summary(modpoissNOZIP)
E1<-residuals(modpoissNOZIP)
p<-length(fixef(modpoissNOZIP))+1
Over<-sum(E1^2)/(nrow(LearningData)-p)
Over#587.7641

modnegbin<-glmmadmb(Eat_Phase2~Individual_Eating+Explore+Social_Eating+(1|Ind),
                    family="nbinom", link="log",
                    zeroInflation=TRUE,
                    data=LearningData)
summary(modnegbin)
E1<-residuals(modnegbin)
p<-length(fixef(modnegbin))+1
Over<-sum(E1^2)/(nrow(LearningData)-p)
Over#1.09773

modnegbinNOZIP<-glmmadmb(Eat_Phase2~Individual_Eating+Explore+Social_Eating+(1|Ind),
                         family="nbinom", link="log",
                         #zeroInflation=TRUE,
                         data=LearningData)
summary(modnegbinNOZIP)
E1<-residuals(modnegbinNOZIP)
p<-length(fixef(modnegbinNOZIP))+1
Over<-sum(E1^2)/(nrow(LearningData)-p)
Over#0.6147248

modnegbin1<-glmmadmb(Eat_Phase2~Individual_Eating+Explore+Social_Eating+(1|Ind),
                     family="nbinom1", link="log",
                     zeroInflation=TRUE,
                     data=LearningData)
summary(modnegbin1)
E1<-residuals(modnegbin1)
p<-length(fixef(modnegbin1))+1
Over<-sum(E1^2)/(nrow(LearningData)-p)
Over#4.04096

modnegbin1NOZIP<-glmmadmb(Eat_Phase2~Individual_Eating+Explore+Social_Eating+(1|Ind),
                          family="nbinom1", link="log",
                          #zeroInflation=TRUE,
                          data=LearningData)
summary(modnegbin1NOZIP)
E1<-residuals(modnegbin1NOZIP,type="pearson")
p<-length(fixef(modnegbin1NOZIP))+1
Over<-sum(E1^2)/(nrow(LearningData)-p)
Over#18.83853


AICtab(modpoiss,modnegbin,modnegbin1,modpoissNOZIP,modnegbinNOZIP,modnegbin1NOZIP)
##modnegbin1 is best fit. But has more oversidpersion than modnegbin

###Coefficient Plot for model selection
multiplot("poisson"=modpoissNOZIP,
"ZIP"=modpoiss,
"negbin"=modnegbinNOZIP,
"ZINB"=modnegbin,
"negbin1"=modnegbin1NOZIP,
"ZINB1"=modnegbin1)



##Model selection of negative binomial model that is underdispersed
model.set.Learning<-dredge(modnegbin)
top.models.Learning<-get.models(model.set.Learning,subset=delta<2)
averaged.model.Learning<-model.avg(top.models.Learning)
summary(averaged.model.Learning)

