<div>
<section>
<h1> Writing reversible jump MCMC samplers in NIMBLE </h1>
<h2> Introduction </h2>
<p> Reversible jump Markov chain Monte Carlo (RJMCMC) is a powerful method for drawing posterior samples over multiple models by jumping between models as part of the sampling. For a simple example that I’ll use below, think about a regression model where we don’t know which explanatory variables to include, so we want to do variable selection. There may be a huge number of possible combinations of variables, so it would be nice to explore the combinations as part of one MCMC run rather than running many different MCMCs on some chosen combinations of variables. To do it in one MCMC, one sets up a model that includes all possible variables and coefficients. Then “removing” a variable from the model is equivalent to setting its coefficient to zero, and “adding” it back into the model requires a valid move to a non-zero coefficient. Reversible jump MCMC methods provide a way to do that. </p>
<p>Reversible jump is different enough from other MCMC situations that packages like WinBUGS, OpenBUGS, JAGS, and Stan don’t do it. An alternative way to set up the problem, which does not involve the technicality of changing model dimension, is to use indicator variables. An indicator variable is either zero or one and is multiplied by another parameter. Thus when the indicator is 0, the parameter that is multipled by 0 is effectively removed from the model. Darren Wilkinson has a nice old <a target="_blank" rel="nofollow" href="https://darrenjw.wordpress.com/2012/11/20/getting-started-with-bayesian-variable-selection-using-jags-and-rjags/">blog post on using indicator variables for Bayesian variable selection</a> in BUGS code. The problem with using indicator variables is that they can create a lot of extra MCMC work and the samplers operating on them may not be well designed for their situation.</p>
<p>NIMBLE lets one program model-generic algorithms to use with models written in the BUGS language. The MCMC system works by first making a configuration in R, which can be modified by a user or a program, and then building and compiling the MCMC. The nimbleFunction programming system makes it easy to write new kinds of samplers.</p>
<p>The aim of this blog post is to illustrate how one can write reversible jump MCMC in NIMBLE. A variant of this may be incorporated into a later version of NIMBLE. </p>
</section>
<section>
<h2> Example model </h2>
<p>For illustration, I’ll use an extremely simple model: linear regression with two candidate explanatory variables. I’ll assume the first, x1, should definitely be included. But the analyst is not sure about the second, x2, and wants to use reversible jump to include it or exclude it from the model. I won’t deal with the issue of choosing the prior probability that it should be in the model. Instead I’ll just pick a simple choice and stay focused on the reversible jump aspect of the example. The methods below could be applied en masse to large models.</p>
<p> Here I’ll simulate data to use:</p>
<div>
<div>
<div>
<pre><span>N</span> <span>&lt;-</span> <span>20</span>
<span>x1</span> <span>&lt;-</span> <span>runif</span><span>(N,</span> <span>-</span><span>1</span><span>,</span> <span>1</span><span>)</span>
<span>x2</span> <span>&lt;-</span> <span>runif</span><span>(N,</span> <span>-</span><span>1</span><span>,</span> <span>1</span><span>)</span>
<span>Y</span> <span>&lt;-</span> <span>rnorm</span><span>(N,</span> <span>1.5</span> <span>+</span> <span>0.5</span> <span>*</span> <span>x1,</span> <span>sd</span> <span>=</span> <span>1</span><span>)</span>
</pre>
</div>
</div>
</div>
<p> I’ll take two approaches to implementing RJ sampling. In the first, I’ll use a traditional indicator variable and write the RJMCMC sampler to use it. In the second, I’ll write the RJMCMC sampler to incorporate the prior probability of inclusion for the coefficient it is sampling, so the indicator variable won’t be needed in the model.</p>
<p> First we’ll need nimble:</p>
<div>
<div>
<div>
<pre><span>library</span><span>(nimble)</span>
</pre>
</div>
</div>
</div>
</section>
<section>
<h2> RJMCMC implementation 1, with indicator variable included </h2>
<p> Here is BUGS code for the first method, with an indicator variable written into the model, and the creation of a NIMBLE model object from it. Note that although RJMCMC technically jumps between models of different dimensions, we still start by creating the largest model so that changes of dimension can occur by setting some parameters to zero (or, in the second method, possibly another fixed value). </p>
<div>
<div>
<div>
<pre><span>simpleCode1</span> <span>&lt;-</span> <span>nimbleCode</span><span>({</span>
    <span>beta0</span> <span>~</span> <span>dnorm</span><span>(</span><span>0</span><span>,</span> <span>sd</span> <span>=</span> <span>100</span><span>)</span>
    <span>beta1</span> <span>~</span> <span>dnorm</span><span>(</span><span>0</span><span>,</span> <span>sd</span> <span>=</span> <span>100</span><span>)</span>
    <span>beta2</span> <span>~</span> <span>dnorm</span><span>(</span><span>0</span><span>,</span> <span>sd</span> <span>=</span> <span>100</span><span>)</span>
    <span>sigma</span> <span>~</span> <span>dunif</span><span>(</span><span>0</span><span>,</span> <span>100</span><span>)</span>
    <span>z2</span> <span>~</span> <span>dbern</span><span>(</span><span>0.8</span><span>)</span>  <span>## indicator variable for including beta2</span>
    <span>beta2z2</span> <span>&lt;-</span> <span>beta2</span> <span>*</span> <span>z2</span>
    <span>for</span><span>(i</span> <span>in</span> <span>1</span><span>:</span><span>N) {</span>
        <span>Ypred[i]</span> <span>&lt;-</span> <span>beta0</span> <span>+</span> <span>beta1</span> <span>*</span> <span>x1[i]</span> <span>+</span> <span>beta2z2</span> <span>*</span> <span>x2[i]</span>
        <span>Y[i]</span> <span>~</span> <span>dnorm</span><span>(Ypred[i],</span> <span>sd</span> <span>= sigma)</span>
    <span>}</span>
<span>})</span>

<span>simpleModel1</span> <span>&lt;-</span> <span>nimbleModel</span><span>(simpleCode1,</span>
                            <span>data</span> <span>=</span> <span>list</span><span>(</span><span>Y</span> <span>= Y,</span> <span>x1</span> <span>= x1,</span> <span>x2</span> <span>= x2),</span>
                            <span>constants</span> <span>=</span> <span>list</span><span>(</span><span>N</span> <span>= N),</span>
                            <span>inits</span> <span>=</span> <span>list</span><span>(</span><span>beta0</span> <span>=</span> <span>0</span><span>,</span> <span>beta1</span> <span>=</span> <span>0</span><span>,</span> <span>beta2</span> <span>=</span> <span>0</span><span>,</span> <span>sigma</span> <span>=</span> <span>sd</span><span>(Y),</span> <span>z2</span> <span>=</span> <span>1</span><span>))</span>
</pre>
</div>
</div>
</div>
<p> Now here are two custom samplers. The first one will sample beta2 <i>only</i> if the indicator variable z2 is 1 (meaning that beta2 is included in the model). It does this by containing a regular random walk sampler but only calling it when the indicator is 1 (we could perhaps set it up to contain <i>any</i> sampler to be used when z2 is 1, but for now it’s a random walk sampler). The second sampler makes reversible jump proposals to move beta2 in and out of the model. When it is out of the model, both beta2 and z2 are set to zero. Since beta2 will be zero every time z2 is zero, we don’t really need beta2z2, but it ensures correct behavior in other cases, like if someone runs default samplers on the model and expects the indicator variable to do its job correctly. For use in reversible jump, z2’s role is really to trigger the prior probability (set to 0.8 in this example) of being in the model. </p>
<p> <i>Don’t worry about the warning message emitted by NIMBLE.</i> They are there because when a nimbleFunction is defined it tries to make sure the user knows anything else that needs to be defined.</p>
<div>
<div>
<div>
<pre><span>RW_sampler_nonzero_indicator</span> <span>&lt;-</span> <span>nimbleFunction</span><span>(</span>
    <span>contains</span> <span>= sampler_BASE,</span>
    <span>setup</span> <span>=</span> <span>function</span><span>(</span><span>model</span><span>,</span> <span>mvSaved</span><span>,</span> <span>target</span><span>,</span> <span>control</span><span>) {</span>
        <span>regular_RW_sampler</span> <span>&lt;-</span> <span>sampler_RW</span><span>(model, mvSaved,</span> <span>target</span> <span>= target,</span> <span>control</span> <span>= control</span><span>$</span><span>RWcontrol)</span>
        <span>indicatorNode</span> <span>&lt;-</span> <span>control</span><span>$</span><span>indicator</span>
    <span>},</span>
    <span>run</span> <span>=</span> <span>function</span><span>() {</span>
        <span>if</span><span>(model[[indicatorNode]]</span> <span>==</span> <span>1</span><span>) regular_RW_sampler</span><span>$</span><span>run</span><span>()</span>
    <span>},</span>
    <span>methods</span> <span>=</span> <span>list</span><span>(</span>
        <span>reset</span> <span>=</span> <span>function</span><span>() {regular_RW_sampler</span><span>$</span><span>reset</span><span>()}</span>
    <span>))</span>
</pre>
</div>
<div>
<pre>## Warning in nf_checkDSLcode(code): For this nimbleFunction to compile, these
## functions must be defined as nimbleFunctions or nimbleFunction methods:
## reset.
</pre>
</div>
<div>
<pre><span>RJindicatorSampler</span> <span>&lt;-</span> <span>nimbleFunction</span><span>(</span>
    <span>contains</span> <span>= sampler_BASE,</span>
    <span>setup</span> <span>=</span> <span>function</span><span>(</span> <span>model</span><span>,</span> <span>mvSaved</span><span>,</span> <span>target</span><span>,</span> <span>control</span> <span>) {</span>
        <span>## target should be the name of the indicator node, 'z2' above</span>
        <span>## control should have an element called coef for the name of the corresponding coefficient, 'beta2' above. </span>
        <span>coefNode</span> <span>&lt;-</span> <span>control</span><span>$</span><span>coef</span>
        <span>scale</span> <span>&lt;-</span> <span>control</span><span>$</span><span>scale</span>
        <span>calcNodes</span> <span>&lt;-</span> <span>model</span><span>$</span><span>getDependencies</span><span>(</span><span>c</span><span>(coefNode, target))</span>
    <span>},</span>
    <span>run</span> <span>=</span> <span>function</span><span>( ) {</span> <span>## The reversible-jump updates happen here.</span>
        <span>currentIndicator</span> <span>&lt;-</span> <span>model[[target]]</span>
        <span>currentLogProb</span> <span>&lt;-</span> <span>model</span><span>$</span><span>getLogProb</span><span>(calcNodes)</span>
        <span>if</span><span>(currentIndicator</span> <span>==</span> <span>1</span><span>) {</span>
            <span>## propose removing it</span>
            <span>currentCoef</span> <span>&lt;-</span> <span>model[[coefNode]]</span>
            <span>logProbReverseProposal</span> <span>&lt;-</span> <span>dnorm</span><span>(</span><span>0</span><span>, currentCoef,</span> <span>sd</span> <span>= scale,</span> <span>log</span> <span>=</span> <span>TRUE</span><span>)</span>
            <span>model[[target]]</span> <span>&lt;&lt;-</span> <span>0</span>
            <span>model[[coefNode]]</span> <span>&lt;&lt;-</span> <span>0</span>
            <span>proposalLogProb</span> <span>&lt;-</span> <span>model</span><span>$</span><span>calculate</span><span>(calcNodes)</span>
            <span>log_accept_prob</span> <span>&lt;-</span> <span>proposalLogProb</span> <span>-</span> <span>currentLogProb</span> <span>+</span> <span>logProbReverseProposal</span>
        <span>}</span> <span>else</span> <span>{</span>
            <span>## propose adding it</span>
            <span>proposalCoef</span> <span>&lt;-</span> <span>rnorm</span><span>(</span><span>1</span><span>,</span> <span>0</span><span>,</span> <span>sd</span> <span>= scale)</span>
            <span>model[[target]]</span> <span>&lt;&lt;-</span> <span>1</span>
            <span>model[[coefNode]]</span> <span>&lt;&lt;-</span> <span>proposalCoef</span>
            <span>logProbForwardProposal</span> <span>&lt;-</span> <span>dnorm</span><span>(</span><span>0</span><span>, proposalCoef,</span> <span>sd</span> <span>= scale,</span> <span>log</span> <span>=</span> <span>TRUE</span><span>)</span>
            <span>proposalLogProb</span> <span>&lt;-</span> <span>model</span><span>$</span><span>calculate</span><span>(calcNodes)</span>
            <span>log_accept_prob</span> <span>&lt;-</span> <span>proposalLogProb</span> <span>-</span> <span>currentLogProb</span> <span>-</span> <span>logProbForwardProposal</span>
        <span>}</span>
        <span>accept</span> <span>&lt;-</span> <span>decide</span><span>(log_accept_prob)</span>
        <span>if</span><span>(accept) {</span>
            <span>copy</span><span>(</span><span>from</span> <span>= model,</span> <span>to</span> <span>= mvSaved,</span> <span>row</span> <span>=</span> <span>1</span><span>,</span> <span>nodes</span> <span>= calcNodes,</span> <span>logProb</span> <span>=</span> <span>TRUE</span><span>)</span>
        <span>}</span> <span>else</span> <span>{</span>
            <span>copy</span><span>(</span><span>from</span> <span>= mvSaved,</span> <span>to</span> <span>= model,</span> <span>row</span> <span>=</span> <span>1</span><span>,</span> <span>nodes</span> <span>= calcNodes,</span> <span>logProb</span> <span>=</span> <span>TRUE</span><span>)</span>
        <span>}</span>
    <span>},</span>
    <span>methods</span> <span>=</span> <span>list</span><span>(</span><span>reset</span> <span>=</span> <span>function</span><span>() {</span>
    <span>})</span>
    <span>)</span>
