1.12. Posterior sampling

1.12.1. Which sampler?

A VAR: use sample_posterior. It covers rfvar_model, svar_model, prfvar_model (pooled) and proxy_svar_model, with constant parameters or any number of Markov chains, constant or time-varying transition probabilities, any prior and any restrictions:

mest  = estimate(m, data = db, estim_var_prior = prior);
mpost = sample_posterior(mest, 5000, burnin = 1000, seed = 1);
irfs  = irf(mpost);                       % one IRF per draw

It is a Metropolis-within-Gibbs sampler. Each sweep draws the regime path in one block (forward filtering, backward sampling), then the parameters block by block, each given the others:

Block

Draw

a row of constant transition probabilities

Dirichlet; exact under a Dirichlet prior on the row

the coefficients (lags, constants, deterministic terms; A+ of a structural VAR given A0)

normal, per regime or pooled, ties and linear restrictions included; exact under minnesota, inw, niw, generate_sims_zha_prior and generate_structural_prior

the covariance of a reduced-form VAR, per state of its chain

inverse-Wishart; exact under an inverse-Wishart or flat prior

a shock standard deviation, a proxy loading

inverse-gamma, normal; exact when the conditional has that form

A0, time-varying transition probabilities, everything under a prior that is not conjugate (user_defined, estim_priors, combined priors), restricted covariances

random-walk Metropolis, shaped by the curvature at the mode and adapted during the burn-in

Every proposal is accepted or rejected against the model’s own posterior completed by the regime path. For an exact block the ratio is one up to rounding: the draw is a Gibbs draw. A point outside the bounds, violating a restriction or, with solve_check_stability true (the default), not mean-square stable has zero posterior and is rejected inside its block, which truncates the conditional exactly; the rejection rates are reported. The third output holds the draws in the format of the samplers below (results{1}.pop), for posterior_sample, mcmc and rise.engine.mdd.mdd, with the acceptance rate of each block, its stability rejections, the inefficiency factors and the regime paths.

Why: the samplers below move all the parameters at once. On a constant VAR under a normal-inverse-Wishart prior, random-walk Metropolis needed 80 to 260 draws per effectively independent draw; sample_posterior needs about one, at a cost of a few posterior evaluations per sweep. The blocks it draws by random-walk Metropolis mix as random-walk Metropolis does. On a structural VAR and on a switching VAR with time-varying transition probabilities (inefficiency factors by Geyer’s initial monotone sequence estimator), the coefficients and the covariances had factors of 1 to 2 (random-walk Metropolis: 29 to 62), A0 20 to 40 and the time-varying transition parameters 15 to 110 (random-walk Metropolis: 29 and 38 to 56); the posterior means and standard deviations of the two samplers agreed within Monte Carlo error (long runs: the largest difference 2.2 Monte Carlo standard errors, the standard deviations within 4 percent), and so did rise_smc on the structural VAR. On the switching VAR, rise_smc (likelihood tempering from the prior, 2000 particles, 30 rungs) kept 99 effective particles out of 2000 at its first rung and ended in the other labeling of the regimes, 20 log points below the mode: a ladder must keep the effective sample size up at every rung. When a VAR goes to pull_objective (the way to the samplers below), RISE prints a note saying so.

Not covered, with the reason: DSGE and DSGE-VAR models, VARs with missing observations (the missing values would have to be drawn too), the mean-group panel estimator (classical) and transition probabilities driven by quantities the data do not show. For those, and for any other model, use the samplers below: rwmh for a start, rise_smc when the posterior may have several modes.

rise_smc starts its chains from iid draws of a proper distribution: the prior (logprior with prior_sampler, likelihood tempering) or the uniform distribution on a finite box (lb, ub, posterior tempering) that holds the posterior. It refuses to start without one (rise_smc:noProperStart), and from a start where the posterior is zero at every draw: the flat priors of a VAR without a prior on its parameters have neither a sampler nor such a box (their bounds are about 6.5e8 on either side). Before October 2026 it ran its first rung with one chain, and the ladder failed without a word.

