#############The following packages need to be installed with: install.packages("name of the package") before calling them
#############code and functions need to be run first before use

#############calling used packages

#computational packages and code
#R version 3.6.1: "Action of the Toes"
library(plyr)#version 1.8.4
library(dplyr)#version 0.8.3
drop.levels <- function(dat){
  # Drop unused factor levels from all factors in a data.frame
  # Author: Kevin Wright.  Idea by Brian Ripley.
  dat[] <- lapply(dat, function(x) x[,drop=TRUE])
  return(dat)
}

#graphical packages
library(ggplot2)#version 3.2.1
library(ggkm)#version 0.6.0; see https://github.com/sachsmc/ggkm

#statistical packages
library(lme4)#version 1.1-21
library(multcomp)#version 1.4-10
library(DHARMa)#version 0.2.4
library(coxme)#2.2-14
library(glmmTMB)#version 0.2.3

#in order for the package multcomp to work with glmmTMB you need this function see: https://github.com/glmmTMB/glmmTMB/blob/master/glmmTMB/vignettes/model_evaluation.rmd
glht_glmmTMB <- function (model, ..., component="cond") {
    glht(model, ...,
         coef. = function(x) fixef(x)[[component]],
         vcov. = function(x) vcov(x)[[component]],
         df = NULL)
}
modelparm.glmmTMB <- function (model, coef. = function(x) fixef(x)[[component]],
                               vcov. = function(x) vcov(x)[[component]],
                               df = NULL, component="cond", ...) {
    multcomp:::modelparm.default(model, coef. = coef., vcov. = vcov.,
                        df = df, ...)
}




######################################################################################################
######################### Fig 1 a,b,c: Crop acidification ############################################
######################################################################################################

#############loading data for Fig.1a
acidification.c.floridanus<-read.delim(file.choose(),header=T)#choose file: Supplementary Data Fig.1a.txt
str(acidification.c.floridanus)
acidification.c.floridanus$time<-factor(acidification.c.floridanus$time,c("0+4h","0+24h","0+48h","48+4h"))#reorder factor time


#############statistcal analysis
m.acidification.c.floridanus<-lmer(log(ph)~time+(1|colony),data=acidification.c.floridanus)
summary(m.acidification.c.floridanus)

#model validation
res.m.acidification.c.floridanus<-simulateResiduals(fittedModel=m.acidification.c.floridanus)
plot(res.m.acidification.c.floridanus)

#significance of predictor time since feeding (four levels: 0+4h, 0+24h, 0+48h, 48h+4h)
m.acidification.c.floridanus0<-lmer(log(ph)~1+(1|colony),data=acidification.c.floridanus)
anova(m.acidification.c.floridanus,m.acidification.c.floridanus0)

#post-hoc comporisons of predictor-levels time since feeding
m.acidification.c.floridanus.glht<-glht(m.acidification.c.floridanus,linfct=mcp(time="Tukey"))
summary(m.acidification.c.floridanus.glht,test=adjusted("Westfall"))


#############plot fig.1a
#calculation of median values and confidence intervals of predictor time since feeding (four levels: 0+4h, 0+24h, 0+48h, 48h+4h)
ph.summary.c.floridanus<-ddply(acidification.c.floridanus,"time",summarize,
N=length(ph),
median=quantile(ph,0.5),
lowerCI=quantile(ph,0.025),
upperCI=quantile(ph,0.975))
ph.summary.c.floridanus

#addition of median values per time since feeding into the data.frame as a new variable
acidification.c.floridanus2<-acidification.c.floridanus%>%group_by(time)%>%mutate(medianph=median(ph))

#definition of universal ph indicator colors: 1-6
ph.colors.rgb1<-c(
"202 58 67",
"235 81 42",
"252 125 19",
"253 190 2",
"254 250 0",
"235 230 54"
)

#transformation of RGB colors into hex colors
ph.colors.hex1<-sapply(strsplit(ph.colors.rgb1, " "), function(ph.colors.rgb1)
    rgb(ph.colors.rgb1[1], ph.colors.rgb1[2], ph.colors.rgb1[3], maxColorValue=255))

#plotting of Fig.1a
fig.1a<-ggplot()+
geom_boxplot(data=acidification.c.floridanus2,mapping=aes(x=time,y=ph,fill=medianph),colour="grey30",lwd=1.5,outlier.shape=NA,alpha=0.5,width=0.4,coef=0)+
scale_fill_gradientn(colours=ph.colors.hex1,breaks=c(1,2,3,4,5,6),limits=c(1,6.5),guide=FALSE)+
geom_point(data = acidification.c.floridanus,mapping=aes(x=time,y=ph,fill=ph),pch=21,color="white",position=position_jitter(width=0.1),size=6.5,alpha=1)+
scale_x_discrete(name="Time after feeding",labels=c("0h+4h","0h+24h","0h+48h","48h+4h"))+
scale_y_continuous(name="pH-value",limits=c(1,6),breaks=c(1,2,3,4,5,6))+
annotate("text",x=c(1,2,3,4),y=c(5.5,4.4,4,5.5),size=14,label=c("a","b","c","a"),fontface=2)+#statistical significance 
annotate("text",x=c(2.5),y=c(6),size=16,label=c("***"),fontface=2)+
theme(axis.line = element_line(colour = "black",size=1.5),
      axis.ticks=element_line(colour="black",size=1.5),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=35),
      axis.text.y=element_text(colour="black",size=35),
      axis.title.x=element_text(colour="black",size=40,margin=margin(20,0,0,0)),
      axis.title.y=element_text(colour="black",size=40,margin=margin(0,22,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15),
      legend.key.size=unit(1.2,"cm"),
      legend.key.height=unit(4,"cm"),
      legend.key=element_blank(),
      legend.position="right")
fig.1a




#############loading data for Fig.1b
mobility.c.floridanus<-read.delim(file.choose(),header=T)#choose file: Supplementary Data Fig.1b.txt
str(mobility.c.floridanus)


#############statistcal analysis
m.mobility.c.floridanus<-lmer(ph~treatment+(1|colony),data=mobility.c.floridanus)
summary(m.mobility.c.floridanus)

#model validation
res.m.mobility.c.floridanus<-simulateResiduals(fittedModel=m.mobility.c.floridanus)
plot(res.m.mobility.c.floridanus)

#significance of predictor ant manipulation (two levels: FA+ and FA-, i.e. ants with and without acidopore access)
m.mobility.c.floridanus0<-lmer(ph~1+(1|colony),data=mobility.c.floridanus)
anova(m.mobility.c.floridanus,m.mobility.c.floridanus0)


#############plot fig.1b
#calculation of median values and confidence intervals of predictor ant manipulation
ph.summary.mobility.c.floridanus<-ddply(mobility.c.floridanus,"treatment",summarize,
N=length(ph),
median=quantile(ph,0.5),
lowerCI=quantile(ph,0.025),
upperCI=quantile(ph,0.975))
ph.summary.mobility.c.floridanus

#addition of median values per ant manipulation into the data.frame as a new variable
mobility.c.floridanus2<-mobility.c.floridanus%>%group_by(treatment)%>%mutate(medianph=median(ph))

#definition of universal ph indicator colors: 1-6
ph.colors.rgb1<-c(
"202 58 67",
"235 81 42",
"252 125 19",
"253 190 2",
"254 250 0",
"235 230 54"
)

#transformation of RGB colors into hex colors
ph.colors.hex1<-sapply(strsplit(ph.colors.rgb1, " "), function(ph.colors.rgb1)
    rgb(ph.colors.rgb1[1], ph.colors.rgb1[2], ph.colors.rgb1[3], maxColorValue=255))

#plotting of Fig.1b
fig.1b<-ggplot()+
geom_boxplot(data=mobility.c.floridanus2,mapping=aes(x=treatment,y=ph,fill=medianph,colour=treatment),outlier.shape=NA,lwd=1.5,alpha=0.5,width=0.6,coef=0)+
scale_fill_gradientn(colours=ph.colors.hex1,breaks=c(1,2,3,4,5,6),limits=c(1,6.5),guide=FALSE)+
scale_color_manual(values=c("grey70","grey30"),guide=FALSE)+
geom_point(data = mobility.c.floridanus, mapping=aes(x=treatment,y=ph,fill=ph),pch=21,color="white",position=position_jitter(width=0.1),size=6.5,alpha=1)+
scale_x_discrete(name="Treatment",labels=c("FA -","FA +"))+
scale_y_continuous(name="pH-value",limits=c(1,6),breaks=c(1,2,3,4,5,6))+
geom_segment(aes(x = 1, y = 5.5, xend = 2, yend = 5.5),lwd=1.5)+
annotate("text",x=c(1.5),y=c(5.6),size=16,label=c("***"),fontface=2)+#statistical significance 
theme(axis.line = element_line(colour = "black",size=1.5),
      axis.ticks=element_line(colour="black",size=1.5),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=35),
      axis.text.y=element_text(colour="black",size=35),
      axis.title.x=element_text(colour="black",size=40,margin=margin(20,0,0,0)),
      axis.title.y=element_text(colour="black",size=40,margin=margin(0,22,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15),
      legend.key.size=unit(1.2,"cm"),
      legend.key.height=unit(4,"cm"),
      legend.key=element_blank(),
      legend.position="right")
