---
title: "Relabeling or Defining Interest Areas"
author: "Vincent Porretta"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Relabeling or Defining Interest Areas}
  %\VignetteEngine{knitr::rmarkdown}
  \usepackage[utf8]{inputenc}
---

```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.width=6, fig.height=4, warning=FALSE)
```

```{r, echo=FALSE, eval=TRUE, message=FALSE}
library(VWPre)
# data(VWdat)
# dat0 <- prep_data(data = VWdat, Subject = "RECORDING_SESSION_LABEL", Item = "itemid")
# dat1 <- relabel_na(data = dat0, NoIA = 4)
# checkdat <- recode_ia(data=dat1, IDs=c("0"="0", "1"="11", "2"="234", "3"="399",
#                                          "4"="444"),
#                         Labels=c("Outside"="Outside", "Target_IA "="Object1",
#                                  "RhymeComp_IA "="Object2", "OnsetComp_IA "="Object3",
#                                  "Distract_IA "="Object4"))
# checkdat <- slice(checkdat, 1:10000)
# save(checkdat, file = "checkdat.rda", compress = "xz")
load("checkdat.rda")
``` 




## Basic interest area relabelling

### Check interest area coding

First, ensure that you have loaded your data appropriately and that you have already carried out initial preprocessing using the functions `prep_data` and `relabel_NA`.
The subsequent preprocessing requires that the interest area IDs are numerically, ranging from 0 (i.e., outside all interest areas) up to a maximum of 8.
So, it's important to check that the IDs present in the data set, conform to this. The `check_ia` functions does just this and indicates how those IDs are mapped to the interest area labels.

```{r, eval= TRUE, echo=TRUE, results='asis', error=TRUE, purl=FALSE}
check_ia(data = checkdat)
```

### Providing new labels and IDs for existing interest areas

The function `recode_ia` can be used to relabel interest area IDs (if they do not conform) or interest area labels (if you desire different ones). 
New IDs and/or labels can be specified using a named character vector. 
The following code serves as an example. 
Note that if your interest area labels contain spaces you must also put the old names in quotes.

```{r, eval= TRUE, echo=TRUE, results='asis'}
newdat <- recode_ia(data=checkdat, IDs=c("0"="0", "11"="1", "234"="2", "399"="3",
                                         "444"="4"), 
                        Labels=c(Outside="Outside", Object1="Target", 
                                 Object2="RhymeCompetitor", Object3="OnsetCompetitor",
                                 Object4="Distractor"))
```

```{r, eval= TRUE, echo=TRUE, results='asis', error=TRUE, purl=FALSE}
check_ia(data = newdat)
```


## Remapping gaze position to newly defined interest areas

Sometimes it is necessary to make changes to the interest areas after data collection.
This may be because it is of interest to examine some other aspect of looking patterns in the experiment, or a mistake was made when initially defining the interest areas in Experiment Builder.
Because this can be a laborious task in Data Viewer, the following example shows how this redefinition and remapping can be done using functions provided in this package prior to completing the preprocessing of the data.
In short, the function `custom_ia` uses a look-up table to determine if the gaze position coordinates fall within newly defined interest areas.
For this you will need to create a look-up table containing the interest area definitions.
Below are the steps that can be used to quickly create this table.

### Creating the look-up table

The look-up table requires specific information. In particular, in needs the event (participant specific trial) for which the interest areas are defined, the label of the interest area, the numeric ID of the interest area, and the top, bottom, left, and right pixel boundaries of the interest area. 
The reason these need to be specified for each event is that it is common for interest areas to move depending on the item/trial.
Creating this sounds like a lot of work, but can actually be accomplished straightforwardly from an interest area report output by Data Viewer (especially if you have included the locations in your data source).

So, first export an interest area report for your data as a tab-delimited text file, including all available columns (to ensure you get all the necessary columns as well as the ones you output from your data source).
Import that into R.

```{r, eval= FALSE, echo=TRUE, results='asis'}
library(VWPre)
IAdat <- read.table("IAreport.txt", header = T, sep = "\t", na.strings = c(".", "NA"))
```