1.12.2. Cost per DSGE posterior evaluation

The sampler and its proposal control how many evaluations are useful. Two existing options can reduce the cost of each evaluation without changing the sampler: Fast estimation kernel reuses setup on eligible analytical-file models, and Steady-state warm starts reuses the last successful numerical steady state as a starting guess. Both are off by default. Match stability screening when comparing kernel paths; compare numerical warm starts at the solver’s accuracy, rather than assume exact equality. The tutorial Estimation/fast_kernel/howto_sampler_speed.m saves timing and accuracy for the same seeded chains, together with the run’s settings.

1.12.3. The sampling function

rise.engine.estimation.rsamplers.rsampler.sample is the function that runs the sampling for different chains on a rise.engine.estimation.rsamplers.rsampler object to get a sample.

The syntax is

results = sample(obj,varargin)

Args:

  • obj is a member of one of the following classes:

    • rise.engine.estimation.rsamplers.rwmh : Random-Walk Metropolis-Hastings

    • rise.engine.estimation.rsamplers.imh : Independent Metropolis-Hastings

    • rise.engine.estimation.rsamplers.apt : Adaptive parallel tempering

    • rise.engine.estimation.rsamplers.slice : slice sampler

    • rise.engine.estimation.rsamplers.usrsmplr : user-defined sampler

  • *varargin* are class-specific extra arguments

Hint

After sampling, RISE has functions for thinning, burnin, etc. through subsetting. See e.g. help on mdd (constructor for marginal data density objects).

Warning

please check the sign of the target function and make sure the algorithm used conforms with that sign. Of course, changing the sign of the target function is easy

newtarget=@(varargin)-target(varargin{:})

Hint

For your convenience, some shortcuts are available so that you do not have to first create an object and then do the sampling. Moreover you do not have to create a new target if the problem is already a minimization problem. Those shortcuts are : sampler_rwmh, sampler_imh, sampler_apt, sampler_slice. They can be called using one of the following syntaxes (for the details for the inputs, see the base functions):

  • results = sampler_XXXX(target,x0,lb,ub)

  • results = sampler_XXXX(target,x0,lb,ub,opts)

1.12.4. Algorithm : Random-walk Metropolis Hastings

rise.engine.estimation.rsamplers.rwmh is the constructor for the Random-walk Metropolis Hastings algorithm

The syntax is

obj = rise.engine.estimation.rsamplers.rwmh(target,x0,lb,ub)
obj = rise.engine.estimation.rsamplers.rwmh(target,x0,lb,ub,opts)
obj = rise.engine.estimation.rsamplers.rwmh(target,x0,lb,ub,opts,constraints)

INPUTS :

  • *target* : objective to MAXIMIZE

  • *x0* : vector of initial conditions

  • *lb* : lower bound

  • *ub* : upper bound

  • *opts* : options for the class. These include the properties from the superclass rise.engine.estimation.rsamplers.rsampler as well as the specific properties of the rwmh algorithm that can be found in the properties list below.

  • *constraints* (optional): - Matrix (n_constraints x 2) where each row [a, b] enforces x(a) <= x(b)

OUTPUT:

  • *obj* : object of class rise.engine.estimation.rsamplers.rwmh

OWN PROPERTIES AND DEFAULT VALUES:

  • *c* = 1. Proposal covariance = c*tunedCov and standard-deviation scale = sqrt(c). The value \(2.38^2/d\), where \(d\) is the parameter dimension, is an asymptotic guideline for high-dimensional smooth product targets with Gaussian random-walk proposals at stationarity.

  • *tunedCov* : covariance matrix of the parameters

  • *proposal* = ‘normal’ : proposal in {‘normal’,’t-student’}

INHERITED PROPERTIES AND DEFAULT VALUES:

  • *nchain* = 1 : number of chains

  • *N* = 5000 : number of draws

  • *thinning* =1 : number of thinning draws

  • *burnin* = 100 : burnin sample

  • *MaxTime* = inf : Max Time

  • *MaxFunEvals* = inf :

