---
title: "Visualisation of Raw or Segmented Accelerometer Data using GENEAsphere."
author: "Activinsights Ltd"
date: "11th September 2017"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteIndexEntry{GENEAsphere}
  \usepackage[utf8]{inputenc}
---

## Data visualisation with GENEActiv .bin files. 

There are a number of ways in which data recorded using the GENEActiv device can be visualised using R. By using the packages GENEAread and GENEAsphere a thorough interpretation of the data can be made using various techniques. This tutorial builds on the knowledge of the previously realised tutorial on GENEAclassify. Please download the dropbox folder GENEAsphereDemo by contacting charles@sweetland-solutions.co.uk for a link to the Dropbox.

This tutorial will take two types of data which are the outputs of the packages GENEAread and GENEAclassify. The function _read.bin_ from _GENEAread_ produces an AccData object in R that represents the raw data from the device. This data can then be visualised using with the _stft_ function from GENEAread or the positionals function from GENEAsphere. The _segmentation_ function from _GENEAclassify_ produces a segmented csv that can be used by the functions within _GENEASphere_ The output from _getSegmentedData_ and _classifyGENEA_ can also be used.

Contents:

  - a.) Installing and loading the libraries
  - b.) loading in the data
  - c.) A standard acceleration plot of raw data
  - d.) plotAccData
  - e.) plotTLM
  - f.) STFT
  - g.) Positionals
  - h.) plotSphere
  - i.) plotSegmentSphere
  - j.) plotSegmentFlat
  - k.) plotSegmentProjection
  - l.) plotSegmentEllipse

Before starting please ensure that you have the following:

  - Completed the tutorial on GENEAclassify
  - Single GENEActiv .bin file
  - A segmented data file in .csv 

## a.) Installing and loading the libraries. 

Please install and load the following libraries. 

```{r Installing and loading packages,eval=FALSE}
install.packages("GENEAread",repos = "http://cran.us.r-project.org") 
install.packages("devtools",repos = "http://cran.us.r-project.org") 
install.packages("changepoint",repos = "http://cran.us.r-project.org")
install.packages("signal",repos = "http://cran.us.r-project.org")
install.packages("mmap",repos = "http://cran.us.r-project.org")
install.packages("misc3d",repos = "http://cran.us.r-project.org")
install.packages("rgl",repos = "http://cran.us.r-project.org")
install.packages("mapproj",repos = "http://cran.us.r-project.org")

library(GENEAread)
library(devtools)
library(changepoint)
library(signal)
library(mmap)
library(misc3d)
library(rgl)
library(mapproj)
```

Install GENEAclassify and GENEAsphere either from a source file, tar.gz, or from GitHub. Please refer to the notes in the previous tutorial if installing from GitHub. 

```{r Installing GENEAclassify,eval=FALSE}
setwd("/Users/owner/Documents/GENEActiv") 
# You will need to change this to the directory where you saved the tar.gz file
install.packages("GENEAclassify_1.4.1.tar.gz", repos=NULL, type="source")

#' Or using a GitHub authentication key which will go in the brackets of auth_token

install_github("https://github.com/JossLangford/GENEAclassify_1.41.git",
               auth_token = "7f0051aaca453eaabf0e60d49bcf752c0fea0668")

#' Once the package has been installed load in the library
library(GENEAclassify)
```

```{r Installing GENEAsphere,eval=FALSE}
# Again install GENEAsphere either from source or GitHub
setwd("/Users/owner/Documents/GENEActiv") 
# You will need to change this to the directory where you saved the tar.gz file
install.packages("GENEAsphere_1.0.tar.gz", repos=NULL, type="source")

## If installing from GitHub please run these lines
install_github("https://github.com/JossLangford/GENEAsphere.git",
               auth_token = "7f0051aaca453eaabf0e60d49bcf752c0fea0668")

library(GENEAsphere)
```

## b.) loading in the data.
The GENEActiv .bin file can be used to create some standard plots within GENEAread but the segmented file will be of more interested to most. Reading in the selected data file for visualisation using the following lines of code. The name of the file and the directory location will need to be changed.

```{r Reading in the data,eval=FALSE}
setwd("/Users/owner/Documents/GENEActiv/GENEAsphereDemo") 
# You will need to change this to the directory containing the data file. 
# Here I have analysed the first day for. 
AccData = read.bin("jl_left wrist_010094_2012-01-30 20-39-54.bin", start = "3:00", end = "1 3:00")
SegData = getSegmentedData("jl_left wrist_010094_2012-01-30 20-39-54.bin", start = "3:00", end = "1 3:00")
```

The output of these two data objects can be viewed using the head and names functions which give more details. In particular AccData is a large data frame with many subsets which can be accessed by using a $ after AccData followed by the name of the subset. In this case data.out gives the raw data from the device.

```{r viewing data objects,eval=FALSE}
names(AccData)
head(AccData)
head(AccData$data.out) # Raw data output
names(SegData)
head(SegData)
```

## c.) A standard acceleration plot of raw data
Standard plots can be created using the simple function _plot_ to show the raw acceleration data against time. From the output of the head function, the AccData is a large data frame containing the information recorded by the GENEActiv device. 

To select the columns of data desired R uses an index system. Firstly by using the $ to tell R what part of the subset of the AccData object to select. AccData\$data.out gives us that specific part of the data. Then using AccData\$data.out[R,C] to specify which row then column is to be used. For example AccData\$data.out[2,4] would return the entry on the 2nd row in the 4th column. Section of the data can be found by using a column. For example taking all of the entries in the 4th column from row 2 to row 100 would be found by running the line AccData\$data.out[2:100,4]. In this case all of the data in a row will be plotted against another which can be done by leaving the row index empty so that R selects every row. As shown with the names function, column 1 is the timestamp given to the data, 2,3 and 4 are x,y and z acceleration respectively. Column 5 is the light measurements, 6 is the number of button presses and 7 is temperature. It is possible to plot any of these against one another as long as the selection made for x and y are of equal length. 