fig.1b




#############loading data for Fig.1c
mobility.formicine.ants<-read.delim(file.choose(),header=T)#choose data: Supplementary Data Fig.1c.txt
str(mobility.formicine.ants)

#subsetting the data frame into the six formicine ant species
mobility.c.maculatus<-subset(mobility.formicine.ants,colony=="c2")
mobility.c.maculatus<-drop.levels(mobility.c.maculatus)
str(mobility.c.maculatus)

mobility.l.fuliginosus<-subset(mobility.formicine.ants,colony=="l1")
mobility.l.fuliginosus<-drop.levels(mobility.l.fuliginosus)
str(mobility.l.fuliginosus)

mobility.f.pratensis<-subset(mobility.formicine.ants,colony=="f1")
mobility.f.pratensis<-drop.levels(mobility.f.pratensis)
str(mobility.f.pratensis)

mobility.f.rufibarbis<-subset(mobility.formicine.ants,colony=="f2")
mobility.f.rufibarbis<-drop.levels(mobility.f.rufibarbis)
str(mobility.f.rufibarbis)

mobility.f.cinerea<-subset(mobility.formicine.ants,colony=="f3")
mobility.f.cinerea<-drop.levels(mobility.f.cinerea)
str(mobility.f.cinerea)

mobility.f.cunicularia<-subset(mobility.formicine.ants,colony=="f4")
mobility.f.cunicularia<-drop.levels(mobility.f.cunicularia)
str(mobility.f.cunicularia)

mobility.f.fuscocinerea<-subset(mobility.formicine.ants,colony=="f5")
mobility.f.fuscocinerea<-drop.levels(mobility.f.fuscocinerea)
str(mobility.f.fuscocinerea)


#############statistcal analysis
wilcox.test(ph~treatment,data=mobility.c.maculatus)
wilcox.test(ph~treatment,data=mobility.l.fuliginosus)
wilcox.test(ph~treatment,data=mobility.f.pratensis)
wilcox.test(ph~treatment,data=mobility.f.rufibarbis)
wilcox.test(ph~treatment,data=mobility.f.cinerea)
wilcox.test(ph~treatment,data=mobility.f.cunicularia)
wilcox.test(ph~treatment,data=mobility.f.fuscocinerea)


#############plot fig.1c
mobility.formicine.ants$species2<-factor(mobility.formicine.ants$species,levels=c("maculatus","fuliginosus","cinerea","cunicularia","fuscocinerea","pratensis","rufibarbis"))#reorder facotr species

#calculation of median values and confidence intervals of predictor ant manipulation (two levels:FA- and FA+) and of factor species (six levels)
ph.summary.mobility.formicine.ants<-ddply(mobility.formicine.ants,c("species2","treatment"),summarize,
N=length(ph),
median=quantile(ph,0.5),
lowerCI=quantile(ph,0.025),
upperCI=quantile(ph,0.975))
ph.summary.mobility.formicine.ants

#addition of median values per ant manipulation into the data.frame as a new variable
mobility.formicine.ants2<-mobility.formicine.ants%>%group_by(colony,treatment)%>%mutate(medianph=median(ph))

#definition of universal ph indicator colors: 1-6
ph.colors.rgb1<-c(
"202 58 67",
"235 81 42",
"252 125 19",
"253 190 2",
"254 250 0",
"235 230 54"
)

#transformation of RGB colors into hex colors
ph.colors.hex1<-sapply(strsplit(ph.colors.rgb1, " "), function(ph.colors.rgb1)
    rgb(ph.colors.rgb1[1], ph.colors.rgb1[2], ph.colors.rgb1[3], maxColorValue=255))

#plotting of Fig.1c
fig.1c<-ggplot()+
geom_boxplot(data=mobility.formicine.ants2,mapping=aes(x=species2,y=ph,fill=medianph,colour=treatment),position=position_dodge(0.5),outlier.shape=NA,lwd=1.5,alpha=0.5,width=0.4,coef=0)+
scale_fill_gradientn(colours=ph.colors.hex1,guide=FALSE,breaks=c(1,2,3,4,5,6),limits=c(1,6.5))+
scale_color_manual(values=c("grey70","grey30"),name="Animal treatment:",labels=c("FA-","FA+"))+
geom_point(data = mobility.formicine.ants, mapping=aes(x=species2,y=ph,fill=ph,group=treatment),pch=21,color="white",position=position_jitterdodge(jitter.width=0.1,jitter.height=0.05,dodge.width=0.5),size=5,alpha=1)+
scale_x_discrete(name="Species",
labels=c(
expression(paste(italic("C. maculatus"))),
expression(paste(italic("L. fuliginosus"))),
expression(paste(italic("F. cinerea"))),
expression(paste(italic("F.cunicularia"))),
expression(paste(italic("F. fuscocinerea"))),
expression(paste(italic("F. pratensis"))),
expression(paste(italic("F. rufibarbis")))
))+
scale_y_continuous(name="pH-value",limits=c(1,6),breaks=c(1,2,3,4,5,6))+
geom_segment(aes(x = 0.875, y = 3.9, xend = 1.125, yend = 3.9),lwd=2)+
geom_segment(aes(x = 1.875, y = 3.9, xend = 2.125, yend = 3.9),lwd=2)+
geom_segment(aes(x = 2.875, y = 4.9, xend = 3.125, yend = 4.9),lwd=2)+
geom_segment(aes(x = 3.875, y = 4.9, xend = 4.125, yend = 4.9),lwd=2)+
geom_segment(aes(x = 4.875, y = 4.9, xend = 5.125, yend = 4.9),lwd=2)+
geom_segment(aes(x = 5.875, y = 5.4, xend = 6.125, yend = 5.4),lwd=2)+
geom_segment(aes(x = 6.875, y = 4.4, xend = 7.125, yend = 4.4),lwd=2)+
annotate("text",x=c(1,2,3,4,5,6,7),y=c(4.1,4.1,5.1,5.1,5.1,5.6,4.6),size=8,label=
c(
expression(paste(italic("P")," = 0.036")),
expression(paste(italic("P")," < 0.001")),
expression(paste(italic("P")," < 0.001")),
expression(paste(italic("P")," = 0.007")),
expression(paste(italic("P")," < 0.001")),
expression(paste(italic("P")," = 0.018")),
expression(paste(italic("P")," < 0.001"))),
fontface=1)+
theme(axis.line = element_line(colour = "black",size=1.5),
      axis.ticks=element_line(colour="black",size=1.5),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=30,angle=50,hjust=1),
      axis.text.y=element_text(colour="black",size=30),
      axis.title.x=element_text(colour="black",size=40,margin=margin(20,0,0,0)),
      axis.title.y=element_text(colour="black",size=40,margin=margin(0,22,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=30),
      legend.text=element_text(size=30),
      legend.key.size=unit(1.2,"cm"),
      legend.key.height=unit(4,"cm"),
      legend.key=element_blank(),
      legend.position="right")
fig.1c



######################################################################################################
###################### Fig. 1 - figure supplement 1: crop acidity baseline ###########################
######################################################################################################

#############loading data for Fig.1 - figure supplement 1
acidification.baseline<-read.delim(file.choose(),header=T)#choose file: Supplementary Data Fig.1 - figure supplement 1.txt
str(acidification.baseline)

#calculation of median values and confidence intervals of predictor status (two levels:satiated and starved) and worker caste (two levels: minor and major)
ph.summary.acidification.baseline<-ddply(acidification.baseline,c("status","caste"),summarize,
N=length(ph),
median=quantile(ph,0.5),
lowerCI=quantile(ph,0.025),
upperCI=quantile(ph,0.975))
ph.summary.acidification.baseline

