---
title: "foieGras-basics"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{foieGras-basics}
  %\VignetteEngine{knitr::rmarkdown}
  \usepackage[utf8]{inputenc}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(foieGras)
library(dplyr)
library(ggplot2)
library(sf)
```

## Disclaimer
This vignette is an extended set of examples to highlight the `foieGras` package's functionality. Please, do NOT interpret these examples as instructions for conducting analysis of animal movement data. Numerous essential steps in a proper analysis have been left out of this document. It is the user's job to understand their data, ensure they are asking the right questions of their data, and that the analyses they undertake appropriately reflect those questions. We can not do this for you!

### foieGras models
This vignette provides a (very) brief overview of how to use `foieGras` to filter animal track locations obtained via the Argos satellite system. `foieGras` provides two state-space models (SSM's) for filtering (ie. estimating "true" locations and associated movement model parameters, while accounting for error-prone observations):  

- a simple Random Walk model, `rw`
- a Correlated Random Walk model, `crw`  

Both models are continuous-time models, that is, they account for time intervals between successive observations, thereby naturally accounting for the irregularly-timed nature of most Argos data. We won't dwell on the details of the models here, those will come in a future paper, except to say there may be advantages to choosing one over the other in certain circumstances. The Random Walk model tends not to deal well with small to moderate gaps (relative to a specified time step) in observed locations and can over-fit to particularly noisy data. The Correlated Random Walk model can often deal better with these small to moderate data gaps and smooth through noisy data but tends to estimate nonsensical movement through larger data gaps.

### input data
`foieGras` expects data to be provided in one of four possible formats.

1) a `data.frame` or `tibble` that looks like this
```{r data 1, echo = FALSE}
data(ellie, package = "foieGras")
head(ellie)
```
where the Argos data are provided via CLS Argos' Kalman filter model (KF) and include error ellipse information for each observed location.  

2) a `data.frame` or `tibble` that looks like this
```{r data 2, echo = FALSE}
data(rope, package = "foieGras")
head(rope)
```
where the Argos data are provided via CLS Argos' Least-Squares model (LS) and do not include error ellipse information.

3) a data.frame or tibble that includes observations with missing KF error ellipse information
```{r data 3, echo = FALSE}
data(ellie, package = "foieGras")
ellie[3:5, c("smaj","smin","eor")] <- NA
head(ellie)
```
in this situation, `foieGras` treats observations with missing error ellipse information as though they are LS-based observations.

4) a `sf` object where observations have any of the previous 3 structures and also include `CRS` information
```{r data 4, echo = FALSE, message=FALSE}
data(ellie, package = "foieGras")
foo <- sf::st_as_sf(ellie, coords=c("lon","lat"), crs = 4326) 
foo <- sf::st_transform(foo, crs = "+init=epsg:3031 +units=km")
head(foo)
```

### fitting a foieGras model
model fitting is comprised of 2 steps: a prefilter step where a number of checks are made on the input data (see `?foieGras::prefilter` for details), including applying the `argsofilter::sdafilter` to identify extreme outlier observations. Additionally, if the input data are not supplied as an `sf` object, `prefilter` guesses at an appropriate projection (typically world mercator, EPSG 3395) to apply to the data. The SSM is then fit to this projected version of the data. Users invoke this process via the `fit_ssm` function:
```{r fit_ssm, message=FALSE}
## load foieGras example data
data(ellie)
## prefilter and fit Random Walk SSM, using a 24 h time step
fit <- fit_ssm(ellie, model = "rw", time.step = 24)
```
these are the minimum arguments required: the input data, the model ("rw" or "crw") and the time.step (in h) to which locations are predicted. Additional control can be exerted over the prefiltering step, via the `vmax`, `ang`, `distlim`, `spdf` and `min.dt` arguments. see `?foieGras::fit_ssm` for details, the defaults for these arguments are quite conservative, usually leading to relative few observations being flagged to be ignored by the SSM. Additional control over the SSM fitting step can also be exerted but these should rarely need to be accessed by users and will not be dealt with here.

### accessing and visualising model fit objects
Simple summary information about the `foieGras` fit can be obtained by calling the fit object:
```{r fit summary}
fit$ssm[[1]]
```
and a summary `plot` method allows a quick visual of the SSM fit to the data:
```{r fit plot, fig.width=7,fig.height=7}
# plot time-series of the predicted values
plot(fit$ssm[[1]], what = "predicted")
```
The predicted values are the state estimates predicted at regular time intervals, specified by `time.step` (here every 24 h). Fitted values (not shown) are the state estimates corresponding to the time of each observation; their time-series are plotted by default - `plot(fit$ssm[[1]])`.

Estimated tracks can be mapped using the `foieGras`-applied projection (here EPSG 3395). We use the `foieGras::grab()` function to access the SSM-predicted values. The (low-res) land is added using the `rnaturalearth` package. The `ggspatial` package's `annotation_spatial` and `layer_spatial` functions ease plotting of `sf` class data.
```{r ggplot map, fig.width=7, fig.height=7, message=FALSE}
library(rnaturalearth)
library(ggspatial)

