Skip to content

Instantly share code, notes, and snippets.

@stuhlmueller
Last active September 18, 2015 16:39
Show Gist options
  • Save stuhlmueller/1ee91b12b2f940509882 to your computer and use it in GitHub Desktop.
Save stuhlmueller/1ee91b12b2f940509882 to your computer and use it in GitHub Desktop.
function MCMC(s, k, a, wpplFn, options) {
var options = _.defaults(
_.clone(options),
{ samples: 100,
kernel: MHKernel,
lag: 0,
burn: 0 });
var log = function(s) {
if (options.verbose) {
console.log(s);
}
};
var acceptedCount = 0;
var aggregator = (options.justSample || options.onlyMAP) ?
new aggregation.MAPEstimator(options.justSample) :
new aggregation.Histogram();
var initialize, run, finish;
initialize = function(){
return Initialize(s, run, a, wpplFn);
};
run = function(s, initialTrace) {
var logAccepted = tapKernel(function(trace) { acceptedCount += trace.info.accepted; });
var printCurrIter = makePrintCurrIteration(log);
var collectSample = makeExtractValue(initialTrace, aggregator.add.bind(aggregator));
var kernel = sequenceKernels(options.kernel, printCurrIter, logAccepted);
var chain = sequenceKernels(
repeatKernel(options.burn, kernel),
repeatKernel(options.samples,
sequenceKernels(
repeatKernel(options.lag + 1, kernel),
collectSample)));
return chain(finish, initialTrace);
};
finish = function() {
var iterations = options.samples * (options.lag + 1) + options.burn;
log('Acceptance ratio: ' + acceptedCount / iterations);
return k(s, aggregator.toERP());
};
return initialize();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment