---
title: "ARO Phase I"
author: "Hall, Nathaniel, Fernandez, L."
format: docx
editor: visual
---

# Phase I Results

------------------------------------------------------------------------

## Load Data and Libraries From Folders

Load the data and packages (ggplot2, plyr, dplyr etc.)

```{r}
#| include: false
#Load Libraries
library(plyr)
library(dplyr)
library(PhysicalActivity)
library(ggplot2)
library(lmerTest)
library(car)
library(emmeans)
library(lme4)
library(Hmisc)
library(readxl)
library(psych)
```

Read in data file

```{r}
df<-read.csv("all_phaseIData.csv")
IA<-read_excel("ARO_IOA.xlsx")

ICC(IA[3:4])
```

Update variables to include a concentration that is set to zero if no odor, indicator if an alert or all clear response occurs and a condition variable that is the interaction of temperature and humidity

```{r}
df$conc2<-df$concentration*df$odorPresence
df$alert<-ifelse(df$response=="all clear",0,1 )
df$condition<-interaction(df$temperature, df$humidity)

```

### Adaptive Threshold Algorithm (3-down 1-up)

Figure 1 show the dog Jack following the 3-down 1-up adaptive threshold procedure for C-4 under standard conditions. Following three correct responses, the concentration was decreased by a half-log. If the dog made a single incorrect response, the concentration was increased by a half-log. Testing continued until completing eight reversals or sixty trials. Threshold was calculated as the geometric mean of the last six reversal points.

```{r}
#| label: fig- Demonstration of adaptive threshold algorithm. 
#| fig-cap: Demonstration of adaptive threshold algorithm. 
#| warning: false

demo<-subset(df, subj_ID=="Jack" & condition=="Std.Std" & run==2 & odor=="C4")
demo$correct<-factor(demo$correct, labels=c("Incorrect", "Correct"))


g<-ggplot(data=demo, aes(x=trialNumber, y=concentration, color=correct))+
  geom_point()+
  scale_y_log10()+ylab("Log Proportion Vapor Saturation")+
  xlab("Trial Number")+
  theme_bw()+
  geom_line(inherit.aes=F, aes(x=trialNumber, y=concentration))+
  theme(legend.title=element_blank())+
  geom_hline(yintercept=0.0129867, linetype="dashed")+
  labs(title="Jack C4")
g


```

## Calculate Thresholds

