R/mcmc_continue.R

Defines functions .continue_mcmc_sampling .rtmb_weighted_chain_mean .rtmb_bind_mcmc_diagnostics .rtmb_bind_mcmc_arrays .rtmb_mcmc_last_states .rtmb_mcmc_map_values .rtmb_mcmc_metric_dimension .rtmb_mcmc_metric_type

#' @noRd
.rtmb_mcmc_metric_type <- function(metric) {
  if (is.list(metric) && identical(metric$type, "hybrid")) return("hybrid")
  if (is.matrix(metric)) return("dense")
  if (is.numeric(metric)) return("diag")
  NA_character_
}

#' @noRd
.rtmb_mcmc_metric_dimension <- function(metric) {
  type <- .rtmb_mcmc_metric_type(metric)
  if (identical(type, "hybrid")) return(as.integer(metric$dim))
  if (identical(type, "dense")) return(nrow(metric))
  if (identical(type, "diag")) return(length(metric))
  NA_integer_
}

#' @noRd
.rtmb_mcmc_map_values <- function(values, map) {
  if (is.null(map)) return(as.numeric(values))

  map_values <- as.character(map)
  active <- !is.na(map_values)
  if (!any(active)) return(numeric(0))
  if (length(map_values) != length(values)) {
    stop(
      "The stored parameter map is incompatible with the fitted parameter dimensions.",
      call. = FALSE
    )
  }

  labels <- if (is.factor(map)) {
    levels(map)[levels(map) %in% map_values[active]]
  } else {
    unique(map_values[active])
  }
  vapply(labels, function(label) {
    as.numeric(values[which(active & map_values == label)[1L]])
  }, numeric(1))
}

#' @noRd
.rtmb_mcmc_last_states <- function(fit, effective_map = NULL) {
  chains <- dim(fit$fit)[2L]
  stored <- fit$chain_state
  if (is.list(stored) && length(stored) == chains &&
      all(vapply(stored, is.numeric, logical(1)))) {
    return(lapply(stored, as.numeric))
  }

  par_list <- fit$model$par_list
  random_flags <- vapply(par_list, function(x) isTRUE(x$random), logical(1))
  target_par_list <- if (isTRUE(fit$laplace) && any(random_flags)) {
    par_list[!random_flags]
  } else {
    par_list
  }
  target_map <- if (is.null(effective_map)) fit$model$map else effective_map
  last_iteration <- dim(fit$fit)[1L]

  lapply(seq_len(chains), function(chain) {
    constrained <- as.numeric(fit$fit[last_iteration, chain, -1L, drop = TRUE])
    constrained_list <- constrained_vector_to_list(constrained, target_par_list)
    unconstrained_list <- to_unconstrained(constrained_list, target_par_list)

    unlist(lapply(names(target_par_list), function(name) {
      .rtmb_mcmc_map_values(
        unconstrained_list[[name]],
        if (!is.null(target_map)) target_map[[name]] else NULL
      )
    }), use.names = FALSE)
  })
}

#' @noRd
.rtmb_bind_mcmc_arrays <- function(old, new, field) {
  if (is.null(old) && is.null(new)) return(NULL)
  if (is.null(old) || is.null(new)) {
    stop(
      "Cannot continue this fit because the stored ", field,
      " quantities do not match those generated by the model. ",
      "Continue sampling before adding custom generated quantities or rotations.",
      call. = FALSE
    )
  }
  old_dimnames <- dimnames(old)
  new_dimnames <- dimnames(new)
  old_schema <- if (is.null(old_dimnames)) NULL else old_dimnames[2:3]
  new_schema <- if (is.null(new_dimnames)) NULL else new_dimnames[2:3]
  if (length(dim(old)) != 3L || length(dim(new)) != 3L ||
      !identical(dim(old)[-1L], dim(new)[-1L]) ||
      !identical(old_schema, new_schema)) {
    stop(
      "Cannot continue this fit because the stored ", field,
      " quantities have a different structure from the new samples. ",
      "Continue sampling before adding custom generated quantities or rotations.",
      call. = FALSE
    )
  }

  n_old <- dim(old)[1L]
  n_new <- dim(new)[1L]
  out <- array(
    NA,
    dim = c(n_old + n_new, dim(old)[2L], dim(old)[3L]),
    dimnames = list(
      iteration = NULL,
      chain = if (is.null(old_dimnames)) NULL else old_dimnames[[2L]],
      variable = if (is.null(old_dimnames)) NULL else old_dimnames[[3L]]
    )
  )
  out[seq_len(n_old), , ] <- old
  out[n_old + seq_len(n_new), , ] <- new
  out
}

