## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 7,
                      fig.height = 4.5, dpi = 96, out.width = "100%")

## ----setup, message = FALSE, warning = FALSE----------------------------------
library(disperseR)
library(ggplot2)
theme_set(theme_minimal(base_size = 11) +
            theme(panel.grid.minor = element_blank(), axis.text = element_text(size = 8)))

## ----scheme, echo = FALSE, fig.height = 3.2-----------------------------------
nodes <- data.frame(x = c(1.2, 4.6), y = c(1, 1.6), lab = c("ARP A", "ARP B"))
arrows <- data.frame(
  x = c(-0.6, 1.5, 4.9, 4.2), y = c(0.2, 1.15, 1.9, 1.35),
  xend = c(0.9, 4.25, 5.2, 1.55), yend = c(0.85, 1.6, 1.35, 0.95),
  phase = c("Type 0", "Type 2", "Type 1", "Type 3"),
  curv = c(0.2, -0.25, -1.6, -0.25))
p <- ggplot() + coord_equal(xlim = c(-0.8, 6.2), ylim = c(0, 2.6)) + theme_void()
for (i in seq_len(nrow(arrows))) {
  p <- p + geom_curve(data = arrows[i, ], aes(x, y, xend = xend, yend = yend, colour = phase),
                      curvature = arrows$curv[i], linewidth = 1,
                      arrow = arrow(length = unit(0.15, "inches"), type = "closed"))
}
p + geom_point(data = nodes, aes(x, y), size = 16, colour = "#4d4d4d") +
  geom_text(data = nodes, aes(x, y, label = lab), colour = "white", size = 3.2) +
  annotate("text", x = -0.6, y = 0.05, label = "start", size = 3) +
  annotate("text", x = c(0.1, 2.9, 5.95, 2.9), y = c(0.75, 1.75, 1.8, 0.85),
           label = c("1. Type 0", "2. Type 2", "3. Type 1", "4. Type 3"), size = 3.2) +
  scale_colour_manual(values = c("Type 0" = "#2a78d6", "Type 1" = "#eb6834",
                                 "Type 2" = "#1baf7a", "Type 3" = "#e87ba4"), guide = "none")

## ----data---------------------------------------------------------------------
head(sim_tracks)
table(sim_tracks$ID, sim_tracks$behaviour)

## ----map-raw, fig.height = 6--------------------------------------------------
behaviour_cols <- c(stay = "#4d4d4d", stopover = "#eb6834", travel = "#2a78d6")
draw.track(sim_tracks, colour.col = "behaviour", time.col = "timestamp", km = TRUE,
           palette = behaviour_cols)

## ----intervals, fig.height = 3------------------------------------------------
dt_h <- unlist(tapply(as.numeric(sim_tracks$timestamp), sim_tracks$ID,
                      function(t) diff(sort(t)) / 3600))
summary(dt_h)
ggplot(data.frame(dt = dt_h[dt_h <= 6]), aes(dt)) +
  geom_histogram(binwidth = 1 / 6, boundary = 0, fill = "#2a78d6", colour = "white") +
  scale_x_continuous(breaks = 0:6) +
  labs(x = "Interval between fixes (hours)", y = "Count", title = "Intervals up to 6 hours")

## ----gaps---------------------------------------------------------------------
split_trk <- divide.track.by.gap(sim_tracks, ids = "ID", time.col = "timestamp",
                                 gap.days = 1)
table(split_trk$id_split)

## ----map-gap, fig.height = 4--------------------------------------------------
draw.track(split_trk, colour.col = "id_split", ids = "M03", time.col = "timestamp",
           km = TRUE, palette = c(M03_1 = "#2a78d6", M03_2 = "#eb6834"))

## ----resample, eval = FALSE---------------------------------------------------
# reg <- resample.ctmm(as.data.frame(split_trk), tint = 3600, ids = "id_split",
#                      timestamp = "timestamp", proj.in = 25830,
#                      static.cols = "sex", verbose = FALSE)

## ----states-------------------------------------------------------------------
head(sim_states)