```{r Plot of acceleration against Time,eval=FALSE}
plot(AccData$data.out[1:1000,1],AccData$data.out[1:1000,2],
     title="Time against X acceleration",
     xlab="Time",ylab="X Acceleration",type="l")
```

## d.) plotAccData

This function plots the choosen variable from the accelerometer data.
```{r, eval = FALSE}
plot.AccData(x, what = ("sd"))
plot.AccData(x, what = ("mean"))
plot.AccData(x, what = ("temperature"))
plot.AccData(x, what = ("light"))
plot.AccData(x, what = ("voltage"))
```

## e.) plotTLM

This plot shows Temperature, light and magnitude on a single plot. 

```{r, eval = FALSE}
plotTLM(x, start = NULL, end = NULL)
```


## f.) STFT

Inside GENEAread there is a function called stft which calculates the short time Fourier transform of the raw input signal. This generates two plots, the top shows the amplitude at various frequencies and bottom plot shows frequency against time. For more information on the variables that can be passed to this function type the command ?stft. 

```{r STFT plot,eval=FALSE}

stft(AccData, start=0.45, end=0.5, plot.it=TRUE)

stft(AccData, start=0.45, end=0.5, plot.it=TRUE,reassign = TRUE)

stft(AccData, start=0.45, end=0.5, plot.it=TRUE, type = "mv")

stft(AccData, start=0.45, end=0.5, plot.it=TRUE, type = "sum")
# Changing the window size
stft(AccData, start=0.45, end=0.5, plot.it=TRUE, win=100)

stft(AccData, start=0.45, end=0.5, plot.it=TRUE, win=1000)

```

## g.) Positionals plot

The positionals function from the GENEAsphere package creates a plot that shows arm elevation on the y-axis against time that also has a colour key which shows wrist rotation. This is very useful for showing regular activities and inside each activity within the sample training data folder from GENEAclassify a plot of the .bin files can be found. The start and end times work in the standard fashion, similar to read.bin.The plot can be changed to show various different visual effects.

```{r postionals plot,eval=FALSE}
positionals(AccData, start=0.45, end= 0.5, length = NULL, filter=2 
            ,bw = TRUE , legend = TRUE, max.points = 1e6, density = FALSE) 
```

The details on how to set different variables can be found by typing ?positionals into the console. 

## h.) Plotsphere plot

The plotSphere function from the GENEAsphere package takes the raw data from the GENEAread package and plots the recordings onto a sphere.

```{r plotsphere plot,eval=FALSE}
plotSphere(AccData, start=0, end= 0.5, length = NULL, time.format = "auto", 
           density = F, arrow = T, add= F)
```

The details on how to set different variables can be found by typing ?plotSphere into the console. 


## i.) plotSegmentSphere

For the following functions, a plot is mapped onto a sphere from a segmented csv file has to be loaded into the environment once the output of _getSegmentedData_ has been found. These functions use the mean Updown and degrees value of the segment as a centre position on the sphere. The distribution is based on the Median Absolute Deviation (mad) and distance from the sphere is given by the magnitude mean. 

```{r loading in the segmentation csv,eval=FALSE}
segmentationCSV="~/GENEAclassification/jl_left wrist_010094_2012-01-30 20-39-54_segmented.csv"

# I find it useful to load in the csv to the workspace so that the rows I'm going to plot can be seen.
csv=read.table(segmentationCSV,sep=",")
```

Now plotting some rows of this csv file.

```{r running plotSegmentSphere,eval=FALSE}
plotRows=c(1:5) # Segments 1 and 5.
plotSegmentSphere(segmentationCSV, plotRows, levels = c(0.9, 0.75, 0.5, 0.25, 0.1), singlePlot = TRUE, col = heat.colors(5), 
                  alpha = c(0.03, 0.05, 0.1, 0.2, 0.3), arrow = FALSE, nsims = 1000)
```

By typing ?plotSegmentSphere a detailed description of the variables is given. 

## j.) plotSegmentFlat

Rather than plotting on a 3D sphere the same information is plotted on a flat sphere with arm elevation on the y axis and wrist rotation on the x axis.

```{r plotSegmentFlat,eval=FALSE}
plotSegmentFlat(segmentationCSV, plotRows, 
                col = c("red",heat.colors(5, alpha = c(0.3, 0.2, 0.1, 0.05, 0.03))),
                singlePlot = TRUE, nsims= 1000)
```

By typing ?plotSegmentFlat a detailed description of the variables is given.

## k.) plotSegmentProjection

```{r plotSegmentProjection,eval=FALSE}
plotSegmentProjection(segmentationCSV, plotRows, projection = "aitoff", 
                      col = "red", singlePlot = TRUE, nsims = 1000)
```

By typing ?plotSegmentProjection a detailed description of the variables is given.

## l.) plotSegmentEllipse

This function plots onto an Ellipse.

```{r plotSegmentEllipse,eval=FALSE}
plotSegmentEllipse(segmentationCSV, plotRows, projection = "aitoff", 
                   col = "red", singlePlot = TRUE, confidenceLevel = 0.05,
                   alpha = thresholds, wrap = FALSE, greyGrid = FALSE)
```

By typing ?plotSegmentEllipse a detailed description of the variables is given.
