#include "RcppArmadillo.h" //Indicates shared library (aka package in R terms). using namespace arma; //Needed to avoid interference between libraries. using namespace Rcpp; // [[Rcpp::depends(RcppArmadillo)]] //including necessary CPP(!) functions from bayesm package //timing functions time_t itime; char buf[100]; void startMcmcTimer() { itime = time(NULL); Rcout << " MCMC Iteration (est time to end - min) \n"; } void infoMcmcTimer(int rep, int R) { time_t ctime = time(NULL); char buf[32]; double timetoend = difftime(ctime, itime) / 60.0 * (R - rep - 1) / (rep+1); sprintf(buf, " %d (%.1f)\n", rep+1, timetoend); Rcout << buf; } void endMcmcTimer() { time_t ctime = time(NULL); char buf[32]; sprintf(buf, " Total Time Elapsed: %.2f \n", difftime(ctime, itime) / 60.0); Rcout << buf; itime = 0; } //function to draw from mv student t distribution //[[Rcpp::export]] vec rmvst(double nu, vec const& mu, mat const& root){ // nu df, mean mu, Sigma=t(root)%*%root // root is upper triangular cholesky root vec rnormd = rnorm(mu.size()); vec nvec = trans(root)*rnormd; return(nvec/sqrt(rchisq(1,nu)[0]/nu) + mu); //rchisq returns a vectorized object, so using [0] allows for the conversion to double } //function to compute log likelihood of MNL //[[Rcpp::export]] double llmnl(vec const& beta, vec const& y, mat const& X){ int n = y.size(); int j = X.n_rows/n; mat Xbeta = X*beta; vec xby = zeros(n); vec denom = zeros(n); for(int i = 0; i(ncolX); rowvec beta = zeros(ncolX); double cloglike, clpost, climp, ldiff, alpha, unif, oldloglike; vec alphaminv; if(nprint>0) startMcmcTimer(); // start main iteration loop for(int rep = 0; rep0) if ((rep+1)%nprint==0) infoMcmcTimer(rep, R); if((rep+1)%keep==0){ mkeep = (rep+1)/keep; betadraw(mkeep-1,span::all) = beta; loglike[mkeep-1] = oldloglike; } } if(nprint>0) endMcmcTimer(); return List::create( Named("betadraw") = betadraw, Named("loglike") = loglike, Named("naccept") = naccept); }