See also

rise.engine.estimation.rsamplers.apt, rise.engine.estimation.rsamplers.imh, rise.engine.estimation.rsamplers.rsampler

1.12.5. Algorithm : Independent Metropolis Hastings

rise.engine.estimation.rsamplers.imh is the constructor for the Independent Metropolis-Hastings algorithm

The syntax is

obj = rise.engine.estimation.rsamplers.imh(target,x0,lb,ub)
obj = rise.engine.estimation.rsamplers.imh(target,x0,lb,ub,opts)
obj = rise.engine.estimation.rsamplers.imh(target,x0,lb,ub,opts,constraints)

INPUTS :

  • *target* : objective to MAXIMIZE

  • *x0* : vector of initial conditions

  • *lb* : lower bound

  • *ub* : upper bound

  • *opts* : options for the class. These include the properties from the superclass rise.engine.estimation.rsamplers.rwmh as well as the specific properties of the imh algorithm that can be found in the properties list.

  • *constraints* (optional): - Matrix (n_constraints x 2) where each row [a, b] enforces x(a) <= x(b)

OUTPUT:

  • *obj* : object of class rise.engine.estimation.rsamplers.imh

OWN PROPERTIES AND DEFAULT VALUES: None

INHERITED PROPERTIES : properties from rise.engine.estimation.rsamplers.rwmh

See also

rise.engine.estimation.rsamplers.rwmh, rise.engine.estimation.rsamplers.apt, rise.engine.estimation.rsamplers.rsampler

1.12.6. Algorithm : Adaptive parallel tempering

rise.engine.estimation.rsamplers.apt is the constructor for the Adaptive Parallel tempering algorithm following [Miasojedow et al., 2013]

The syntax is

obj = rise.engine.estimation.rsamplers.apt(target,x0,lb,ub)
obj = rise.engine.estimation.rsamplers.apt(target,x0,lb,ub,opts)
obj = rise.engine.estimation.rsamplers.apt(target,x0,lb,ub,opts,constraints)

INPUTS :

  • *target* : objective to MAXIMIZE

  • *x0* : vector of initial conditions

  • *lb* : lower bound

  • *ub* : upper bound

  • *opts* : options for the class. These include the properties from the superclass rise.engine.estimation.rsamplers.rwmh as well as the specific properties of the apt algorithm that can be found in the properties list below.

  • *constraints* (optional): - Matrix (n_constraints x 2) where each row [a, b] enforces x(a) <= x(b)

OUTPUT :

  • obj : object of class rise.engine.estimation.rsamplers.apt

OWN PROPERTIES AND DEFAULT VALUES:

  • *H* = 12 : Number of tempering stages, an integer of at least 2 (the chain swaps neighboring stages)

  • *alpha* = .234 : target acceptance rate

  • *alpha_swap* = .234 : target acceptance rate for swaps

  • *rwm_fixed_p* = 0 : prob of drawing from a fixed initial proposal

  • *rwm_exp* = 0.6 : Exponent of random-walk adaptation step size

  • *cov_exp* = 1 : Exponent of the step size of the proposal mean and covariance adaptation. 1 makes them running averages of all the draws (Haario et al. 2001). Smaller values weight the recent draws more, which makes the proposals follow the chain and under-disperses the draws: 0.6, the exponent before 2026-10, gave standard deviations 23% too small on a 26-parameter Gaussian after 50,000 iterations.

  • *adapt_until* = 10000 : Iterations during which the proposal scales, means and covariances and the temperatures adapt, counted over every run of the chain: a run continued from a previous result counts on from it, so a run split in segments gives the same draws as one run. Afterwards they are frozen and the chain is an exact (non-adaptive) parallel-tempering MCMC: discard at least the adaptation period. inf adapts throughout; a value below 1 is a fraction of the iterations of the chain’s first run (burnin + N*thinning).

  • *sw_exp_rm* = 0.6 : Exp. of temperature adaptation step size

  • *ram_adapt* = false : Use the robust AM adaptation

  • *separate_shape_adaptation* = true :separate covariance for each temperature. When false, the stages share one covariance (and one mean); with ram_adapt = true, each stage in turn updates the shared factor with 1/H of the step of the separate case

  • *fixed_temperatures* = false : fixed temperatures

