---
title: "Infectivity of *Plasmodium* parasites to *Aedes aegypti* and *Anopheles stephensi* mosquitoes maintained on blood-free meals of SkitoSnack"
subtitle: "Statistical Appendix"
output: 
  pdf_document:
    number_sections: true
date: "`r Sys.Date()`"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE,warning = FALSE,message = FALSE,fig.height = 3,fig.width = 5)

library(ggplot2)
library(lme4)
library(dplyr)
library(cowplot)
library(boot)
```

# Introduction

There are 4 main types of effects we are measuring (engorgement rates, hatch rates, oocyst counts per infected midgut, and sporozoites per infected mosquito). We list the data by generation and colony  in the main tables of the paper (Tables 1-4). In those Tables we use averages and interquartile ranges throughout. 

For hatch rates  and oocyst counts, there are two levels of summarization. For example, for hatch rates we first take the average and interquartile range (IQR) of groups of eggs. These are presented for each generation/colony row. Then we take the unweighted average and IQR of those averages within each generation. Oocyst counts averages and IQRs are done similarly. We use IQR throughout Tables 1-4 for consistency, even though it is non-standard to calculate an IQR with only 2-4 observations.

For comparing the effects of the meal, bovine blood versus SkitoSnack, the analyses for each of the 4 types of effects are different and necessarily more sophisticated, so that each can properly account for any of the types of variability in its measurement  (e.g., variation between colonies, generations, mosquitoes, eggs, oocysts, and sporozoites).  We provide the details of those analyses in separate sections of  this supplement.  These analyses were performed in `r R.version$version.string`. 

# Engorgement Rate 

## Analysis Details 

* In the sections below we present analyses to determine whether the type of meal (BB: bovine blood or SS: SkitoSnack) has an effect on engorgement rates for *Aedes aegypti* and *Anopheles stephensi*.
* We consider a logistic regression mixed effects model.  
  * *Random effects*: In our work, considered to be factors (or categorical variables) with levels that are  a random sample from some population. These are the colony replicates for each generation.
  * *Fixed effects*: In our work, considered to be factors with treatments that are pre-specified by the researcher and are constant across individuals (mosquitoes). These are meal and generation.
* The models were fit using the package lme4, citation: Bates D, Mächler M, Bolker B, Walker S (2015). "Fitting Linear Mixed-Effects Models Using lme4." *Journal of Statistical Software*, 67(1), 1–48.
* The 95% confidence intervals for the estimated probabilities were obtained via bootstrap with 1000 iterations.
* The reference meal is BB and reference generation is F0. 
* A likelihood ratio test (LRT) was performed to assess an interaction between generation and meal. 
* An LRT was performed to assess the overall generation effect.

\newpage 

## *Aedes aegypti*

```{r}
Data=read.csv("/Volumes/ortegavillaa$/My Documents/Ana/NIAID/SkitoSnacks/2023Data/EngorgementRates_AA.csv")

Data$Replicate=as.factor(Data$Replicate)
Data$Generation=factor(Data$Generation,
                       levels=c("F0","F1","F3","F5","F7"))

Data$Replicate2=Data$Replicate
levels(Data$Replicate2)=c("black","orange","blue","green","black","orange","blue","green",
                          "black","orange","blue","green","black","orange","blue","green",
                          "orange","blue","green","orange","blue","green",
                          "orange","blue","orange","blue","orange","orange")
