# Simulate many times 

library(parallel)
library(doParallel)
library(doRNG)

source("JDS_Submission/simulation_setup.R")

S <- 250
seed <- 3333

set.seed(seed)

# List of parameters

# Setting 1:
params <- expand.grid(
  missing_mech = c("MAR"),
  SNR = c(.3, 1, 3),
  p = c(10, 40),
  rho = c(.45),
  p_missing = c(.3, .7),
  plot = F,
  corr = c("exchangeable"), 
  stringsAsFactors = FALSE
)
# 
nrow(params)

## Setting 2: 

params2 <- expand.grid(
  missing_mech = c("MAR"),
  SNR = c(.3, 1, 3),
  p = c(10, 40),
  rho = c(.1),
  p_missing = c(.3, .7), 
  plot = F, 
  corr = c("autoregressive"),
  stringsAsFactors = F
) 

nrow(params2)

# Rbind them together
params <- bind_rows(params, params2)

nrow(params)
params

## set up cluster info

cl <- makeCluster(14, setup_strategy = "sequential")

results <- data.frame()

clusterExport(cl, varlist = c("medcoeffit", "MI.lasso", "simulate_once", "S"), envir = environment())
registerDoParallel(cl)

pb <- dplyr::progress_estimated(nrow(params))
sims <- list()

for(i in 1:nrow(params)) {
  args <- as.list(params[i,])
  
  sims[[i]] <- foreach::foreach(
    s = 1:S,
    .combine = "rbind") %dorng% {
    
    val <- suppressWarnings(try(do.call(simulate_once, args), silent = TRUE))
    val$result$sim <- s
    cbind(val$result, args)
  }
  pb$tick()$print() 
}

stopCluster(cl)

save(sims, params, seed, file = "JDS_Submission/sim_results.RData")
