mac-theobio / McMasterPandemic

SEIR+ model
GNU General Public License v3.0
20 stars 5 forks source link

Regular expression validation for formula parser #131

Closed stevencarlislewalker closed 2 years ago

ZachLevine-11 commented 2 years ago
bettertests_try <- function(s){
  validone <- grepl(pattern = "^~\\s*\\(((\\s*1/\\s*)?(\\s*1\\s*-\\s*)?[A-z_.0-9])+\\)$", ignore.case = TRUE, x = s)
  mess <- paste(rep("\\s*\\(((\\s*1/\\s*)?(\\s*1\\s*-\\s*)?[A-z_.0-9])+\\)\\s*[+*]+", times = nchar(gsub(s, pattern = "[^+*]", replacement = "")) + 1), collapse = "", sep = "")
  pat <- paste("^~*", substr(mess, start = 1, stop = nchar(mess) - 5), "$", collapse = "", sep = "")
  valid_many <-  try(grepl(pattern = pat, ignore.case = TRUE, x = s), silent = TRUE)
  if (inherits(valid_many, 'try-error')){
    warning("We couldn't check this for you, your answer may fail")
    return(TRUE)
  }
  else{
    validone | valid_many
  }
}

##make some tests
sometests <- function(test_function){
  tests <- c(test_function("~ (A) * (B) + (Dave)") == TRUE,
  test_function("~ (1-A) + (1/Gregory) +  (STEVE)") == TRUE,
  test_function(" ( 1 - A) * (1/STEVE) * (GREGORY)") == TRUE,
  test_function("(A)*") == FALSE,
  test_function("( 1 - A)") == TRUE,
  test_function("(ST.EVEN) * (1/1-A) + (C)") == TRUE,
  test_function("(ST.EVEN) * (1-1/1/A) + (C)") == FALSE,
  ##for really long inputs, we cant check it so we just return TRUE.
  test_function(paste(rep("(ST.EVEN) * (1-1/1/A) + (C)", 213), sep = "", collapse = "")) == TRUE
  )
  print(paste0("Passed: ", sum(tests), "/", length(tests), " tests"))
}