```

```{r,fig.cap="*Aedes aegypti* engorgement rate (%). Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook. "}
p=ggplot(Data,aes(x=Meal,y=EngorgementRate*100,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2.5,
             position = position_jitter(h=0,w=0.1))+
  facet_grid(. ~ Generation)+theme_bw()+
  labs(x="",y=expression(atop(italic("Aedes aegypti"),"\n Engorgement Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(hjust = 0.5),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank())+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,100,by=20),limits=c(0,100))
print(p)
```

```{r}

Data$NumberNotEngorged=Data$TotalNumber-Data$NumberEngorged

Model=glmer(cbind(NumberEngorged,NumberNotEngorged)~Meal+Generation+Meal*Generation+(1|Replicate),data=Data,family="binomial",control = glmerControl(optimizer = "bobyqa"))

ModelRed=glmer(cbind(NumberEngorged,NumberNotEngorged)~Meal+Generation+(1|Replicate),data=Data,family="binomial",control = glmerControl(optimizer = "bobyqa"))

LRT=anova(Model,ModelRed)
pvalue=round(LRT$`Pr(>Chisq)`[2],3)

ModelRedRed=glmer(cbind(NumberEngorged,NumberNotEngorged)~Meal+(1|Replicate),
                  data=Data,family="binomial",
                  control = glmerControl(optimizer = "bobyqa"))

LRT2=anova(ModelRed,ModelRedRed)
pvalue2=round(LRT2$`Pr(>Chisq)`[2],3)
```

* We performed an LRT to determine whether there was a significant interaction between generation and meal. The p-value of the test is p: `r pvalue`. 

```{r,include=FALSE}
ConfInt=confint(ModelRed,parm="beta_")

ResultsOR=data.frame("OR"=exp(summary(ModelRed)$coefficients[,1]),
                      "Lower"=exp(ConfInt[,1]),
                      "Upper"=exp(ConfInt[,2]),
                      "p.value"=summary(ModelRed)$coefficients[,4])
ResultsOR=ResultsOR[-1,]
rownames(ResultsOR)=c("SS vs. BB","F1 vs. F0","F3 vs. F0","F5 vs. F0","F7 vs. F0")

```

* We found a significant effect due to meal. The odds of a mosquito engorging when the meal is SS are `r round(ResultsOR[1,1],2)` (95%CI:[`r round(ResultsOR[1,2],2)`,`r round(ResultsOR[1,3],2)`]) times higher than when the meal is BB. 
* We found a significant effect due to generation from a LRT p: `r pvalue2`. This is an overall effect, though each individual test of each generation to F0 may not be significant as displayed on the table below. 

```{r}

knitr::kable(ResultsOR,digits=3,caption="*Aedes aegypti* summary table in OR scale")

```

```{r,fig.cap="Observed (dots) and estimated (horizontal line) engorgement rates and bootstrap 95% confidence intervals (vertical lines) for *Aedes aegypti*. Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook. "}

NewData=Data[c(1,5,9,13,17,20,23,25,27,28),c(1,2,3,7)]

PredictFunction=function(mm){
  predict(mm,newdata=NewData,type="response")
}

Test=bootMer(ModelRed, PredictFunction,nsim=1000)

Confints=apply(Test$t, quantile, probs=c(0.025,0.975), na.rm=TRUE,MARGIN=2)

Probabilities=data.frame("Meal"=NewData$Meal,"Generation"=NewData$Generation,
                         "Probability"=Test$t0,"Lower"=Confints[1,],
                         "Upper"=Confints[2,],
                         "AverageProbability"=apply(Test$t, mean, na.rm=TRUE,MARGIN=2))

ggplot(Data,aes(x=Meal,y=EngorgementRate*100,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2.5,
             position = position_jitter(h=0,w=0.1))+
  facet_grid(. ~ Generation)+theme_bw()+
  labs(x="Diet",y=expression(atop(italic("Aedes aegypti"),"\n Engorgement Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(hjust = 0.5),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank())+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,100,by=20))+
  geom_point(data=Probabilities,
             aes(x=Meal,y=AverageProbability*100),color="black",shape="-",size=10)+
  geom_errorbar(data=Probabilities,aes(min=Lower*100,max=Upper*100,y=AverageProbability*100),
                color="black",width=1)

p.aedes=ggplot(Data,aes(x=Meal,y=EngorgementRate*100,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2.5,
             position = position_jitter(h=0,w=0.1))+
  facet_grid(. ~ Generation)+theme_bw()+
  labs(x="",y=expression(atop(italic("Aedes aegypti"),"\n Engorgement Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank(),
        plot.subtitle = element_text(hjust=0.5))+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,100,by=20))+
  geom_point(data=Probabilities,
             aes(x=Meal,y=AverageProbability*100),color="black",shape="-",size=10)+
  geom_errorbar(data=Probabilities,aes(min=Lower*100,max=Upper*100,y=AverageProbability*100),
                color="black",width=1)+
  ggtitle("A",subtitle = expression(italic("Aedes aegypti")))

```

\newpage

## *Anopheles stephensi*

```{r}
Data=read.csv("/Volumes/ortegavillaa$/My Documents/Ana/NIAID/SkitoSnacks/2023Data/EngorgementRates_AS.csv")

Data$Replicate=as.factor(Data$Replicate)
Data$Generation=factor(Data$Generation,
                       levels=c("F0","F1","F3","F5","F10","F15","F63"))


Data$Replicate2=factor(Data$Replicate,
                       levels=c("F0, BB0","F0, BB1","F0, BB2","F0, BB3","F0, SS0","F0, SS1",
                                "F0, SS2","F0, SS3","F1, BB0","F1, BB1","F1, BB2","F1, BB3",
                                "F1, SS0","F1, SS1","F1, SS2","F1, SS3",
                                "F3, BB1","F3, BB2","F3, BB3","F3, SS1","F3, SS2","F3, SS3",
                                "F5,BB","F5,SS",
                                "F10,BB1","F10,BB2","F10,BB3","F10,SS1","F10,SS2","F10,SS3",
                                "F15,BB1","F15,BB2","F15,BB3","F15,SS1","F15,SS2","F15,SS3",
                                "F63, BB1","F63, BB2","F63, BB3","F63, SS1","F63, SS2","F63, SS3"))

levels(Data$Replicate2)=c("black","orange","blue","green","black","orange","blue","green",
                          "black","orange","blue","green","black","orange","blue","green",
                          "orange","blue","green","orange","blue","green",
                          "blue","blue",
                          "orange","blue","green","orange","blue","green",
                          "orange","blue","green","orange","blue","green",
                          "orange","blue","green","orange","blue","green")


Data$NumberNotEngorged=Data$TotalNumber-Data$NumberEngorged


Model=glmer(cbind(NumberEngorged,NumberNotEngorged)~Meal+Generation+Meal*Generation+(1|Replicate),
            data=Data,family="binomial",control = glmerControl(optimizer = "bobyqa"))

ModelRed=glmer(cbind(NumberEngorged,NumberNotEngorged)~Meal+Generation+(1|Replicate),
               data=Data,family="binomial",control = glmerControl(optimizer = "bobyqa"))

LRT=anova(Model,ModelRed)
pvalue=round(LRT$`Pr(>Chisq)`[2],3)

ModelRedRed=glmer(cbind(NumberEngorged,NumberNotEngorged)~Meal+(1|Replicate),
                  data=Data,family="binomial",
                  control = glmerControl(optimizer = "bobyqa"))

LRT2=anova(ModelRed,ModelRedRed)
pvalue2=round(LRT2$`Pr(>Chisq)`[2],3)

```

```{r, fig.cap="*Anopheles stephensi* engorgement rate (%). Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook. "}
p=ggplot(Data,aes(x=Meal,y=EngorgementRate*100,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2.5,
             position = position_jitter(h=0,w=0.1))+
  facet_grid(. ~ Generation)+theme_bw()+
  labs(x="Diet",y=expression(atop(italic("Anopheles stephensi"),"\n Engorgement Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(hjust = 0.5),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank())+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,100,by=20),limits=c(0,100))
print(p)
```

* We performed an LRT to determine whether there was a significant interaction between generation and meal. The p-value of the test is p: `r pvalue`. 
* Because of our significant interaction results, we performed individual contrasts to test whether there is a significant difference between SS and BB at each generation. 

```{r}
VarMat=vcov(Model)

BBEstimates=matrix(c(1,0,0,0,0,0,0,0,0,0,0,0,0,0,
                     1,0,1,0,0,0,0,0,0,0,0,0,0,0,
                     1,0,0,1,0,0,0,0,0,0,0,0,0,0,
                     1,0,0,0,1,0,0,0,0,0,0,0,0,0,
                     1,0,0,0,0,1,0,0,0,0,0,0,0,0,
                     1,0,0,0,0,0,1,0,0,0,0,0,0,0,
                     1,0,0,0,0,0,0,1,0,0,0,0,0,0),
                   byrow=T,nrow=7)

SSEstimates=matrix(c(1,1,0,0,0,0,0,0,0,0,0,0,0,0,
                     1,1,1,0,0,0,0,0,1,0,0,0,0,0,
                     1,1,0,1,0,0,0,0,0,1,0,0,0,0,
                     1,1,0,0,1,0,0,0,0,0,1,0,0,0,
                     1,1,0,0,0,1,0,0,0,0,0,1,0,0,
                     1,1,0,0,0,0,1,0,0,0,0,0,1,0,
                     1,1,0,0,0,0,0,1,0,0,0,0,0,1),
                   byrow=T,nrow=7)

Contrasts=SSEstimates-BBEstimates

Betas=matrix(summary(Model)$coefficients[,1],nrow=14)

ContrastEstimates=Contrasts%*%Betas
ContrastSE=sqrt(diag(Contrasts%*%VarMat%*%t(Contrasts)))

pvalues=2*pnorm(abs(ContrastEstimates/ContrastSE),lower.tail = FALSE)

ResultsLog=data.frame("Estimate"=ContrastEstimates,
                      "Lower"=ContrastEstimates-qnorm(0.975)*ContrastSE,
                      "Upper"=ContrastEstimates+qnorm(0.975)*ContrastSE,
                      "p.value"=pvalues)

ResultsOR=data.frame("OR"=exp(ContrastEstimates),
                      "Lower"=exp(ContrastEstimates-qnorm(0.975)*ContrastSE),
                      "Upper"=exp(ContrastEstimates+qnorm(0.975)*ContrastSE),
                      "p.value"=pvalues)
rownames(ResultsOR)=c("F0: SS vs BB","F1: SS vs BB","F3: SS vs BB",
                      "F5: SS vs BB","F10: SS vs BB","F15: SS vs BB",
                      "F63: SS vs BB")

knitr::kable(ResultsOR,digits=2,caption="Engorgement odds ratios and 95% confidence intervals associated with SS vs BB at each generation for *Anopheles stephensi*")

```


```{r,fig.cap="Engorgement odds ratios and 95% confidence intervals associated with SS vs BB at each generation for *Anopheles stephensi*"}
ResultsOR$Generation=c("F0","F1","F3","F5","F10","F15","F63")

ResultsOR$Generation=factor(ResultsOR$Generation,
                            levels=c("F0","F1","F3","F5","F10","F15","F63"))

p=ggplot(ResultsOR,aes(x=Generation,y=OR))+geom_point()+theme_bw()+
  labs(y=expression(atop(italic("Anopheles stephensi")," OR of SS vs BB with 95% CI")))+
  geom_errorbar(aes(min=Lower,max=Upper),width=0.2)+
  scale_y_continuous(trans="log",breaks=c(0.1,1,10,50,100))+
  geom_hline(yintercept=1,linetype=2,color="darkgray")+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 12),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(hjust = 0.5))

print(p)
```



* Although the generation effect appears to be significant as shown in the LRT and the above figures, we do not see a meaningful pattern. Therefore, to get an overall averaging estimate of the meal effect we treat the interaction as part of the error.

```{r}
ConfInt=confint(ModelRed,parm="beta_")

ResultsOR=data.frame("OR"=exp(summary(ModelRed)$coefficients[,1]),
                      "Lower"=exp(ConfInt[,1]),
                      "Upper"=exp(ConfInt[,2]),
                      "p.value"=summary(ModelRed)$coefficients[,4])
ResultsOR=ResultsOR[-1,]
rownames(ResultsOR)=c("SS vs. BB","F1 vs. F0","F3 vs. F0","F5 vs. F0","F10 vs. F0",
                      "F15 vs. F0","F63 vs. F0")


```

```{r}

knitr::kable(ResultsOR,digits=3,caption="*Anopheles stephensi* summary table in OR scale")

```

* We found a significant effect due to meal. The odds of a mosquito engorging when the meal is SS are `r round(ResultsOR[1,1],2)` (95%CI:[`r round(ResultsOR[1,2],2)`,`r round(ResultsOR[1,3],2)`]) times higher than when the meal is SS. 


* We also calculated the engorgement probabilities at each generation and meal combination.

```{r,fig.cap="Observed (dots) and estimated (horizontal line) engorgement rates and bootstrap 95% confidence intervals (vertical lines) for *Anopheles stephensi*. Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook. "}

NewData=Data[c(1,5,9,13,17,20,23,24,25,28,31,34,37,40),c(1,2,3,7)]

Test=bootMer(ModelRed, PredictFunction,nsim=1000)

Confints=apply(Test$t, quantile, probs=c(0.025,0.975), na.rm=TRUE,MARGIN=2)

Probabilities=data.frame("Meal"=NewData$Meal,"Generation"=NewData$Generation,
                         "Probability"=Test$t0,"Lower"=Confints[1,],
                         "Upper"=Confints[2,],
                         "AverageProbability"=apply(Test$t, mean, na.rm=TRUE,MARGIN=2))

ggplot(Data,aes(x=Meal,y=EngorgementRate*100,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2.5,
             position = position_jitter(h=0,w=0.1))+
  facet_grid(. ~ Generation)+theme_bw()+
  labs(x="Diet",y=expression(atop(italic("Anopheles stephensi"),"\n Engorgement Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(hjust = 0.5),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank())+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,100,by=20),limits=c(0,100))+
  geom_point(data=Probabilities,
             aes(x=Meal,y=AverageProbability*100),color="black",shape="-",size=10)+
  geom_errorbar(data=Probabilities,aes(min=Lower*100,max=Upper*100,y=AverageProbability*100),
                color="black",width=1)
  
p.anoph=ggplot(Data,aes(x=Meal,y=EngorgementRate*100,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2.5,
             position = position_jitter(h=0,w=0.1))+
  facet_grid(. ~ Generation)+theme_bw()+
  labs(x="",y=expression(atop(italic("Anopheles stephensi"),"\n Engorgement Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank(),
        plot.subtitle=element_text(hjust=0.5))+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,100,by=20),limits=c(0,100))+
  geom_point(data=Probabilities,
             aes(x=Meal,y=AverageProbability*100),color="black",shape="-",size=10)+
  geom_errorbar(data=Probabilities,aes(min=Lower*100,max=Upper*100,y=AverageProbability*100),
                color="black",width=1)+
  ggtitle("B", subtitle = expression(italic("Anopheles stephensi")))
```


## Summary Figure 

```{r,fig.width=9,fig.height=4.5,fig.cap="Engorgement rates of *Aedes aegypti* and *Anopheles stephensi* female mosquitoes offered meals of bovine blood (BB) or SkitoSnack (SS). A. Results from 1-4 biological replicate colonies of *Aedes aegypti* at generations F0, F1, F3, F5, and F7. B. Results from 1-4 biological replicate colonies of *Anopheles stephensi* at generations F0, F1, F3, F5, F10, F15, and F63. Colors represent the data from the different replicate colonies fed on BB (circles), or SS (triangles). Horizontal lines mark the estimated the estimated  engorgement rate and vertical lines mark the bootstrap 95% confidence intervals of the engorgement rate."}

plot_grid(p.aedes,p.anoph,ncol=2,rel_widths = c(9/20,11/20))

pdf("Figure1.pdf",width=10,height=5)
plot_grid(p.aedes,p.anoph,ncol=2,rel_widths = c(9/20,11/20))
invisible(dev.off())
```

\newpage 

# Hatch Rate

## Analysis Details

* In the sections below we present analyses to determine whether the type of meal (BB: bovine blood or SS: SkitoSnack) has an effect on hatch rate.
* We consider a logistic regression with quasibinomial family for our variable of interest. 
* We  include a generation by meal interaction to estimate the effect of diet at each generation and use a test of deviance to assess whether the interaction is significant.
* If the interaction is not significant it is removed from the model. 
* Reference values: The reference for Meal is BB and for Generation is F0.

\newpage 

## *Aedes aegypti*

```{r}
AeAegyptiHatchSep=read.csv("/Volumes/ortegavillaa$/My Documents/Ana/NIAID/SkitoSnacks/2023Data/HatchRates_AA.csv")

AeAegyptiHatch=AeAegyptiHatchSep%>%
  group_by(MosquitoContainer)%>%
  summarise("Meal"=first(Meal),
            "Replicate"=first(Replicate),
            "Generation"=first(Generation),
            "NumberEggs"=sum(NumberEggs),
            "NumberLarvae"=sum(NumberLarvae),
            "HatchRate"=sum(NumberLarvae)/sum(NumberEggs))




AeAegyptiHatch$Replicate=as.factor(AeAegyptiHatch$Replicate)
AeAegyptiHatch$MosquitoContainer=as.factor(AeAegyptiHatch$MosquitoContainer)
AeAegyptiHatch$Generation=factor(AeAegyptiHatch$Generation,
                                 levels=c("F0","F1","F3","F5","F10"))

AeAegyptiHatch$Meal=as.factor(AeAegyptiHatch$Meal)

AeAegyptiHatch$Replicate2=AeAegyptiHatch$Replicate
levels(AeAegyptiHatch$Replicate2)=c(rep(c("0","2","3"),2),rep(c("0","1","2","3"),2),
                                    rep(c("1","2","3"),6))



AeAegyptiHatchSep$Replicate2=as.factor(AeAegyptiHatchSep$Replicate)
levels(AeAegyptiHatchSep$Replicate2)=c(rep(c("0","2","3"),2),rep(c("0","1","2","3"),2),
                                    rep(c("1","2","3"),6))

AeAegyptiHatchSep$HatchRate=AeAegyptiHatchSep$NumberLarvae/AeAegyptiHatchSep$NumberEggs
AeAegyptiHatch$EggsRemaining=AeAegyptiHatch$NumberEggs-AeAegyptiHatch$NumberLarvae

```

```{r,include=TRUE,fig.cap="Observed hatch rates (%) for *Aedes aegypti*. Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook. "}
AeAegyptiHatchSep$Generation=factor(AeAegyptiHatchSep$Generation,
                                    levels=c("F0","F1","F3","F5","F10"))


p=ggplot(AeAegyptiHatchSep,aes(x=Meal,y=HatchRate*100))+
  geom_boxplot(fill="white",outlier.size = -1)+
  geom_point(aes(color=Replicate2,shape=Meal),size=2.5,position = position_jitterdodge())+
  facet_grid(. ~ Generation)+theme_classic()+labs(x="",y=expression(atop(italic("Aedes aegypti"),"\n Hatch Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),
        strip.text =element_text(size = 14),
        title= element_text(size = 15),
        strip.background = element_blank())+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  annotate("segment",x=0.75,xend=2.25,y=105,yend=105)


print(p)
```

```{r}

AeAeH.mod=glm(cbind(NumberLarvae,EggsRemaining)~Meal*Generation,
                data=AeAegyptiHatch,family="quasibinomial")

AeAeH.modRed=glm(cbind(NumberLarvae,EggsRemaining)~Meal+Generation,
                data=AeAegyptiHatch,family="quasibinomial")

AeAeH.modRedred=glm(cbind(NumberLarvae,EggsRemaining)~Meal,
                data=AeAegyptiHatch,family="quasibinomial")


InteractionTest=anova(AeAeH.mod,AeAeH.modRed,test="Chisq")
p.inter=InteractionTest$`Pr(>Chi)`[2]

GenTest=anova(AeAeH.modRed,AeAeH.modRedred,test="Chisq")
p.gen=GenTest$`Pr(>Chi)`[2]

Intervals=confint(AeAeH.modRed)
Coeffi=summary(AeAeH.modRed)$coefficients

ModelSummary=data.frame("OR"=exp(Coeffi[,1]),"Lower"=exp(Intervals[,1]),
           "Upper"=exp(Intervals[,2]),"p.value"=Coeffi[,4])
ModelSummary$p.value=ifelse(ModelSummary$p.value<0.001,"<0.001",
                            round(ModelSummary$p.value,3))
```

* We did not find sufficient evidence of a significant interaction, test of deviance p: `r round(p.inter,3)`.
* We found evidence of a significant generation effect, test of deviance p: `r round(p.gen,3)`.
* We found evidence of significant effect of meal p:`r ModelSummary[2,4]`. The odds of an egg hatching are `r round(ModelSummary[2,1],2)` times lower (95%CI:[`r round(ModelSummary[2,2],2)`,`r round(ModelSummary[2,3],2)`]) when the meal is SkitoSnack when compared to bovine blood.

```{r,include=TRUE}

knitr::kable(ModelSummary,caption="*Aedes aegypti* hatch rates model summary",digits=2)
```

* Below we present observed hatch rates with estimated hatch rates and 95% bootstrap confidence intervals.

```{r}


NewData=AeAegyptiHatch[c(1,4,7,11,15,18,21,24,27,30),c(1,2,3,4)]

PredictFunction=function(Dat,indices){
  ModelBoot=glm(cbind(NumberLarvae,EggsRemaining)~Meal+Generation,
                data=Dat[indices,],family="quasibinomial")
  predict(ModelBoot,newdata=NewData,type="response")
}

Test=boot(data=AeAegyptiHatch,statistic=PredictFunction,R=1000,strata=AeAegyptiHatch$Generation)


Confints=apply(Test$t, quantile, probs=c(0.025,0.975), na.rm=TRUE,MARGIN=2)

Probabilities=data.frame("Meal"=NewData$Meal,"Generation"=NewData$Generation,
                         "Probability"=Test$t0,"Lower"=Confints[1,],
                         "Upper"=Confints[2,],
                         "AverageProbability"=apply(Test$t, mean, na.rm=TRUE,MARGIN=2))

p.aedes=ggplot(AeAegyptiHatchSep,aes(x=Meal,y=HatchRate*100,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2.5,
             position = position_jitterdodge())+
  facet_grid(. ~ Generation)+theme_bw()+
  labs(x="",y=expression(atop(italic("Aedes aegypti"),"\n Hatch Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank(),
        plot.subtitle = element_text(hjust=0.5))+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,100,by=20),limits=c(0,100))+
  geom_point(data=Probabilities,
             aes(x=Meal,y=Probability*100),color="black",shape="-",size=10)+
  geom_errorbar(data=Probabilities,aes(min=Lower*100,max=Upper*100,y=AverageProbability*100),
                color="black",width=1)+
  ggtitle("A",subtitle=expression(italic("Aedes aegypti")))

```

```{r,fig.cap="Hatch rates and 95% bootstrap confidence intervals for *Aedes aegypti*. Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook."}
ggplot(AeAegyptiHatchSep,aes(x=Meal,y=HatchRate*100,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2.5,
             position = position_jitterdodge())+
  facet_grid(. ~ Generation)+theme_bw()+
  labs(x="",y=expression(atop(italic("Aedes aegypti"),"\n Average Hatch Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank())+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,100,by=20),limits=c(0,100))+
  geom_point(data=Probabilities,
             aes(x=Meal,y=Probability*100),color="black",shape="-",size=10)+
  geom_errorbar(data=Probabilities,aes(min=Lower*100,max=Upper*100,y=AverageProbability*100),
                color="black",width=1)
```

\newpage 

## *Anopheles stephensi*

```{r}
AnSData=read.csv("/Volumes/ortegavillaa$/My Documents/Ana/NIAID/SkitoSnacks/2023Data/HatchRates_AS.csv")

AnSData1=AnSData[AnSData$Generation!="F63",]
AnSData2=AnSData[AnSData$Generation=="F63",]

AnSDataAvg=AnSData1%>%
  group_by(MosquitoContainer)%>%
  summarise("Meal"=first(Meal),
            "Replicate"=first(Replicate),
            "Generation"=first(Generation),
            "NumberEggs"=sum(NumberEggs),
            "NumberLarvae"=sum(NumberLarvae),
            "HatchRate"=sum(NumberLarvae)/sum(NumberEggs))

AnSDataAvg2=AnSData2%>%
  group_by(MosquitoContainer)%>%
  summarise("Meal"=first(Meal),
            "Replicate"=first(Replicate),
            "Generation"=first(Generation),
            "NumberEggs"=sum(NumberEggs),
            "NumberLarvae"=sum(NumberLarvae),
            "HatchRate"=sum(NumberLarvae)/sum(NumberEggs))

AnStephenAvgData=rbind(AnSDataAvg,AnSDataAvg2)

AnStephenAvgData$Replicate=as.factor(AnStephenAvgData$Replicate)
AnStephenAvgData$MosquitoContainer=as.factor(AnStephenAvgData$MosquitoContainer)
AnStephenAvgData$Generation=factor(AnStephenAvgData$Generation,levels=c("F0","F1","F3","F5",
                                                                        "F10","F15","F63"))
AnStephenAvgData$Meal=as.factor(AnStephenAvgData$Meal)

AnSData$Replicate2=as.factor(AnSData$Replicate)
levels(AnSData$Replicate2)=c(rep(c("1","2","3"),10),c("2","3","2","3"),rep(c("1","2","3"),2))

AnSData$HatchRate=AnSData$NumberLarvae/AnSData$NumberEggs


AnStephenAvgData$Replicate2=AnStephenAvgData$Replicate
levels(AnStephenAvgData$Replicate2)=c(rep(c("1","2","3"),10),c("2","3","2","3"),rep(c("1","2","3"),2))
```

```{r, include=TRUE,fig.cap="Observed hatch rates for *Anopheles stephensi*. Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook. "}
AnSData$Generation=factor(AnSData$Generation,
                          levels=c("F0","F1","F3", "F5","F10","F15","F63"))


p=ggplot(AnSData,aes(x=Meal,y=HatchRate*100,shape=Meal))+
  geom_boxplot(fill="white",outlier.size = -1)+
  geom_point(aes(color=Replicate2,shape=Meal),size=2.5,position = position_jitterdodge())+
  facet_grid(. ~ Generation)+theme_classic()+
  labs(x="",y=expression(atop(italic("Anopheles stephensi"),"\n Hatch Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),
        strip.text =element_text(size = 14),
        title= element_text(size = 15),
        strip.background = element_blank())+
  scale_color_manual(values=c("darkorange1","blue","springgreen3"))+
  annotate("segment",x=0.75,xend=2.25,y=105,yend=105)

print(p)

```


```{r}

AnStephenAvgData$EggsRemaining=AnStephenAvgData$NumberEggs-AnStephenAvgData$NumberLarvae


AnStH.mod=glm(cbind(NumberLarvae,EggsRemaining)~Meal*Generation,
                data=AnStephenAvgData,family="quasibinomial")

AnStH.modRed=glm(cbind(NumberLarvae,EggsRemaining)~Meal+Generation,
                data=AnStephenAvgData,family="quasibinomial")

AnStH.modRedred=glm(cbind(NumberLarvae,EggsRemaining)~Meal,
                data=AnStephenAvgData,family="quasibinomial")


InteractionTest=anova(AnStH.mod,AnStH.modRed,test="Chisq")
p.inter=InteractionTest$`Pr(>Chi)`[2]

GenTest=anova(AnStH.modRed,AnStH.modRedred,test="Chisq")
p.gen=GenTest$`Pr(>Chi)`[2]

Intervals=confint(AnStH.modRed)
Coeffi=summary(AnStH.modRed)$coefficients

ModelSummary=data.frame("OR"=exp(Coeffi[,1]),"Lower"=exp(Intervals[,1]),
           "Upper"=exp(Intervals[,2]),"p.value"=Coeffi[,4])
ModelSummary$p.value=ifelse(ModelSummary$p.value<0.001,"<0.001",
                            round(ModelSummary$p.value,3))

```

* We found no significant interaction. Test of deviance p: `r round(p.inter,3)`.
* We found evidence of a significant generation effect. Test of deviance p: `r ifelse(round(p.gen,3)==0,"<0.001",round(p.gen,3))`.
* We found evidence of a significant effect of meal p:`r ModelSummary[2,4]`. The odds of an egg hatching are `r round(ModelSummary[2,1],2)` times lower (95%CI:[`r round(ModelSummary[2,2],2)`,`r round(ModelSummary[2,3],2)`]) when the meal is SkitoSnack when compared to bovine blood.

```{r, include=TRUE}

knitr::kable(ModelSummary,digits=3,caption="*Anopheles stephensi* hatch rate model summary")

```

* Below we present observed hatch rates with estimated hatch rates and 95% bootstrap confidence intervals.


```{r}


NewData=AnStephenAvgData[c(1,4,7,10,13,16,19,21,23,26,29,32,35,38),c(1,2,3,4)]

PredictFunction=function(Dat,indices){
  ModelBoot=glm(cbind(NumberLarvae,EggsRemaining)~Meal+Generation,
                data=Dat[indices,],family="quasibinomial")
  predict(ModelBoot,newdata=NewData,type="response")
}

Test=boot(data=AnStephenAvgData,statistic=PredictFunction,R=1000,strata=AnStephenAvgData$Generation)


Confints=apply(Test$t, quantile, probs=c(0.025,0.975), na.rm=TRUE,MARGIN=2)

Probabilities=data.frame("Meal"=NewData$Meal,"Generation"=NewData$Generation,
                         "Probability"=Test$t0,"Lower"=Confints[1,],
                         "Upper"=Confints[2,] )



p.ano=ggplot(AnSData,aes(x=Meal,y=HatchRate*100,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2.5,
             position = position_jitterdodge())+
  facet_grid(. ~ Generation)+theme_bw()+
  labs(x="",y=expression(atop(italic("Anopheles stephensi"),"\n Hatch Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank(),
        plot.subtitle = element_text(hjust=0.5))+
  scale_color_manual(values=c("darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,100,by=20))+
  geom_point(data=Probabilities,
             aes(x=Meal,y=Probability*100),color="black",shape="-",size=10)+
  geom_errorbar(data=Probabilities,aes(min=Lower*100,max=Upper*100,y=Probability*100),
                color="black",width=1)+
  ggtitle("B",subtitle = expression(italic("Anopheles stephensi")))

```

```{r,fig.cap="Observed (dots) and estimated (horizontal line) hatch rates and bootstrap 95% confidence intervals (vertical lines) for *Anopheles stephensi*. Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook. "}

ggplot(AnSData,aes(x=Meal,y=HatchRate*100,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2.5,
             position = position_jitterdodge())+
  facet_grid(. ~ Generation)+theme_bw()+
  labs(x="",y=expression(atop(italic("Anopheles stephensi"),"\n Hatch Rate (%)")))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank(),
        plot.subtitle = element_text(hjust=0.5))+
  scale_color_manual(values=c("darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,100,by=20))+
  geom_point(data=Probabilities,
             aes(x=Meal,y=Probability*100),color="black",shape="-",size=10)+
  geom_errorbar(data=Probabilities,aes(min=Lower*100,max=Upper*100,y=Probability*100),
                color="black",width=1)

```


\newpage

## Summary Figure 

```{r,fig.width=10,fig.height=5,fig.cap="Hatch rates of *Aedes aegypti* and *Anopheles stephensi* female mosquitoes offered meals of bovine blood (BB) or SkitoSnack (SS). A. Results from 3-4 biological replicate colonies of *Aedes aegypti* at generations F0, F1, F3, F5, and F10. B. Results from 2-3 biological replicate colonies of *Anopheles stephensi* at generations F0, F1, F3, F5, F10, F15, and F63. Colors represent the data from the different replicate colonies fed on BB (circles), or SS (triangles). Horizontal  lines mark the estimated hatch rates and vertical lines mark bootstrap 95% confidence intervals of the hatch rate."}
plot_grid(p.aedes,p.ano,ncol=2,rel_widths = c(9/20,11/20))

pdf("Figure2.pdf",width=10,height=5)
plot_grid(p.aedes,p.ano,ncol=2,rel_widths = c(9/20,11/20))
invisible(dev.off())
```



\newpage

# Vector Susceptibility Analysis - Oocyst Counts 

## Analysis Details

* In the sections below we present analyses to determine whether the type of meal (BB: bovine blood or SS: SkitoSnack) has an effect on oocyst counts.
* We are using a negative binomial model, where our response is the count of oocysts in the midgut.
* We consider a mixed effects model to control for the correlation within groups or similar factors.
    * *Random effect*: Replicate colonies for each generation
    * *Fixed effect*: Meal and generation. 
* The models were fit using the package lme4, citation: Bates D, Mächler M, Bolker B, Walker S (2015). "Fitting Linear Mixed-Effects Models Using lme4." *Journal of Statistical Software*, 67(1), 1–48.
* The 95% confidence intervals for the estimated probabilities were obtained via bootstrap with 1000 iterations.
* For all analyses the reference meal is bovine blood.
* The analysis is limited to infected mosquitoes, therefore mosquitoes with zero oocyst counts were eliminated.
* We performed a vector susceptibility sensitivity analysis to compare the fraction of dissected mosquitoes with oocysts present between the BB and SS meal groups using a quasi-binomial model within each mosquito species/generation combination.

```{r}
quasiBinomTest<-function(x,n,group){
  # test for difference using quasi-binomial model
  group<- as.factor(group)
  gout<-glm(cbind(x,n-x)~group,family=quasibinomial())
  sout<-summary(gout)
  # if dispersion is less than 1, use binomial (i.e., don't allow it 
  # to be easier to reject than binomial family)
  if (sout$dispersion<1){
     gout<-glm(cbind(x,n-x)~group,family=binomial())
     sout<-summary(gout)
  }
  two.sided.p.value<- sout$coef[2,4]
  two.sided.p.value
}

```

## *Aedes aegypti*

* The reference generation is F5

```{r}
DataAe=read.csv("/Volumes/ortegavillaa$/My Documents/Ana/NIAID/SkitoSnacks/2023Data/VectorInfectivity_AA.csv",
                stringsAsFactors=TRUE)
DataAe=DataAe[DataAe$Oocysts>0,]

DataAe$Replicate2=DataAe$Replicate
levels(DataAe$Replicate2)=c("black","orange","blue","green","black","orange","blue","green",
                            "orange","blue","green","orange","blue","green",
                            "orange","blue","green","orange","blue","green")


p=ggplot(DataAe,aes(x=Meal,y=Oocysts,shape=Meal,color=Replicate2))+
  geom_boxplot(fill="white",outlier.shape = NA,color="black")+
  geom_point(aes(shape=Meal),size=2, position = position_jitterdodge())+
  facet_grid(. ~ Generation)+
  theme_bw()+labs(x="",y=expression(atop(paste(italic("Plasmodium gallinaceum"),"oocysts/"),paste("infected ",italic("Aedes aegypti")))))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(hjust = 0.5),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank())+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,250,by=50),limits=c(0,250))


Model=glmer.nb(Oocysts~Meal+Generation+Meal*Generation+(1|Replicate),
            data=DataAe,control = glmerControl(optimizer = "bobyqa"))

ModelRed=glmer.nb(Oocysts~Meal+Generation+(1|Replicate),
            data=DataAe,control = glmerControl(optimizer = "bobyqa"))

DataAe$Generation2=relevel(DataAe$Generation,ref="F5")

ModelRed2=glmer.nb(Oocysts~Meal+Generation2+(1|Replicate),
            data=DataAe,control = glmerControl(optimizer = "bobyqa"))

LRT=anova(Model,ModelRed)
pvalue=round(LRT$`Pr(>Chisq)`[2],3)


Intervals=confint(ModelRed,method="boot",nsim=1000)

Results=data.frame("Estimate"=summary(ModelRed)$coefficients[,1],
                   "Lower"=Intervals[-1,1],
                   "Upper"=Intervals[-1,2],
                   "P.value"=summary(ModelRed)$coefficients[,4])

Intervals2=confint(ModelRed2,method="boot",nsim=1000)

Results2=data.frame("Estimate"=summary(ModelRed2)$coefficients[,1],
                   "Lower"=Intervals2[-1,1],
                   "Upper"=Intervals2[-1,2],
                   "P.value"=summary(ModelRed2)$coefficients[,4])

```

```{r,fig.cap="Observed oocyst counts for *Aedes aegypti*. Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook. "}
print(p)
```

* We performed a likelihood ratio test (LRT) to determine whether there was a significant interaction between generation and meal. The p-value of the test is p: `r pvalue`. 
* Because of our interaction results we will work with a model that does not include an interaction term.

```{r}
knitr::kable(Results2,digits=3,caption="Oocysts count estimates and 95% bootstrap confidence intervals for *Aedes aegypti*")

```

* We don't have sufficient evidence to say there is a significant difference between meals (p: `r round(Results[2,4],3)`). 
* However, our best estimate of the meal effect is that changing the meal from BB to SS would increase the number of oocysts in the midgut on average by a factor of e$^{\beta_{SS}}\rightarrow$ `r round(exp(Results[2,1]),3)`. This means that the mean number of oocysts in the midgut is `r round(exp(Results[2,1]),3)` times higher when the meal is SS than when the meal is BB with 95% confidence bounds [`r round(exp(Results[2,2]),3)`,`r round(exp(Results[2,3]),3)`].
* There is a significant generation effect.
    * Generation F1 significantly differs from F5 p: `r round(Results2[3,4],3)`.  This means that the mean number of oocysts in the midgut is `r round(exp(Results2[3,1]),3)` times higher in generation F1 than in F5, the 95% CI is [`r round(exp(Results2[3,2]),3)`,`r round(exp(Results2[3,3]),3)`].
    * Generation F3 significantly differs from F5 p: `r round(Results2[4,4],3)`.  This means that the mean number of oocysts in the midgut is `r round(exp(Results2[4,1]),3)` times higher in generation F3 than in F5, the 95% CI is [`r round(exp(Results2[4,2]),3)`,`r round(exp(Results2[4,3]),3)`].
* The plot below presents the observed oocysts counts by generation, along with oocyst count estimates (dark horizontal line) and bootstrap 95% confidence intervals.   
    
```{r,fig.cap="Observed (dots) and estimated (horizontal line) oocyst counts and bootstrap 95% confidence intervals (vertical lines) for *Aedes aegypti*. Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook. "}
NewData=DataAe[c(1,45,88,117,149,189),]

PredictFunction=function(mm){
  exp(predict(mm,newdata=NewData))
}

Test=bootMer(ModelRed2, PredictFunction,nsim=1000)

Confints=apply(Test$t, quantile, probs=c(0.025,0.975), na.rm=TRUE,MARGIN=2)

Estimates=data.frame("Meal"=NewData$Meal,"Generation"=NewData$Generation,
                         "Estimates"=Test$t0,"Lower"=Confints[1,],
                         "Upper"=Confints[2,],
                         "BootEstimates"=apply(Test$t, mean, na.rm=TRUE,MARGIN=2))

ggplot(DataAe,aes(x=Meal,y=Oocysts,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2, position = position_jitterdodge())+
  facet_grid(. ~ Generation)+
  theme_bw()+labs(x="",y=expression(atop(paste(italic("Plasmodium gallinaceum")," oocysts/"),paste("infected ",italic("Aedes aegypti")))))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(hjust = 0.5),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank())+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  geom_point(data=Estimates,aes(y=Estimates),color="black",shape="-",size=10)+
  geom_errorbar(data=Estimates,aes(y=Estimates,ymin=Lower,ymax=Upper),
                color="black",width=1)+
  scale_y_continuous(breaks=seq(0,250,by=50),limits=c(0,250))

p.aedes=ggplot(DataAe,aes(x=Meal,y=Oocysts,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2, position = position_jitterdodge())+
  facet_grid(. ~ Generation)+
  theme_bw()+labs(x="",y=expression(atop(paste(italic("Plasmodium gallinaceum ")," oocysts/"),paste("infected ",italic("Aedes aegypti")))))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank(),
        plot.subtitle = element_text(hjust=0.5))+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  geom_point(data=Estimates,aes(y=Estimates),color="black",shape="-",size=10)+
  geom_errorbar(data=Estimates,aes(y=Estimates,ymin=Lower,ymax=Upper),color="black",width=1)+
  ggtitle("A",subtitle = expression(italic("Aedes aegypti")))+
  scale_y_continuous(breaks=seq(0,250,by=50),limits=c(0,250))
```

\newpage

### Vector Susceptibility Sensitivity Analysis 

```{r}
TableSensitivityAA<- data.frame(
   generation=rep(c(rep("F1",4),rep("F3",3),rep("F5",3)),2),
   feed=c(rep("BB",10),rep("SS",10)),
   n.with.oocysts=c(9,14,14,7,9,12,8,21,9,9,
                 10,11,13,8,10,10,10,23,7,9),
  n.dissected=c(9,14,14,7,9,12,8,21,10,10,
                 10,11,13,9,10,10,10,23,7,10) )

g<-c("F1","F3","F5")
p.value.Tab3 <- rep(NA,3)
names(p.value.Tab3)<- paste0("Generation: ",g) 

for (i in 1:3){
   pick<- TableSensitivityAA$generation==g[i]
   p.value.Tab3[i]<-   quasiBinomTest(TableSensitivityAA$n.with.oocysts[pick],
               TableSensitivityAA$n.dissected[pick],
               TableSensitivityAA$feed[pick])
}

p.value.Tab3=as.data.frame(p.value.Tab3)
names(p.value.Tab3)="p-value"
knitr::kable(p.value.Tab3,digits=3,caption="p-values from the quasi-binomial model comparing, for each generation, the proportion of dissected mosquitoes with oocysts from the two meal groups for *Aedes aegypti*")

```

We found no significant differences in the fraction of infected mosquitoes at any of the three generations.



## *Anopheles stephensi*

* The generation reference is F8.

```{r}
DataComplete=read.csv('/Volumes/ortegavillaa$/My Documents/Ana/NIAID/SkitoSnacks/2023Data/VectorInfectivity_AS.csv', stringsAsFactors=TRUE)

DataComplete$Generation=relevel(DataComplete$Generation,ref="F8")

DataComplete=DataComplete[DataComplete$Oocysts>0,]

DataComplete$Replicate2=DataComplete$Replicate
levels(DataComplete$Replicate2)=c("orange","blue","green","orange","blue","green",
                                  "orange","blue","green","orange","blue","green")

p=ggplot(DataComplete,aes(x=Meal,y=Oocysts,shape=Meal,color=Replicate2))+
  geom_boxplot(fill="white",outlier.shape = NA,color="black")+
  geom_point(aes(shape=Meal),size=2, position = position_jitterdodge())+
  facet_grid(. ~ Generation)+
  theme_bw()+labs(x="",y=expression(atop(paste(italic("Plasmodium falciparum "),"oocysts/"),paste("infected ",italic("Anopheles stephensi")))))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(hjust = 0.5),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank())+
  scale_color_manual(values=c("darkorange1","blue","springgreen3"))+
  scale_y_continuous(breaks=seq(0,250,by=50),limits=c(0,250))


Model=glmer.nb(Oocysts~Meal+Generation+Meal*Generation+(1|Replicate),
            data=DataComplete,control = glmerControl(optimizer = "bobyqa"))

ModelRed=glmer.nb(Oocysts~Meal+Generation+(1|Replicate),
            data=DataComplete,control = glmerControl(optimizer = "bobyqa"))

LRT=anova(Model,ModelRed)
pvalue=round(LRT$`Pr(>Chisq)`[2],3)

Intervals=confint(ModelRed,method="boot",nsim=1000)

Results=data.frame("Estimate"=summary(ModelRed)$coefficients[,1],
                   "Lower"=Intervals[-1,1],
                   "Upper"=Intervals[-1,2],
                   "P.value"=summary(ModelRed)$coefficients[,4])
Results$P.value=ifelse(Results$P.value<0.001,"<0.001",round(Results$P.value,3))
```

```{r,,fig.cap="Observed oocyst counts for *Anopheles stephensi*. Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook. "}

print(p)

```

* We performed a likelihood ratio test (LRT) to determine whether there was a significant interaction between generation and meal. The p-value of the test is p: `r pvalue`. 
* Because of our interaction results we will work with a model that does not include an interaction term.

```{r}
knitr::kable(Results,digits=3,caption="Oocysts count estimates and 95% bootstrap confidence intervals for *Anopheles stephensi*")

```

* We don't have sufficient evidence to say there is a significant difference between meals (p: `r round(as.numeric(Results[2,4]),3)`). 
* However, our best estimate of the meal effect is that changing the meal from BB to SS would decrease the number of oocysts in the midgut on average by a factor of e$^{\beta_{SS}}\rightarrow$ `r round(exp(Results[2,1]),3)`. This means that the mean number of oocysts in the midgut is `r round(exp(Results[2,1]),3)` times lower when the meal is SS than when the meal is BB with 95% confidence bounds [`r round(exp(Results[2,2]),3)`,`r round(exp(Results[2,3]),3)`].
* There is a significant generation effect. Generation F63 significantly differs from F8 (p: `r Results[3,4]`).  This means that the mean number of oocysts in the midgut is `r round(exp(Results[3,1]),3)` times higher in generation F63 than in F8, the 95% CI is [`r round(exp(Results[3,2]),3)`,`r round(exp(Results[3,3]),3)`].
* The plot below presents the observed oocysts counts by generation, along with oocyst count estimates and bootstrap 95% confidence intervals.

```{r,fig.cap="Observed (dots) and estimated (horizontal line) oocyst counts and bootstrap 95% confidence intervals (vertical lines) for *Anopheles stephensi*. Circles and triangles represent the data from the different replicate colonies fed on BB (circles), or SS (triangles), respectively. The colors correspond to the replicates which match the colors used in Additional file 3: Microsoft Excel workbook. "}
NewData=DataComplete[c(1,129,255,277),]

PredictFunction=function(mm){
  exp(predict(mm,newdata=NewData))
}

Test=bootMer(ModelRed, PredictFunction,nsim=1000)

Confints=apply(Test$t, quantile, probs=c(0.025,0.975), na.rm=TRUE,MARGIN=2)

Estimates=data.frame("Meal"=NewData$Meal,"Generation"=NewData$Generation,
                         "Estimates"=Test$t0,"Lower"=Confints[1,],
                         "Upper"=Confints[2,],
                         "BootEstimates"=apply(Test$t, mean, na.rm=TRUE,MARGIN=2))

ggplot(DataComplete,aes(x=Meal,y=Oocysts,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2, position = position_jitterdodge())+
  facet_grid(. ~ Generation)+
  theme_bw()+labs(x="",y=expression(atop(paste(italic("Plasmodium falciparum")," oocysts/"),paste("infected ",italic("Anopheles stephensi")))))+
   theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank(),
        plot.subtitle = element_text(hjust=0.5))+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  geom_point(data=Estimates,aes(y=Estimates),color="black",shape="-",size=10)+
  geom_errorbar(data=Estimates,aes(y=Estimates,ymin=Lower,ymax=Upper),
                color="black",width=1)+
  scale_y_continuous(breaks=seq(0,280,by=50),limits=c(0,280))

p.anoph=ggplot(DataComplete,aes(x=Meal,y=Oocysts,shape=Meal,color=Replicate2))+
  geom_point(aes(shape=Meal),size=2, position = position_jitterdodge())+
  facet_grid(. ~ Generation)+
  theme_bw()+labs(x="",y=expression(atop(paste(italic("Plasmodium falciparum")," oocysts/"),paste("infected ",italic("Anopheles stephensi")))))+
  theme(legend.position = 'none',axis.title = element_text(size = 14),
        axis.text = element_text(size = 10),strip.text =element_text(size = 14),
        title= element_text(size = 15),plot.title = element_text(),
        panel.grid.major = element_blank(),panel.grid.minor = element_blank(),
        plot.subtitle = element_text(hjust=0.5))+
  scale_color_manual(values=c("black","darkorange1","blue","springgreen3"))+
  geom_point(data=Estimates,aes(y=Estimates),color="black",shape="-",size=10)+
  geom_errorbar(data=Estimates,aes(y=Estimates,ymin=Lower,ymax=Upper),
                color="black",width=1)+
  scale_y_continuous(breaks=seq(0,280,by=50),limits=c(0,280))+
  ggtitle("B", subtitle=expression(italic("Anopheles stephensi")))
```

\newpage

### Vector Suceptibility Senstivity Analysis 

```{r}
Table7<- data.frame(
   generation=rep(c(rep("F8",3),rep("F63",3)),2),
   feed=c(rep("BB",6),rep("SS",6)),
   n.with.oocysts=c(30,54,27,10,10,9,
                    37,56,22,9,8,5),
  n.dissected=c(32,64,32,10,11,9,
                  37,59,30,9,10,9) )


g<-c("F8","F63")
p.value.Tab7 <- rep(NA,2)
names(p.value.Tab7)<- paste0("Generation,",g) 

for (i in 1:2){
   pick<- Table7$generation==g[i]
   p.value.Tab7[i]<-   quasiBinomTest(Table7$n.with.oocysts[pick],
               Table7$n.dissected[pick],
               Table7$feed[pick])
}

p.value.Tab7=as.data.frame(p.value.Tab7)
names(p.value.Tab7)="p-value"
knitr::kable(p.value.Tab7,digits=3,caption="p-values from the quasi-binomial model comparing, for each generation, the proportion of dissected mosquitoes with oocysts from the two meal groups for *Anopheles stephensi*")


```

We found no significant differences in the fraction of infected mosquitoes at any of the three generations.

## Summary Figure

```{r,fig.width=10,fig.height=5,fig.cap="Oocyst counts from *Plasmodium* infections from colonies maintained on bovine blood (BB) or SkitoSnack (SS). A. Oocyst counts in mosquitoes Results from 3-4 biological replicate colonies of *Aedes aegypti* at generations F1, F3, and F5. B. Results from  biological replicate colonies of *Anopheles stephensi* at generations F8, and F63. Colors represent the data from the different replicate colonies fed on BB (circles), or SS (triangles). Horizontal and vertical lines mark the estimated mean and bootstrap 95% confidence intervals of the oocyst counts."}

plot_grid(p.aedes,p.anoph,ncol=2,rel_widths = c(11/20,9/20))

pdf("Figure3.pdf",width=10,height=5)
plot_grid(p.aedes,p.anoph,ncol=2,rel_widths = c(11/20,9/20))
invisible(dev.off())
```

# Sporozoite Analysis

## Analysis Details

* For *Aedes aegypti* we perform a two-sample t-test on log transformed data and transform the results back to represent the fold-change. For *Anopheles stephensi* we performed a generalized linear regression with a Gaussian family and fixed effects for meal and generation. 
* Each considered data point represents a mosquito colony.
* The geometric mean ratio (GMR) is presented for SkitoSnack over bovine blood.

```{r}
## Sporozoites per mosquito
## Each point represents a colony

foldchangeTest<-function(y,x, invert=FALSE){
  # do t test on log transformed 
  # data and transform back to fold change
  if (length(unique(x))!=2) stop("x should be group indicator")
  x<- as.character(x)
  tout<-t.test(log(y)~x)
  gmean<- exp( tout$estimate) 
  GMR<-  gmean[1]/gmean[2]
  CI<- exp(tout$conf.int)
  if (invert){
    GMR<- 1/GMR
    CI<- c(1/CI[2],1/CI[1])
  }
  out<-list(gmeans=exp(tout$estimate),GMR=unname(GMR), lowerCL=CI[1], upperCL=CI[2], two.sided.p=tout$p.value)
  out
}
```

## *Aedes aegypti*

```{r}
spor.aeg<-c(44666,67750,59000,90667)
grp<-c("BB","BB","SS","SS")
#
#y<-spor.aeg
#x<-grp

Test=foldchangeTest(spor.aeg,grp,invert=TRUE)

TableResults=data.frame("GMR"=Test$GMR,"Lower 95%CI"=Test$lowerCL,"Upper 95%CI"=Test$upperCL,"p.value"=Test$two.sided.p)
names(TableResults)=c("GMR","Lower 95%CI","Upper 95%CI","p.value" )
```

* The geometric mean in the bovine blood group is `r format(Test$gmeans[1],scientific=1)`, and in the SkitoSnack group is `r format(Test$gmeans[2],scientific=1)`.
* The table below presents results for *Aedes aegypti*

```{r}
knitr::kable(TableResults,caption="Geometric mean ratio (GMR) and 95% CI of sporozoite counts for *Aedes aegypti*",digits=2)
```

## *Anopheles stephensi*

```{r}

ansteph.spor=read.csv("AnStephSpor.csv")

ansteph.spor$generation<- factor(ansteph.spor$generation, levels=c("F8","F63"))
ansteph.spor$log.SPZ.per.female<- log(ansteph.spor$SPZ.per.female)

gout2<-glm(log.SPZ.per.female~meal + generation,
    data=ansteph.spor)
ci2<- confint(gout2)

gmean<-function(x){ exp(mean(log(x)))}
g<- c("F8","F63")
m<-c("BB","SS")
out<-matrix(NA,2,2,dimnames=list(g,m))

for (i in 1:2){
  for (j in 1:2){
    out[i,j]<- gmean( ansteph.spor$SPZ.per.female[ansteph.spor$generation==g[i] & ansteph.spor$meal==m[j]])
  }
}

TableMeans=data.frame("Generation"=c("F8","F63"),
                      "Geometric mean bovine blood"=c(out[,1]),
                      "Geometric mean SkitoSnack"=c(out[,2]))

names(TableMeans)=c("Generation","Geometric mean bovine blood","Geometric mean SkitoSnack")

rownames(TableMeans)=NULL

meal.effect<- c(coef(gout2)["mealSS"],ci2["mealSS",])

meal.effect=exp(meal.effect)

TableResultsAn=data.frame("GMR"=meal.effect[1],
                        "Lower 95%CI"=meal.effect[2],
                        "Upper 95%CI"=meal.effect[3],
                        "p.value"=summary(gout2)$coefficients[2,4])
names(TableResultsAn)=c("GMR","Lower 95%CI","Upper 95%CI","p.value")
rownames(TableResultsAn)="SS vs BB"

```

* The sporozoite means by generation and meal are presented in the table below:


```{r}
knitr::kable(TableMeans,caption="Sporozoite count geometric means by meal and generation for *Anopheles stephensi*",digits=2)
```

* The table below presents GMR of SS to BB along with 95% CI for *Anopheles stephensi*

```{r}
knitr::kable(TableResultsAn,caption="GMR and 95% CI of sporozoite counts for *Anopheles stephensi*",digits=2)
```