## ----hmm, eval = FALSE--------------------------------------------------------
# reg <- sim_states[, c("id_split", "time", "x", "y", "sex")]
# 
# hmm <- fitHMM.wrap(reg, ids = "id_split", stationary = TRUE,
#                    mean.step.1 = 700, sd.step.1 = 400,
#                    mean.step.2 = 150, sd.step.2 = 100,
#                    ang.con.1 = 0.7, ang.con.2 = 0.1)

## ----hmm-load, include = FALSE------------------------------------------------
# The two HMMs of this vignette are fitted beforehand with the code shown
# (data-raw/vignette_hmm.R), to keep the CRAN check within its time limit.
# Los dos HMM de esta vignette se ajustan antes con el código mostrado
# (data-raw/vignette_hmm.R), para que el check de CRAN no supere su tiempo límite.
hmm_fits <- readRDS("hmm_fits.rds")
hmm <- hmm_fits$hmm

## ----hmm-print----------------------------------------------------------------
hmm$models$global_model$mle$step

## ----map-states, fig.height = 6-----------------------------------------------
st <- hmm$data
st$id_split <- as.character(st$ID)
st$ID <- sub("_[0-9]+$", "", st$id_split)
st$state_name <- ifelse(st$state == 1, "Transit", "Encamped")
draw.track(st, colour.col = "state_name", km = TRUE,
           palette = c(Transit = "#eb6834", Encamped = "#2a78d6"))

## ----epsilon, message = FALSE-------------------------------------------------
eps <- get.epsilon(sim_states)
eps
draw.step.densities(sim_states, threshold = eps)

## ----arp----------------------------------------------------------------------
arp <- get.arp(sim_states, epsilon = eps, delta.days = 2, pct.state1 = 0.2)
arp
arp$arp_clusters$F02

## ----map-arp, fig.height = 6--------------------------------------------------
ad <- arp$data
ad$cluster <- ifelse(ad$arp, paste("ARP", ad$cluster_id), "not ARP")
arp_ids <- sort(unique(ad$cluster_id[ad$arp]))
cl_cols <- c("not ARP" = "grey80",
             setNames(rep(c("#2a78d6", "#eb6834", "#1baf7a", "#6250d6", "#e87ba4"),
                          length.out = length(arp_ids)), paste("ARP", arp_ids)))
draw.track(ad, colour.col = "cluster", km = TRUE, palette = cl_cols) +
  theme(legend.position = "none")

## ----link---------------------------------------------------------------------
linked <- link.arp(arp, thres = 24 * 3600)
table(linked$data$ID, linked$data$arp_link)

## ----linked-f04, fig.height = 4.5---------------------------------------------
draw.linked.clusters(linked, ids = "F04", grid_spacing = 1000)

## ----linked-m01, fig.height = 4.5---------------------------------------------
m01_arp <- linked$data[linked$data$ID == "M01" & linked$data$linked_clusters == "arp_1", ]
draw.linked.clusters(linked, ids = "M01", grid_spacing = 1000) +
  coord_cartesian(xlim = range(m01_arp$x) + c(-500, 500),
                  ylim = range(m01_arp$y) + c(-500, 500))

## ----classify-----------------------------------------------------------------
mov <- class.mov(linked)
mov

## ----map-phases, fig.height = 6-----------------------------------------------
draw.track(mov, colour.col = "phase", km = TRUE)

## ----map-phases-zoom, fig.height = 4.5----------------------------------------
draw.track(mov, colour.col = "phase", ids = "M01", colour.path = TRUE, km = TRUE)
draw.track(mov, colour.col = "phase", ids = "F05", colour.path = TRUE, km = TRUE)

## ----timeline, fig.height = 3-------------------------------------------------
draw.timeline(mov)

## ----summary------------------------------------------------------------------
ph <- phase.summary(mov)
head(ph[, c("ID", "phase", "from", "to", "start", "duration_days", "distance_km")], 8)

# Distance travelled outside ARPs and time until the first ARP
data.frame(
  non_arp_km = round(tapply(ph$distance_km[ph$phase != "ARP"],
                            ph$ID[ph$phase != "ARP"], sum), 1),
  days_to_first_arp = round(tapply(ph$duration_days[ph$phase == "Type 0"],
                                   ph$ID[ph$phase == "Type 0"], sum), 1)
)

