R/LatLon_latxlonx.R

Defines functions latlon_latxlonx

Documented in latlon_latxlonx

#' latlon_latxlonx
#'
#' @param latneed numeric site latitude
#' @param lonneed numeric site longitude
#' @param latdelta numeric simulation delta in minute for the lat dim . This comes from the params file
#' @param londelta numeric simulation delta in minute for the lon dim. This comes from the params file
#'
#' @return
#' @export
#'
#' @examples
latlon_latxlonx <- function(latneed = 40.0628,
                            lonneed = -88.1961,
                            latdelta = 0.5,
                            londelta = 0.5
                            ) {

  #Find out in which tile does this lat/lon fall
  pSIMS_ext_path <- system.file("Utils", 'pSIMS_extents.csv', package = "pSIMSSiteMaker")
  PSIMS_extents <- read.csv2(pSIMS_ext_path, sep=',')

  current_tile <- PSIMS_extents %>%
    dplyr::filter(
      xmax> lonneed,
      xmin<lonneed,
      ymin< latneed,
      ymax>latneed
    )

  if(nrow(current_tile)<1) stop("The lat/lon does not fall into any pSIMS tile")

  idxs <- (current_tile%>%
    pull(name) %>%
    strsplit('/'))[[1]] %>% as.numeric()

  tlatidx <- idxs[1]
  tlonidx <- idxs[2]
  # Tile deltas and indices
  tlatdelta <- 120
  tlondelta <- 120
  # what tile we want to simulate

  ## USER EDIT: what are the associated lat and long degree boundaries of these tiles?
  lats  <-  c(current_tile$ymin, current_tile$ymax)
  lons  <-  c(current_tile$xmin, current_tile$xmax)
  split       <-  1
  slatidx     <-  1
  slonidx     <-  1
  tslatdelta  <-  tlatdelta / split
  tslondelta  <-  tlondelta / split
  tslatidx    <-  split * (tlatidx - 1) + slatidx
  tslonidx    <-  split * (tlonidx - 1) + slonidx
  latlines  <-  rev(seq(lats[1], lats[2], length.out = tslatdelta / latdelta + 1))
  lonlines  <- seq(lons[1], lons[2], length.out = tslondelta / londelta + 1)
  # what coordinates do you need?

  # find i and j
  latdiffs  <- latlines - latneed
  min  <- min(latdiffs[which(latdiffs > 0)])
  i  <- which(latdiffs == min)
  londiffs  <- lonlines - lonneed
  min  <- max(londiffs[which(londiffs < 0)])
  j  <- which(londiffs == min)
  # Subtile deltas and indices
  latidx  <- ceiling((tlatdelta * (tlatidx - 1) + tslatdelta * (slatidx - 1) + latdelta * i) / latdelta)
  lonidx  <- ceiling((tlondelta * (tlonidx - 1) + tslondelta * (slonidx - 1) + londelta * j) / londelta)
  return(list( tlatidx=tlatidx, tlonidx= tlonidx, latidx=latidx, lonidx=lonidx))
}
AgronomicForecastingLab/pSIMSSiteMaker documentation built on March 6, 2021, 2:27 p.m.