library(BatchExperiments)

get_data_wrapper <- function(job, static,..., tr, ip, gr, pon=0, pfi=0){
  stopifnot(all(tr >0, ip>0, gr>tr))
  # It would seem simpler to use the model ~1 insead of ~0 + scale,
  # but only ~0 + scale gives the model matrices rownames (with R <
  # 2.15), which some code depends on.
  get_data(static=static, jump=job$id, trans_rate_model="~0+scale",
           trans_rate_coefs=tr, ip_coefs=ip, growth_rate_coefs=gr,...)
}

reg <- makeExperimentRegistry(id="simStudy2",
                              packages=c("EpiGLM", "plyr"))
repls <- 2

nn <- Sys.info()["nodename"]
if (nn == "phylocluster.ccbb.utexas.edu"){
  resources <- list(queue="wilke")
  chunk.size <- 225
} else {
  resources <- list()
  chunk.size <- 1
}

propFreeImp <- rep(c(0, 0.078, 0.53), 2)
propOnsetNA <- rep(c(0, 0.052), each=3)
tmpf <- function(x, y) {
  r <- data.frame(OutbreakNumber=1, CaseType="person", scale=1,
                  initialInf=1, propOnsetNA=y, propFreeImp=x)
  r$outbreak_code <- paste(r$OutbreakNumber, r$CaseType, sep="_")
  r
}
statics <- mapply(tmpf, x=propFreeImp, y=propOnsetNA, SIMPLIFY=FALSE)

pdf <- data.frame(tr=c(0.0037), logtr=FALSE, gr=c(0.2688), ip=c(3.32),
                  ip_dispersion=0.58)
tmpf <- function(x, reg){
  id <- paste("prob", x$propFreeImp, "N", x$propOnsetNA, sep="")
  id <- gsub("\\.", "p", id)
  addProblem(reg, id=id, static=x, dynamic=get_data_wrapper)
  makeDesign(id, exhaustive=list(floor_times=c(FALSE, TRUE),
                   nreps=c(1, 10, 100)), design=pdf)
}
prob.designs <- lapply(statics, tmpf, reg=reg)

adf <- data.frame(terms="scale", intercept="no", method="uniroot", logip=FALSE)
addAlgorithm(reg, id="est", fun=get_est)

alg.design <- makeDesign("est", design=adf)

tmpf <- function(x, reg, alg.design) {
  addExperiments(reg, prob.designs=x, algo.designs=alg.design, repls=repls)
}
invisible(lapply(prob.designs, tmpf, reg, alg.design))

summarizeExperiments(reg)

num.experiments <- max(findExperiments(reg))
num.chunks <- ceiling(num.experiments / chunk.size)
tmpf <- function(x){
  seq(from=x, to=num.experiments, by=num.chunks)
}
chunks <- lapply(seq_len(num.chunks), tmpf)
#chunks <- chunk(findExperiments(reg), chunk.size=chunk.size)

submitJobs(reg, ids=chunks, resources=resources)

showStatus(reg)
save.image(file="simStudy.RData")
q('no')
