From dfb6c7befefb4dc05d45750dd4c56c85a5c0e023 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 6 Jun 2025 12:35:07 +0200 Subject: [PATCH 1/2] thinning after stan --- R/mcmc.R | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/R/mcmc.R b/R/mcmc.R index c0c7554b6..ac78454c4 100644 --- a/R/mcmc.R +++ b/R/mcmc.R @@ -89,14 +89,19 @@ fit_mcmc <- function( mmrm_initial$sigma ) + # We perform thinning after the rstan::sampling call, + # so that we keep the whole chain in the stan fit object. + thin <- method$control$thin + method$control$thin <- 1 + control <- complete_control_bayes( control = method$control, - n_samples = method$n_samples, + n_samples = method$n_samples * thin, quiet = quiet, stan_data = stan_data, mmrm_initial = mmrm_initial ) - + sampling_args <- c( list( object = get_stan_model(), @@ -128,7 +133,10 @@ fit_mcmc <- function( fit <- stan_fit$results check_mcmc(fit, method$n_samples) - draws <- extract_draws(fit, method$n_samples) + draws <- extract_draws(fit, method$n_samples * thin) + # Perform thinning on parameter draws + draws$beta <- draws$beta[seq(1, method$n_samples * thin, by = thin)] + draws$sigma <- draws$sigma[seq(1, method$n_samples * thin, by = thin)] ret_obj <- list( "samples" = draws, From ba7cb11c0364d07e8be349f02cb72ffbbef34f41 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 18 Jun 2025 14:29:19 +0200 Subject: [PATCH 2/2] basic test --- tests/testthat/test-mcmc.R | 42 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/tests/testthat/test-mcmc.R b/tests/testthat/test-mcmc.R index d9a41fa23..8cf19ab4d 100644 --- a/tests/testthat/test-mcmc.R +++ b/tests/testthat/test-mcmc.R @@ -683,3 +683,45 @@ test_that("fit_mcmc works with multiple chains", { n_visits = 3 ) }) + +test_that("full chain (before thinning) is retained in the stan fit object", { + + skip_if_not(is_full_test()) + + set.seed(7251) + + mcoefs <- list( + "int" = 10, + "age" = 3, + "sex" = 6, + "trtslope" = 7 + ) + sigma <- as_vcov(c(3, 5, 7), c(0.1, 0.4, 0.7)) + + dat <- get_mcmc_sim_dat(1000, mcoefs, sigma) + mat <- model.matrix(data = dat, ~ 1 + sex + age + group + visit + group * visit) + + method <- method_bayes( + n_samples = 150, + same_cov = TRUE, + control = control_bayes( + warmup = 200, + thin = 3, + ) + ) + + fit <- fit_mcmc( + designmat = mat, + outcome = dat$outcome, + group = dat$group, + subjid = dat$id, + visit = dat$visit, + method = method, + quiet = TRUE + ) + # Samples are thinned + expect_true(length(fit$samples$beta) == method$n_samples) + expect_true(length(fit$samples$sigma) == method$n_samples) + # Stan fit object retains unthinned samples + expect_true(nrow(as.matrix(fit$fit)) == method$n_samples * method$control$thin) +}) \ No newline at end of file