INHERITED PROPERTIES : properties from rise.engine.estimation.rsamplers.rwmh

See also

rise.engine.estimation.rsamplers.rwmh, rise.engine.estimation.rsamplers.imh, rise.engine.estimation.rsamplers.rsampler

1.12.7. Algorithm : Slice Sampler

rise.engine.estimation.rsamplers.slice is the constructor for the slice algorithm following [Planas et al., 2015] and [Planas and Rossi, 2018]

The syntax is

obj = rise.engine.estimation.rsamplers.slice(target,x0,lb,ub)
obj = rise.engine.estimation.rsamplers.slice(target,x0,lb,ub,opts)
obj = rise.engine.estimation.rsamplers.slice(target,x0,lb,ub,opts,constraints)

INPUTS:

  • *target* : objective to MAXIMIZE

  • *x0* : vector of initial conditions

  • *lb* : lower bound

  • *ub* : upper bound

  • *opts* : options for the class. These include the properties from the superclass rise.engine.estimation.rsamplers.rsampler.

  • *constraints* (optional): - Matrix (n_constraints x 2) where each row [a, b] enforces x(a) <= x(b)

OUTPUT:

  • *obj* : object of class rise.engine.estimation.rsamplers.slice (a subclass of rise.engine.estimation.rsamplers.rsampler, like rise.engine.estimation.rsamplers.rwmh, but not an rwmh object)

OWN PROPERTIES AND DEFAULT VALUES: None

INHERITED PROPERTIES AND DEFAULT VALUES (from the base class rise.engine.estimation.rsamplers.rsampler):

  • *nchain* = 1 : number of chains

  • *N* = 5000 : number of draws

  • *thinning* =1 : number of thinning draws

  • *burnin* = 100 : burnin sample

  • *MaxTime* = inf : Max Time

  • *MaxFunEvals* = inf :

See also

rise.engine.estimation.rsamplers.apt, rise.engine.estimation.rsamplers.imh, rise.engine.estimation.rsamplers.rsampler, rise.engine.estimation.rsamplers.rwmh

1.12.8. Algorithm : usrsmplr Sampler

rise.engine.estimation.rsamplers.usrsmplr runs a sampling function that you write inside the sampler protocol of RISE. RISE supplies the target, the starting point, the admissible region and the chain options; your function returns the draws; sample stores them as it stores those of the built-in samplers, so that mcmc and mdd process them in the same way.

The syntax is

obj=rise.engine.estimation.rsamplers.usrsmplr(usersmplr,target,x0,lb,ub)
obj=rise.engine.estimation.rsamplers.usrsmplr(usersmplr,target,x0,lb,ub,opts)
obj=rise.engine.estimation.rsamplers.usrsmplr(usersmplr,target,x0,lb,ub,opts,constraints)
results=sample(obj)

INPUTS :

  • usersmplr : the sampling function, as a function handle or a name, or as a cell {fun,arg1,arg2,...} whose further entries are passed to the function after its seven standard inputs.

  • target, x0, lb, ub, constraints : as for rise.engine.estimation.rsamplers.rwmh: the function to MAXIMIZE (the log posterior kernel), the starting point, the bounds and the ordering constraints.

  • opts : the options N, burnin and nchain of the sampler class, and tunedCov (default: the identity).

THE SAMPLING FUNCTION is called once per chain as

[draws,logpost_vals,Sigma,funevals,accept_rate]=usersmplr(target,x0,tunedCov,N,burnin,frame,control,arg1,arg2,...)