## change units from km to m (attempt to avoid win-builder error)
ploc_sf <- grab(fit, what = "predicted") %>% st_transform(., crs = "+init=epsg:3395 +units=m")

## get coastline data
coast <- ne_countries(scale=110, returnclass = "sf") 

ggplot() +
  annotation_spatial(data = coast, fill = grey(0.8), lwd = 0) +
  layer_spatial(data = ploc_sf, colour = "firebrick", size = 1.25) +
  scale_x_continuous(breaks = seq(-180, 180, by = 5)) +
  scale_y_continuous(breaks = seq(-85, -30, by = 5)) +
  theme_bw()
```

The tracks can also be transformed to other projections and locations coloured by date
```{r reproject ggplot map, fig.width=7, fig.height=7}
## use Antarctic Polar Stereographic projection approximately centred on the track midpoint
coast <- coast %>% st_transform(., crs = "+init=epsg:3031 +lon_0=85 +units=m")

lab_dates <- with(ploc_sf, seq(min(date), max(date), l = 5)) %>% as.Date()

ggplot() +
  annotation_spatial(data = coast, fill = grey(0.8), lwd = 0) +
  layer_spatial(data = ploc_sf, aes(colour = as.numeric(as.Date(date))), size = 1.25) + 
  theme(legend.position = "bottom", 
        legend.text = element_text(size = 8, vjust = 0), 
        legend.key.width = unit(1.5, "cm"),
        legend.key.height = unit(0.5, "cm"),
        legend.title = element_blank()
  ) + scale_colour_viridis_c(breaks = as.numeric(lab_dates), 
                             option = "viridis", 
                             labels = lab_dates, 
                             end = 0.95)
```

The estimated locations can be accessed for further analysis, custom mapping, etc... by using the `grab` function. They can be returned as a projected sf object or as a simple unprojected tibble. Note, that for all `foieGras` outputs the `x`, `y`, `x.se` and `y.se` units are in km.
```{r grab}
## grab predicted locations from fit object as a projected sf object 
plocs_sf <- grab(fit, what = "p")

## grab predicted locations in unprojected form
plocs <- grab(fit, what = "p", as_sf = FALSE)

## unprojected form looks like this
plocs
```

`fit_ssm` can be applied to single tracks as shown, it can also fit to multiple individual tracks in a single input `tibble` opr `data.frame`. The SSM is fit to each individual separately. The resulting output is a compound `tibble` with rows corresponding to each individual `foieGras` fit object. 
```{r multi-fits}
# load royal penguin example data
data(rope)

fit <- fit_ssm(rope, vmax = 20, model = "crw", time.step = 6)

# list fit outcomes for all penguins
fit
```
individual `id` is displayed in the 1st column, all fit output (`ssm`) in the 2nd column, and `convergence` status of each model fit is displayed in the 3rd column

The individual fits can easily be combined and plotted together using the `grab` function. Fitted values can be `grab`-bed using `what = "fitted"`, or just `"f"`, and predicted values using `"p"`.
```{r plot all rope, fig.width=7, fig.height=7}
plocs <- grab(fit, what = "p")

ggplot(plocs, aes(colour = id)) + 
  geom_sf() + 
  scale_colour_viridis_d(option="cividis")
```
