
# compare models using cross validation

# --------------------------------------------------------------------------------------------------------------------------------
# functions

merge_all <- function(dflist, by.var) {
    Reduce(function(...) merge(..., by = by.var, all = TRUE), dflist)
}

"%!in%" <- Negate("%in%")

# --------------------------------------------------------------------------------------------------------------------------------
# options

options(stringsAsFactors = FALSE)

# --------------------------------------------------------------------------------------------------------------------------------
# packages

# installpackages("caret", dependencies = c("Imports", "Depends", "Suggests"))
packages <- c("caret", "e1071", "subselect", "ipred", "parallel", "doParallel", "corrplot",  "rowr", "ggplot2") 
sapply(packages, require, character.only = TRUE)


# --------------------------------------------------------------------------------------------------------------------------------
# load data

project_dir <- "path-to-output-directory"
data_dir <- "path-to-input-directory"

# load pre-processed data
load(file.path(data_dir, "data_PP.Rdata"))


# --------------------------------------------------------------------------------------------------------------------------------
# tuning parameters

# https://machinelearningmastery.com/tune-machine-learning-algorithms-in-r/

modelMethods <- c("cubist", "rf", "xgbLinear", "rqnc", "gamSpline", "penalized", "BstLm", 
                                "simpls", "widekernelpls", "glmnet", "gaussprPoly", "pcr", "lm")
tuningParams <- lapply(modelMethods, modelLookup)
names(tuningParams) <- modelMethods
tuningParams

# --------------------------------------------------------------------------------------------------------------------------------
control <- trainControl(method = "repeatedcv", number = 10, repeats = 10, allowParallel = TRUE)
metric <- "RMSE"

# --------------------------------------------------------------------------------------------------------------------------------
# data for genus response
dat_genus <- cv_data_PP$genus_PP$dataset_PP[, colnames(cv_data_PP$genus_PP$dataset_PP) %!in% 
    c("fips", "region",  paste("totalOntree", c("n", "i", "e", "int"), sep = "."), responseColumns[responseColumns %!in% "genus"])]
   
# --------------------------------------------------------------------------------------------------------------------------------
# parallel processing
cluster <- makeCluster(detectCores() - 1) # convention to leave 1 core for OS
registerDoParallel(cluster)

# -------------------------------------------------------------------------------------------------------------------------------- 

cat("starting model fitting", "\n")
   
set.seed(7)
cv_cubist_genus <- train(genus ~ . , method = "cubist", metric = metric, trControl = control, na.action = "na.exclude", 
    tuneGrid = data.frame(committees = 100, neighbors = 9),
    data = dat_genus)

set.seed(7)
mtry <- floor(sqrt(ncol(dat_genus[, !(colnames(dat_genus) %in% "genus")])))
tunegrid <- expand.grid(.mtry=mtry) # grid or random search?
cv_rf_genus <- train(genus ~ . , method = "rf", metric = metric, trControl = control, na.action = "na.exclude", 
    tuneGrid = tunegrid,
    data = dat_genus)
    
set.seed(7)
cv_xgbLinear_genus <- train(genus ~ . , method = "xgbLinear", metric = metric, trControl = control, na.action = "na.exclude", 
    data = dat_genus)
    
set.seed(7)
cv_rqnc_genus <- train(genus ~ . , method = "rqnc", metric = metric, trControl = control, na.action = "na.exclude", 
    data = dat_genus)

set.seed(7)
cv_gamSpline_genus <- train(genus ~ . , method = "gamSpline", metric = metric, trControl = control, na.action = "na.exclude", 
    data = dat_genus)

set.seed(7)
cv_penalized_genus <- train(genus ~ . , method = "penalized", metric = metric, trControl = control, na.action = "na.exclude", 
    tuneGrid = data.frame(lambda1 = 0, lambda2 = 1),
    data = dat_genus)

set.seed(7)
cv_BstLm_genus <- train(genus ~ . , method = "BstLm", metric = metric, trControl = control, na.action = "na.exclude", 
    data = dat_genus)

set.seed(7)
cv_simpls_genus <- train(genus ~ . , method = "simpls", metric = metric, trControl = control, na.action = "na.exclude", 
    data = dat_genus)

set.seed(7)
cv_widekernelpls_genus <- train(genus ~ . , method = "widekernelpls", metric = metric, trControl = control, na.action = "na.exclude", 
    data = dat_genus)

set.seed(7)
cv_glmnet_genus <- train(genus ~ . , method = "glmnet", metric = metric, trControl = control, na.action = "na.exclude", 
    data = dat_genus)

set.seed(7)
cv_gaussprPoly_genus <- train(genus ~ . , method = "gaussprPoly", metric = metric, trControl = control, na.action = "na.exclude", 
    data = dat_genus)

set.seed(7)
cv_pcr_genus <- train(genus ~ . , method = "pcr", metric = metric, trControl = control, na.action = "na.exclude", 
    data = dat_genus)

set.seed(7)
cv_lm_genus <- train(genus ~ . , method = "lm", metric = metric, trControl = control, na.action = "na.exclude", 
    data = dat_genus)
                
cat("finished model fitting", "\n")


# de-register parallel processing cluster
stopCluster(cluster)
registerDoSEQ()


# --------------------------------------------------------------------------------------------------------------------------------
# save output

cv_models_comp <- list(
    "cubist" = cv_cubist_genus,
    "rf" = cv_rf_genus,
    "xgbLinear" = cv_xgbLinear_genus, 
    "rqnc" = cv_rqnc_genus,
    "gamSpline" = cv_gamSpline_genus,
    "penalized" = cv_penalized_genus,
    "BstLm" = cv_BstLm_genus,
    "simpls" = cv_simpls_genus,
    "widekernelpls" = cv_widekernelpls_genus,
    "glmnet" = cv_glmnet_genus,
    "gaussprPoly" = cv_gaussprPoly_genus,
    "pcr" = cv_pcr_genus,
    "lm" = cv_lm_genus
   )

save(cv_models_comp, file = file.path(project_dir, "cv_models_comp_genus.Rdata"), compress = "gzip")

    


