---
# Code originally from:
#'   author = {Matt Crane, Inês Silva, Benjamin Michael Marshall, Colin Thomas Strine},
#'   title = {Lots of movement, little progress: a review of reptile home range literature},
#'   journal = {PeerJ},
#'   volume = {9},
#'   number = {e11742},
#'   pages = {1-25},
#'   doi = {10.7717/peerj.11742},
#'   url = {https://peerj.com/articles/11742/},
#'   year = {2021}
#' }

# Edited by Cameron Wesley Hodges 2021-07-25 for publication of: 
# title = {Malayan kraits (Bungarus candidus) show affinity to anthropogenic structures in a human dominated landscape}
## authors= {Cameron Wesley Hodges, Benjamin Michael Marshall, Jacques George Hill III, and Colin Thomas Strine}
## year = {2021}
---

```{r echo = FALSE, message=FALSE}
 
library(dplyr)
library(ggplot2)
library(sp)
library(readr)
  
animalData <- read.csv(file = "BUCA_data_complete.csv", 
                       stringsAsFactors = FALSE)

utm47data <- animalData[animalData$UTMzone == "47N",]
# tell R the utm zone that the data was collected in, and make a SP object
sp47 <- SpatialPoints(coords= cbind(utm47data[,4], utm47data[,5]), proj4string = CRS("+init=epsg:32647"))
# now that R knows it was collected in 47N we can convert it to 48N
sp48convert <- spTransform(sp47, CRS("+init=epsg:32648"))
# extract the newly converted locations and place them back in the orignal dataframe
animalData$x[animalData$UTMzone == "47N"] <- sp48convert@coords[,1]
animalData$y[animalData$UTMzone == "47N"] <- sp48convert@coords[,2]

##### set projection system (If all locations were in UTM Zone 48)
crs.proj <- CRS("+proj=utm +zone=48 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0")


animalData <- animalData %>% 
  group_by(animal) %>% 
  mutate(datetime = as.POSIXct(datetime, format = "%m/%d/%Y %H:%M",
                                            tz = "Asia/Bangkok")) %>% 
  arrange(datetime) %>% 
  mutate(step.length = sqrt((x - lag(x))^2 +
                              (y - lag(y))^2),
         time.lag = as.numeric(difftime(datetime, lag(datetime),
                             units = "hours")))





summaryTable <- animalData %>% 
  group_by(animal) %>% 
  summarise(datapoints = length(datetime),
            duration = as.numeric(difftime(max(datetime),
                                           min(datetime),
                                             units = "days")),
            timelag = paste0(round(digits = 2, mean(time.lag, na.rm = TRUE)), " ±",
                             round(digits = 2,
                                   sd(time.lag, na.rm = TRUE)/
                                     sqrt(length(time.lag)))),
            moves = sum(step.length > 0, na.rm = TRUE),
            step.length = paste0(round(digits = 2, mean(step.length, na.rm = TRUE)), 
                                 " ±", round(digits = 2, sd(step.length, na.rm = TRUE)/
                                               sqrt(length(step.length))))
            )

intextSummaries <- summaryTable %>% 
  summarise(datapointsMean = mean(datapoints),
            datapointsSE = sd(datapoints)/sqrt(length(datapoints)),
            movesMean = mean(moves),
            movesSE = sd(moves)/sqrt(length(moves)),
            durationMean = mean(duration),
            durationSE = sd(duration)/sqrt(length(duration))
            )
write_csv(intextSummaries, "In text summary data.csv")

overallSummaries <- animalData %>% 
  ungroup() %>% 
  summarise(timelagMean = mean(time.lag, na.rm = TRUE),
            timelagSE = sd(time.lag, na.rm = TRUE)/sqrt(length(time.lag)),
            timelagMax = max(time.lag, na.rm = TRUE),
            timelagMin = min(time.lag, na.rm = TRUE),
            steplengthMean = mean(step.length, na.rm = TRUE),
            steplengthSE = sd(step.length, na.rm = TRUE)/sqrt(length(step.length))
            )

```

We tracked `r length(unique(animalData$individual.local.identifier))` individuals for an average of `r round(intextSummaries$durationMean, digits = 2)` ±`r round(intextSummaries$durationSE, digits = 2)` days. During the tracking period, we located individuals on average every `r round(overallSummaries$timelagMean, digits = 2)` ±`r round(overallSummaries$timelagSE, digits = 2)` days, and detected `r round(intextSummaries$movesMean, digits = 2)` ±`r round(intextSummaries$movesSE, digits = 2)` moves per individual with a mean step length of `r round(overallSummaries$steplengthMean, digits = 2)` ±`r round(overallSummaries$steplengthSE, digits = 2)` m.

```{r echo=FALSE}
knitr::kable(summaryTable, digits = 2,
             caption = "Table 1. Summary of animal tracking",
             col.names = c("Animal ID", "# datapoints", 
                           "Duration (days)",
                           "Mean time lag ±SE (hours)",
                           "# moves",
                           "Mean step length ±SE (m)"
                           ),
             align = "c")
```

```{r echo=FALSE, fig.align='center', fig.cap="Figure 1. The tracking duration of all indivudals.", fig.dim=c(12, 4)}
write_csv(overallSummaries, "Summary of animal tracking.csv")

ggplot(animalData) +
  geom_point(aes(x = datetime, y = animal,
                 colour = time.lag > 48 & !is.na(time.lag)),
             size = 1, shape = "|") +
  scale_colour_manual(values = c("grey10", "darkred"),
                      labels = c("< 48 hour time lag",
                                 "> 48 hour time lag")) +
  labs(x = "Date", y = "Animal ID", colour = "Time lag larger\nthan planned") +
  theme_bw() +
  theme(axis.title = element_text(face = 2),
        axis.title.y = element_text(hjust = 0, angle = 0)) +
  guides(colour = guide_legend(override.aes = list(size = 5)))


```

```{r echo=FALSE, message=FALSE, warning=FALSE, fig.align='center', fig.cap="Figure 2. The distribution and mean (dashed line) lag time between tracks. Note, x-axis is square-rooted and truncated at 96 hours", fig.dim=c(8, 4)}
ggsave(file = "Tracking durations.png", width = 200, height = 150,
       dpi = 600, units = "mm")

lagtimeplot <- animalData %>% 
  filter(!is.na(time.lag)) %>% 
  ggplot() +
  geom_vline(aes(xintercept = mean(time.lag)),
             linetype = 2, alpha = 0.5) +
  geom_density(aes(x = time.lag), fill = "black", alpha = 0.5, colour = NA) +
  annotate("text", x = 96, y = 0.85,
           label = paste0("Mean lag = ", 
                          round(digits = 2, overallSummaries$timelagMean),
                          " ± ", 
                          round(digits = 2, overallSummaries$timelagSE),
                          " hours\n",
                          "Range = ", 
                          round(digits = 2, overallSummaries$timelagMin),
                          " - ", 
                          round(digits = 2, overallSummaries$timelagMax), " hours"),
           fontface = 4, hjust = 1) +
  theme_bw() +
  labs(x = "Time lag between tracks (hours)", y = "Density") +
  scale_x_sqrt(breaks = c(2, seq(0,12,6), seq(24, 120, 24),
                          seq(240, 800, 240)),
               limits = c(0, 96)) +
  theme(axis.title.y = element_text(angle = 0, vjust = 1, face = 2),
        axis.title.x = element_text(hjust = 1, face = 2))

lagtimeplot
ggsave(lagtimeplot, file = "Time lag between tracks.png", width = 200, height = 150,
       dpi = 600, units = "mm")
```