```{r, eval= TRUE, echo=FALSE, results='asis'}
library(VWPre)
#data(IAdat)
load("IAdat.rda")
```
You will notice that the data are organized so that there is one row per interest area for each trial.

```{r, eval= TRUE, echo=FALSE, results='asis'}
knitr::kable(head(IAdat[, c("RECORDING_SESSION_LABEL", "TRIAL_INDEX", "IA_LABEL")], 12))
```

Next, create the Event column. Typically this is done using the Subject Identifier and Trial Index.

```{r, eval= TRUE, echo=TRUE, results='asis'}
IAdat$Event <- interaction(IAdat$RECORDING_SESSION_LABEL, IAdat$TRIAL_INDEX, drop = T)
``` 

Next you need to create a column which indicates the location of each interest area for a specific trial.
If you defined this in your data source and output all columns to the eye-tracking file, these should already be included in your interest area report.
In the example below, the columns (NAME_reg) indicate a numeric index (in this case Cartesian quadrants) of where the target and other objects were located per trial. 
This information must be unified into a single column so that it can be used later to merge in other information.

```{r, eval= TRUE, echo=TRUE, results='asis'}
dat1 <- IAdat %>% mutate(ScreenLoc = ifelse(IA_LABEL=="Target", target_reg,
                        ifelse(IA_LABEL=="RhymeComp", rhymecomp_reg,
                               ifelse(IA_LABEL=="OnsetComp", onsetcomp_reg,
                                      ifelse(IA_LABEL=="Distractor", distractor_reg, NA))))
                  )
```

To create the bounding boxes of the region locations, make a dataframe that includes the top, bottom, left, and right pixel boundaries. 
These will, of course, be dependent on the resolution of the screen used in the experiment.

```{r, eval= TRUE, echo=TRUE, results='asis'}
Loc_Table <- data_frame(ScreenLoc = c(1, 2, 3, 4), 
                        Top = c(40, 40, 740, 740),
                        Bottom = c(340, 340, 1040, 1040),
                        Left = c(1160, 460, 460, 1160),
                        Right = c(1460, 760, 760, 1460))
```

The dataframe should look similar to the following.

```{r, eval= TRUE, echo=FALSE, results='asis'}
knitr::kable(head(Loc_Table))
```

This table will be merged with the interest area report, matching by ScreenLoc column.

```{r, eval= TRUE, echo=TRUE, results='asis'}
dat2 <- inner_join(dat1, Loc_Table, by="ScreenLoc")
```

The look-up table (as with other functions in VWPre) requires a numeric interest area ID column.
This can be created directly from the `IA_LABEL` column, as follows by corresponding the Labels to the IDs.

```{r, eval= TRUE, echo=TRUE, results='asis'}
dat2$IA_ID <- case_when(
  dat2$IA_LABEL == "Target" ~ 1,
  dat2$IA_LABEL == "RhymeComp" ~ 2,
  dat2$IA_LABEL == "OnsetComp" ~ 3,
  dat2$IA_LABEL == "Distractor" ~ 4
)
```

Lastly, select only the required columns for the look-up table.

```{r, eval= TRUE, echo=TRUE, results='asis'}
LookUpTable <- dat2 %>% select(Event, IA_LABEL, IA_ID, Top, Bottom, Left, Right)
```

The table should now look similar to the following.

```{r, eval= TRUE, echo=FALSE, results='asis'}
knitr::kable(head(LookUpTable, 12))
```

### Performing the gaze remapping

Make sure your sample report has been loaded appropriately and that you have carried out the function `prep_data`. 
This will ensure that the necessary columns are coded appropriately and that the Event column has been created.
Then simply feed that data frame, along with the lookup table, to the function `custom_ia`.

```{r, eval=FALSE, echo=TRUE, results='asis'}
remapped <- custom_ia(data = sampledata, iaLookup = LookUpTable)
```

This function examines the gaze coordinates of each sample for each event and evaluates which interest area it falls in, based on the information contained in the lookup table.
Because this works row-wise, it can take a bit of time for large datasets.

After the remapping is complete, you are then ready to continue preprocessing your data. 
Please refer to the [Basic Preprocessing](VWPre_Basic_Preprocessing.html) vignette for further details.