#addition of median values per status and caste into the data.frame as a new variable
acidification.baseline2<-acidification.baseline%>%group_by(status,caste)%>%mutate(medianph=median(ph))

#definition of universal ph indicator colors: 1-6
ph.colors.rgb1<-c(
"202 58 67",
"235 81 42",
"252 125 19",
"253 190 2",
"254 250 0",
"235 230 54"
)

#transformation of RGB colors into hex colors
ph.colors.hex1<-sapply(strsplit(ph.colors.rgb1, " "), function(ph.colors.rgb1)
    rgb(ph.colors.rgb1[1], ph.colors.rgb1[2], ph.colors.rgb1[3], maxColorValue=255))

#plotting of Fig.1 - figure supplement 1
fig.1.figure.supplement1<-ggplot()+
geom_boxplot(data=acidification.baseline2,mapping=aes(x=status,y=ph,fill=medianph,colour=caste),position=position_dodge(0.5),outlier.shape=NA,lwd=1.5,alpha=0.5,width=0.4,coef=0)+
scale_fill_gradientn(colours=ph.colors.hex1,guide=FALSE,breaks=c(1,2,3,4,5,6),limits=c(1,6.5))+
scale_color_manual(values=c("grey70","grey30"),name="Worker caste:",labels=c("Major","Minor"))+
geom_point(data = acidification.baseline, mapping=aes(x=status,y=ph,fill=ph,group=caste),pch=21,color="white",position=position_jitterdodge(jitter.width=0.1,jitter.height=0.05,dodge.width=0.5),size=5,alpha=1)+
scale_x_discrete(name="Animal feeding status",labels=c("Colony:\nsatiated","Colony cohort:\nstarved"))+
scale_y_continuous(name="pH-value",limits=c(1,6),breaks=c(1,2,3,4,5,6))+
theme(axis.line = element_line(colour = "black",size=1.5),
      axis.ticks=element_line(colour="black",size=1.5),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=30,angle=30,hjust=1),
      axis.text.y=element_text(colour="black",size=30),
      axis.title.x=element_text(colour="black",size=40,margin=margin(20,0,0,0)),
      axis.title.y=element_text(colour="black",size=40,margin=margin(0,22,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=30),
      legend.text=element_text(size=30),
      legend.key.size=unit(1.2,"cm"),
      legend.key.height=unit(4,"cm"),
      legend.key=element_blank(),
      legend.position="right")
fig.1.figure.supplement1




######################################################################################################
###################### Fig. 1 - figure supplement 2: acidopore grooming ##############################
######################################################################################################

#############loading data for Fig. 1 - figure supplement 2
acidopore.grooming<-read.delim(file.choose(),header=T)#choose file: Supplementary Data Fig.1 - figure supplement 2.txt
str(acidopore.grooming)
food.treatment1<-factor(acidopore.grooming$food.treatment,levels=c("unfed","water","honey"))#reorder factor treatment


#############statistcal analysis
m.grooming<-glmer.nb(groomingevents~food.treatment+(1|colony),data=acidopore.grooming)
summary(m.grooming)

#model validation
res.m.grooming<-simulateResiduals(fittedModel=m.grooming)
plot(res.m.grooming)

#significance of predictor food treatment (three levels: unfed, water, honey)
m.grooming0<-glmer.nb(groomingevents~1+(1|colony),data=acidopore.grooming)
anova(m.grooming,m.grooming0)

#post-hoc comporisons of predictor-levels food treatment
m.grooming.glht<-glht(m.grooming,linfct=mcp(food.treatment="Tukey"))
summary(m.grooming.glht,test=adjusted("Westfall"))


############plot Fig. 1 - figure supplement 2
fig.1.figure.supplement2<-ggplot()+
geom_boxplot(data=acidopore.grooming,mapping=aes(x=food.treatment1,y=groomingevents,fill=food.treatment1),outlier.shape=NA,lwd=1.5,alpha=0.2,width=0.4,coef=0)+
geom_point(data=acidopore.grooming,mapping=aes(x=food.treatment1,y=groomingevents,color=food.treatment1),position=position_jitter(width=0.1),size=4,alpha=0.7)+
scale_fill_manual(values=c("white","white","white"),name="Food treatment (Mean/Median):",labels=c("unfed","water","honey"),guide=FALSE)+
scale_colour_manual(values=c("grey","dodgerblue","yellow1"),name="Raw data",guide=FALSE)+
scale_x_discrete(name="Food",labels=c("unfed","water","honey"))+
scale_y_continuous(name="Acidopre grooming frequency",limits=c(-0.5,15))+
annotate("text",x=c(1,2,3),y=c(8,11,11),size=10,label=c("a","b","b"),fontface=2)+
annotate("text",x=c(2),y=c(14),size=16,label=c("***"),fontface=2)+
theme(axis.line = element_line(colour = "black",size=1.5),
      axis.ticks=element_line(colour="black",size=1.5),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=18),
      axis.text.y=element_text(colour="black",size=18),
      axis.title.x=element_text(colour="black",size=25,margin=margin(20,0,0,0)),
      axis.title.y=element_text(colour="black",size=25,margin=margin(0,22,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15),
      legend.key.size=unit(1.2,"cm"),
      legend.key=element_blank(),
      legend.position="right")
fig.1.figure.supplement2




######################################################################################################
############################### Fig. 1 - figure supplement 3: pH midgut  #############################
######################################################################################################


#############loading data for Fig.1 - figure supplement 3
ph.midgut<-read.delim(file.choose(), header=T)#choose data: Supplementary Data Fig.1 - figure supplement 3.txt
str(ph.midgut)


#############statistcal analysis
m.ph.midgut<-lmer(ph~gutregion+(1|colony),data=ph.midgut)
summary(m.ph.midugut)

#model validation
res.m.ph.midgut<-simulateResiduals(fittedModel=m.ph.midgut)
plot(res.m.ph.midgut)

#significance of predictor gutregion (five levels: crop, midgut.position1, midgut.position2, midgut.position3, midgut.position4)
m.ph.midgut0<-lmer(ph~1+(1|colony),data=ph.midgut)
anova(m.ph.midgut,m.ph.midgut0)

#post-hoc comporisons of predictor-levels position 
m.ph.midgut.glht<-glht(m.ph.midgut,linfct=mcp(gutregion="Tukey"))
summary(m.ph.midgut.glht,test=adjusted("Westfall"))


#############plot Fig.1 - figure supplement 3
#calculation of median values and confidence intervals of predictor position 
ph.summary.midgut<-ddply(ph.midgut,"gutregion",summarize,
N=sum(!is.na(ph)),
median=quantile(ph,0.5,na.rm=TRUE),
lowerCI=quantile(ph,0.025,na.rm=TRUE),
upperCI=quantile(ph,0.975,na.rm=TRUE))
ph.summary.midgut

#addition of median values per position into the data.frame as a new variable
ph.midgut2<-ph.midgut%>%group_by(gutregion)%>%mutate(medianph=median(ph,na.rm=TRUE))

#definition of universal ph indicator colors: 1-7
ph.colors.rgb<-c(
"202 58 67",
"235 81 42",
"252 125 19",
"253 190 2",
"254 250 0",
"235 230 54",
"133 203 40"
)

#transformation of RGB colors into hex colors
ph.colors.hex<-sapply(strsplit(ph.colors.rgb, " "), function(ph.colors.rgb)
    rgb(ph.colors.rgb[1], ph.colors.rgb[2], ph.colors.rgb[3], maxColorValue=255))

#plotting of Fig.1 - figure supplement 3
fig.1.figure.supplement3<-ggplot()+
geom_boxplot(data=ph.midgut2,mapping=aes(x=gutregion,y=ph,fill=medianph),colour="grey30",lwd=1.5,outlier.shape=NA,alpha=0.5,coef=0)+
scale_fill_gradientn(colours=ph.colors.hex,guide=FALSE,breaks=c(1,2,3,4,5,6,7),limits=c(1,7.5))+
geom_point(data=ph.midgut2,mapping=aes(x=gutregion,y=ph,fill=ph),pch=21,color="white",position=position_jitter(width=0.1),size=6.5,alpha=1)+
scale_x_discrete(name="Gut position",labels=c("Crop","Midgut\nposition 1","Midgut\nposition 2","Midgut\nposition 3","Midgut\nposition 4"))+
scale_y_continuous(name="pH-value",limits=c(1,7),breaks=c(1,2,3,4,5,6,7))+
annotate("text",x=c(1,2,3,4,5),y=c(4.5,6.5,6.5,6.5,6.5),size=9,label=c("a","b","b","b","b"),fontface=2)+
theme(axis.line = element_line(colour = "black",size=1.5),
      axis.ticks=element_line(colour="black",size=1.5),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=20),
      axis.text.y=element_text(colour="black",size=20),
      axis.title.x=element_text(colour="black",size=25,margin=margin(20,0,0,0)),
      axis.title.y=element_text(colour="black",size=25,margin=margin(0,22,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15),
      legend.key.size=unit(1.2,"cm"),
      legend.key.height=unit(3.6,"cm"),
      legend.key=element_blank(),
      legend.position="right")
