diff --git a/BayesianTools/R/mcmcRun.R b/BayesianTools/R/mcmcRun.R index 2e4f7d1..f64ee35 100644 --- a/BayesianTools/R/mcmcRun.R +++ b/BayesianTools/R/mcmcRun.R @@ -103,8 +103,9 @@ runMCMC <- function(bayesianSetup , sampler = "DEzs", settings = NULL){ if(restart == T) if(!getPossibleSamplerTypes()$restartable[which(getPossibleSamplerTypes()$BTname == settings$sampler)]) stop("This sampler can not be restarted") - ########### Recursive call in case multiple chains are to be run - if(settings$nrChains >1){ + ########### Recursive call for multiple chains or restarting a sampler list + if(settings$nrChains > 1 || + (restart && inherits(bayesianSetup, "mcmcSamplerList"))){ # Initialize output list out<- list() diff --git a/BayesianTools/tests/testthat/test-runMCMC-singleton-list.R b/BayesianTools/tests/testthat/test-runMCMC-singleton-list.R new file mode 100644 index 0000000..87f6439 --- /dev/null +++ b/BayesianTools/tests/testthat/test-runMCMC-singleton-list.R @@ -0,0 +1,48 @@ +# Suggested regression test for BayesianTools/tests/testthat/. +for (sampler in c("DEzs", "DREAMzs")) { + testthat::test_that(paste(sampler, "resumes singleton and longer sampler lists"), { + set.seed(1) + setup <- createBayesianSetup( + likelihood = function(x) sum(dnorm(x, log = TRUE)), + lower = rep(-10, 2), + upper = rep(10, 2) + ) + fit <- runMCMC( + setup, sampler = sampler, + settings = list(iterations = 30, burnin = 0, nrChains = 1, + startValue = 3, message = FALSE) + ) + testthat::expect_s3_class(fit, "mcmcSampler") + + for (settings in list(NULL, list(iterations = 15, burnin = 0, + message = FALSE))) { + # A singleton list should resume just like the first entry of a longer list. + set.seed(2) + longer <- runMCMC(createMcmcSamplerList(list(fit, fit)), settings = settings) + set.seed(2) + singleton <- runMCMC(createMcmcSamplerList(list(fit)), settings = settings) + + testthat::expect_s3_class(singleton, "mcmcSamplerList") + testthat::expect_length(singleton, 1L) + testthat::expect_s3_class(longer, "mcmcSamplerList") + testthat::expect_length(longer, 2L) + testthat::expect_identical(singleton[[1]]$chain, longer[[1]]$chain) + testthat::expect_identical(singleton[[1]]$X, longer[[1]]$X) + testthat::expect_identical(singleton[[1]]$Z, longer[[1]]$Z) + + for (output in list(singleton, longer)) { + for (i in seq_along(output)) { + testthat::expect_s3_class(output[[i]], "mcmcSampler") + for (j in seq_along(fit$chain)) { + before <- as.matrix(fit$chain[[j]]) + after <- as.matrix(output[[i]]$chain[[j]]) + testthat::expect_gt(nrow(after), nrow(before)) + testthat::expect_identical( + unname(after[seq_len(nrow(before)), , drop = FALSE]), unname(before) + ) + } + } + } + } + }) +}