R/publicLotekToSG.R

Defines functions publicLotekToSG

Documented in publicLotekToSG

#' filter and convert public Lotek tag detections to SG format
#'
#' A set of .rds files generated by publicDTA() from a set of Lotek
#' DTA files for a single receiver are merged, filtered, and output
#' as a SensorGnome-style site tag dataset.
#'
#' @param year the deployment year
#' 
#' @param absDir An absolute directory in the SensorGnome hierarchy which
#' corresponds to a single site. All files in the folder with names
#' ending in "_raw_public_tags.rds" should be from the same receiver,
#' which is treated as a site.  The project name and site name are
#' taken to be the last two components of the path.
#' e.g. /SG/contrib/2013/taylor/sonora
#'
#' @param tagDB a .csv file of tag registrations, containing only the
#' public fields proj, id, freq, bi
#'
#' @param ... further parameters to filterTags(), which is called on
#' the merged dataset.
#'
#' @return A dataframe compatible with SensorGnome databases, consisting
#' of non-duplicated filtered tag records present in \code{tagDB}
#' 
#' As a side-effect, the dataframe is written to a file called
#' YEAR_PROJ_SITE_alltags.rds in the folder \code{path}.
#'
#' @author John Brzustowski \email{jbrzusto is at fastmail.fm}

publicLotekToSG = function(absDir, year, tagDB, ...) {
  files = dir(absDir, pattern=".*_raw_public_tags.rds$", full.names=TRUE)
  if (length(files) == 0)
    stop("Specified directory contains no files named *_raw_public_tags.rds")

  siteName = basename(absDir)
  projName = basename(dirname(absDir))
  
  y = readRDS(files[1])
  x = list()
  x[[y$recv]] = y
  ## short codes for site and project
  site = y$site
  proj = y$proj
  
  for (f in files[-1]) {
    y = readRDS(f)
    ## sanity check: proj and site should be constant
    if (y$site != site || y$proj != proj)
      stop(sprintf("Files %s and %s contain data from different projects or sites", files[1], f))
    
    if (is.null(x[[y$recv]])) {
      x[[y$recv]] = y
    } else {
      x[[y$recv]]$tags = rbind(x[[y$recv]]$tags, y$tags)
    }
  }
  rv = NULL
  for (recv in names(x)) {
    x[[recv]]$tags = x[[recv]]$tags[order(x[[recv]]$tags$ts), ]
    x[[recv]]$tags = x[[recv]]$tags[! duplicated(x[[recv]]$tags), ]

    try ({
      x[[recv]]$tags = filterTags(x[[recv]], tagDB, ...)$tags
      rv = rbind(rv, SGify(x[[recv]]$tags, year, proj, site, recv))
    }, silent=TRUE)

  }

  saveRDS(rv, file.path(absDir, sprintf("%4d_%s_%s_alltags.rds", year, projName, siteName)))
  return(rv)
}
jbrzusto/sensorgnome-R-package documentation built on May 18, 2019, 9:19 p.m.