Skip to content

Using listeners to notify when sampling is complete

brian-lau edited this page Sep 25, 2014 · 12 revisions

StanFit objects issue a notification when sampling is complete. This is useful for automating things that should be done when sampling is finished. Below is a minimal example of listening for the exit notification:

model_code = {
'data {'
'    int<lower=0> N;'
'    int<lower=0,upper=1> y[N];'
'}'
'parameters {'
'    real<lower=0,upper=1> theta;'
'}'
'model {'
'for (n in 1:N)'
'    y[n] ~ bernoulli(theta);'
'}'
};

data = struct('N',10,'y',[0, 1, 0, 0, 0, 0, 0, 0, 0, 1]);

model = StanModel('model_code',model_code);

% Compile the Stan model. This takes a bit of time
model.compile();

% Create the StanFit object, with some extra warmup so the notification isn't immediately triggered
fit = model.sampling('data',data,'warmup',100000,'verbose',false);

% Attach the listener
addlistener(fit,'exit',@exitHandler);

where the listener callback is defined as (make sure this function is in your Matlab path):

function exitHandler(src,data)
   fprintf('\n');
   beep;
   fprintf('Listener notified!\n');
   fprintf('Stan finished. Chains exited with exitValue = \n');
   disp(src.exit_value)
   fprintf('\n');
end

Currently, notifications are sent only when sampling completes successfully. This may be expanded in the future to include different notifications. More information can be found in the Matlab documentation.

Clone this wiki locally