njtierney / mmcc

Fast, tidy functions for mcmc diagnostics and summaries, built with data.table
http://mmcc.njtierney.com/
Other
24 stars 5 forks source link

make mcmc_to_dt an S3 method #28

Closed njtierney closed 5 years ago

njtierney commented 5 years ago

So that there can be an mcmc_to_dt for "stanfit" / "rstan" objects

njtierney commented 5 years ago
library(mmcc)
library(tidyverse)

old_mcmc_to_dt_stan <- function(mcmc_object){

samples_data <- purrr::map(mcmc_object@sim$samples, as.data.frame)

n_chain <- mcmc_object@sim$chains

n_iter <- mcmc_object@sim$iter

# convert to data.table
tidy_fit_stan <- samples_data %>%
    dplyr::bind_rows() %>%
    tibble::as_tibble() %>%
    dplyr::mutate(chain = rep(1:n_chain, each = n_iter),
                  iteration = rep(1:n_iter, 4)) %>%
    tidyr::gather(key = "parameter",
                  value = "value",
                  -chain,
                  -iteration) %>%
    dplyr::select(iteration,
                  chain,
                  parameter,
                  value)
tidy_fit_stan
}

bm1 <- 
bench::mark(
    old = old_mcmc_to_dt_stan(example_stan_model),
    new = mcmc_to_dt(example_stan_model),
    check = FALSE
)

summary(bm1, relative = TRUE)
#> # A tibble: 2 x 10
#>   expression   min  mean median   max `itr/sec` mem_alloc  n_gc n_itr
#>   <chr>      <dbl> <dbl>  <dbl> <dbl>     <dbl>     <dbl> <dbl> <dbl>
#> 1 old         6.17  5.79   5.67  4.74      1         13.7     1  1   
#> 2 new         1     1      1     1         5.79       1       1  5.64
#> # … with 1 more variable: total_time <dbl>

autoplot(bm1)

Created on 2019-02-02 by the reprex package (v0.2.1)

samclifford commented 5 years ago

Perhaps this points towards the necessity of an mmcc class, which may have other classes, and there being as_mmcc.mcmc, as_mmcc.mcmc.list and as_mmcc.stanfit. Objects with only one chain might end up with a constant chain column.