```{r}
#Threshold
df2<-df
df2<-ddply(df2, .(subj_ID,condition, run, odor ), transform, maxConc=max(concentration) )
rev<-subset(df2, reversal>1)

rev<-ddply(df2, .(subj_ID, odor, temperature, humidity, run, reversal, maxConc), transform, rnumb=seq(1,length(reversal)))
rev<-ddply(rev, .(subj_ID, session, odor, run, condition, reversal, maxConc), transform, rmax=max(rnumb))
Thresh<-subset(rev, rmax==rnumb)
#Thresh<-subset(Thresh, reversal>1)

library(reshape2)
Thresh2<-dcast(Thresh, subj_ID+ session+ odor+ run+condition+maxConc~reversal, value.var="concentration")
Thresh2$`2`<-ifelse(is.na(Thresh2$`2`), Thresh2$maxConc, Thresh2$`2`)
Thresh2$`3`<-ifelse(is.na(Thresh2$`3`), Thresh2$maxConc, Thresh2$`3`)
Thresh2$`4`<-ifelse(is.na(Thresh2$`4`), Thresh2$maxConc, Thresh2$`4`)
Thresh2$`5`<-ifelse(is.na(Thresh2$`5`), Thresh2$maxConc, Thresh2$`5`)
Thresh2$`6`<-ifelse(is.na(Thresh2$`6`), Thresh2$maxConc, Thresh2$`6`)
Thresh2$`7`<-ifelse(is.na(Thresh2$`7`), Thresh2$maxConc, Thresh2$`7`)
Thresh2$Threshold<-(log10(Thresh2$`2`)+log10(Thresh2$`3`)+
  log10(Thresh2$`4`)+log10(Thresh2$`5`)+log10(Thresh2$`6`)+log10(Thresh2$`7`))/6

test<-subset(Thresh2, odor=="TNT")
Thresh3<-subset(Thresh2, select=c(subj_ID, odor, run, condition, Threshold))
Thresh4<-dcast(Thresh3, subj_ID+odor+run~condition, value.var="Threshold")
Thresh4$HighTempHighHumidity<-Thresh4$HT.HH-Thresh4$Std.Std
Thresh4$HighTempLowHumidity<-Thresh4$HT.LH-Thresh4$Std.Std
Thresh4$LowTempHighHumidity<-Thresh4$LT.HH-Thresh4$Std.Std
Thresh4$LowTempLowHumidity<-Thresh4$LT.LH-Thresh4$Std.Std

Thresh5<-subset(Thresh4, select=c(subj_ID, odor, run, LowTempHighHumidity, HighTempHighHumidity,
                                 HighTempLowHumidity, LowTempLowHumidity))

Thresh6<-melt(Thresh5, id.vars=c("subj_ID", "odor", "run"))

Thresh2$Group<-ifelse(Thresh2$odor=="SP" & Thresh2$subj_ID %in% c("Moni", "Dasty", "Jack", "Luna"), "HH", "CD")
Thresh2$Group<-ifelse(Thresh2$odor=="AN" & Thresh2$subj_ID %in% c("Moni", "Dasty", "Jack", "Luna"), "HH", Thresh2$Group)
Thresh2$Group<-ifelse(Thresh2$odor=="C4" & Thresh2$subj_ID %in% c("Bello", "Rocket", "Dalton", "Zulu"), "HH", Thresh2$Group)
Thresh2$Group<-ifelse(Thresh2$odor=="TNT" & Thresh2$subj_ID %in% c("Bello", "Rocket", "Dalton", "Zulu"), "HH", Thresh2$Group)

sum<-ddply(Thresh2, .( odor, condition), summarise, mean=mean(Threshold))
```

Clean up the condition names

```{r}
Thresh2$condition<-revalue(Thresh2$condition, c("Std.Std"="Standard", "HT.LH"="High Temp Low Humid","LT.LH"="Low Temp Low Humid", "LT.HH"="Low Temp High Humid", "HT.HH"="High Temp High Humid"))
```

Graph the change in Threshold by Odor and Environmental condition

```{r}
g<-ggplot(data=Thresh2, aes(x=condition, y=Threshold))+
  stat_summary(fun="mean", geom="point")+
  stat_summary(fun="mean", geom="line")+
  stat_summary(fun.data="mean_cl_boot", geom="errorbar", width=0.1)+
  theme_classic()+facet_wrap(~odor)+
  ylab("Log Proportion of Vapor Saturation Threshold")+xlab("Odor")+
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
g
```

Add Breed Information

```{r}

Thresh2$breed<-ifelse(Thresh2$subj_ID %in% c("Moni", "Luna", "Zulu","Bello"), "GSP", "Lab")

```

## Add heart rate information

Merge heart rate data from all dogs and all sessions

Load HR data + data management

```{r}
HR <- read.csv("AnalysisData_Stg1_HRdata.csv")

HR[c('Dog', 'other')] <-
  str_split_fixed(HR$filename, '_Actigraph_', 2)

HR[c('HR', 'thresholdnumber', 'odor')] <- str_split_fixed(HR$other, '_', 3)

HR[c('odor', 'filetype')] <- str_split_fixed(HR$odor, '.csv', 2)

HR<-HR[,c(2:4, 6, 8:10)]
HR<-HR[,c(1:4, 6:7)]

HR$Heart.Rate <- as.numeric(HR$Heart.Rate)
HR1<-subset(HR, Heart.Rate>0)

```

Find mean HR per session

```{r}

detach("package:dplyr")
library(dplyr)

HR2<- HR1 %>% group_by(odor, Dog, thresholdnumber) %>% mutate(MeanHR=mean(Heart.Rate, na.rm=T))


```

Merge HR and threshold data