#' @noRd
.rtmb_bind_mcmc_diagnostics <- function(old, new, n_old, n_new, chains,
                                        default = NA_real_) {
  if (is.null(old)) old <- matrix(default, nrow = n_old, ncol = chains)
  if (is.null(new)) new <- matrix(default, nrow = n_new, ncol = chains)
  if (!identical(dim(old), c(n_old, chains)) ||
      !identical(dim(new), c(n_new, chains))) {
    stop("Stored MCMC diagnostics are incompatible with the posterior draws.", call. = FALSE)
  }
  out <- rbind(old, new)
  dimnames(out) <- list(iteration = NULL, chain = paste0("chain", seq_len(chains)))
  out
}

#' @noRd
.rtmb_weighted_chain_mean <- function(old, new, n_old, n_new, chains) {
  old <- if (length(old) == chains) as.numeric(old) else rep(NA_real_, chains)
  new <- if (length(new) == chains) as.numeric(new) else rep(NA_real_, chains)
  out <- numeric(chains)
  for (chain in seq_len(chains)) {
    if (is.finite(old[chain]) && is.finite(new[chain])) {
      out[chain] <- (n_old * old[chain] + n_new * new[chain]) / (n_old + n_new)
    } else if (is.finite(new[chain])) {
      out[chain] <- new[chain]
    } else {
      out[chain] <- old[chain]
    }
  }
  names(out) <- paste0("chain", seq_len(chains))
  out
}