Its inputs are:

  • target : the function to maximize, of a column vector. Where the function given to the constructor errors, it returns -1e+30. It does not check the bounds.

  • x0 : the starting point, a column vector.

  • tunedCov : the tunedCov option.

  • N, burnin : the N and burnin options: the number of draws to return and the number of iterations to discard before them.

  • frame : a function of a column vector that clamps it into the bounds and applies the ordering constraints; frame(x) equals x exactly when x is admissible.

  • control : the progress monitor; control(i) at iteration i advances the progress bar. Calling it is optional.

Its outputs are:

  • draws : a d x N matrix, the draws kept after burn-in, one per column.

  • logpost_vals : a 1 x N vector, the value of target at each draw. RISE stores it with the draw (field f); the best draw and the log-posterior values of mcmc and every estimator of mdd read it.

  • Sigma : the final proposal covariance, stored as SIG.

  • funevals : the number of evaluations of target.

  • accept_rate : the acceptance rate after burn-in.

RISE does not thin the draws, and it enforces neither MaxTime nor MaxFunEvals for this sampler: the function receives N and burnin only and keeps its own budget. Checkpointing (store_file) and delayed acceptance (da_surrogate) are refused. Passing the results of a previous sample as x0 continues each chain from its last draw, without burn-in, and appends the new draws.

EXAMPLE : a random-walk Metropolis sampler, saved as my_rwmh.m, whose extra input is the scale of the proposal. A proposal outside the admissible region is rejected rather than clamped onto its boundary.

function [draws,logpost_vals,Sigma,funevals,accept_rate]=my_rwmh(target,x0,tunedCov,N,burnin,frame,control,scale)
% MY_RWMH  random-walk Metropolis for rise.engine.estimation.rsamplers.usrsmplr

arguments

    target (1,1) function_handle

    x0 (:,1) double

    tunedCov double

    N (1,1) double

    burnin (1,1) double

    frame (1,1) function_handle

    control (1,1) function_handle

    scale (1,1) double = 1

end

d=numel(x0);

R=chol(tunedCov,'lower');

x=x0;

f=target(x);

funevals=1;

draws=zeros(d,N);

logpost_vals=zeros(1,N);

accepted=0;

for i=1:burnin+N

    xprop=x+scale*R*randn(d,1);

    if isequal(frame(xprop),xprop)

        fprop=target(xprop);

        funevals=funevals+1;

        if log(rand)<fprop-f

            x=xprop;

            f=fprop;

            if i>burnin

                accepted=accepted+1;

            end

        end

    end

    if i>burnin

        draws(:,i-burnin)=x;

        logpost_vals(i-burnin)=f;

    end

    control(i);

end

Sigma=tunedCov;

accept_rate=accepted/N;

end

and its use on an estimated model m_est:

[objective,lb,ub,x0,SIG]=pull_objective(m_est);

target=@(x)-objective(x);

opts=struct('N',2000,'burnin',500,'tunedCov',SIG);

obj=rise.engine.estimation.rsamplers.usrsmplr({@my_rwmh,0.5},target,x0,lb,ub,opts);

results=sample(obj);

mc=mcmc(results);

1.12.9. Tuning the proposal scale

The Metropolis-Hastings samplers (rwmh, imh) draw their proposals from a normal or t-student distribution with covariance c*tunedCov, and the scale c (default 1) decides how well the chain mixes. sample takes the tuning options as a second argument:

results = sample(smplr, struct('do_tuning', true));

Option

Default

Meaning

do_tuning

false

tune the scale c during the run

stepsize

100

iterations per tuning batch (both samplers)

alpha

0.234

target acceptance rate (random walk only)

persistence_rho

0.7

share of the previous correction kept at each update (random walk only)

TolFun_local

0.02

tolerance of a batch’s acceptance rate around alpha (random walk only)

TolFun_global

0.05

tolerance of the overall acceptance rate around alpha (random walk only)

max_success

4

tuning stops after max_success+1 successive batches within both tolerances (random walk only)

Random walk (rwmh). After each batch of stepsize iterations the scale is multiplied by a correction that moves the batch’s acceptance rate toward alpha: a batch that accepts too little shortens the steps, one that accepts too much lengthens them. Tuning stops once max_success+1 successive batches are within TolFun_local of alpha while the overall rate is within TolFun_global.