fig.1.figure.supplement3




######################################################################################################
############################### Fig 2 a,b: Serratia viability in vivo ################################
######################################################################################################

#############loading data for Fig.2a,b
growth.serratia<-read.delim(file.choose(),header=T)#choose data file: Supplementary Data Fig.2a,b.txt
str(growth.serratia)

#create factor variable time2 from the continuous variable time
growth.serratia$time2<-as.factor(growth.serratia$time)

#subsetting the data frame into two groups (serratia.crop, serratia.midgut)
growth.serratia.crop<-subset(growth.serratia,gutregion=="crop")
growth.serratia.crop<-drop.levels(growth.serratia.crop)
growth.serratia.midgut<-subset(growth.serratia,gutregion=="midgut")
growth.serratia.midgut<-drop.levels(growth.serratia.midgut)

#calculation of median values and confidence intervals of change in CFUs relative to 0h in the crop
growth.serratia.summary<-ddply(growth.serratia,c("gutregion","time"),summarise,
N=length(cfu.change.relative),
median=quantile(cfu.change.relative,0.5),
lowerCI=quantile(cfu.change.relative,0.025),
upperCI=quantile(cfu.change.relative,0.975))
growth.serratia.summary

#removal of time factor levels 4h and 48h in the midgut of serratia fed ants, as these levels consisted only of zeros and were not included in the statistical analysis
growth.serratia.midgut1<-subset(growth.serratia.midgut,time2!="48"&time2!="4")
growth.serratia.midgut1<-drop.levels(growth.serratia.midgut1)


#############statistical analysis Fig. 2a
m.growth.serratia.crop<-glmmTMB(cfu~time2+(1|colony),ziformula=~1,data=growth.serratia.crop,family=nbinom1)
summary(m.growth.serratia.crop)

#model validation
res.m.growth.serratia.crop<-simulateResiduals(fittedModel=m.growth.serratia.crop)
plot(res.m.growth.serratia.crop)

#significance of predictor time since feeding (five levels: 0h, 0.5h, 4h, 24h, 48h)
m.growth.serratia.crop0<-glmmTMB(cfu~1+(1|colony),ziformula=~1,data=growth.serratia.crop,family=nbinom1)
anova(m.growth.serratia.crop,m.growth.serratia.crop0)

#post-hoc comporisons of predictor-levels time since feeding
m.growth.serratia.crop.glht<-glht(m.growth.serratia.crop,linfct=mcp(time2="Tukey"))
summary(m.growth.serratia.crop.glht,test=adjusted("Westfall"))


#############plot Fig. 2a
fig.2a<-ggplot()+
geom_boxplot(data=growth.serratia.crop,aes(x=time2,y=cfu.change.relative),fill="white",outlier.shape=NA,lwd=1.5,alpha=0.3,coef=0,width=0.4)+
geom_point(data=growth.serratia.crop,aes(x=time2,y=cfu.change.relative),pch=21,fill="deeppink1",color="white",alpha=1,position=position_jitter(width=0.1),size=5)+
annotate("text",x=c(1,2,3,4,5),y=c(6.5,6.5,0.7,0.7,0.7),size=9,label=c("a","a","b","b","b"),fontface=2)+
scale_x_discrete(name="Time",labels=c("0h","0.5h","4h","24h","48h"))+
scale_y_continuous(name="CFU change",limits=c(-0.01,7.5))+
theme(axis.line = element_line(colour = "black",size=2),
      axis.ticks=element_line(colour="black",size=2),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=25),
      axis.text.y=element_text(colour="black",size=25),
      axis.title.x=element_text(colour="black",size=30,margin=margin(25,0,0,0)),
      axis.title.y=element_text(colour="black",size=30,margin=margin(0,25,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15,face="italic"),
      legend.key.size=unit(1.2,"cm"),
      legend.key=element_blank(),
      aspect.ratio=1)
fig.2a


#############statistical analysis Fig. 2b
m.growth.serratia.midgut<-glmmTMB(cfu~time2+(1|colony),data=growth.serratia.midgut1,ziformula=~1,family=nbinom2)
summary(m.growth.serratia.midgut)

#model validation
res.m.growth.serratia.midgut<-simulateResiduals(fittedModel=m.growth.serratia.midgut)
plot(res.m.growth.serratia.midgut)

#statistical significance of predictor time (three levels: 0h, 0.5h, 24h)
m.growth.serratia.midgut1<-glmmTMB(cfu~1+(1|colony),data=growth.serratia.midgut1,ziformula=~1,family=nbinom2)
anova(m.growth.serratia.midgut,m.growth.serratia.midgut1)


#############plot Fig. 2b
fig.2b<-ggplot()+
geom_boxplot(data=growth.serratia.midgut,aes(x=time2,y=cfu.change.relative),fill="white",outlier.shape=NA,lwd=1.5,alpha=0.7,coef=0,width=0.4)+
geom_point(data=growth.serratia.midgut,aes(x=time2,y=cfu.change.relative),fill="deeppink1",pch=21, color="white",alpha=1,position=position_jitter(width=0.1),size=5)+
annotate("text",x=c(3),y=c(0.15),size=9,label=c(expression(paste(italic("P")," = 0.593"))),fontface=2)+
scale_x_discrete(name="Time",labels=c("0h","0.5h","4h","24h","48h"))+
scale_y_continuous(name="CFU change",limits=c(-0.01,0.17))+
theme(axis.line = element_line(colour = "black",size=2),
      axis.ticks=element_line(colour="black",size=2),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=25),
      axis.text.y=element_text(colour="black",size=25),
      axis.title.x=element_text(colour="black",size=30,margin=margin(25,0,0,0)),
      axis.title.y=element_text(colour="black",size=30,margin=margin(0,25,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15,face="italic"),
      legend.key.size=unit(1.2,"cm"),
      legend.key=element_blank(),
      aspect.ratio=1)
fig.2b




######################################################################################################
############ Fig. 2 - figure supplement 1a,b: food passage fluorescent particles #####################
######################################################################################################

#############loading data for Fig. 2 - figure supplement 1a,b
food.flow<-read.delim(file.choose(),header=T)#choose data file: Supplementary Data Fig.2 - figure supplement 1a,b.txt
str(food.flow)
food.flow$time<-factor(food.flow$time,levels=c("2h","4h","6h","8h","12h","14h","16h","18h","24h","48h"))#reorder factor time
food.flow$gutregion<-factor(food.flow$gutregion,levels=c("crop","midgut","hindgut"))#reorder factor gutregion

#calculation of median values and confidence intervals of particles in gutregion over time per minor and major workers
food.flow.summary<-ddply(food.flow,c("caste","gutregion","time"),summarise,
N=length(particles),
median=quantile(particles,0.5),
lowerCI=quantile(particles,0.025),
upperCI=quantile(particles,0.975))
food.flow.summary

#subsetting the data frame food.flow into two groups (food.flow.minor, food.flow.major)
food.flow.minor<-subset(food.flow,caste=="minor")
food.flow.minor<-drop.levels(food.flow.minor)
food.flow.major<-subset(food.flow,caste=="major")
food.flow.major<-drop.levels(food.flow.major)


#############plot Fig.2 - figure supplement 1a
#subsetting the data frame food.flow.summary into three groups (food.flow.summary.minor.crop, food.flow.summary.minor.midgut, food.flow.summary.minor.hindgut)
food.flow.summary.minor<-subset(food.flow.summary,caste=="minor")
food.flow.summary.minor<-drop.levels(food.flow.summary.minor)
food.flow.summary.minor.crop<-subset(food.flow.summary.minor,gutregion=="crop")
food.flow.summary.minor.crop<-drop.levels(food.flow.summary.minor.crop)
food.flow.summary.minor.midgut<-subset(food.flow.summary.minor,gutregion=="midgut")
food.flow.summary.minor.midgut<-drop.levels(food.flow.summary.minor.midgut)
food.flow.summary.minor.hindgut<-subset(food.flow.summary.minor,gutregion=="hindgut")
food.flow.summary.minor.hindgut<-drop.levels(food.flow.summary.minor.hindgut)