</pre>
</div>
</div>
</div>
<p>Now we’ll set up and run the samplers:</p>
<div>
<div>
<div>
<pre><span>mcmcConf1</span> <span>&lt;-</span> <span>configureMCMC</span><span>(simpleModel1)</span>
<span>mcmcConf1</span><span>$</span><span>removeSamplers</span><span>(</span><span>'z2'</span><span>)</span>
<span>mcmcConf1</span><span>$</span><span>addSampler</span><span>(</span><span>target</span> <span>=</span> <span>'z2'</span><span>,</span>
                     <span>type</span> <span>= RJindicatorSampler,</span>
                     <span>control</span> <span>=</span> <span>list</span><span>(</span><span>scale</span> <span>=</span> <span>1</span><span>,</span> <span>coef</span> <span>=</span> <span>'beta2'</span><span>))</span>
<span>mcmcConf1</span><span>$</span><span>removeSamplers</span><span>(</span><span>'beta2'</span><span>)</span>
<span>mcmcConf1</span><span>$</span><span>addSampler</span><span>(</span><span>target</span> <span>=</span> <span>'beta2'</span><span>,</span>
                     <span>type</span> <span>=</span> <span>'RW_sampler_nonzero_indicator'</span><span>,</span>
                     <span>control</span> <span>=</span> <span>list</span><span>(</span><span>indicator</span> <span>=</span> <span>'z2'</span><span>,</span>
                                    <span>RWcontrol</span> <span>=</span> <span>list</span><span>(</span><span>adaptive</span> <span>=</span> <span>TRUE</span><span>,</span>
                                                   <span>adaptInterval</span> <span>=</span> <span>100</span><span>,</span>
                                                   <span>scale</span> <span>=</span> <span>1</span><span>,</span>
                                                   <span>log</span> <span>=</span> <span>FALSE</span><span>,</span>
                                                   <span>reflective</span> <span>=</span> <span>FALSE</span><span>)))</span>

