The goal of mcunit is to provide unit tests for MCMC and Monte Carlo methods. It extends the package testthat.
You can install the current version of mcunit from bitbucket with:
::install_bitbucket("agandy/mcunit") devtools
This shows how to test if a sampler has a specific mean:
<- function(n) rnorm(n,mean=3.2,1)
sampler expect_mc_iid_mean(sampler,mean=3.2)
expect_mc_iid_mean(sampler,mean=3.5)
#> Error: Test failed with p-value=2.734643e-20 in iteration 1
This shows check of a simple MCMC sampler
<- list(genprior=function() rnorm(1),
object gendata=function(theta) rnorm(5,theta),
stepMCMC=function(theta,data,thinning){
<- function(x) prod(dnorm(data,x))*dnorm(x)
f for (i in 1:thinning){
= rnorm(1,mean=theta,sd=1)
thetanew if (runif(1)<f(thetanew)/f(theta))
<- thetanew
theta
}
theta
}
)expect_mcmc_reversible(object)
## And now with an error in the sampler:
## sampling until sample is accepted.
$stepMCMC <- function(theta,data,thinning){
object<- function(x) prod(dnorm(data,x))*dnorm(x)
f for (i in 1:thinning){
repeat{
= rnorm(1,mean=theta,sd=1)
thetanew if (runif(1)<f(thetanew)/f(theta)) break;
}<- thetanew
theta
}
theta
}expect_mcmc_reversible(object,control=list(n=1e4))
#> Error: Test failed with p-value=3.586124e-11 in iteration 1