#plot Fig.2 - figure supplement 1a
fig.2.figure.supplement1a<-ggplot()+
geom_line(data = food.flow.summary.minor.crop,aes(x=time,y=median+1,group="time"),colour="blue",lwd=1.5,alpha=0.8)+
geom_line(data = food.flow.summary.minor.midgut,aes(x=time,y=median+1,group="time"),colour="skyblue",lwd=1.5,alpha=0.8)+
geom_line(data = food.flow.summary.minor.hindgut,aes(x=time,y=median+1,group="time"),colour="turquoise",lwd=1.5,alpha=0.8)+
geom_point(data = food.flow.minor,mapping=aes(x=time,y=particles+1,fill=gutregion),pch=21,color="white",position=position_jitter(width=0.1),size=7,alpha=1)+
scale_fill_manual(values=c("blue","skyblue","turquoise"))+
scale_x_discrete(name="Time after feeding",labels=c("2h","4h","6h","8h","12h","14h","16h","18h","24h","48h"))+
scale_y_continuous(trans="log10",name="Number particles",limits=c(-1,3000))+
annotation_logticks(sides="l",size=1, short = unit(0.25, "cm"), mid = unit(0.5, "cm"), long = unit(0.8,  "cm"))+
theme(axis.line = element_line(colour = "black",size=1.5),
      axis.ticks=element_line(colour="black",size=1.5),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=35),
      axis.text.y=element_text(colour="black",size=35),
      axis.title.x=element_text(colour="black",size=40,margin=margin(20,0,0,0)),
      axis.title.y=element_text(colour="black",size=40,margin=margin(0,22,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15),
      legend.key.size=unit(1.2,"cm"),
      legend.key.height=unit(4,"cm"),
      legend.key=element_blank(),
      legend.position="right")
fig.2.figure.supplement1a


#############plot Fig.2 - figure supplement 1b
#subsetting the data frame food.flow.summary into three groups (food.flow.summary.major.crop, food.flow.summary.major.midgut, food.flow.summary.major.hindgut)
food.flow.summary.major<-subset(food.flow.summary,caste=="major")
food.flow.summary.major<-drop.levels(food.flow.summary.major)
food.flow.summary.major.crop<-subset(food.flow.summary.major,gutregion=="crop")
food.flow.summary.major.crop<-drop.levels(food.flow.summary.major.crop)
food.flow.summary.major.midgut<-subset(food.flow.summary.major,gutregion=="midgut")
food.flow.summary.major.midgut<-drop.levels(food.flow.summary.major.midgut)
food.flow.summary.major.hindgut<-subset(food.flow.summary.major,gutregion=="hindgut")
food.flow.summary.major.hindgut<-drop.levels(food.flow.summary.major.hindgut)

#plot Fig.2 - figure supplement 1b
fig.2.figure.supplement1b<-ggplot()+
geom_line(data = food.flow.summary.major.crop,aes(x=time,y=median+1,group="time"),colour="blue",lwd=1.5,alpha=0.8)+
geom_line(data = food.flow.summary.major.midgut,aes(x=time,y=median+1,group="time"),colour="skyblue",lwd=1.5,alpha=0.8)+
geom_line(data = food.flow.summary.major.hindgut,aes(x=time,y=median+1,group="time"),colour="turquoise",lwd=1.5,alpha=0.8)+
geom_point(data = food.flow.major,mapping=aes(x=time,y=particles+1,fill=gutregion),pch=21,color="white",position=position_jitter(width=0.1),size=7,alpha=1)+
scale_fill_manual(values=c("blue","skyblue","turquoise"))+
scale_x_discrete(name="Time after feeding",labels=c("2h","4h","6h","8h","12h","14h","16h","18h","24h","48h"))+
scale_y_continuous(trans="log10",name="Number particles",limits=c(-1,3000))+
annotation_logticks(sides="l",size=1, short = unit(0.25, "cm"), mid = unit(0.5, "cm"), long = unit(0.8,  "cm"))+
theme(axis.line = element_line(colour = "black",size=1.5),
      axis.ticks=element_line(colour="black",size=1.5),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=35),
      axis.text.y=element_text(colour="black",size=35),
      axis.title.x=element_text(colour="black",size=40,margin=margin(20,0,0,0)),
      axis.title.y=element_text(colour="black",size=40,margin=margin(0,22,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15),
      legend.key.size=unit(1.2,"cm"),
      legend.key.height=unit(4,"cm"),
      legend.key=element_blank(),
      legend.position="right")
fig.2.figure.supplement1b




######################################################################################################
################### Fig. 2 - figure supplement 2a,b: E.coli viability in vivo ########################
######################################################################################################

#############loading data for Fig. 2 - figure supplement 2a,b
growth.ecoli<-read.delim(file.choose(),header=T)#choose data file: Supplementary Data Fig.2 - figure supplement 2a,b.txt
str(growth.ecoli)

#create factor variable time2 from the continuous variable time
growth.ecoli$time2<-as.factor(growth.ecoli$time)

#subsetting the data frame into two groups (ecoli.crop, ecoli.midgut)
growth.ecoli.crop<-subset(growth.ecoli,gutregion=="crop")
growth.ecoli.crop<-drop.levels(growth.ecoli.crop)
growth.ecoli.midgut<-subset(growth.ecoli,gutregion=="midgut")
growth.ecoli.midgut<-drop.levels(growth.ecoli.midgut)

#calculation of median values and confidence intervals of change in CFUs relative to 0h in the crop
growth.ecoli.summary<-ddply(growth.ecoli,c("gutregion","time"),summarise,
N=length(cfu.change.relative),
median=quantile(cfu.change.relative,0.5),
lowerCI=quantile(cfu.change.relative,0.025),
upperCI=quantile(cfu.change.relative,0.975))
growth.ecoli.summary

#removal of time factor levels 0h in the midgut of e.coli fed ants, as this level consisted only of zeros and were not included in the statistical analysis
growth.ecoli.midgut1<-subset(growth.ecoli.midgut,time2!="0")
growth.ecoli.midgut1<-drop.levels(growth.ecoli.midgut1)


#############statistical analysis Fig. 2 - figure supplement 2a
m.growth.ecoli.crop<-glmmTMB(cfu~time2+colony,data=growth.ecoli.crop,ziformula=~1,family=nbinom1)
summary(m.growth.ecoli.crop)

#model validation
res.m.growth.ecoli.crop<-simulateResiduals(fittedModel=m.growth.ecoli.crop)
plot(res.m.growth.ecoli.crop)

#statistical significance of predictor time since feeding (five levels: 0h, 0.5h, 4h, 24h, 48h)
m.growth.ecoli.crop0<-glmmTMB(cfu~colony,data=growth.ecoli.crop,ziformula=~1,family=nbinom1)
anova(m.growth.ecoli.crop,m.growth.ecoli.crop0)

#statistical significance of predictor colony (four levels: C313, C322, C333, C94)
m.growth.ecoli.crop1<-glmmTMB(cfu~time2,data=growth.ecoli.crop,ziformula=~1,family=nbinom1)
anova(m.growth.ecoli.crop,m.growth.ecoli.crop1)

#post-hoc comporisons of predictor-levels time since feeding
m.growth.ecoli.crop1.glht<-glht(m.growth.ecoli.crop1,linfct=mcp(time2="Tukey"))
summary(m.growth.ecoli.crop1.glht,test=adjusted("Westfall"))

#############plot Fig. 2 - figure supplement 2a
fig.2.figure.supplement2a<-ggplot()+
geom_boxplot(data=growth.ecoli.crop,aes(x=time2,y=cfu.change.relative),fill="white",outlier.shape=NA,lwd=1.5,alpha=0.3,coef=0,width=0.4)+
geom_point(data=growth.ecoli.crop,aes(x=time2,y=cfu.change.relative),pch=21,fill="darkolivegreen",color="white",alpha=1,size=5,position=position_jitter(width=0.1))+
annotate("text",x=c(1,2,3,4,5),y=c(2.5,1.5,1,0.5,0.5),size=9,label=c("a","b","c","d","d"),fontface=2)+#statistical significance 
scale_x_discrete(name="Time",labels=c("0h","0.5h","4h","24h","48h"))+
scale_y_continuous(name="CFU change",limits=c(-0.01,3))+
theme(axis.line = element_line(colour = "black",size=2),
      axis.ticks=element_line(colour="black",size=2),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=25),
      axis.text.y=element_text(colour="black",size=25),
      axis.title.x=element_text(colour="black",size=30,margin=margin(25,0,0,0)),
      axis.title.y=element_text(colour="black",size=30,margin=margin(0,25,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15,face="italic"),
      legend.key.size=unit(1.2,"cm"),
      legend.key=element_blank(),
      aspect.ratio=1)