## ----transfer, message = FALSE------------------------------------------------
raw_phases <- transfer.disperseR(sim_tracks, mov, id.col = "ID",
                                 time.col = "timestamp", max.diff = 3600)
table(raw_phases$ID, raw_phases$phase)

## ----truth--------------------------------------------------------------------
truth_of <- function(d) {
  vapply(seq_len(nrow(d)), function(i) {
    raw <- sim_tracks[sim_tracks$ID == d$ID[i], ]
    raw$behaviour[which.min(abs(as.numeric(raw$timestamp) - d$time_s[i]))]
  }, character(1))
}
truth <- truth_of(mov$data)

phase_sequence <- function(m) {
  sapply(split(m$data$phase, m$data$ID), function(p) paste(rle(p)$values, collapse = " > "))
}
n_clusters <- function(a) sapply(a$arp_clusters, nrow)

## ----hmm-vs-phases------------------------------------------------------------
resident <- data.frame(
  truth = truth == "stay",
  hmm = mov$data$state == 2,
  disperseR = mov$data$phase == "ARP"
)
# Proportion of the locations of each simulated behaviour classified as resident
round(sapply(resident[, -1], function(r) tapply(r, truth, mean)), 2)

# Number of resident episodes per individual
n_runs <- function(r, id) tapply(r, id, function(z) sum(rle(z)$values))
cbind(truth = n_runs(resident$truth, mov$data$ID),
      hmm = n_runs(resident$hmm, mov$data$ID),
      disperseR = n_runs(resident$disperseR, mov$data$ID))

## ----hmm-vs-phases-plot, fig.height = 2.6-------------------------------------
cmp <- rbind(
  data.frame(ID = "1. simulated", time = mov$data$time, status = truth),
  data.frame(ID = "2. HMM state", time = mov$data$time,
             status = ifelse(resident$hmm, "stay", "travel")),
  data.frame(ID = "3. disperseR", time = mov$data$time,
             status = ifelse(resident$disperseR, "stay", "travel"))
)
cmp <- cmp[rep(mov$data$ID, 3) == "F05", ]
draw.timeline(cmp, phase.col = "status", palette = behaviour_cols) +
  labs(title = "F05: resident (stay) or not")

## ----hmm-2states, eval = FALSE------------------------------------------------
# hmm2 <- fitHMM.wrap(reg, ids = "id_split",
#                     mean.step.1 = 300, sd.step.1 = 300,
#                     mean.step.2 = 20, sd.step.2 = 20,
#                     ang.con.1 = 0.5, ang.con.2 = 0.1)

## ----hmm-2states-load, include = FALSE----------------------------------------
hmm2 <- hmm_fits$hmm2

## ----hmm-2states-data---------------------------------------------------------
st2 <- hmm2$data
st2$ID <- sub("_[0-9]+$", "", as.character(st2$ID))

## ----hmm-2states-compare, message = FALSE-------------------------------------
hmm2$models$global_model$mle$step
eps2 <- get.epsilon(st2)
c(three_states = eps, two_states = eps2)

## ----hmm-2states-arp----------------------------------------------------------
arp2 <- get.arp(st2, epsilon = eps2, delta.days = 2, pct.state1 = 0.5)
rbind(three_states = n_clusters(arp),
      two_states = n_clusters(arp2))
phase_sequence(class.mov(link.arp(arp2, thres = 24 * 3600)))[c("M01", "F02")]

## ----epsilon-table, message = FALSE-------------------------------------------
eps_tab <- sapply(c("density", "mean", "median"), function(m) {
  c(global = get.epsilon(sim_states, method = m),
    unlist(get.epsilon(sim_states, method = m, mode = "individual", ids = "ID")),
    unlist(get.epsilon(sim_states, method = m, mode = "groups", group.col = "sex")))
})
round(eps_tab)

## ----epsilon-effect-----------------------------------------------------------
eps_values <- c(eps / 4, eps / 2, eps, 2 * eps, 4 * eps)
eps_effect <- sapply(eps_values, function(e)
  n_clusters(get.arp(sim_states, epsilon = e, delta.days = 2, pct.state1 = 0.2)))