Independence sampler (imh). Its proposal does not move with the chain, so its acceptance rate measures how well the proposal covers the posterior, and the best scale is the one that maximizes it. Shrinking c toward a target rate, as the random walk does, makes an independence proposal narrower than the posterior and lowers its acceptance rate further (before this was fixed, the scale collapsed to about 1e-200 on a multimodal target). The sampler tries the scales c0*2^k, with c0 the starting c, for one batch of stepsize iterations each, from k=4 down to k=-4: broad proposals first, so that the chain finds where the posterior mass lies before the narrow ones are judged from there. A first, unscored batch at c0*2^4 moves the chain off its start, the center of the proposal, where it accepts nearly every proposal whatever the scale. The score of a scale is its estimated stationary acceptance rate: the chain’s states so far, each weighted by how long the chain stayed in it, stand for draws from the posterior, and the proposals made at that scale for draws from the proposal. All the scales are judged against the same states, so a narrow scale at which the chain stalls far out scores almost nothing without dragging down the scales tried meanwhile. While the best scale is at an edge of the grid, the grid grows by one step (up to c0*2^20 and c0*2^-20); a parabola in log2(c) through the best scale and its two neighbors then refines it by at most half a step, and c stays fixed for the rest of the run (results{1}.c reports it). alpha, persistence_rho, the two tolerances and max_success play no role. Two warnings can come up:

  • rsamplers:imhTuningFailed: no proposal was accepted at any scale of the grid. The scale stays at c0.

  • rsamplers:imhTuningAtSearchEdge: the acceptance rate was still rising at c0*2^20 (or c0*2^-20), where the search stops: tunedCov is far out of scale with the posterior.

The search takes at least ten batches (10*stepsize iterations). The draws made during the search come from several scales: set burnin to cover it so that the draws you keep come from the tuned proposal. The search relies on tunedCov being about the right size (the inverse Hessian at the mode is): a proposal hundreds of times narrower than the posterior leaves the chain drifting at every scale of the grid, and the search ends inside it. Checkpoints (store_file, below) save the state of either tuner, so a resumed chain continues the search where it stopped. The tutorial Estimation/independence_sampler_tuning tunes the independence sampler on the posterior of a regime-switching model.

1.12.10. Adaptation in the tempered sampler

apt adapts while it runs: each temperature’s proposal (its scale toward the target acceptance rate alpha, its mean and covariance toward those of the draws) and the temperatures themselves (toward alpha_swap between neighbors). Two options control it.

  • cov_exp (default 1) is the exponent of the step size of the mean and covariance adaptation. At 1 they are running averages of all the draws. A smaller exponent weights the recent draws more: the proposals then follow the chain where it happens to be, and the draws are too concentrated.

  • adapt_until (default 10000) is the number of iterations during which everything adapts, counted over every run of the chain. Afterwards the chain is an exact, non-adaptive parallel-tempering MCMC: discard at least that period as burn-in. inf adapts throughout. A value below 1 is a fraction of the iterations of the chain’s first run.

Until 2026-10 the means and covariances adapted with a step of n^-0.6 for the whole run, and a continued run restarted the adaptation clock. The table compares the former default, the present one and the random walk, on equal budgets (several seeds each; the dispersion ratio is the 5-95% range of the draws over the true one, 1 being right). The present apt froze after 10,000 iterations, except on the banana (40,000 of 200,000) and the RANK posterior (4,000 of 20,000):

Target

former apt

present apt

rwmh

Gaussian, 26 parameters (BBL RANK covariance), sd ratio

0.773

1.003

0.997

Gaussian, 10 parameters, condition number 1e4, sd ratio

0.947

1.001

1.001

Rosenbrock banana, 10 parameters, sd ratio

0.871

0.995

0.988

Bimodal mixture, weight of the larger mode (0.70)

0.741

0.705

0.669

