R/runJAGS.R

#' @title Call JAGS to get the posterior draws.
#' 
#' @description This function calls jags to get the posterior draws.
#' 
#' @param bdat a list of containing the data necessary for the JAGS model
#' @param calcInits a list or function that generates a list of intial values for the JAGS model
#' @param sims the number of MCMC simulations used for each chain after a burnin of 10 percent of sims
#' @param numChains number of MCMC chains to use
#' @param details if details=TRUE, more detailed results are returned.  
#' 
#' @return If details=FALSE, a list of MCMC chains for the monitored model parameters is returned. If details=TRUE, a model object generated by the jags function is returned (this contains the simulations along with additional information)
runJAGS <- function(bdat, calcInits, sims=10000, numChains=3, 
                    details=FALSE){
  # figure out what parameters to monitor based on bdat
  datNames <- names(bdat)
  
  nMult <- max(c(1,round(sims/1000)))
  
  saveList <- c("prod","logCap","obsSD","escapement","wildEscapementAge3to5","recruits","predictedRecruits")
  #if("marineSurvivalIndex" %in% datNames) saveList <- c(saveList,"msCoef") 
  #if("flow" %in% datNames) saveList <- c(saveList,"msCoef")
  saveList <- c(saveList,"flowCoef","msCoef")
  if("A" %in% datNames) saveList <- c(saveList,c("procSD","AEQm","maturationRate","App"))
  
  m1 <- jags(data=bdat, inits=calcInits, parameters.to.save=saveList, model.file="mod1.txt",
             n.chains=numChains, n.iter=1100*nMult, n.burnin=100*nMult, n.thin=nMult, 
             DIC=TRUE, digits=5)
  if(details) resultsOut <- m1
  else resultsOut <- m1$BUGSoutput$sims.list #posterior draws
  resultsOut
}
eeholmes/DM documentation built on May 26, 2019, 3:36 p.m.