colnames(eps_effect) <- paste0(round(eps_values), " m")
eps_effect

## ----arp-variants-------------------------------------------------------------
n_arp <- function(delta = 2, pct = 0.2, minPts = 3) {
  n_clusters(get.arp(sim_states, epsilon = eps, delta.days = delta,
                     pct.state1 = pct, minPts = minPts))
}
rbind("delta.days = 0.5" = n_arp(delta = 0.5),
      "delta.days = 1"   = n_arp(delta = 1),
      "delta.days = 2"   = n_arp(delta = 2),
      "delta.days = 3"   = n_arp(delta = 3),
      "pct.state1 = 0.5" = n_arp(pct = 0.5),
      "minPts = 10"      = n_arp(minPts = 10))

## ----arp-short----------------------------------------------------------------
mov_short <- class.mov(link.arp(get.arp(sim_states, epsilon = eps, delta.days = 0.5,
                                        pct.state1 = 0.2), thres = 24 * 3600))
rbind("delta.days = 0.5" = tapply(mov_short$data$phase[truth == "stopover"] == "ARP",
                                  mov_short$data$ID[truth == "stopover"], mean),
      "delta.days = 2"   = tapply(mov$data$phase[truth == "stopover"] == "ARP",
                                  mov$data$ID[truth == "stopover"], mean))

## ----thres-curve, fig.height = 3.5, warning = FALSE---------------------------
thres_h <- c(0, 2, 4, 6, 9, 12, 18, 24, 36, 48, 72, 96)
counts <- do.call(rbind, lapply(thres_h, function(h) {
  p <- phase.summary(suppressWarnings(class.mov(link.arp(arp, thres = h * 3600))))
  data.frame(thres = h, phase = c("Type 1", "Type 2", "Type 3"),
             n = as.vector(table(factor(p$phase, c("Type 1", "Type 2", "Type 3")))))
}))
ggplot(counts, aes(thres, n, colour = phase)) +
  geom_line(linewidth = 0.8) + geom_point(size = 2) +
  geom_vline(xintercept = 24, linetype = "dashed", colour = "grey50") +
  scale_colour_manual(values = c("Type 1" = "#eb6834", "Type 2" = "#1baf7a",
                                 "Type 3" = "#e87ba4"), name = NULL) +
  scale_x_continuous(breaks = c(0, 12, 24, 48, 72, 96)) +
  labs(x = "thres (hours)", y = "Number of movements (all individuals)")

## ----thres-sequences----------------------------------------------------------
thres_seq <- sapply(c(0, 24, 96), function(h)
  phase_sequence(suppressWarnings(class.mov(link.arp(arp, thres = h * 3600))))[c("M01", "F04")])
colnames(thres_seq) <- paste("thres =", c(0, 24, 96), "h")
thres_seq

## ----establish----------------------------------------------------------------
est_seq <- sapply(c(1, 3, 9), function(d)
  phase_sequence(class.mov(linked, establish = TRUE,
                           establish.days = d))[c("F02", "M01", "F05")])
colnames(est_seq) <- paste("establish.days =", c(1, 3, 9))
est_seq

## ----mcp----------------------------------------------------------------------
phase_sequence(class.mov(linked, arp.links = "mcp"))[c("M01", "F04")]

## ----transfer-methods, message = FALSE----------------------------------------
methods <- c("temporal", "spatial", "forward", "backward", "movement", "arp")
tr <- lapply(setNames(methods, methods), function(m)
  transfer.disperseR(sim_tracks, mov, id.col = "ID", time.col = "timestamp",
                     method = m, max.diff = 3600))
data.frame(
  agreement_with_temporal = round(sapply(tr, function(d)
    mean(d$phase == tr$temporal$phase, na.rm = TRUE)), 3),
  fixes_in_ARP = sapply(tr, function(d) sum(d$phase == "ARP", na.rm = TRUE)),
  no_match_within_1h = sapply(tr, function(d) sum(is.na(d$phase))))