Multivariate t, 3 degrees of freedom, dispersion ratio

0.695

1.018

1.005

BBL’s RANK posterior, sd ratio against the authors’ draws

0.645

0.986

1.060

BBL’s RANK posterior, log MDD (6590.6)

6585.4

6590.9

6591.0

On the RANK posterior, with 240,000 evaluations each, the random walk’s slowest coordinate has about 43 effective draws, against 75 to 107 for the present apt, hence its wider sd ratios (0.96 to 1.34, against 0.91 to 1.09).

Adapting throughout with running averages (adapt_until = inf) also removes the bias on these targets except the multivariate t, where the draws come out about 4% too dispersed even after 200,000 iterations: with infinite fourth moments the running covariance never settles. Freezing the adaptation makes the chain exact whatever the target, at a cost in ESS per evaluation of 0 to 30% against adapting throughout.

1.12.11. Delayed acceptance: surrogate-accelerated chains

The Metropolis-Hastings samplers (rwmh, imh) accept a da_surrogate option: a cheap approximation of the log posterior (e.g. @(x)predict(s, x) from a surrogate fitted by emulate) that screens every proposal before the true posterior is evaluated. Only proposals that survive the screen pay for a true evaluation, and a second accept/reject step keeps the chain’s stationary distribution exactly the true posterior, provided the surrogate is finite wherever the posterior is positive (where it is -Inf the screen rejects every proposal). Where the surrogate fails (it throws, or returns no real number), the step is a plain Metropolis-Hastings step on the true posterior. See the Surrogates chapter for the full story and a worked fs2000 example (~70% of true evaluations skipped, ~3x wall time).

1.12.12. Checkpointing and resuming chains

Long runs should not die with a crash. The Metropolis-Hastings samplers accept three persistence options:

opts.store_file  = 'mychain.mat';   % checkpoint file (MAT v7.3 = HDF5)
opts.store_every = 500;             % checkpoint frequency (iterations)
opts.resume      = false;           % restart from the checkpoint

With store_file set, the complete chain state – draws so far, current position, rng state, adaptive-tuning state, and the delayed-acceptance surrogate value when active – is written every store_every iterations (atomically: a crash mid-write cannot corrupt the previous checkpoint). Setting resume = true restarts from the checkpoint, and because the rng and tuning states are restored exactly, the continued chain is bit-for-bit the chain that would have run uninterrupted, provided it is the same chain: the same target, bounds, starting point, proposal and covariance, burn-in, thinning, kind of sampler (rwmh or imh), use of a delayed-acceptance surrogate and tuning options. The checkpoint records these settings, and a chain that resumes it with other ones stops with the error rsamplers:checkpointMismatch, naming the settings that differ; to start a new chain, set resume = false or use another store_file. Only N may change (a larger one extends the chain). The target is a function and cannot be compared, so the chain evaluates it at the current point of the checkpoint before it goes on: a value other than the recorded one raises the warning rsamplers:checkpointTargetChanged (the model, the data or the prior changed since the checkpoint was written, or the target is stochastic, as with a particle filter, where the warning is expected). A checkpoint written by an earlier version has no record of its settings and resumes with the warning rsamplers:checkpointUnsigned. A completed run can also be extended: resume with a larger N and the chain picks up where it stopped. With nchain > 1, _chain<k> is appended to the file name per chain. The tempered apt and slice samplers do not support checkpointing yet and error early rather than silently ignoring the option.

1.12.13. User-defined Algorithms: Another approach

The user-defined sampler above runs a sampling function inside the sampler protocol of RISE. A sampler that runs on its own can also be used, provided that its output is organized in the way RISE understands. Here is an example in which we write a wrapping function wrapped_dramrun around the delayed-rejection adaptive Metropolis (DRAM) sampler available here .

 1     function r=wrapped_dramrun(m,x0,SIG,N)
 2     % wrapped_dramrun : RISE wrapper for the DRAM code
 3
 4     arguments
 5
 6         m (1,1) rise.engine.models.rise_model
 7
 8         x0 double = []
 9
