---
title: "Using BCPA on a one-dimensional variable"
author: "Elie Gurarie"
date: "November 14, 2018"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Using BCPA on a one-dimensional variable}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---


```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, fig.width = 6, fig.height = 4)
```

# Comments

The BCPA was originally formulated to analyze irregular movement data collected on marine mammals, but in essence it simply reduced movement data (X-Y-Time) to a univariate time-series.  There are - in my opinion - better (i.e. more informative and more robust) tools for dealing with movement data specifically, (e.g. at https://github.com/EliGurarie/smoove), but the BCPA might still be useful for irregular univariate time series.  An example (again from marine mammals) is depth data.  A recent update to BCPA makes this analysis somewhat smoother.   Here is an example on simulated data.  

Note - to date this is available only on the GitHub version of BCPA, i.e. the first step is:
```{r, eval = FALSE}
require(devtools)
install_github("EliGurarie/bcpa")
```

The code for this example can also be found in the help file for the `WindowSweep()` function. 

# Analysis

## Depth data simulation

Load `bcpa`, and a few other handy packages:
```{r}
require(magrittr)
require(lubridate)
require(bcpa)
```

We simulate some data with four phases / three change points: surface to medium to deep to surface, that occur at fixed times. 

```{r, echo = -1}
set.seed(42)
n.obs <- 100
time = (Sys.time() - dhours(runif(n.obs, 0, n.obs))) %>% sort

d1 <- 50; d2 <- 100
t1 <- 25; t2 <- 65; t3 <- 85
sd1 <- 1; sd2 <- 5; sd3 <- 10

dtime <- difftime(time, min(time), units="hours") %>% as.numeric
phases <- cut(dtime, c(-1, t1, t2, t3, 200), labels = c("P1","P2","P3","P4")) 
means <- c(0,d1,d2,0)[phases]
sds <- c(sd1,sd2,sd3,sd1)[phases]
depth <- rnorm(n.obs,means, sds)
# make all depths positive!
depth <- abs(depth)
mydata <- data.frame(time, depth)
```

The structure of the data is very simple:

```{r}
head(mydata)
```

Plot simulated depth data

```{r}
with(mydata, plot(time, depth, type = "o"))
```

Perform the window sweep.  Note that you specify the response variable (`depth`) and the time variable (`time`):

```{r}
depth.ws <- WindowSweep(mydata, variable = "depth", time.var = "time", windowsize = 25, windowstep = 1, progress=FALSE)
```

Here are some plots and the summary of the change point analysis:
```{r}
plot(depth.ws, ylab = "Depth (m)")
plot(depth.ws, type = "flat", cluster = 8, ylab = "Depth (m)")
ChangePointSummary(depth.ws, cluster = 8)
```

This is a pretty artificial example, but it works well. 