R/check_params.R

Defines functions parse_rh_constr_func check_params

Documented in check_params

#' check_params
#'
#' Function to check if parameters are valid and compare them to default parameters from a version of RHESSys
#' @param rh_file Path to the appropriate construct file in the RHESSys source code, e.g. construct_stratum_defaults.c
#' @param def_file Path to a appropriate parameter definition file to be compared to the RHESSys defaults
#' @author Will Burke
#' @export

check_params = function(rh_file, def_file) {
  # ------------------------------ Read in def file ------------------------------
  def_read = readLines(def_file, warn = FALSE)
  def_read = def_read[nchar(def_read) > 0]
  def_table_list =  strsplit(trimws(def_read), "\\s+")
  list_lens <- max(lengths(def_table_list))
  def_table <- as.data.frame(do.call(rbind, lapply(def_table_list, `length<-`, list_lens)), stringsAsFactors = FALSE)
  names(def_table)[1:2] = c("Value", "Name")
  def_table = def_table[,1:2]
  defaultparams = parse_rh_constr_func(rh_file)
  combparams = merge(defaultparams, def_table, by = "Name", all = T)
  return(combparams)
}

#' @export
parse_rh_constr_func = function(rh_file) {
  rawlines = trimws(readLines(rh_file))
  i=1
  while (i < length(rawlines)) {
    if (!grepl(";", rawlines[i])  & (!startsWith(rawlines[i], "/*")| !startsWith(rawlines[i], "//"))) {
      rawlines[i] =  paste0(rawlines[i]," ", rawlines[i + 1])
      rawlines = rawlines[-(i+1)]
    } else {
      i = i+1
    }
  }
  paramlines = rawlines[grepl("getStrParam|getIntParam|getFloatParam|getDoubleParam", rawlines)]
  paramtext = regmatches(paramlines, gregexpr("(getStrParam\\(|getIntParam\\(|getFloatParam\\(|getDoubleParam\\().*?\\)", paramlines))
  if (any(!endsWith(unlist(paramtext), ")"))) {
    cat("Something went wrong in c file parsing.")
  }
  paramsep = strsplit(gsub("\"","", gsub("\\)", "", gsub(".*\\(","", unlist(paramtext)))), ",")
  paramsep = lapply(paramsep, trimws)
  paramdf = as.data.frame(do.call(rbind, paramsep))[,3:6]
  names(paramdf) = c("Name", "Type", "DefaultValue", "UseDefault")
  paramdf = paramdf[,c("Name", "DefaultValue", "UseDefault")]
  return(paramdf)
}
ryanrbart/rhessysR documentation built on March 29, 2024, 4:30 p.m.