R/argos2tmb.r

Defines functions argos2tmb

Documented in argos2tmb

##' Format a track data for filtering
##'
##' This is an internal function used by \code{rwg} to format track
##' data for the TMB filter.
##'
##' The input track is given as a dataframe where each row is an
##' observed location and columns
##' \describe{
##' \item{'date'}{observation time (POSIXct,GMT),}
##' \item{'lon'}{observed longitude,}
##' \item{'lat'}{observed latitude,}
##' \item{'lc'}{ARGOS location class.}
##' }
##'
##' From this it calculates interpolation indices \code{idx} and
##' weights \code{ws} such that if \code{x} is the matrix of predicted
##' states, the fitted locations are \code{ws*x[idx+1,] +
##' (1-ws)*x[idx+2,]}. If \code{extrap} is \code{TRUE}, the final
##' observations occur after the final predicted state and the fitted
##' locations are extrapolations from the final states, otherwise the
##' final observations occur before the final predicted state and all
##' fitted locations are interpolations.
##'
##' By default the function uses the same ARGOS multiplication factors
##' to scale location accuracy by location class as used in
##' the crawl R-package.
##'
##' @title Correlated Random Walk Filter
##' @param d a data frame of observations (see details)
##' @param tstep the time step to predict to (in days)
##' @param extrap if TRUE, the final predicted state occurs
##'   immediately before the last observation, otherwise the final
##'   predicted state occurs immediately after the last observation.
##' @param amf Argos error scale mmultiplication factors
##' @return A list with components
##' \item{\code{y}}{a 2 column matrix of the lon,lat observations}
##' \item{\code{K}}{a 2 column matrix of the ARGOS scale factors}
##' \item{\code{idx}}{a vector of interpolation indices}
##' \item{\code{ws}}{a vector of interpolation weights}
##' \item{\code{ts}}{the times at which states are predicted (POSIXct,GMT)}
##' \item{\code{dt}}{the time step at which states are predicted (secs)}
##' @export
argos2tmb <- function (d, tstep = 1, extrap = FALSE, amf = amfCRAWL()) {

  ## Check ARGOS location accuracies
  d$lc <- factor(d$lc, levels = c("3", "2", "1", "0", "A", "B"), ordered = TRUE)

  ## Merge ARGOS error multiplication factors
  d <- merge(d, amf, by = "lc", all.x = TRUE)
  d <- d[order(d$date), ]

  ## Interpolation indices and weights
  dt <- tstep * 86400
  tms <- (as.numeric(d$date) - as.numeric(d$date[1])) / dt
  index <- floor(tms)
  if(extrap) index <- pmax(index, max(index) - 1)
  weights <- 1 - (tms - index)

  list(y = cbind(d$lon, d$lat),
       K = cbind(d$AMFlon, d$AMFlat),
       idx = index,
       ws = weights,
       ts = seq(d$date[1], by = dt, length.out = max(index) + 2),
       dt = dt)
}
ianjonsen/bssm documentation built on July 3, 2017, 10:33 p.m.