<span>mcmc1</span> <span>&lt;-</span> <span>buildMCMC</span><span>(mcmcConf1)</span>
<span>compiled1</span> <span>&lt;-</span> <span>compileNimble</span><span>(simpleModel1, mcmc1)</span>
<span>compiled1</span><span>$</span><span>mcmc1</span><span>$</span><span>run</span><span>(</span><span>10000</span><span>)</span>
</pre>
</div>
<div>
<pre>## |-------------|-------------|-------------|-------------|
## |-------------------------------------------------------|
</pre>
</div>
<div>
<pre>## NULL
</pre>
</div>
<div>
<pre><span>samples1</span> <span>&lt;-</span> <span>as.matrix</span><span>(compiled1</span><span>$</span><span>mcmc1</span><span>$</span><span>mvSamples)</span>
</pre>
</div>
</div>
</div>
<p>Here is a trace plot of the beta2 (slope) samples. The thick line at zero corresponds to having beta2 removed from the model. </p>
<div>
<div>
<div>
<pre><span>plot</span><span>(samples1[,</span><span>'beta2'</span><span>])</span>
</pre>
</div>
</div>
<div><a target="_blank" rel="nofollow" href="https://i1.wp.com/r-nimble.org/wp-content/uploads/2017/02/plot1-1.png?ssl=1"><img sizes="(max-width: 300px) 100vw, 300px" alt="" class="wp-image-628" src="https://i2.wp.com/r-nimble.org/wp-content/uploads/2017/02/plot1-1-300x180.png?resize=300%2C180&ssl=1" data-recalc-dims="1"></a>
<p>And here is a trace plot of the z2 (indicator variable) samples.</p>
<div>
<div>
<div>
<pre><span>plot</span><span>(samples1[,</span><span>'z2'</span><span>])</span>
</pre>
</div>
</div>
<div><a target="_blank" rel="nofollow" href="https://i1.wp.com/r-nimble.org/wp-content/uploads/2017/02/plot2-1.png?ssl=1"><img sizes="(max-width: 300px) 100vw, 300px" alt="" class="wp-image-629" src="https://i2.wp.com/r-nimble.org/wp-content/uploads/2017/02/plot2-1-300x180.png?resize=300%2C180&ssl=1" data-recalc-dims="1"></a>
<p>The chains look reasonable.</p>
<p>As a quick check of reasonableness, let’s compare the beta2 samples to what we’d get if it was always included in the model. I’ll do that by setting up default samplers and then removing the sampler for z2 (and z2 should be 1).</p>
<div>
<div>
<div>
<pre><span>mcmcConf1b</span> <span>&lt;-</span> <span>configureMCMC</span><span>(simpleModel1)</span>
<span>mcmcConf1b</span><span>$</span><span>removeSamplers</span><span>(</span><span>'z2'</span><span>)</span>
<span>mcmc1b</span> <span>&lt;-</span> <span>buildMCMC</span><span>(mcmcConf1b)</span>
<span>compiled1b</span> <span>&lt;-</span> <span>compileNimble</span><span>(simpleModel1, mcmc1b)</span>
<span>compiled1b</span><span>$</span><span>mcmc1b</span><span>$</span><span>run</span><span>(</span><span>10000</span><span>)</span>
</pre>
</div>
<div>
<pre>## |-------------|-------------|-------------|-------------|
## |-------------------------------------------------------|
</pre>
</div>
<div>
<pre>## NULL
</pre>
</div>
<div>
<pre><span>samples1b</span> <span>&lt;-</span> <span>as.matrix</span><span>(compiled1b</span><span>$</span><span>mcmc1b</span><span>$</span><span>mvSamples)</span>
<span>plot</span><span>(samples1b[,</span><span>'beta2'</span><span>])</span>
</pre>
</div>
</div>
<div><a target="_blank" rel="nofollow" href="https://i1.wp.com/r-nimble.org/wp-content/uploads/2017/02/check-first-samplers-1.png?ssl=1"><img sizes="(max-width: 300px) 100vw, 300px" alt="" class="wp-image-625" src="https://i1.wp.com/r-nimble.org/wp-content/uploads/2017/02/check-first-samplers-1-300x180.png?resize=300%2C180&ssl=1" data-recalc-dims="1"></a>
<div>
<pre><span>qqplot</span><span>(samples1[ samples1[,</span><span>'z2'</span><span>]</span> <span>==</span> <span>1</span><span>,</span> <span>'beta2'</span><span>], samples1b[,</span><span>'beta2'</span><span>])</span>
<span>abline</span><span>(</span><span>0</span><span>,</span><span>1</span><span>)</span>
</pre>
</div>
</div>
<div><a target="_blank" rel="nofollow" href="https://i2.wp.com/r-nimble.org/wp-content/uploads/2017/02/check-first-samplers-2.png?ssl=1"><img sizes="(max-width: 300px) 100vw, 300px" alt="" class="wp-image-626" src="https://i2.wp.com/r-nimble.org/wp-content/uploads/2017/02/check-first-samplers-2-300x180.png?resize=300%2C180&ssl=1" data-recalc-dims="1"></a>
<p>That looks correct, in the sense that the distribution of beta2 given that it’s in the model (using reversible jump) should match the distribution of beta2 when it is<br>
always in the model.</p>
<section>
<h2> RJ implementation 2, without indicator variables </h2>
<p>Now I’ll set up the second version of the model and samplers. I won’t include the indicator variable in the model but will instead include the prior probability for inclusion in the sampler. One added bit of generality is that being “out of the model” will be defined as taking some fixedValue, to be provided, which will typically but not necessarily be zero. These functions are very similar to the ones above.</p>
<p> Here is the code to define and build a model without the indicator variable:</p>
<div>
<div>
<div>
<pre><span>simpleCode2</span> <span>&lt;-</span> <span>nimbleCode</span><span>({</span>
    <span>beta0</span> <span>~</span> <span>dnorm</span><span>(</span><span>0</span><span>,</span> <span>sd</span> <span>=</span> <span>100</span><span>)</span>
    <span>beta1</span> <span>~</span> <span>dnorm</span><span>(</span><span>0</span><span>,</span> <span>sd</span> <span>=</span> <span>100</span><span>)</span>
    <span>beta2</span> <span>~</span> <span>dnorm</span><span>(</span><span>0</span><span>,</span> <span>sd</span> <span>=</span> <span>100</span><span>)</span>
    <span>sigma</span> <span>~</span> <span>dunif</span><span>(</span><span>0</span><span>,</span> <span>100</span><span>)</span>
    <span>for</span><span>(i</span> <span>in</span> <span>1</span><span>:</span><span>N) {</span>
        <span>Ypred[i]</span> <span>&lt;-</span> <span>beta0</span> <span>+</span> <span>beta1</span> <span>*</span> <span>x1[i]</span> <span>+</span> <span>beta2</span> <span>*</span> <span>x2[i]</span>
        <span>Y[i]</span> <span>~</span> <span>dnorm</span><span>(Ypred[i],</span> <span>sd</span> <span>= sigma)</span>
    <span>}</span>
<span>})</span>