fig.2.figure.supplement2a


#############statistical analysis Fig. 2 - figure supplement 2b
m.growth.ecoli.midgut<-glmmTMB(cfu~time2+(1|colony),data=growth.ecoli.midgut1,ziformula=~1,family=nbinom1)
summary(m.growth.ecoli.midgut)

#model validation
res.m.growth.ecoli.midgut<-simulateResiduals(fittedModel=m.growth.ecoli.midgut)
plot(res.m.growth.ecoli.midgut)

#statistical significance of predictor time since feeding (four levels: 0.5h, 4h, 24h, 48h)
m.growth.ecoli.midgut0<-glmmTMB(cfu~1+(1|colony),data=growth.ecoli.midgut1,ziformula=~1,family=nbinom1)
anova(m.growth.ecoli.midgut,m.growth.ecoli.midgut0)

#post-hoc comporisons of predictor-levels time since feeding
m.growth.ecoli.midgut.glht<-glht(m.growth.ecoli.midgut,linfct=mcp(time2="Tukey"))
summary(m.growth.ecoli.midgut.glht,test=adjusted("Westfall"))


#############plot Fig. 2 - figure supplement 2b
fig.2.figure.supplement2b<-ggplot()+
geom_boxplot(data=growth.ecoli.midgut,aes(x=time2,y=cfu.change.relative),fill="white",outlier.shape=NA,lwd=1.5,alpha=0.3,coef=0,width=0.4)+
geom_point(data=growth.ecoli.midgut,aes(x=time2,y=cfu.change.relative),pch=21,fill="darkolivegreen",color="white",alpha=1,size=5,position=position_jitter(width=0.1))+
annotate("text",x=c(2,3,4,5),y=c(0.02,0.02,0.02,0.02),size=9,label=c("ab","a","a","b"),fontface=2)+
scale_x_discrete(name="Time",labels=c("0h","0.5h","4h","24h","48h"))+
scale_y_continuous(name="CFU change",limits=c(-0.01,0.05))+
theme(axis.line = element_line(colour = "black",size=2),
      axis.ticks=element_line(colour="black",size=2),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=25),
      axis.text.y=element_text(colour="black",size=25),
      axis.title.x=element_text(colour="black",size=30,margin=margin(25,0,0,0)),
      axis.title.y=element_text(colour="black",size=30,margin=margin(0,25,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15,face="italic"),
      legend.key.size=unit(1.2,"cm"),
      legend.key=element_blank(),
      aspect.ratio=1)
fig.2.figure.supplement2b




######################################################################################################
##################### Fig. 2 - figure supplement 3: Serratia growth in vitro #########################
######################################################################################################

#############loading data for Fig. 2 - figure supplement 3
serratia.growth.invitro<-read.delim(file.choose(),header=T)#choose file: Supplementary Data Fig. 2 - figure supplement 3.txt
str(serratia.growth.invitro)

#calculation of median values and confidence intervals of change in CFUs relative to pH 5
serratia.growth.invitro.summary<-ddply(serratia.growth.invitro,c("ph"),summarize,
median.cfu.change=quantile(cfu.change.relative,0.5),
lowerCI.cfu.change=quantile(cfu.change.relative,0.025),
upperCI.cfu.change=quantile(cfu.change.relative,0.975))
serratia.growth.invitro.summary

#removal of pH levels 2 and 3 from serratia.growth.invitro, as these levels consisted only of zeros
serratia.growth.invitro1<-subset(serratia.growth.invitro,ph=="pH5"|ph=="pH4")
serratia.growth.invitro1<-drop.levels(serratia.growth.invitro1)
str(serratia.growth.invitro1)


#############statistical analysis Fig. 2 - figure supplement 3
m.serratia.growth.invitro1<-glm.nb(cfu~ph,data=serratia.growth.invitro1)
summary(m.serratia.growth.invitro1)

#model validation
res.m.serratia.growth.invitro1<-simulateResiduals(fittedModel=m.serratia.growth.invitro1)
plot(res.m.serratia.growth.invitro1)

#statistical significance of predictor pH-level (two levels: pH5, pH4)
m.serratia.growth.invitro10<-glm.nb(cfu~1,data=serratia.growth.invitro1)
anova(m.serratia.growth.invitro1,m.serratia.growth.invitro10)


#############plot Fig. 2 - figure supplement 3
fig.2.figure.supplement3<-ggplot()+
geom_boxplot(data=serratia.growth.invitro,aes(x=ph,y=cfu.change.relative),fill="white",outlier.shape=NA,lwd=1.5,position=position_dodge(0.6),alpha=0.6,coef=0,width=0.4)+
geom_point(data=serratia.growth.invitro,aes(x=ph,y=cfu.change.relative,colour=ph),position=position_jitterdodge(dodge=0.6),size=4,alpha=0.8)+
scale_colour_manual(values=c("deeppink1","deeppink1","deeppink1","deeppink1"),name="Raw data",guide=FALSE)+
scale_x_discrete(name="pH of honeywater",labels=c("2","3","4","5"))+
scale_y_continuous(name="CFU change",limits=c(0,1.7))+
annotate("text",x=c(3.5),y=c(1.5),size=16,label=c(expression(paste(italic("P")," < 0.001"))),fontface=2)+#statistical significance 
geom_segment(aes(x = 3, y = 1.4, xend = 4, yend = 1.4),lwd=2)+
theme(axis.line = element_line(colour = "black",size=1.5),
      axis.ticks=element_line(colour="black",size=1.5),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=30),
      axis.text.y=element_text(colour="black",size=30),
      axis.title.x=element_text(colour="black",size=40,margin=margin(20,0,0,0)),
      axis.title.y=element_text(colour="black",size=40,margin=margin(0,22,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15),
      legend.key.size=unit(1.2,"cm"),
      legend.key=element_blank(),
      legend.position="bottom",
      aspect.ratio=1)
fig.2.figure.supplement3




######################################################################################################
############################### Fig 3: Individual survival ###########################################
######################################################################################################

#############loading data for Fig.3
survival<-read.delim(file.choose(),header=T)#choose data file: Supplementary Data Fig.3.txt
str(survival)


#############statistcal analysis
m.survival<-coxme(Surv(time.death.hours,status)~treatment+(1|experiment.block)+(1|colony),data=survival)
print(m.survival)

#significance of predictor ant treatment (four levels: Serratia- FA-, Serratia- FA+, Serratia-+FA-, Serratia+ FA+)
m.survival0<-coxme(Surv(time.death.hours,status)~1+(1|experiment.block)+(1|colony),data=survival)
anova(m.survival,m.survival0)

#post-hoc comporisons of predictor-levels ant treatment
m.survival.glht<-glht(m.survival,linfct=mcp(treatment="Tukey"))
summary(m.survival.glht,test=adjusted("Westfall"))


#############plot Fig. 3 
fig.3<-ggplot(survival,aes(time=time.death.hours,status=status,linetype=treatment,colour=treatment))+
geom_km(lwd=2)+
scale_colour_manual(values=c("grey","grey","black","black"),name="Animal treatment",label=c("Serratia- | FA-","Serratia- | FA+","Serratia+ | FA-","Serratia+ | FA+"))+
scale_linetype_manual(values=c("solid","dashed","solid","dashed"),name="Animal treatment",labels=c("Serratia- | FA-","Serratia- | FA+","Serratia+ | FA-","Serratia+ | FA+"))+
scale_x_continuous(name="Time after feeding [h]",limits=c(0,160),breaks=seq(0,120,24))+
scale_y_continuous(name="Proportion survival",limits=c(0,1))+
geom_segment(aes(x=140,y=0.12,xend=150,yend=0.12),lwd=1.5,col="grey",lty=2)+
geom_segment(aes(x=140,y=0.10,xend=150,yend=0.10),lwd=1.5,col="black",lty=2)+
geom_segment(aes(x=140,y=0.08,xend=150,yend=0.08),lwd=1.5,col="grey",lty=1)+
geom_segment(aes(x=140,y=0.00,xend=150,yend=0.00),lwd=1.5,col="black",lty=1)+
annotate("text",x=c(155,155),y=c(0.105,0.005),size=10,label=c("a","b"),fontface=2)+
theme(axis.line = element_line(colour = "black",size=2),
      axis.ticks=element_line(colour="black",size=2),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=25),
      axis.text.y=element_text(colour="black",size=25),
      axis.title.x=element_text(colour="black",size=30,margin=margin(25,0,0,0)),
      axis.title.y=element_text(colour="black",size=30,margin=margin(0,25,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15),
      legend.key.size=unit(1.5,"cm"),
      legend.key=element_blank(),
      legend.position=c(0.8,0.8),
      aspect.ratio=1)
