---
title: "2. Land-cover change analysis with TWDTW"
author: "Victor Maus"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{1. Land-cover change analysis with TWDTW}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
bibliography: ./../inst/REFERENCES.bib
---

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

This vignette provides a short guide on how to perform a Time-Weighted Dynamic Time Warping (TWDTW) analysis on raster image time series using `dtwSat`. For more details about TWDTW read @Maus:2016 and @Maus:2019.

# Create multi-band image time series

`dtwSat` provides a set of images extracted from `MOD13Q1` dataset for a region within the Brazilian Amazon. You can load these images with
```{r , echo = TRUE, eval = TRUE, warning = FALSE, message = FALSE}
library(dtwSat)  
  
evi  <- brick(system.file("lucc_MT/data/evi.tif",  package = "dtwSat"))
ndvi <- brick(system.file("lucc_MT/data/ndvi.tif", package = "dtwSat"))
red  <- brick(system.file("lucc_MT/data/red.tif",  package = "dtwSat"))
blue <- brick(system.file("lucc_MT/data/blue.tif", package = "dtwSat"))
nir  <- brick(system.file("lucc_MT/data/nir.tif",  package = "dtwSat"))
mir  <- brick(system.file("lucc_MT/data/mir.tif",  package = "dtwSat"))
doy  <- brick(system.file("lucc_MT/data/doy.tif",  package = "dtwSat"))
```

The `tif` files above have been pre-processed, so that a single file has the complete time series for each band. One can also built the time series for each band from independent files using the function `stack` from the R package `raster`. 

Note that every band must have the same extend, resolution, and number of images, i.e. the same number of observations across space and time. To create the multi-band image time series we need the dates of each observation, which for the set of images above are
```{r , echo = TRUE, eval = TRUE, warning = FALSE, message = FALSE}
timeline <- scan(system.file("lucc_MT/data/timeline", package = "dtwSat"), what="date")
timeline
```

Finally, we can create the multi-band image time series with
```{r , echo = TRUE, eval = TRUE, warning = FALSE, message = FALSE}
rts <- twdtwRaster(evi, ndvi, red, blue, nir, mir, timeline = timeline, doy = doy)
rts
```

The multi-band image time series has `r length(rts)` bands and `r length(index(rts))` observations ranging from `r index(rts)[1]` to `r tail(index(rts), 1)`.

# Create a library of vegetation profiles 

To crate a library of profiles we need a set of samples. `dtwSat` provides a set of samples of land cover classes for the study area. We can load the samples with
```{r , echo = TRUE, eval = TRUE, warning = FALSE, message = FALSE}
field_samples <- read.csv(system.file("lucc_MT/data/samples.csv", package = "dtwSat"))
head(field_samples)
```

We split this samples into a training and a validation set, such that
```{r , echo = TRUE, eval = TRUE, warning = FALSE, message = FALSE}
library(caret)

set.seed(1) # set for reproducibility 

I <- unlist(createDataPartition(field_samples$label, p = 0.1))

training_samples <- field_samples[I,]

validation_samples <- field_samples[-I,]
```

To get the time series for each sample in the training set, we can run
```{r , echo = TRUE, eval = TRUE, warning = FALSE, message = FALSE}
training_ts <- getTimeSeries(rts, 
                             y = training_samples, 
                             proj4string = "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
```

Finally, we can use the training samples to crate the profiles library with
```{r , echo = TRUE, eval = TRUE, warning = FALSE, message = FALSE}
profiles_library <- createPatterns(training_ts, 
                                   freq = 8, 
                                   formula = y ~ s(x))

plot(profiles_library, type = "patterns")
```

The function `createPatterns` using generalized additive models (GAMs) to create the profiles. For details see `?gam` from `mgcv` package.



# Classify image time series

```{r , echo = TRUE, eval = TRUE, warning = FALSE, message = FALSE}
system.time(
  twdtw_lucc <- twdtwApply(x = rts, 
                           y = profiles_library, 
                           alpha = -0.1,
                           beta = 50,
                           progress = 'text', 
                           minrows = 30,
                           legacy = FALSE,
                           time.window = TRUE)
)
```

Note the argument `legacy = FALSE`. Setting this argument to `FALSE` considerably improves the performance of the processing as it does not keep any intermediate dataset. Using `time.window = TRUE` implements a change in the TWDTW algorithm to reduce processing.

One can also run TWDTW in parallel. For a small area, the performance is not much better than the sequential processing. However, for larger areas, the parallel processing can reduce processing time. To run `twdtwApply` in parallel setup and register a cluster before calling the function, such that
```{r, echo = TRUE, eval = FALSE, warning = FALSE, message = FALSE}
library(doParallel)
library(parallel)
library(foreach)

cl <- makeCluster(detectCores(), type = "FORK")
registerDoParallel(cl)

system.time(
  twdtw_lucc <- twdtwApply(x = rts, 
                           y = profiles_library, 
                           alpha = -0.1,
                           beta = 50,
                           progress = 'text', 
                           minrows = 30,
                           legacy = FALSE,
                           time.window = TRUE)
)

registerDoSEQ()
stopCluster(cl)
```

# Assess classifiaction results

`dtwSat` provides a set of functions to asses the classification results. For example with
```{r , echo = TRUE, eval = TRUE, warning = FALSE, message = FALSE}
# Plot TWDTW distances for the first year 
  plot(twdtw_lucc, type = "distance", time.levels = 1)
  
# Plot TWDTW classification results 
  plot(twdtw_lucc, type = "map")

# Plot mapped area time series 
  plot(twdtw_lucc, type = "area")
  
# Plot land-cover changes
  plot(twdtw_lucc, type = "changes")
```

The package also offers a set of methods to assess the classification accuracy and visualize the results.
```{r , echo = TRUE, eval = TRUE, warning = FALSE, message = FALSE}
# Assess classification 
  twdtw_assess <- 
    twdtwAssess(twdtw_lucc, 
                y = validation_samples, 
                proj4string = "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0",
                conf.int = .95)
  
# Plot map accuracy 
  plot(twdtw_assess, type = "accuracy")
  
# Plot area uncertainty 
  plot(twdtw_assess, type = "area")
  
# Plot misclassified samples  
  plot(twdtw_assess, type = "map", samples = "incorrect")
  
# Get latex table with error matrix 
  twdtwXtable(twdtw_assess, table.type = "matrix")
  
# Get latex table with error accuracy 
  twdtwXtable(twdtw_assess, table.type = "accuracy")
  
# Get latex table with area uncertainty 
  twdtwXtable(twdtw_assess, table.type = "area")
```

This short introduction showed how to use `dtwSat` for land-cover change analyse. To learn TWDTW read @Maus:2016 and @Maus:2019.

# References