<span>simpleModel2</span> <span>&lt;-</span> <span>nimbleModel</span><span>(simpleCode2,</span>
                            <span>data</span> <span>=</span> <span>list</span><span>(</span><span>Y</span> <span>= Y,</span> <span>x1</span> <span>= x1,</span> <span>x2</span> <span>= x2),</span>
                            <span>constants</span> <span>=</span> <span>list</span><span>(</span><span>N</span> <span>= N),</span>
                            <span>inits</span> <span>=</span> <span>list</span><span>(</span><span>beta0</span> <span>=</span> <span>0</span><span>,</span> <span>beta1</span> <span>=</span> <span>0</span><span>,</span> <span>beta2</span> <span>=</span> <span>0</span><span>,</span> <span>sigma</span> <span>=</span> <span>sd</span><span>(Y)))</span>
</pre>
</div>
</div>
</div>
<p> And here are the samplers (again, ignore the warning): </p>
<div>
<div>
<div>
<pre><span>RW_sampler_nonzero</span> <span>&lt;-</span> <span>nimbleFunction</span><span>(</span>
    <span>## &quot;nonzero&quot; is a misnomer because it can check whether it sits at any fixedValue, not just 0</span>
    <span>contains</span> <span>= sampler_BASE,</span>
    <span>setup</span> <span>=</span> <span>function</span><span>(</span><span>model</span><span>,</span> <span>mvSaved</span><span>,</span> <span>target</span><span>,</span> <span>control</span><span>) {</span>
        <span>regular_RW_sampler</span> <span>&lt;-</span> <span>sampler_RW</span><span>(model, mvSaved,</span> <span>target</span> <span>= target,</span> <span>control</span> <span>= control</span><span>$</span><span>RWcontrol)</span>
        <span>fixedValue</span> <span>&lt;-</span> <span>control</span><span>$</span><span>fixedValue</span>
    <span>},</span>
    <span>run</span> <span>=</span> <span>function</span><span>() {</span> <span>## Now there is no indicator variable, so check if the target node is exactly</span>
                       <span>## equal to the fixedValue representing &quot;not in the model&quot;.</span>
        <span>if</span><span>(model[[target]]</span> <span>!=</span> <span>fixedValue) regular_RW_sampler</span><span>$</span><span>run</span><span>()</span>
    <span>},</span>
    <span>methods</span> <span>=</span> <span>list</span><span>(</span>
        <span>reset</span> <span>=</span> <span>function</span><span>() {regular_RW_sampler</span><span>$</span><span>reset</span><span>()}</span>
    <span>))</span>