fig.3




######################################################################################################
#################################### Fig 4: Survival trophallaxis ####################################
######################################################################################################


#############loading data for Fig.4
survival.trophallaxis<-read.delim(file.choose(),header=T)#choose data file: Supplementary Data Fig.4.txt
str(survival)


#############statistical analysis
m.survival.trophallaxis<-coxme(Surv(time.death,status.death)~treatment+(1|colony)+(1|experiment.block)+(1|petridish),data=survival.trophallaxis)
print(m.survival.trophallaxis)

#significance of predictor ant treatment (four levels: donor FA+, donor FA-, receiver FA+, receiver FA-)
m.survival.trophallaxis0<-coxme(Surv(time.death,status.death)~1+(1|colony)+(1|experiment.block)+(1|petridish),data=survival.trophallaxis)
anova(m.survival.trophallaxis,m.survival.trophallaxis0)

#post-hoc comparisons of predictor-levels ant treatment
m.survival.trophallaxis.glht<-glht(m.survival.trophallaxis,linfct=mcp(treatment="Tukey"))
summary(m.survival.trophallaxis.glht,test=adjusted("Westfall"))

#hazard ratios between predictor-levels ant treatment through releveling of predictor
treatment1<-factor(survival.trophallaxis$treatment,levels=c("receiverFA+","receiverFA-","donorFA+","donorFA-"))
treatment2<-factor(survival.trophallaxis$treatment,levels=c("donorFA+","receiverFA+","receiverFA-","donorFA-"))
treatment3<-factor(survival.trophallaxis$treatment,levels=c("receiverFA-","receiverFA+","donorFA+","donorFA-"))
m.survival.trophallaxis1<-coxme(Surv(time.death,status.death)~treatment1+(1|colony)+(1|experiment.block)+(1|petridish),data=survival.trophallaxis)
print(m.survival.trophallaxis1)
m.survival.trophallaxis2<-coxme(Surv(time.death,status.death)~treatment2+(1|colony)+(1|experiment.block)+(1|petridish),data=survival.trophallaxis)
print(m.survival.trophallaxis2)
m.survival.trophallaxis3<-coxme(Surv(time.death,status.death)~treatment3+(1|colony)+(1|experiment.block)+(1|petridish),data=survival.trophallaxis)
print(m.survival.trophallaxis3)


#############plot Fig. 4
fig.4<-ggplot(survival.trophallaxis,aes(time=time.death,,status=status.death,linetype=treatment,colour=treatment))+
geom_km(lwd=2)+
scale_colour_manual(values=c("grey","grey","black","black"),name="Animal:",labels=c("donor FA-","donor FA+","receiver FA- with\ndonor FA-","receiver FA- with\ndonor FA+"))+
scale_linetype_manual(values=c("dashed","solid","dashed","solid"),name="Animal:",label=c("donor FA-","donor FA+","receiver FA- with\ndonor FA-","receiver FA- with\ndonor FA+"))+
scale_x_continuous(name="Time in days",breaks=seq(0,14,2))+
scale_y_continuous(name="Proportion survival",limits=c(0,1))+
annotate("text",x=c(12.5,12.5,12.5,12.5),y=c(0.26,0.17,0.1,0.06),size=10,label=c("a","b","c","c"),fontface=2)+
theme(axis.line = element_line(colour = "black",size=2),
      axis.ticks=element_line(colour="black",size=2),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=25),
      axis.text.y=element_text(colour="black",size=25),
      axis.title.x=element_text(colour="black",size=30,margin=margin(25,0,0,0)),
      axis.title.y=element_text(colour="black",size=30,margin=margin(0,25,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15),
      legend.key.size=unit(1.5,"cm"),
      legend.key=element_blank(),
      legend.position=c(0.8,0.8),
      aspect.ratio=1)
fig.4




#####################################################################################################
######################### Fig.4 - figure supplement 1: trophallaxis behavior ########################
#####################################################################################################

#############loading data for Fig.4 - figure supplement 1
trophallaxis<-read.delim(file.choose(),header=T)#choose file: Supplementary Data Fig.4 - figure supplement 1.txt
str(trophallaxis)


#############statistcal analysis
m.duration.trophallaxis<-lmer(sqrt(sum.duration.trophallaxis)~ant.pair+(1|colony)+(1|experimental.block),data=trophallaxis)
summary(m.duration.trophallaxis)

#model validation
res.m.duration.trophallaxis<-simulateResiduals(fittedModel=m.duration.trophallaxis)
plot(res.m.duration.trophallaxis)

#significance of predictor food treatment (three levels: unfed, water, honey)
m.duration.trophallaxis0<-lmer(sqrt(sum.duration.trophallaxis)~1+(1|colony)+(1|experimental.block),data=trophallaxis)
anova(m.duration.trophallaxis,m.duration.trophallaxis0)


#############plot Fig.4 - figure supplement 1
fig.4.figure.supplement1<-ggplot()+
geom_boxplot(data=trophallaxis,mapping=aes(x=ant.pair,y=sum.duration.trophallaxis,fill=ant.pair),outlier.shape=NA,lwd=1.5,width=0.4,coef=0)+
geom_point(data=trophallaxis,mapping=aes(x=ant.pair,y=sum.duration.trophallaxis,color=ant.pair),position=position_jitter(width=0.1),size=4,alpha=0.9)+
scale_fill_manual(values=c("white","white"),name="Animal pairing:",labels=c("donorFA- receiverFA-","donorFA+ receiverFA-"),guide=FALSE)+
scale_colour_manual(values=c("deeppink1","deeppink1"),name="Raw data:",labels=c("no","yes"),guide=FALSE)+
scale_x_discrete(name="Animal pairing",labels=c("donorFA- receiverFA-","donorFA+ receiverFA-"))+
scale_y_continuous(name="Duration trophallaxis [s]",limits=c(-5,1800),breaks=seq(0,1800,200))+
geom_segment(aes(x = 1, y = 1750, xend = 2, yend = 1750),lwd=2)+
annotate("text",x=c(1.5),y=c(1800),size=10,label=c(expression(paste(italic("P")," = 0.268"))),fontface=2)+
theme(axis.line = element_line(colour = "black",size=1.5),
      axis.ticks=element_line(colour="black",size=1.5),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=20),
      axis.text.y=element_text(colour="black",size=20),
      axis.title.x=element_text(colour="black",size=25,margin=margin(20,0,0,0)),
      axis.title.y=element_text(colour="black",size=25,margin=margin(0,22,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15),
      legend.key.size=unit(1.2,"cm"),
      legend.key=element_blank(),
      legend.position="right")
fig.4.figure.supplement1




######################################################################################################
################################ Fig 5 a,b: Asaia viability in vivo ##################################
######################################################################################################

#############loading data for Fig.5a,b
growth.asaia<-read.delim(file.choose(),header=T)#choose data file: Supplementary Data Fig.5a,b.txt
str(growth.asaia)

#create factor variable time2 from the continuous variable time
growth.asaia$time2<-as.factor(growth.asaia$time)

#subsetting the data frame into two groups (growth.asaia.crop, growth.asaia.midgut)
growth.asaia.crop<-subset(growth.asaia,gutregion=="crop")
growth.asaia.crop<-drop.levels(growth.asaia.crop)
growth.asaia.midgut<-subset(growth.asaia,gutregion=="midgut")
growth.asaia.midgut<-drop.levels(growth.asaia.midgut)

#calculation of median values and confidence intervals of change in CFUs relative to 0h in the crop
growth.asaia.summary<-ddply(growth.asaia,c("gutregion","time"),summarise,
N=length(cfu.change.relative),
median=quantile(cfu.change.relative,0.5),
lowerCI=quantile(cfu.change.relative,0.025),
upperCI=quantile(cfu.change.relative,0.975))
growth.asaia.summary

#removal of time factor levels 0h in the midgut of asaia fed ants, as this level consisted only of zeros and is not included in the statistical analysis
growth.asaia.midgut1<-subset(growth.asaia.midgut,time2!="0")
growth.asaia.midugt1<-drop.levels(growth.asaia.midgut1)