#' @noRd
.continue_mcmc_sampling <- function(fit, sampling, thin, seed, max_treedepth,
                                    parallel, inplace, globals, progress) {
  if (!inherits(fit, "mcmc_fit")) {
    stop("continue_sampling() requires an MCMC_Fit object.", call. = FALSE)
  }
  if (!is.numeric(sampling) || length(sampling) != 1L || !is.finite(sampling) ||
      sampling < 1 || sampling != as.integer(sampling)) {
    stop("'sampling' must be a positive integer.", call. = FALSE)
  }
  sampling <- as.integer(sampling)
  if (!is.numeric(seed) || length(seed) != 1L || !is.finite(seed)) {
    stop("'seed' must be a finite numeric scalar.", call. = FALSE)
  }
  for (argument in c("parallel", "inplace", "globals")) {
    value <- get(argument)
    if (!is.logical(value) || length(value) != 1L || is.na(value)) {
      stop("'", argument, "' must be TRUE or FALSE.", call. = FALSE)
    }
  }
  progress <- match.arg(progress, c("auto", "none", "bar", "message"))

  config <- fit$sampler_config
  if (!is.list(config)) config <- list()
  original_thin <- config$thin %||% 1L
  if (is.null(thin)) thin <- original_thin
  if (!is.numeric(thin) || length(thin) != 1L || !is.finite(thin) ||
      thin < 1 || thin != as.integer(thin)) {
    stop("'thin' must be a positive integer.", call. = FALSE)
  }
  thin <- as.integer(thin)
  if (is.null(max_treedepth)) {
    max_treedepth <- config$max_treedepth %||% fit$max_treedepth %||% 10L
  }
  if (!is.numeric(max_treedepth) || length(max_treedepth) != 1L ||
      !is.finite(max_treedepth) || max_treedepth < 1 ||
      max_treedepth != as.integer(max_treedepth)) {
    stop("'max_treedepth' must be a positive integer.", call. = FALSE)
  }
  max_treedepth <- as.integer(max_treedepth)

  chains <- dim(fit$fit)[2L]
  if (!is.list(fit$metric) || length(fit$metric) != chains ||
      length(fit$eps) != chains) {
    stop(
      "This fit does not contain reusable NUTS state. ",
      "Run sample() again with the current BayesRTMB version before continuing it.",
      call. = FALSE
    )
  }

  metric_types <- fit$metric_effective
  if (length(metric_types) != chains || anyNA(metric_types)) {
    metric_types <- vapply(fit$metric, .rtmb_mcmc_metric_type, character(1))
  }
  if (any(!metric_types %in% c("diag", "dense", "hybrid"))) {
    stop("The stored NUTS mass matrix type is not supported for continuation.", call. = FALSE)
  }
  effective_map <- config$map %||% fit$model$map
  chain_states <- .rtmb_mcmc_last_states(fit, effective_map)
  for (chain in seq_len(chains)) {
    state <- chain_states[[chain]]
    metric_dimension <- .rtmb_mcmc_metric_dimension(fit$metric[[chain]])
    if (!is.numeric(state) || any(!is.finite(state)) ||
        !is.finite(metric_dimension) || length(state) != metric_dimension ||
        !is.finite(fit$eps[chain]) || fit$eps[chain] <= 0) {
      stop(
        "The stored NUTS state for chain ", chain,
        " is incompatible with the current model.",
        call. = FALSE
      )
    }
  }

  delta <- config$delta %||% 0.8
  nuts_variant <- fit$nuts_variant %||% config$nuts_variant %||% "multinomial"
  metric_init <- config$metric_init %||% fit$metric_init %||% "identity"
  metric_adaptation <- config$metric_adaptation %||%
    fit$metric_adaptation %||% "stan_window"
  metric_regularization <- config$metric_regularization %||% TRUE
  metric_shrinkage <- config$metric_shrinkage %||% 5
  metric_min <- config$metric_min %||% 1e-6
  metric_max <- config$metric_max %||% 1e6
  metric_argument <- config$metric %||% fit$metric_requested
  if (length(metric_argument) != 1L ||
      !metric_argument %in% c("auto", "diag", "dense", "hybrid")) {
    metric_argument <- if (length(unique(metric_types)) == 1L) metric_types[1L] else "diag"
  }
  resume <- list(
    chain_state = chain_states,
    metric = fit$metric,
    eps = as.numeric(fit$eps),
    metric_type = as.character(metric_types)
  )

  segment <- fit$model$sample(
    sampling = sampling,
    warmup = 1L,
    chains = chains,
    thin = thin,
    seed = seed,
    delta = delta,
    max_treedepth = max_treedepth,
    nuts_variant = nuts_variant,
    metric = metric_argument,
    metric_init = metric_init,
    metric_adaptation = metric_adaptation,
    metric_regularization = metric_regularization,
    metric_shrinkage = metric_shrinkage,
    metric_min = metric_min,
    metric_max = metric_max,
    parallel = parallel,
    laplace = isTRUE(fit$laplace),
    init_jitter = 0,
    map = effective_map,
    globals = globals,
    progress = progress,
    .resume = resume
  )

  n_old <- dim(fit$fit)[1L]
  n_new <- dim(segment$fit)[1L]
  merged_fit <- .rtmb_bind_mcmc_arrays(fit$fit, segment$fit, "parameter")
  merged_random <- .rtmb_bind_mcmc_arrays(
    fit$random_fit, segment$random_fit, "random-effect"
  )
  merged_transform <- .rtmb_bind_mcmc_arrays(
    fit$transform_fit, segment$transform_fit, "transformed"
  )
  merged_generate <- .rtmb_bind_mcmc_arrays(
    fit$generate_fit, segment$generate_fit, "generated"
  )
  merged_leapfrog <- .rtmb_bind_mcmc_diagnostics(
    fit$n_leapfrog, segment$n_leapfrog, n_old, n_new, chains
  )
  merged_divergent <- .rtmb_bind_mcmc_diagnostics(
    fit$divergent, segment$divergent, n_old, n_new, chains, default = FALSE
  )
  storage.mode(merged_divergent) <- "logical"
  merged_energy <- .rtmb_bind_mcmc_diagnostics(
    fit$energy, segment$energy, n_old, n_new, chains
  )

  posterior_mean <- fit$posterior_mean
  if (is.null(posterior_mean)) {
    posterior_mean <- numeric(length(fit$model$pl_full$names))
    names(posterior_mean) <- fit$model$pl_full$names
  }
  fixed_mean <- apply(merged_fit[, , -1L, drop = FALSE], 3L, mean)
  posterior_mean[names(fixed_mean)] <- fixed_mean
  if (!is.null(merged_random)) {
    random_mean <- apply(merged_random, 3L, mean)
    posterior_mean[names(random_mean)] <- random_mean
  }

  accept <- .rtmb_weighted_chain_mean(
    fit$accept, segment$accept, n_old, n_new, chains
  )
  old_treedepth <- if (length(fit$treedepth) == chains) {
    as.numeric(fit$treedepth)
  } else {
    rep(NA_real_, chains)
  }
  new_treedepth <- as.numeric(segment$treedepth)
  treedepth <- vapply(seq_len(chains), function(chain) {
    max(c(old_treedepth[chain], new_treedepth[chain]), na.rm = TRUE)
  }, numeric(1))
  names(treedepth) <- paste0("chain", seq_len(chains))

  old_pd <- if (length(fit$pd_error_count) == chains) {
    as.integer(fit$pd_error_count)
  } else {
    integer(chains)
  }
  new_pd <- if (length(segment$pd_error_count) == chains) {
    as.integer(segment$pd_error_count)
  } else {
    integer(chains)
  }

  new_config <- config
  previous_sampling <- config$sampling %||% (n_old * original_thin)
  new_config$sampling <- previous_sampling + sampling
  new_config$chains <- chains
  new_config$thin <- thin
  new_config$seed <- seed
  new_config$delta <- delta
  new_config$max_treedepth <- max_treedepth
  new_config$nuts_variant <- nuts_variant
  new_config$metric <- metric_argument
  new_config$metric_init <- metric_init
  new_config$metric_adaptation <- metric_adaptation
  new_config$metric_regularization <- metric_regularization
  new_config$metric_shrinkage <- metric_shrinkage
  new_config$metric_min <- metric_min
  new_config$metric_max <- metric_max
  new_config$laplace <- isTRUE(fit$laplace)
  new_config$retained_draws <- dim(merged_fit)[1L]
  new_config$continuations <- (config$continuations %||% 0L) + 1L
  new_config$map <- effective_map
  history <- config$continuation_history
  if (!is.list(history)) history <- list()
  new_config$continuation_history <- c(history, list(list(
    sampling = sampling,
    thin = thin,
    seed = seed,
    max_treedepth = max_treedepth
  )))

  target <- if (isTRUE(inplace)) fit else fit$clone(deep = TRUE)
  target$fit <- merged_fit
  target$random_fit <- merged_random
  target$transform_fit <- merged_transform
  target$generate_fit <- merged_generate
  target$n_leapfrog <- merged_leapfrog
  target$divergent <- merged_divergent
  target$energy <- merged_energy
  target$accept <- accept
  target$treedepth <- treedepth
  target$eps <- segment$eps
  target$metric <- segment$metric
  target$metric_type <- segment$metric_type
  target$metric_effective <- segment$metric_effective
  target$chain_state <- segment$chain_state
  target$sampler_config <- new_config
  target$posterior_mean <- posterior_mean
  target$max_treedepth <- max_treedepth
  target$pd_error_count <- old_pd + new_pd
  target$log_ml <- NULL

  if (isTRUE(inplace)) invisible(target) else target
}

Try the BayesRTMB package in your browser

Any scripts or data that you put into this service are public.

BayesRTMB documentation built on Nov. 24, 2026, 9:06 a.m.