-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspatial_data_test.Rmd
279 lines (219 loc) · 7.99 KB
/
spatial_data_test.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
---
title: "Hawaiian SFPW movement analysis"
author: "Amy Van Cise"
date: "April 18, 2017"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Introduction
This workshop is an introduction to the use of the crawl package to predict individual movement paths from the posterior distributin of a correlated random walk model. Using the model fits, we can calculate utilization distributions for comparison with environmental variables.
```{r read data, echo=FALSE, warning=FALSE, message=FALSE, cache=TRUE}
rm(list=ls())
library(tidyverse)
library(lubridate)
library(magrittr)
library(stringr)
setwd("C:/Users/Amy/Documents/1 SIO/6 Year/crawl workhop/avancise.github.io")
data<-readr::read_csv("Gmac example tag data.csv")[,2:77]
colnames(data)<-tolower(colnames(data))
##specify date formate using lubridate
data<-data %>%
dplyr::mutate(date2=paste(data$date,data$time, sep=" ")) %>%
dplyr::mutate(datetime=lubridate::mdy_hms(date2))
#count number of tags
ntags<- data$animal %>% unique() %>% length()
#convert location quality to 3,2,1,A,B
data$lc94<-data$lc94 %>%
replace(list=which(data$lc94=="DP"),values="L3") %>%
str_sub(start=-1)
##convert dataframe into a spatial data class (sf)
spdata<-data %>% sf::st_as_sf(coords=c("longitud","latitude")) %>%
sf::st_set_crs(.,4326)
```
###Data included
Tag data from `r ntags` short-finned pilot whales tagged near Maui. The data set includes latitude, longitude, location quality and datetime. The last column was modified from date and time columns to be understood in the R environment.
##Data plot
Using leaflet, an interactive plot of the data for two individuals.
```{r pressure, echo=FALSE, warning=FALSE, message=FALSE, cache=TRUE}
library(leaflet)
library(sf)
library(sp)
library(mapview)
library(ggthemes)
pal <- colorFactor(ggthemes::ptol_pal()(2),
domain = spdata$animal)
m<-spdata %>%
leaflet() %>%
addProviderTiles(provider="Esri.OceanBasemap") %>%
addCircleMarkers(radius=1,weight=2, opacity=0.5, color = ~pal(animal)) %>%
#addPolylines(lng=~x, lat=~y, group = ~animal, color='red') %>%
addLegend(pal = pal,values = ~animal,labels = ~animal)
m
```
###Crawl model fit
For each individual, fit a correlated random walk model to the data and estimate parameters a and P.
```{r crawlinput, warning=FALSE, message=FALSE, echo=FALSE, cache=TRUE}
library(crawl)
library(pander)
spdata<-spdata %>% sf::st_transform(2785)
##function to add x and y columns to spatial data class
sfc_as_cols <- function(x, names = c("x","y")) {
stopifnot(inherits(x,"sf") && inherits(sf::st_geometry(x),"sfc_POINT"))
ret <- do.call(rbind,sf::st_geometry(x))
ret <- tibble::as_tibble(ret)
stopifnot(length(names) == ncol(ret))
ret <- setNames(ret,names)
dplyr::bind_cols(x,ret)
}
spdata<-spdata %>% sfc_as_cols
#nest spdata
spdata<-spdata %>%
group_by(animal) %>%
nest()
## set initial parameters for model
init_params <- function(d) {
ret <- list(a = c(d$x[1], 0,
d$y[1], 0),
P = diag(c(10 ^ 2, 10 ^ 2,
10 ^ 2, 10 ^ 2)))
ret
}
##attach parameters to the dataset
spdata <- spdata %>%
dplyr::mutate(init = purrr::map(data,init_params)
)
#make sure errors are correctly ordered
order_lc<-function(x) {
x$lc94 = factor(x$lc94, levels = c("3","2","1","0","A","B"))
return(x)
}
spdata<-spdata %>%
dplyr::mutate(data=purrr::map(data,order_lc))
#set priors for all the parameters to be estimated
fit_crawl <- function(d, init) {
prior<-function(p){
dnorm(p[1],log(250), 0.2, log=TRUE) +
dnorm(p[2],log(500), 0.2, log=TRUE) +
dnorm(p[3],log(1500), 0.2, log=TRUE) +
dnorm(p[4],log(2500), 0.4, log=TRUE) +
dnorm(p[5],log(2500), 0.4, log=TRUE) +
dnorm(p[6],log(2500), 0.4, log=TRUE) +
dnorm(p[8],-4, 2, log=TRUE)
}
fit<- crawl::crwMLE(
mov.model = ~1,
err.model = list(x= ~lc94-1),
data=d,
method="Nelder-Mead",
Time.name = "datetime",
initial.state = init,
prior = prior,
attempts = 8,
control = list(
trace = 0
),
initialSANN = list(
maxit = 1500,
trace = 0
)
)
fit
}
spdatafit <- spdata %>%
dplyr::mutate(fit = purrr::map2(data,init, fit_crawl),
params = map(fit, crawl::tidy_crwFit))
##table of parameters
panderOptions('knitr.auto.asis', FALSE)
spdatafit$params %>%
walk(pander::pander,caption = "crwMLE fit parameters")
```
###Predicted paths
Using the fit parameters, predict the most likely paths for two animals. The below graphs show the estimated x and y track for each individual, and then a final map pulling all the data together.
```{r crawlpredictions, warning=FALSE, message=FALSE, echo=FALSE, cache=TRUE}
##crawl predictions
spdatafit <- spdatafit %>%
dplyr::mutate(predict = purrr::map(fit,
crawl::crwPredict,
predTime = '1 hour'))
#graphs of x and y vs time
spdatafit$predict %>% purrr::walk(crawl::crwPredictPlot)
##function to change predictions to a spatial object
as.sf <- function(p,id,epsg,type,loctype) {
p <-
sf::st_as_sf(p, coords = c("mu.x","mu.y")) %>%
dplyr::mutate(TimeNum = lubridate::as_datetime(TimeNum),
deployid = id) %>%
dplyr::rename(pred_dt = TimeNum) %>%
filter(loctype %in% loctype) %>%
sf::st_set_crs(.,epsg)
if (type == "POINT") return(p)
if (type == "LINE") {
p <- p %>% dplyr::arrange(pred_dt) %>%
sf::st_geometry() %>%
st_cast("MULTIPOINT",ids = as.integer(as.factor(p$deployid))) %>%
st_cast("MULTILINESTRING") %>%
st_sf(deployid = unique(p$deployid))
return(p)
}
}
#convert fit to spatial object using above function
spdatafit <- spdatafit %>%
dplyr::mutate(sf_points = purrr::map2(predict, animal,
as.sf,
epsg = 2785,
type = "POINT",
loctype = "p"),
sf_line = purrr::map2(predict, animal,
as.sf,
epsg = 2785,
type = "LINE",
loctype = "p"))
#pull predicted lines from spdata and rbind the lines together
sf_pred_lines <- spdatafit$sf_line %>%
lift(rbind)() %>%
sf::st_set_crs(2785)
n <- length(unique(sf_pred_lines$deployid)) #calculate # of individuals
pal <- colorFactor(ggthemes::ptol_pal()(n),
domain = sf_pred_lines$deployid) #set color pallete
#map of paths
m <- sf_pred_lines %>%
sf::st_transform(4326) %>%
leaflet() %>%
addProviderTiles("Esri.OceanBasemap") %>%
addPolylines(weight = 2, color = ~pal(deployid)) %>%
addLegend(pal = pal,values = ~deployid,labels = ~deployid)
#suspendScroll()
m
```
##Simulate error in track prediction
Use the posterior distributin of the model to generate N simulated tracksCreate and map simulated tracks from posterior distribution using crawlr.
```{r crawlr sim tracks, warning=FALSE, message=FALSE, echo=FALSE}
library(crawlr)
getsims<-function(x, iter, fixpath=FALSE, basemap) {
predTimes <- seq(
lubridate::ceiling_date(min(x$data$datetime), "hour"),
lubridate::floor_date(max(x$data$datetime), "hour"),
"1 hour"
)
trk<-crawlr::get_sim_tracks(x, iter=iter, predTimes)
}
tracks<-getsims(spdatafit$fit[[1]], 20)
sim_points <- crawlr::get_sim_points(tracks, locType = "p", CRS("+init=epsg:2785"))
##map of predicted lines
#convert to sf object
sim_points <- sf::st_as_sf(sim_points)
sim_points <- sf::st_transform(sim_points,4326)
#build map using leaflet
m<-sf_pred_lines %>%
sf::st_transform(4326) %>%
leaflet() %>%
addProviderTiles("Esri.OceanBasemap") %>%
addCircleMarkers(data = sample_frac(sim_points, 0.25), radius = 2, weight = 2,
opacity = 3, stroke = FALSE,
color = "purple") %>%
addPolylines(weight = 2, color = ~pal(deployid)) %>%
addLegend(pal = pal, values = ~deployid, labels = ~deployid)
m
```