#' Save a Stan Model Version
#' This function saves a stan model, the MCMC trace, and the input data for future reference. The function makes a directory called "inference", under which it creates a directory for each model form, and each of these subdirectories contain timestamped directories for each fit of the model.
#' @param stan_file Path to the stan model file
#' @param stan_fit An object of class "stanfit"
#' @param stan_data The input data to Stan
#' @export
save_fit <- function(stan_file, stan_fit, stan_data, dir = 'inference') {
    model_name <- gsub('.stan', '', basename(stan_file))
    save_stamp <- format(Sys.time(), format = '%Y-%m-%d_%H.%M.%S')

    if (!file.exists(dir)) dir.create(dir)
    if (!file.exists(file.path(dir, model_name))) dir.create(file.path(dir, model_name))

    save_dir <- file.path(dir, model_name, save_stamp)

    model_file <- file.path(save_dir, 'model.stan')
    file.copy(stan_file, model_file, overwrite = TRUE)

    fit_file <- file.path(save_dir, 'fit.rdata')
    save(stan_fit, file = fit_file)

    data_file <- file.path(save_dir, 'data.rdata')
    save(stan_data, file = data_file)
carterce1997/stansave documentation built on May 26, 2019, 4:39 p.m.