R/rvn_rvc_write.R

Defines functions rvn_rvc_write

Documented in rvn_rvc_write

#' @title Write Raven Initial Condition (rvc) file
#'
#' @description Given initial conditions for state variables at HRUs, generates a rvc file
#'
#' @param filename filepath of rvc file to write to (with .rvc extension)
#' @param initHRU dataframe of initial conditions for state variables (columns) for each HRU (rows).
#' columns must be valid SV names and there must be an explicit column of HRU ids named 'HRU'.
#' @param init_date datetime of model start
#' @param description (optional) Description added after file header
#' @param author (optional) Name of author, to be printed in file header.
#'
#' @return \item{TRUE}{return \code{TRUE} if the function is executed properly}
#' @author Leland Scantlebury
#' @export rvn_rvc_write
#' @seealso
#' \code{\link{rvn_rvc_res}}
#' \code{\link{rvn_rvc_from_custom_output}}
#'
#' @examples
#' # Create an initial condition HRU table where SOIL[0] is 0.5mm for all HRUs
#' # Check.names is set to FALSE to allow for brackets in the column name
#' initHRU <- data.frame('HRU'=1:10, 'SOIL[0]'=0.5, check.names=FALSE)
#' model_start = as.Date('2001-10-01')
#'
#' # Generate RVC file
#' rvn_rvc_write(filename = file.path(tempdir(), "New.rvc"),
#'               initHRU = initHRU,
#'               init_date = model_start,
#'               author = 'Harry Potter')
rvn_rvc_write <- function(filename, initHRU, init_date,
                          description="Generated by RavenR rvn_rvc_write",
                          author=NULL) {

  #-- Check if init_date is a valid date
  if (as.Date(init_date)!=init_date){
    stop("init_date is not a valid datetime object")
  }

  #-- Ensure HRU column in initHRU
  if(!('HRU' %in% names(initHRU))) {
    stop("Must have HRU column in initHRU dataframe")
  }

  #-- Start file
  rvn_write_Raven_newfile(filename = filename,
                          filetype = 'rvc',
                          description = description,
                          author = author)

  #-- Time Stamp
  rvn_write_Raven_label('TimeStamp', value=format(init_date, "%Y-%m-%d %H:%M:%S"),
                        filename = filename)

  #-- SV table by HRU
  rvn_write_Raven_label('HRUStateVariableTable', filename = filename)
  svs <- names(initHRU)
  svs <- svs[-which(names(initHRU)=='HRU')]
  names(initHRU)[which(names(initHRU)=='HRU')]
  rvn_write_Raven_table(df = initHRU,
                        filename = filename,
                        attributes = svs,
                        units = rep('mm', length(svs)))
  rvn_write_Raven_label('EndHRUStateVariableTable',filename = filename)

  #TODO Support for BasinInitialConditions?

  #TODO Support for BasinStateVariables?

  #TODO Tie-in rvn_rvc_res?

  return(TRUE)
}
rchlumsk/RavenR documentation built on April 19, 2024, 5:15 a.m.