</pre>
</div>
<div>
<pre>## Warning in nf_checkDSLcode(code): For this nimbleFunction to compile, these
## functions must be defined as nimbleFunctions or nimbleFunction methods:
## reset.
</pre>
</div>
<div>
<pre><span>RJsampler</span> <span>&lt;-</span> <span>nimbleFunction</span><span>(</span>
    <span>contains</span> <span>= sampler_BASE,</span>
    <span>setup</span> <span>=</span> <span>function</span><span>(</span> <span>model</span><span>,</span> <span>mvSaved</span><span>,</span> <span>target</span><span>,</span> <span>control</span> <span>) {</span>
        <span>## target should be a coefficient to be set to a fixed value (usually zero) or not</span>
        <span>## control should have an element called fixedValue (usually 0),</span>
        <span>## a scale for jumps to and from the fixedValue,</span>
        <span>## and a prior prob of taking its fixedValue</span>
        <span>fixedValue</span> <span>&lt;-</span> <span>control</span><span>$</span><span>fixedValue</span>
        <span>scale</span> <span>&lt;-</span> <span>control</span><span>$</span><span>scale</span>
        <span>## The control list contains the prior probability of inclusion, and we can pre-calculate</span>
        <span>## this log ratio because it's what we'll need later.</span>
        <span>logRatioProbFixedOverProbNotFixed</span> <span>&lt;-</span> <span>log</span><span>(control</span><span>$</span><span>prior)</span> <span>-</span> <span>log</span><span>(</span><span>1</span><span>-</span><span>control</span><span>$</span><span>prior)</span>
        <span>calcNodes</span> <span>&lt;-</span> <span>model</span><span>$</span><span>getDependencies</span><span>(target)</span>
    <span>},</span>
    <span>run</span> <span>=</span> <span>function</span><span>( ) {</span> <span>## The reversible-jump moves happen here</span>
        <span>currentValue</span> <span>&lt;-</span> <span>model[[target]]</span>
        <span>currentLogProb</span> <span>&lt;-</span> <span>model</span><span>$</span><span>getLogProb</span><span>(calcNodes)</span>
        <span>if</span><span>(currentValue</span> <span>!=</span> <span>fixedValue) {</span> <span>## There is no indicator variable, so check if current value matches fixedValue</span>
            <span>## propose removing it (setting it to fixedValue)</span>
            <span>logProbReverseProposal</span> <span>&lt;-</span> <span>dnorm</span><span>(fixedValue, currentValue,</span> <span>sd</span> <span>= scale,</span> <span>log</span> <span>=</span> <span>TRUE</span><span>)</span>
            <span>model[[target]]</span> <span>&lt;&lt;-</span> <span>fixedValue</span>
            <span>proposalLogProb</span> <span>&lt;-</span> <span>model</span><span>$</span><span>calculate</span><span>(calcNodes)</span>
            <span>log_accept_prob</span> <span>&lt;-</span> <span>proposalLogProb</span> <span>-</span> <span>currentLogProb</span> <span>-</span> <span>logRatioProbFixedOverProbNotFixed</span> <span>+</span> <span>logProbReverseProposal</span>
        <span>}</span> <span>else</span> <span>{</span>
            <span>## propose adding it</span>
            <span>proposalValue</span> <span>&lt;-</span> <span>rnorm</span><span>(</span><span>1</span><span>, fixedValue,</span> <span>sd</span> <span>= scale)</span>
            <span>model[[target]]</span> <span>&lt;&lt;-</span> <span>proposalValue</span>
            <span>logProbForwardProposal</span> <span>&lt;-</span> <span>dnorm</span><span>(fixedValue, proposalValue,</span> <span>sd</span> <span>= scale,</span> <span>log</span> <span>=</span> <span>TRUE</span><span>)</span>
            <span>proposalLogProb</span> <span>&lt;-</span> <span>model</span><span>$</span><span>calculate</span><span>(calcNodes)</span>
            <span>log_accept_prob</span> <span>&lt;-</span> <span>proposalLogProb</span> <span>-</span> <span>currentLogProb</span> <span>+</span> <span>logRatioProbFixedOverProbNotFixed</span> <span>-</span> <span>logProbForwardProposal</span>
        <span>}</span>
        <span>accept</span> <span>&lt;-</span> <span>decide</span><span>(log_accept_prob)</span>
        <span>if</span><span>(accept) {</span>
            <span>copy</span><span>(</span><span>from</span> <span>= model,</span> <span>to</span> <span>= mvSaved,</span> <span>row</span> <span>=</span> <span>1</span><span>,</span> <span>nodes</span> <span>= calcNodes,</span> <span>logProb</span> <span>=</span> <span>TRUE</span><span>)</span>
        <span>}</span> <span>else</span> <span>{</span>
            <span>copy</span><span>(</span><span>from</span> <span>= mvSaved,</span> <span>to</span> <span>= model,</span> <span>row</span> <span>=</span> <span>1</span><span>,</span> <span>nodes</span> <span>= calcNodes,</span> <span>logProb</span> <span>=</span> <span>TRUE</span><span>)</span>
        <span>}</span>
    <span>},</span>
    <span>methods</span> <span>=</span> <span>list</span><span>(</span><span>reset</span> <span>=</span> <span>function</span><span>() {</span>
    <span>})</span>
    <span>)</span>
</pre>
</div>
</div>
</div>
<p> Now let’s set up and use the samplers</p>
<div>
<div>
<div>
<pre><span>mcmcConf2</span> <span>&lt;-</span> <span>configureMCMC</span><span>(simpleModel2)</span>
<span>mcmcConf2</span><span>$</span><span>removeSamplers</span><span>(</span><span>'beta2'</span><span>)</span>

<span>mcmcConf2</span><span>$</span><span>addSampler</span><span>(</span><span>target</span> <span>=</span> <span>'beta2'</span><span>,</span>
                     <span>type</span> <span>=</span> <span>'RJsampler'</span><span>,</span>
                     <span>control</span> <span>=</span> <span>list</span><span>(</span><span>fixedValue</span> <span>=</span> <span>0</span><span>,</span> <span>prior</span> <span>=</span> <span>0.8</span><span>,</span> <span>scale</span> <span>=</span> <span>1</span><span>))</span>