#############statistical analysis Fig. 5a
m.growth.asaia.crop<-glmmTMB(cfu~time2+(1|colony),data=growth.asaia.crop,ziformula=~1,family=nbinom2)
summary(m.growth.asaia.crop)

#model validation
res.m.growth.asaia.crop<-simulateResiduals(fittedModel=m.growth.asaia.crop)
plot(res.m.growth.asaia.crop)

#statistical significance of predictor time since feeding (five levels: 0h, 0.5h, 4h, 24h, 48h)
m.growth.asaia.crop0<-glmmTMB(cfu~1+(1|colony),data=growth.asaia.crop,ziformula=~1,family=nbinom2)
anova(m.growth.asaia.crop,m.growth.asaia.crop0)

#post-hoc comporisons of predictor-levels time since feeding
m.growth.asaia.crop.glht<-glht(m.growth.asaia.crop,linfct=mcp(time2="Tukey"))
summary(m.growth.asaia.crop.glht,test=adjusted("Westfall"))


#############plot Fig. 5a
fig.5a<-ggplot()+
geom_boxplot(data=growth.asaia.crop,aes(x=time2,y=cfu.change.relative),fill="white",outlier.shape=NA,lwd=1.5,alpha=0.3,coef=0,width=0.4)+
geom_point(data=growth.asaia.crop,aes(x=time2,y=cfu.change.relative),pch=21,fill="grey70",color="white",alpha=1,size=5,position=position_jitter(width=0.1))+
annotate("text",x=c(1,2,3,4,5),y=c(3,3,1.7,0.8,0.5),size=9,label=c("a","a","b","c","d"),fontface=2)+#statistical significance 
scale_x_discrete(name="Time",labels=c("0h","0.5h","4h","24h","48h"))+
scale_y_continuous(name="CFU change",limits=c(-0.01,4))+
theme(axis.line = element_line(colour = "black",size=2),
      axis.ticks=element_line(colour="black",size=2),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=25),
      axis.text.y=element_text(colour="black",size=25),
      axis.title.x=element_text(colour="black",size=30,margin=margin(25,0,0,0)),
      axis.title.y=element_text(colour="black",size=30,margin=margin(0,25,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15,face="italic"),
      legend.key.size=unit(1.2,"cm"),
      legend.key=element_blank(),
      aspect.ratio=1)
fig.5a


#############statistical analysis Fig. 5b
m.growth.asaia.midgut<-glmmTMB(cfu~time2+(1|colony),data=growth.asaia.midgut1,ziformula=~1,family=nbinom1)
summary(m.growth.asaia.midgut)

#model validation
res.m.growth.asaia.midgut<-simulateResiduals(fittedModel=m.growth.asaia.midgut)
plot(res.m.growth.asaia.midgut)

#statistical significance of predictor time since feeding (four levels: 0.5h, 4h, 24h, 48h)
m.growth.asaia.midgut0<-glmmTMB(cfu~1+(1|colony),data=growth.asaia.midgut1,ziformula=~1,family=nbinom1)
anova(m.growth.asaia.midgut,m.growth.asaia.midgut0)

#post-hoc comporisons of predictor-levels time since feeding
m.growth.asaia.midgut.glht<-glht(m.growth.asaia.midgut,linfct=mcp(time2="Tukey"))
summary(m.growth.asaia.midgut.glht,test=adjusted("Westfall"))


#############plot Fig. 5b
fig.5b<-ggplot()+
geom_boxplot(data=growth.asaia.midgut,aes(x=time2,y=cfu.change.relative),fill="white",outlier.shape=NA,lwd=1.5,alpha=0.3,coef=0,width=0.4)+
geom_point(data=growth.asaia.midgut,aes(x=time2,y=cfu.change.relative),pch=21,fill="grey70",color="white",alpha=1,size=5,position=position_jitter(width=0.1))+
annotate("text",x=c(2,3,4,5),y=c(0.02,0.02,0.03,0.065),size=9,label=c("a","a","b","c"),fontface=2)+
scale_x_discrete(name="Time",labels=c("0h","0.5h","4h","24h","48h"))+
scale_y_continuous(name="Change in CFU's",limits=c(-0.01,0.065))+
theme(axis.line = element_line(colour = "black",size=2),
      axis.ticks=element_line(colour="black",size=2),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=25),
      axis.text.y=element_text(colour="black",size=25),
      axis.title.x=element_text(colour="black",size=30,margin=margin(25,0,0,0)),
      axis.title.y=element_text(colour="black",size=30,margin=margin(0,25,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15,face="italic"),
      legend.key.size=unit(1.2,"cm"),
      legend.key=element_blank(),
      aspect.ratio=1)
fig.5b




######################################################################################################
##################### Fig. 5 - figure supplement 1: Asaia growth in vitro ############################
######################################################################################################

#############loading data for Fig. 5 - figure supplement 1
asaia.growth.invitro<-read.delim(file.choose(),header=T)#choose file: Supplementary Data Fig. 5 - figure supplement 1.txt
str(asaia.growth.invitro)

#calculation of median values and confidence intervals of change in CFUs relative to pH 5
asaia.growth.invitro.summary<-ddply(asaia.growth.invitro,c("ph"),summarize,
median.cfu.change=quantile(cfu.change.relative,0.5),
lowerCI.cfu.change=quantile(cfu.change.relative,0.025),
upperCI.cfu.change=quantile(cfu.change.relative,0.975))
asaia.growth.invitro.summary

#removal of pH level 2 from asaia.growth.invitro, as this level consisted only of zeros
asaia.growth.invitro1<-subset(asaia.growth.invitro,ph!="pH2")
asaia.growth.invitro1<-drop.levels(asaia.growth.invitro1)
str(asaia.growth.invitro1)


#############statistical analysis Fig. 5 - figure supplement 1
m.asaia.growth.invitro1<-glm.nb(cfu~ph,data=asaia.growth.invitro1)
summary(m.asaia.growth.invitro1)

#model validation
res.m.asaia.growth.invitro1<-simulateResiduals(fittedModel=m.asaia.growth.invitro1)
plot(res.m.asaia.growth.invitro1)

#statistical significance of predictor pH-level (two levels: pH5, pH4)
m.asaia.growth.invitro10<-glm.nb(cfu~1,data=asaia.growth.invitro1)
anova(m.asaia.growth.invitro1,m.asaia.growth.invitro10)

#post-hoc comparison among predictor levels of pH (three levels: pH5, pH4, pH3)
m.asaia.growth.invitro1.glht<-glht(m.asaia.growth.invitro1,linfct=mcp(ph="Tukey"))
summary(m.asaia.growth.invitro1.glht,test=adjusted("Westfall"))


#############plot Fig. 5 - figure supplement 1
fig.5.figure.supplement1<-ggplot()+
geom_boxplot(data=asaia.growth.invitro,aes(x=ph,y=cfu.change.relative),fill="white",outlier.shape=NA,lwd=1.5,position=position_dodge(0.6),alpha=0.6,coef=0,width=0.4)+
geom_point(data=asaia.growth.invitro,aes(x=ph,y=cfu.change.relative,colour=ph),position=position_jitterdodge(dodge=0.6),size=4,alpha=0.8)+
scale_colour_manual(values=c("grey40","grey40","grey40","grey40"),name="Raw data:",guide=FALSE)+
annotate("text",x=c(2,3,4),y=c(0.9,1.4,1.4),size=9,label=c("b","a","a"),fontface=2)+#statistical significance 
scale_x_discrete(name="pH of honeywater",labels=c("2","3","4","5"))+
scale_y_continuous(name="CFU change",limits=c(0,1.7))+
annotate("text",x=c(2.5),y=c(1.7),size=16,label=c("***"),fontface=2)+#statistical significance 
theme(axis.line = element_line(colour = "black",size=1.5),
      axis.ticks=element_line(colour="black",size=1.5),
      axis.ticks.length=unit(0.3,"cm"),
      axis.text.x=element_text(colour="black",size=30),
      axis.text.y=element_text(colour="black",size=30),
      axis.title.x=element_text(colour="black",size=40,margin=margin(20,0,0,0)),
      axis.title.y=element_text(colour="black",size=40,margin=margin(0,22,0,0)),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      legend.title=element_text(size=15),
      legend.text=element_text(size=15),
      legend.key.size=unit(1.2,"cm"),
      legend.key=element_blank(),
      legend.position="bottom",
      aspect.ratio=1)
fig.5.figure.supplement1