```{r}
HR3<-HR2[,c(4:7)]

HR3[c('thr', 'session')] <- 
  str_split_fixed(HR3$thresholdnumber, 'r', 2)
HR3<-HR3[,c(1, 3:4, 6)]

HR4 <- distinct(HR3)

HR4$subj_ID <- HR4$Dog
HR4<-HR4[,c(2:5)]

HR_Thresh <- merge(Thresh2,HR4, by.x = c("subj_ID", "odor", "session"), by.y = c("subj_ID", "odor", "session"))

```

Find max heart rate

```{r}
#Find max HR
HR_max <- HR1

HR_max<-HR1 %>% group_by(Dog, thresholdnumber, odor) %>% 
  mutate(maxHR=max(Heart.Rate, na.rm=T))

HR_max<-HR_max[c(4:7)]

HR_max <- distinct(HR_max)

HR_max[c('thr', 'session')] <- 
  str_split_fixed(HR_max$thresholdnumber, 'r', 2)

HRmax_Threshold <- merge(HR_Thresh, HR_max, by.x = c("subj_ID", "odor", "session"), by.y = c("Dog", "odor", "session"))
```

Predict Threshold differences based on the odor, condition and interaction as well as breed, heart rate, and order of testing.

```{r}
library(lmerTest)
mod<-lmer(data=HRmax_Threshold, Threshold~odor*condition+breed+Group+MeanHR+ maxHR (1|subj_ID))
library(car)
Anova(mod)

library(emmeans)
x<-lsmeans(mod, "trt.vs.ctrl"~condition|odor, ref=5)
summary(x)
```

# Effect of temperature

## 

Does magnitude of internal temperature change affect detection performance?

```{r}
temp<-read.csv("AnalysisData/Phase1_Temp.csv")

colnames(temp)<-c("Dog", "Date", "Condition", "Odor", "Session", "StartTime", "0", "5",
                  "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60",
                  "end Temp", "EndTime", "5minPost")

temp$Condition<-revalue(temp$Condition, c("40C_70%H"= "High Temp High Humid",
                                          "40C_40%H"="High Temp Low Humid",
                                          "0C_90%H"= "Low Temp High Humid",
                                          "0C_50%H"= "Low Temp Low Humid",
                                          "22C_50%H"="Standard",
                                          "40C 70%H"="High Temp High Humid"
))

tempL<-melt(temp, id.vars=c("Dog", "Date", "Condition", "Odor", "Session", "StartTime",
                  "end Temp", "EndTime", "5minPost"))

tempL$value<-as.numeric(tempL$value)
tempL$BL<-ifelse(tempL$variable==0, tempL$value, -1)
tempL<-tempL %>% group_by(Dog, Condition, Odor, Session) %>% mutate(BL1=max(BL))
tempL<-tempL %>% filter(BL1>0)
tempL$Tincrease<-tempL$value-tempL$BL1

TempLSum<-tempL %>% group_by(Dog, Condition, Odor, Session) %>% summarise(maxTincrease=max(Tincrease, na.rm=T))
```

Subset Data for Standard and hot because cold makes no sense

```{r}
t2<-TempLSum %>% filter(Condition %in% c("Standard", "High Temp High Humid", "High Temp Low Humid"))
```

Merge data with the threshold "2" data

```{r}
t3<-merge(Thresh2, t2, by.x=c("subj_ID", "session", "odor", "condition"),
          by.y=c("Dog", "Session", "Odor", "Condition"))
```

```{r}
library(lmerTest)
mod<-lmer(data=t3, Threshold~odor*condition+breed+Group+maxTincrease+(1|subj_ID))
library(car)
Anova(mod)
```

```{r}
tSum<-t3 %>% group_by()
```

```{r}
library(gtsummary)

Thresh2$condition<-droplevels(Thresh2$condition)
Thresh2%>% select(condition, Threshold) %>% 
  tbl_summary(by=condition,
   statistic = list(all_continuous() ~ "{mean} ({sd})"))



Thresh2%>% select(condition, odor, Threshold) %>% 
  tbl_strata(
    strata = odor,
    .tbl_fun =
      ~ .x %>%
        tbl_summary(by = condition) %>%
        add_n(),
    .header = "**{strata}**, N = {n}"
  )


```