10         SIG double = []
11
12         N (1,1) double = 2000
13
14     end
15
16     [objective,lb,ub,x0_,vcov]=pull_objective(m);
17
18     if isempty(SIG)
19
20         SIG=vcov;
21
22     end
23
24     if isempty(x0)
25
26         x0=x0_;
27
28     end
29
30     % the inputs of DRAM: row vectors, minus twice the log posterior
31     model=struct();
32
33     model.ssfun=@(p,varargin)2*objective(p.');
34
35     data={};
36
37     param=struct();
38
39     param.par0=x0.';
40
41     param.bounds=[lb,ub].';
42
43     opts=struct();
44
45     opts.qcov=SIG;
46
47     opts.nsimu=N;
48
49     % call to the DRAM code
50     [results,chain]=dramrun(model,data,param,opts);
51
52     % the draws in the form RISE expects, each with its log posterior
53     draws=chain.';
54
55     f=zeros(1,N);
56
57     for id=1:N
58
59         f(id)=-objective(draws(:,id));
60
61     end
62
63     r=struct();
64
65     r.pop=struct('x',num2cell(draws,1),'f',num2cell(f));
66
67     [~,ibest]=max(f);
68
69     r.best=r.pop(ibest);
70
71     r.stats.accept_ratio=results.accepted;
72
73     r.stats.funevals=nan;
74
75     r.stats.time_elapsed=nan;
76
77     r.SIG=results.qcov;
78
79     r.c=results.adascale^2;
80
81     r.x0=x0;
82
83     end

As the code shows, there are three main articulations of the program :

  1. Obtain from RISE and from the user the inputs that DRAM requires

  2. Run DRAM

  3. Transform the output of DRAM so that it can be further processed by RISE

Obtaining the DRAM inputs

Some samplers can be run directly using the log-posterior kernel, which can be obtained in RISE through the function pull_objective: its first output is a function of a column vector of parameters that returns minus the log-posterior kernel, the prior included.

The DRAM code on the other hand works with “sums of squares”, minus twice the log densities, of a row vector of parameters: one function for the likelihood and an optional one for the prior. Twice the RISE objective is minus twice the log posterior, so the wrapper gives it to DRAM as the sum of squares and gives DRAM no prior function. RISE stores the parameters vertically while DRAM stores them horizontally, hence the transposition.

model.ssfun=@(p,varargin)2*objective(p.');

The other elements required by the DRAM code are easier to collect. These include : the starting vector (x0), the number of draws (N), the proposal covariance matrix (qcov), the bounds, and additional inputs to the sum of squares if any (data).

Running DRAM

With the inputs collected, we can then go ahead and run the DRAM sampler.

[results,chain]=dramrun(model,data,param,opts);

Transforming the DRAM output

If we want to process the output of DRAM through RISE, we need to transform the DRAM output in a form that RISE expects: one structure per chain, whose field pop holds each draw x with the value f of the log-posterior kernel at that draw, and whose fields best (the draw with the highest f), stats, SIG and c describe the run.

DRAM does not return the value of the posterior kernel at its draws, so the wrapper evaluates it there: N more evaluations of the posterior, the cost of N iterations of a sampler. Setting every f to nan (and best to any draw) saves them, but then only what depends on the draws alone is valid – the parameter statistics, densities, trace plots and convergence diagnostics of mcmc – and not what reads f: the best draw and the log-posterior values of mcmc, and every estimator of the marginal data density (mdd).

1.13. Processing Posterior draws : The mcmc class

1.13.3. Visualizing posteriors (and priors)

See Visualizing priors and posteriors.

1.14. Marginal Data Density computation : the mdd class

1.14.3. Initialization failures

A nonfinite or complex initial numeric log target returns no draws and the named SAMPLER_INVALID_START status. A callback that throws at the start retains its original exception identifier and stack. Proposal-time handling is unchanged. See Numerical failure statuses for the DRAM optional sixth output and the existing five-output callback protocol.