<span>mcmcConf2</span><span>$</span><span>addSampler</span><span>(</span><span>target</span> <span>=</span> <span>'beta2'</span><span>,</span>
                     <span>type</span> <span>=</span> <span>'RW_sampler_nonzero'</span><span>,</span>
                     <span>control</span> <span>=</span> <span>list</span><span>(</span><span>fixedValue</span> <span>=</span> <span>0</span><span>,</span>
                                     <span>RWcontrol</span> <span>=</span> <span>list</span><span>(</span><span>adaptive</span> <span>=</span> <span>TRUE</span><span>,</span>
                                     <span>adaptInterval</span> <span>=</span> <span>100</span><span>,</span>
                                     <span>scale</span> <span>=</span> <span>1</span><span>,</span>
                                     <span>log</span> <span>=</span> <span>FALSE</span><span>,</span>
                                     <span>reflective</span> <span>=</span> <span>FALSE</span><span>)))</span>

<span>mcmc2</span> <span>&lt;-</span> <span>buildMCMC</span><span>(mcmcConf2)</span>
<span>compiled2</span> <span>&lt;-</span> <span>compileNimble</span><span>(simpleModel2, mcmc2)</span>

<span>compiled2</span><span>$</span><span>mcmc2</span><span>$</span><span>run</span><span>(</span><span>10000</span><span>)</span>
</pre>
</div>
<div>
<pre>## |-------------|-------------|-------------|-------------|
## |-------------------------------------------------------|
</pre>
</div>
<div>
<pre>## NULL
</pre>
</div>
<div>
<pre><span>samples2</span> <span>&lt;-</span> <span>as.matrix</span><span>(compiled2</span><span>$</span><span>mcmc2</span><span>$</span><span>mvSamples)</span>
</pre>
</div>
</div>
</div>
<p> And again let’s look at the samples. As above, the horizontal line at 0 represents having beta2 removed from the model. </p>
<div>
<div>
<div>
<pre><span>plot</span><span>(samples2[,</span><span>'beta2'</span><span>])</span>
</pre>
</div>
</div>
<div><a target="_blank" rel="nofollow" href="https://i1.wp.com/r-nimble.org/wp-content/uploads/2017/02/plot3-1.png?ssl=1"><img sizes="(max-width: 300px) 100vw, 300px" alt="" class="wp-image-630" src="https://i1.wp.com/r-nimble.org/wp-content/uploads/2017/02/plot3-1-300x180.png?resize=300%2C180&ssl=1" data-recalc-dims="1"></a>
<p>Now let’s compare those results to results from the first method, above. They should match.</p>
<div>
<div>
<div>
<pre><span>mean</span><span>(samples1[,</span><span>'beta2'</span><span>]</span><span>==</span><span>0</span><span>)</span>
</pre>
</div>
<div>
<pre>## [1] 0.12
</pre>
</div>
<div>
<pre><span>mean</span><span>(samples2[,</span><span>'beta2'</span><span>]</span><span>==</span><span>0</span><span>)</span>
</pre>
</div>
<div>
<pre>## [1] 0.1173
</pre>
</div>
<div>
<pre><span>qqplot</span><span>(samples1[ samples1[,</span><span>'beta2'</span><span>]</span> <span>!=</span> <span>0</span><span>,</span><span>'beta2'</span><span>], samples2[samples2[,</span><span>'beta2'</span><span>]</span> <span>!=</span> <span>0</span><span>,</span><span>'beta2'</span><span>])</span>
<span>abline</span><span>(</span><span>0</span><span>,</span><span>1</span><span>)</span>
</pre>
</div>
</div>
<div><a target="_blank" rel="nofollow" href="https://i1.wp.com/r-nimble.org/wp-content/uploads/2017/02/compare-two-methods-1.png?ssl=1"><img sizes="(max-width: 300px) 100vw, 300px" alt="" class="wp-image-627" src="https://i2.wp.com/r-nimble.org/wp-content/uploads/2017/02/compare-two-methods-1-300x180.png?resize=300%2C180&ssl=1" data-recalc-dims="1"></a>
<p>They match well.<br>

<section>
<h3> How to apply this for larger models. </h3>
<p> The samplers above could be assigned to arbitrary nodes in a model. The only additional code would arise from adding more samplers to an MCMC configuration. It would also be possible to refine the reversible-jump step to adapt the scale of its jumps in order to achieve better mixing. For example, one could try <a target="_blank" rel="nofollow" href="http://onlinelibrary.wiley.com/doi/10.1111/j.1467-9469.2008.00606.x/abstract"> this method by Ehlers and Brooks</a>. We’re interested in hearing from you if you plan to try using RJMCMC on your own models.</p>
</section>
<p><br>
</p>
<p> <img height="1" width="1" src="https://r-nimble.org/?feed-stats-post-id=634"></p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://r-nimble.org/writing-reversible-jump-mcmc-in-nimble"> R – NIMBLE</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/CdNmEq6mvVM"></a></div></div></div></div></div></section></div></div></div></div></div></div></section></div>