Learn R Programming

mcunit

The goal of mcunit is to provide unit tests for MCMC and Monte Carlo methods. It extends the package testthat.

Installation

You can install the current version of mcunit from bitbucket with:

devtools::install_bitbucket("agandy/mcunit")

Example

This shows how to test if a sampler has a specific mean:

sampler <- function(n) rnorm(n,mean=3.2,1)
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

object <- list(genprior=function() rnorm(1),
               gendata=function(theta) rnorm(5,theta),
               stepMCMC=function(theta,data,thinning){
                   f <- function(x) prod(dnorm(data,x))*dnorm(x)  
                   for (i in 1:thinning){
                       thetanew = rnorm(1,mean=theta,sd=1)
                       if (runif(1)<f(thetanew)/f(theta))
                           theta <- thetanew
                   }
                   theta
               }
               )
expect_mcmc_reversible(object)
## And now with an error in the sampler:
## sampling until sample is accepted.
object$stepMCMC <- function(theta,data,thinning){
    f <- function(x) prod(dnorm(data,x))*dnorm(x)  
    for (i in 1:thinning){
        repeat{
            thetanew = rnorm(1,mean=theta,sd=1)            
            if (runif(1)<f(thetanew)/f(theta)) break;
        }
        theta <- thetanew
    }
    theta
}
expect_mcmc_reversible(object,control=list(n=1e4))
#> Error: Test failed with p-value=3.586124e-11 in iteration 1

Copy Link

Version

Install

install.packages('mcunit')

Monthly Downloads

204

Version

0.3.2

License

GPL-3

Maintainer

Axel Gandy

Last Published

April 2nd, 2021

Functions in mcunit (0.3.2)

expect_bernoulli

Test Bernoulli distribution using buckets
expect_mcmc_reversible

Test of MCMC chain assuming reversibility of the chain
expect_mc_iid_ks

Test iid samples for correct cdf using KS test
expect_mc_test

Test if p-values are coming from the null using a sequential approach.
expect_mc_iid_chisq

Test iid samples for correct cdf using chisq test
expect_mcmc

Test of MCMC chain
mcunit-package

mcunit: Unit Tests for MC Methods
expect_mc_iid_mean

Test iid samples for correct mean