---
title: "Infants redundancy -- central fixation experiment"
author: "Shira Tal & Jenny Culbertson"
date: "04/08/2023"
output:
  html_document: default
---

# LOAD PACKAGES
```{r setup, include=FALSE}
knitr::opts_chunk$set(message = FALSE, warning = FALSE)
library(plyr)
library(dplyr)
library(ggplot2)
library(lme4)
library(tidyverse)
```

# SET PATHS & GET DATA
*NB: First set your working directory to the source file location.*
Set paths
```{r}
data_path = "data/"
plot_path = "plots/"
```
Read in data
```{r}
file.names = list.files(data_path,pattern="*.csv", full.names=TRUE)
d<-do.call(rbind, lapply(file.names, function(x) read.csv(x, header=T, na.strings="NULL", comment.char="",stringsAsFactors=FALSE)))
```
Separate familiarization and testing blocks
```{r}
fam <- d %>% filter(block == "familiarization")
test <- d %>% filter(block == "testing")
```

# FAMILIARIZATION LOOKING ANALYSIS
Split up the keyDurations column into a vector of keys presses, and a vector of durations. If only a single key press occurred during the trial, then it will be a single value.
```{r}
fam_looks <- fam %>%
  mutate(keyDurations = gsub('["{}]', '', keyDurations)) %>%
  mutate(keyDurations = gsub("\\[|\\]", '', keyDurations)) %>%
  separate_rows(keyDurations, sep = ',') %>%
  separate(keyDurations, c('col1', 'col2'), sep = ':') %>%
  pivot_wider(names_from = col1, values_from = col2, values_fn = list) # %>%  # there are potentially multiple looks, so output these as a list (of keys or durations)
```
Get total looking time during familiarization trial. Make sure to unlist the durations vector and make it numeric (the code above makes everything into lists of strings, since there are letters involved!).
```{r}
fam_summary = ddply(fam_looks, c("participant", "condition"), summarise, total_looks = sum(as.numeric(as.character(unlist(duration)))))
```
Pretty up the labels for plotting
```{r}
fam_summary$condition <- recode(fam_summary$condition, agreement = 'Agreement', no_agreement  = 'No Agreement')
```
Plot looking time by trial type by condition.
NB: can comment in dotplot part once there is actually more than one data point!
```{r, fig.width=4, fig.height=4}
ggplot(fam_summary, aes(x=condition, y=total_looks, fill=condition)) +
#      geom_dotplot(binaxis = "y", stackdir = "center", position = "dodge", 
#                   stackratio = .45, binwidth = 0.01, dotsize=4) +
      stat_summary(fun.data = mean_cl_boot, geom = "errorbar", width=.2, size=0.75, position = position_dodge(0.85)) +
      stat_summary(fun = mean, geom = "point", size=2, position = position_dodge(0.85)) +
      theme(legend.position="none") +
      theme(axis.title.x = element_text(vjust = 0,size=16), axis.text.x= element_text(size=12)) +
      theme(axis.title.y = element_text(size=16), axis.text.y= element_text(size=12)) +
      ylim(0,30000) + # change this as relevant (this is the total duration of the debug training audio)
      ylab("Total looking time (ms)") +
	    xlab("Condition") 
ggsave(paste(plot_path,'fam_looks_by_condition.png',sep=""), device="png", width = 4, height = 4)
```
# TEST LOOKING ANALYSIS
Split up the keyDurations column into a vector of keys presses, and a vector of durations. If only a single key press occurred during the trial, then it will be a single value.
```{r}
test_looks <- test %>%
  mutate(keyDurations = gsub('["{}]', '', keyDurations)) %>%
  mutate(keyDurations = gsub("\\[|\\]", '', keyDurations)) %>%
  separate_rows(keyDurations, sep = ',') %>%
  separate(keyDurations, c('col1', 'col2'), sep = ':') %>%
  pivot_wider(names_from = col1, values_from = col2, values_fn = list)
```
Get total looking time during familiarization trial.
NB: Make sure to unlist the durations vector and make it numeric (the code above makes everything into lists of strings, since there are letters involved!).
NB: If we instead want average looks per trial, then need to add in trial as a variable below, and use mean rather than sum.
```{r}
test_summary = ddply(test_looks, c("participant", "condition", "test_trial_type"), summarise, total_looks = sum(as.numeric(as.character(unlist(duration)))))
```
Pretty up the labels for plotting
```{r}
test_summary$condition <- recode(test_summary$condition, agreement = 'Agreement', no_agreement  = 'No Agreement')
test_summary$test_trial_type <- recode(test_summary$test_trial_type, gram = 'Grammatical', ungram  = 'Ungrammatical')
```
Plot looking time by trial type by condition.
NB: can comment in dotplot part once there is actually more than one data point!
```{r, fig.width=4, fig.height=4}
ggplot(test_summary, aes(x=test_trial_type, y=total_looks, fill=test_trial_type)) +
      # geom_dotplot(binaxis = "y", stackdir = "center", position = "dodge", 
      #              stackratio = .45, binwidth = 0.01, dotsize=4) +
      # stat_summary(fun.data = mean_cl_boot, geom = "errorbar", width=.2, size=0.75, position = position_dodge(0.85)) +
      stat_summary(fun = mean, geom = "point", size=2, position = position_dodge(0.85)) +
      theme(legend.position="none") +
      theme(axis.title.x = element_text(vjust = 0,size=16), axis.text.x= element_text(size=12)) +
      theme(axis.title.y = element_text(size=16), axis.text.y= element_text(size=12)) +
      theme(strip.text=element_text(size=12)) +
      ylab("Total looking time (ms)") +
	    xlab("Trial type") +
      #ylim(0,1) +
      facet_grid(~condition)
ggsave(paste(plot_path,'test_looks_by_condition.png',sep=""), device="png", width = 4, height = 4)
```