---
title: "Quickstart example"
author: "Georg Rüppel"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    toc: yes
vignette: |
  %\VignetteIndexEntry{Quickstart example}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

The methods provided in this package are applicable to various types of automated radio-telemetry data, including---but not limited to---the [Motus Wildlife Tracking System](https://motus.org).

```{r, include=FALSE}
options(max.print = 50)
```

```{r, message=FALSE}
library(movetrack)
library(ggplot2)
theme_set(theme_bw(base_size = 15))

# Load example data
data(motusData)
``` 

## Modelling

Parse your preprocessed raw data to `track()` and adjust additional arguments as needed.
Input arguments are unique track IDs, timestamps, station locations, antenna bearings, and signal strength for each detection.
By default, these input variable names align with standard Motus variable conventions.
Use `aRange` to specify theoretical antenna detection ranges in kilometres.
This can be a single integer value or a named list of values for different antenna types defined in the `aType` column.
By default, approximations for different Yagi-antennas, as suggested in the [Motus Docs](https://docs.motus.org/en/stations/station-equipment/antennas#antenna-types), are used:

|  Antenna type  | Theoretical range |
|----------------|------------------:|
| 3-element Yagi |             ~5 km |
| 4-element Yagi |             ~6 km |
| 5-element Yagi |             ~8 km |
| 6-element Yagi |            ~10 km |
| 9-element Yagi |            ~15 km |

With `dTime`, specify the time interval in minutes for which positions are estimated.
The default is 2 min, but this should be adjusted according to the tag's burst interval and the expected flight speed---longer burst intervals or faster movements typically require longer intervals.
Specify the number of states in the model using the `states` argument, where each state represents a distinct movement behaviour such as migratory flight, local movement, or stopover (default: 2).
Optionally, the argument `i_lambda` can be used to fix the lag-correlation parameter across all tracks (see `vignette("hmm")`).
Set `model = FALSE` to extract the internally calculated coarse raw positions and measurement errors for each time interval without modelling.

Here, we model the animals' flight paths from the example data using `track()` with default arguments.
The number of printed screen updates is reduced using the `refresh` argument passed to `cmdstanr::sample()`. 
See there for additional sampling options. 

```{r model, warning=FALSE, message=FALSE}
fit <- track(motusData, refresh = 1e3)
```

## Inspect results

`track()` returns a `movetrack` object containing complete posterior distributions for positions at each time step, along with corresponding distances in m and speeds between positions in m/s.
We can peek at the results by simply running

```{r}
fit
```

and transform it into a `data.frame` with

```{r}
df <- as.data.frame(fit)
```

We can summarise one or multiple variables and inspect convergence measures using `summary.movetrack()`:

```{r}
summary(fit, var = "distance")
```

To easily extract a defined number of posterior draws from the model for each time interval, run:

```{r}
getDraws(fit, n = 10)
```

## Plot results

We can plot the results per individual and output variable using `plot()`:

```{r plot, warning=FALSE, fig.cap="Estimated median longitude together with 90% highest posterior density intervals over time."}
plot(fit, vars = "lon", id = 49237)
```

## Map flight paths

We can visualise the results on a static map using `mapTrack()`:

```{r map, fig.cap="Modelled movement trajectories per individual. Posterior means are shown together with 50 posterior draws, circles on the map indicate receiver locations with detections of the animals."}
mapTrack(fit) +
  geom_point(aes(recvDeployLon, recvDeployLat), data = motusData)
```

We could also create an interactive [Leaflet](https://rstudio.github.io/leaflet) map using the following code:

```{r leaflet}
library(sfheaders)
library(leaflet)

# Extract draws
draws <- getDraws(fit) |>
  sf_linestring("lon", "lat", linestring_id = "tID")

# Leaflet map
fit |>
  as.data.frame() |>
  sf_linestring("lon", "lat", linestring_id = "ID") |>
  leaflet() |>
  addTiles() |>
  addPolylines(data = draws, color = "grey", weight = 1, opacity = 0.2) |>
  addPolylines(color = ~ c("orange", "blue"))
```
