/* Constructor accepts feature values, class labels (-1 or +1) and sample weights; Passed data will be stored as a reference to original data; */ DSC::DSC(const mat &features, const ivec &classes, const vec &weights, const int &nThresholds) : N_THRESHOLDS(nThresholds), features(features), classes(classes), weights(weights) { /* Separating features by classes: */ mat class1Features = features.rows(find(classes == -1)); mat class2Features = features.rows(find(classes == +1)); /* Determining the ranges for each feature: */ minFeatures = min(features) - 1e-10; maxFeatures = max(features) + 1e-10; ranges = maxFeatures - minFeatures; /* Distribution of threshold values for each feature; */ mat class1ThresholdsMat = floor(((class1Features.each_row() - minFeatures).each_row() / ranges) * (N_THRESHOLDS - 1) + 1 - 1e-10); class1ThresholdsMat(find(class1ThresholdsMat < 0)).zeros(); mat class2ThresholdsMat = ceil(((class2Features.each_row() - minFeatures).each_row() / ranges) * (N_THRESHOLDS - 1) + 1 + 1e-10); class2ThresholdsMat(find(class2ThresholdsMat > N_THRESHOLDS - 1)).fill(N_THRESHOLDS - 1); /* Threshold values is vectorized by column: */ class1Thresholds = vectorise(class1ThresholdsMat); class2Thresholds = vectorise(class2ThresholdsMat); /* Providing indexes of features for each label; After that matrix is vectorized by column: */ featureIndexes1 = vectorise(repmat(linspace<rowvec>(0, features.n_cols - 1, features.n_cols), class1Features.n_rows, 1)); featureIndexes2 = vectorise(repmat(linspace<rowvec>(0, features.n_cols - 1, features.n_cols), class2Features.n_rows, 1)); }
LCP smooth_lcp(const sp_mat & smoother, const vector<sp_mat> & blocks, const mat & Q, const bvec & free_vars){ uint n = smoother.n_rows; assert(n == smoother.n_cols); uint A = blocks.size(); uint N = n*(A+1); assert(A >= 1); assert(size(n,n) == size(blocks.at(0))); assert(size(n,A+1) == size(Q)); assert(N == free_vars.n_elem); // Smooth blocks vector<sp_mat> sblocks = block_rmult(smoother,blocks); // Smooth Q mat sQ = mat(size(Q)); sQ.col(0) = Q.col(0); // State weights unchanged sQ.tail_cols(A) = smoother * Q.tail_cols(A); sp_mat M = build_M(sblocks); vec q = vectorise(sQ); return LCP(M,q,free_vars); }
rowvec Connectome::richClub(const mat &W, int klevel) { /* inputs: W: weighted connection matrix optional: k-level: max level of RC(k). When k-level is -1, k-level is set to max of degree of W output: rich: rich-club curve adopted from Opsahl et al. Phys Rev Lett, 2008, 101(16) */ rowvec nodeDegree = degree(W); if (klevel == -1) klevel = nodeDegree.max(); vec wrank = sort(vectorise(W),"descend"); rowvec Rw = rowvec(1,W.n_rows).fill(datum::nan); uvec smallNodes; for (uint kk=0;kk<klevel;++kk) { smallNodes = find(nodeDegree<kk+1); if (smallNodes.is_empty()) continue; mat cutOutW = W; smallNodes = sort(smallNodes,"descend"); for (uint i =0;i<smallNodes.n_elem;++i) { cutOutW.shed_row(smallNodes(i)); cutOutW.shed_col(smallNodes(i)); } double Wr = accu(cutOutW); uvec t = find(cutOutW != 0); if (!t.is_empty()) Rw(kk) = Wr/ accu(wrank.subvec(0,t.n_elem-1)); } return Rw; }
vec build_q_vec(const Simulator * sim, const Discretizer * disc, double gamma, bool include_oob){ uint N = disc->number_of_all_nodes(); uint n = disc->number_of_spatial_nodes(); // One oob nodes Points points = disc->get_spatial_nodes(); mat costs = sim->get_costs(points); uint A = sim->num_actions(); assert(size(n,A) == size(costs)); if(include_oob){ double tail = 1.0 / (1.0 - gamma); costs = join_vert(costs,tail*ones<rowvec>(A)); assert(size(N,A) == size(costs)); } vec weights = sim->get_state_weights(points); assert(n == weights.n_elem); if(include_oob){ weights = join_vert(weights,zeros<vec>(1)); assert(N == weights.n_elem); } vec q = join_vert(-weights,vectorise(costs)); if(include_oob) assert((A+1)*N == q.n_elem); else assert((A+1)*n == q.n_elem); return q; }
static inline bool is_converge (const int n, const cx_cube& r1, const cx_cube &r2, const double err) { for (int i=0; i<n; ++i) { const mat& tmp = abs(r1.slice(i)-r2.slice(i)); if (any(vectorise(tmp)>err)) { return false; } } return true; }
// [[Rcpp::export]] arma::mat BeQTL2(const arma::mat & A, const arma::mat & B, const arma::umat & Bootmat){ int bsi= Bootmat.n_rows; arma::mat C(A.n_cols*B.n_cols,Bootmat.n_rows); arma::mat tC(A.n_rows,B.n_rows); for(int i=0; i<bsi; i++){ tC = cor(A.rows(Bootmat.row(i)),B.rows(Bootmat.row(i))); C.col(i) = vectorise(tC,0); } C.elem(find_nonfinite(C)).zeros(); return reshape(median(C,1),A.n_cols,B.n_cols); }
//[[Rcpp::export]] List gp_gdp(vec y, mat X, mat cand_S, vec init, vec priors, int B, int burn, bool printProg) { int n = y.size(); int num_params = cand_S.n_rows; mat In = eye<mat>(n,n); int acc_rate = 0; mat param = zeros<mat>(B+burn,num_params); double log_ratio; vec cand = zeros<vec>(num_params); vec curr = zeros<vec>(num_params); List ret; clock_t start_time = clock(); int freq = 50; param.row(0) = reshape(init,1,num_params); Rcout << endl; for (int b=1; b<B+burn; b++) { // Update s2, phi, tau: curr = vectorise(param.row(b-1)); cand = mvrnorm(curr, cand_S); // s2, phi, tau, d1,...,dp log_ratio = log_like_plus_log_prior(y,X,cand,In,priors) - log_like_plus_log_prior(y,X,curr,In,priors); if ( log_ratio > log(randu()) ) { param.row(b) = reshape(cand,1,num_params); if (b > burn) acc_rate++; } else { param.row(b) = param.row(b-1); } if (printProg) time_remain(start_time, b, B+burn-1, freq); if (b % freq == 0) start_time = clock(); } Rcout << endl; param.col(0) = exp(param.col(0)); param.col(1) = (priors[3]*exp(param.col(1))+priors[2]) / ( exp(param.col(1))+1 );// inverse logit param.col(2) = exp(param.col(2)); Rcout <<"Acceptance Rate: " << acc_rate * 1.0 / B << endl; Rcout <<"The parameters in $param are 's2,phi,tau'" << endl; ret["param"] = param.tail_rows(B); //s2, phi, tau ret["acc_rate"] = acc_rate * 1.0 / B; ret["y"] = y; ret["X"] = X; ret["cand_S"] = cand_S; return ret; }
void origNISim::initialize() { mat W_t(maxVertexId, maxVertexId, fill::zeros); for (int i = 0; i < maxVertexId; i++) { int e = origGraphSrc[i + 1], s = origGraphSrc[i]; for (int j = s; j < e; j++) { W_t(i, origGraphDst[j]) = 1.0; } } double sumRow; double Degr = 0; for (int i = 0; i < maxVertexId; i++) { sumRow = 0; for (int j = 0; j < maxVertexId; j++) sumRow += W_t(i, j); if (sumRow == 0.0) { printf("node %d has no ingoing edges\n", i); } else { for (int j = 0; j < maxVertexId; j++) W_t(i, j) = W_t(i, j) / sumRow; } Degr += sumRow; } //start svd Mat<double> U; Col<double> s; Mat<double> V_t; svd(U, s, V_t, W_t); mat V = V_t.t(); U = U.submat(0, 0, maxVertexId - 1, Rank - 1); V = V.submat(0, 0, Rank - 1, maxVertexId - 1); s = s.submat(0, 0, Rank - 1, 0); Ku = kron(U, U);//kronecker roduct mat sigma = kron(s, s);//one column mat K_sigma = diagmat(sigma); Kv = kron(V, V); mat K_vu = Kv * Ku; mat I(maxVertexId, maxVertexId); I.eye(); A = inv(inv(K_sigma) - decayFactor * K_vu); V_r = Kv * vectorise(I); A.save(Apath); V_r.save(V_rpath); Kv.save(Kvpath); Ku.save(Kupath); }
void ArmadilloSolver::createSystem(float *kp0, float *kp1, int n_kp /*,int max_bases */) { /* * Generate y * */ if (this->debug) std::cout << "[DEBUG] \t Creating data and vectorizing..." << std::endl; // Note that these are transposed, since armadillo uses column-major ordering. fmat kp0_(kp0,2,n_kp, false, true); fmat kp1_(kp1,2,n_kp, false, true); fmat kp0t = kp0_.t(); fmat uv = (kp1_.t()-kp0t); this->y = vectorise(uv); // column-wise if (this->debug) std::cout << "[DEBUG] \t Creating A ..." << std::endl; /* * Generate A * */ int n_bases_per = this->nc/2; //if (max_bases > 0) // n_bases = min(max_bases,this->nc); this->A = zeros<fmat>(2*n_kp, 2*n_bases_per); fmat kp0tr = floor(kp0t); fvec indices_ = kp0tr.col(1) * this->pc_width + kp0tr.col(0); uvec indices = conv_to<uvec>::from(indices_); if (this->debug) std::cout << "[DEBUG] \t Filling A ..." << std::endl; fmat Au = this->flow_bases_u_t.rows(indices); fmat Av = this->flow_bases_v_t.rows(indices); this->A.submat(0,0,n_kp-1,n_bases_per-1) = Au; this->A.submat(n_kp,n_bases_per,2*n_kp-1,2*n_bases_per-1) = Av; if (this->debug) std::cout << "[DEBUG] \t Done." << std::endl; }
//Script that takes two matrices, performs bootstrapped correlation, and returns the median // [[Rcpp::export]] arma::mat BeQTL(const arma::mat & A, const arma::mat & B, const arma::umat & Bootmat){ int bsi= Bootmat.n_rows; Rcpp::Rcout<<"Starting Bootstrap!"<<std::endl; arma::mat C(A.n_cols*B.n_cols,Bootmat.n_rows); arma::mat tA(A.n_rows,A.n_cols); arma::mat tB(B.n_rows,B.n_cols); arma::mat tC(A.n_rows,B.n_rows); for(int i=0; i<bsi; i++){ tA = A.rows(Bootmat.row(i)); tB = B.rows(Bootmat.row(i)); tC = cor(tA,tB); C.col(i) = vectorise(tC,0); } C.elem(find_nonfinite(C)).zeros(); return reshape(median(C,1),A.n_cols,B.n_cols); }
//[[Rcpp::export]] mat one_pred_gp_gdp(mat X, vec y, mat param_row) { vec param = vectorise(param_row); double s2 = param[0]; double phi = param[1]; double tau = param[2]; vec d = param.tail(param.size()-3); int n = X.n_rows; mat XdX = xDx(X,d % d); mat K = tau * exp(-phi*XdX); mat Xt = X.t(); mat I = eye(n,n); mat S_i = (K.i() + I / s2).i(); vec mu = S_i*y / s2; vec pred_y = mvrnorm(mu,S_i); return reshape(pred_y,1,n); }
// [[Rcpp::export]] List rhierLinearModel_rcpp_loop(List const& regdata, mat const& Z, mat const& Deltabar, mat const& A, double nu, mat const& V, double nu_e, vec const& ssq, vec tau, mat Delta, mat Vbeta, int R, int keep, int nprint){ // Keunwoo Kim 09/16/2014 // Purpose: run hiearchical regression model // Arguments: // Data list of regdata,Z // regdata is a list of lists each list with members y, X // e.g. regdata[[i]]=list(y=y,X=X) // X has nvar columns // Z is nreg=length(regdata) x nz // Prior list of prior hyperparameters // Deltabar,A, nu.e,ssq,nu,V // note: ssq is a nreg x 1 vector! // Mcmc // list of Mcmc parameters // R is number of draws // keep is thining parameter -- keep every keepth draw // nprint - print estimated time remaining on every nprint'th draw // Output: // list of // betadraw -- nreg x nvar x R/keep array of individual regression betas // taudraw -- R/keep x nreg array of error variances for each regression // Deltadraw -- R/keep x nz x nvar array of Delta draws // Vbetadraw -- R/keep x nvar*nvar array of Vbeta draws // Model: // nreg regression equations // y_i = X_ibeta_i + epsilon_i // epsilon_i ~ N(0,tau_i) // nvar X vars in each equation // Prior: // tau_i ~ nu.e*ssq_i/chisq(nu.e) tau_i is the variance of epsilon_i // beta_i ~ N(ZDelta[i,],V_beta) // Note: ZDelta is the matrix Z * Delta; [i,] refers to ith row of this product! // vec(Delta) | V_beta ~ N(vec(Deltabar),Vbeta (x) A^-1) // V_beta ~ IW(nu,V) or V_beta^-1 ~ W(nu,V^-1) // Delta, Deltabar are nz x nvar // A is nz x nz // Vbeta is nvar x nvar // NOTE: if you don't have any z vars, set Z=iota (nreg x 1) // Update Note: // (Keunwoo Kim 04/07/2015) // Changed "rmultireg" to return List object, which is the original function. // Efficiency is almost same as when the output is a struct object. // Nothing different from "rmultireg1" in the previous R version. int reg, mkeep; mat Abeta, betabar, ucholinv, Abetabar; List regdatai, rmregout; unireg regout_struct; int nreg = regdata.size(); int nvar = V.n_cols; int nz = Z.n_cols; // convert List to std::vector of struct std::vector<moments> regdata_vector; moments regdatai_struct; // store vector with struct for (reg=0; reg<nreg; reg++){ regdatai = regdata[reg]; regdatai_struct.y = as<vec>(regdatai["y"]); regdatai_struct.X = as<mat>(regdatai["X"]); regdatai_struct.XpX = as<mat>(regdatai["XpX"]); regdatai_struct.Xpy = as<vec>(regdatai["Xpy"]); regdata_vector.push_back(regdatai_struct); } mat betas(nreg, nvar); mat Vbetadraw(R/keep, nvar*nvar); mat Deltadraw(R/keep, nz*nvar); mat taudraw(R/keep, nreg); cube betadraw(nreg, nvar, R/keep); if (nprint>0) startMcmcTimer(); //start main iteration loop for (int rep=0; rep<R; rep++){ // compute the inverse of Vbeta ucholinv = solve(trimatu(chol(Vbeta)), eye(nvar,nvar)); //trimatu interprets the matrix as upper triangular and makes solve more efficient Abeta = ucholinv*trans(ucholinv); betabar = Z*Delta; Abetabar = Abeta*trans(betabar); //loop over all regressions for (reg=0; reg<nreg; reg++){ regout_struct = runiregG(regdata_vector[reg].y, regdata_vector[reg].X, regdata_vector[reg].XpX, regdata_vector[reg].Xpy, tau[reg], Abeta, Abetabar(span::all,reg), nu_e, ssq[reg]); betas(reg,span::all) = trans(regout_struct.beta); tau[reg] = regout_struct.sigmasq; } //draw Vbeta, Delta | {beta_i} rmregout = rmultireg(betas,Z,Deltabar,A,nu,V); Vbeta = as<mat>(rmregout["Sigma"]); //conversion from Rcpp to Armadillo requires explict declaration of variable type using as<> Delta = as<mat>(rmregout["B"]); //print time to completion and draw # every nprint'th draw if (nprint>0) if ((rep+1)%nprint==0) infoMcmcTimer(rep, R); if((rep+1)%keep==0){ mkeep = (rep+1)/keep; Vbetadraw(mkeep-1, span::all) = trans(vectorise(Vbeta)); Deltadraw(mkeep-1, span::all) = trans(vectorise(Delta)); taudraw(mkeep-1, span::all) = trans(tau); betadraw.slice(mkeep-1) = betas; } } if (nprint>0) endMcmcTimer(); return List::create( Named("Vbetadraw") = Vbetadraw, Named("Deltadraw") = Deltadraw, Named("betadraw") = betadraw, Named("taudraw") = taudraw); }
PLCP approx_lcp(const sp_mat & value_basis, const sp_mat & smoother, const vector<sp_mat> & blocks, const mat & Q, const bvec & free_vars){ //Sizing and checking uint n = smoother.n_rows; assert(n == smoother.n_cols); uint A = blocks.size(); assert(A >= 1); assert(size(n,n) == size(blocks.at(0))); assert(size(n,A+1) == size(Q)); uint N = n*(A+1); assert(N == free_vars.n_elem); assert(n == value_basis.n_rows); // Smooth blocks vector<sp_mat> sblocks = block_rmult(smoother,blocks); // Build freebie flow bases for the smoothed problem bool ignore_q = false; vector<sp_mat> flow_bases; vec q; if(ignore_q){ flow_bases = make_freebie_flow_bases_ignore_q(value_basis, sblocks); // Project smoothed costs onto `freebie' basis mat sQ = mat(size(Q)); sQ.col(0) = Q.col(0); for(uint a = 0; a < A; a++){ sp_mat F = flow_bases.at(a); sQ.col(a+1) = F * F.t() * smoother * Q.col(a+1); } q = vectorise(sQ); } else{ mat sQ = mat(size(Q)); sQ.col(0) = Q.col(0); sQ.tail_cols(A) = smoother * Q.tail_cols(A); q = vectorise(sQ); flow_bases = make_freebie_flow_bases(value_basis, sblocks, sQ); } // Build the basis blocks and the basis matrix block_sp_vec p_blocks; p_blocks.reserve(A + 1); p_blocks.push_back(value_basis); p_blocks.insert(p_blocks.end(), flow_bases.begin(), flow_bases.end()); assert((A+1) == p_blocks.size()); sp_mat P = block_diag(p_blocks); // Build LCP matrix M and the U coefficient matrix sp_mat M = build_M(sblocks);// + 1e-10 * speye(N,N); // Regularize sp_mat U = P.t() * M * P * P.t(); return PLCP(P,U,q,free_vars); }
SegImage* MeanFiller::fillDynamic(int startX, int startY, int startZ, int startRadius) { int cols, rows, slices; int minx, miny, minz, maxx, maxy, maxz; cube sample, xes; vec values; stack<triple> historyEntity; image->getSize(cols, rows, slices); cube result = zeros(rows, cols, slices); cube sphere = Utils::sphere(startRadius); result(startY, startX, startZ, arma::size(sphere)) = sphere; res_image = Utils::convert(result); Utils::bounds(result, minx, miny, minz, maxx, maxy, maxz); double thres; history.clear(); result.reset(); if (minx < 3) minx = 3; if (maxx > cols - 2) maxx = cols - 2; if (miny < 3) miny = 3; if (maxy > rows - 2) maxy = rows - 2; if (minz < 3) minz = 3; if (maxz > slices - 2) maxz = slices - 2; bool flag = false; while (!flag) { flag = true; xes = Utils::convert_d(image->getRegion(minx, miny, maxx, maxy, minz, maxz)); sample = wBright * Utils::convert_d(res_image->getRegion(minx, miny, maxx, maxy, minz, maxz)) + wCurv * xes; sample = Utils::conv3(Utils::conv3(sample, kernel), kernel); sample %= -xes + 1; values = sort(nonzeros(vectorise(sample))); thres = values(quantile * values.size()); for (int i = minx; i < maxx; i++) { for (int j = miny; j < maxy; j++) { for (int k = minz; k < maxz; k++) { if (image->getVoxel(i, j, k) > 0 && res_image->getVoxel(i, j, k) == 0) { if (sample(j-miny, i - minx, k - minz) > thres) { res_image->setVoxel(i, j, k, 255); if (i <= minx && i >= 4) minx = i - 1; if (i >= maxx && i <= cols - 4 && maxx < i + 1) maxx = i + 1; if (j <= miny && j >= 4) miny = j - 1; if (j >= maxy && j <= rows - 4 && maxy < j + 1) maxy = j + 1; if (k <= minz && k >= 4) minz = k - 1; if (k >= maxz && k <= slices - 4 && maxz < k + 1) maxz = k + 1; historyEntity.push(triple(i, j, k)); flag = false; } } } } } if (!flag) { if (history.size() >= h_size) { stack<triple> first = history.back(); while (!first.empty()) { first.pop(); } history.pop_back(); } history.push_front(historyEntity); } } return res_image; }
//Class constructor TimeSegmentation(Tobj &G, Col <T1> map_in, Col <T1> timeVec_in, uword a, uword b, uword c, uword interptype = 1, uword shots = 1) { cout << "Entering Class constructor" << endl; n1 = a; //Data size n2 = b;//Image size L = c; //number of time segments type = interptype; // type of time segmentation performed Nshots = shots; // number of shots obj = &G; fieldMap = map_in; cout << "N1 = " << n1 << endl; cout << "N2 = " << n2 << endl; cout << "L = " << L << endl; AA.set_size(n1, L); //time segments weights timeVec = timeVec_in; T_min =timeVec.min(); T1 rangt = timeVec.max()-T_min; tau = (rangt + datum::eps) / (L - 1); // it was L-1 before timeVec = timeVec-T_min; uword NOneShot = n1/Nshots; if (L==1) { tau = 0; AA.ones(); } else { Mat <CxT1> tempAA(NOneShot, L); if (type==1) {// Hanning interpolator cout << "Hanning interpolation" << endl; for (unsigned int ii = 0; ii<L; ii++) { for (unsigned int jj = 0; jj<NOneShot; jj++) { if ((std::abs(timeVec(jj)-((ii)*tau)))<=tau) { tempAA(jj, ii) = 0.5+0.5*std::cos((datum::pi)*(timeVec(jj)-((ii)*tau))/tau); } else { tempAA(jj, ii) = 0.0; } } } AA = repmat(tempAA, Nshots, 1); } else if (type==2) { // Min-max interpolator: Exact LS interpolator cout << "Min Max time segmentation" << endl; Mat <CxT1> Ltp; Ltp.ones(1, L); Col <CxT1> ggtp; ggtp.ones(n2, 1); Mat <CxT1> gg; gg = exp(i*fieldMap*tau)*Ltp; Mat <CxT1> iGTGGT; iGTGGT.set_size(L+1, n2); Mat <CxT1> gl; gl.zeros(n2, L); for (unsigned int ii = 0; ii<L; ii++) { for (unsigned int jj = 0; jj<n2; jj++) { gl(jj, ii) = pow(gg(jj, ii), (T1) (ii+1)); } } Mat <CxT1> G; G.set_size(n2, L); for (unsigned int jj = 0; jj<L; jj++) { if (jj==0) { G.col(jj) = ggtp; } else { G.col(jj) = gl.col(jj-1); } } Col <CxT1> glsum; Mat <CxT1> GTG; GTG.zeros(L, L); GTG.diag(0) += n2; glsum = sum(gl.t(), 1); Mat <CxT1> GTGtp(L, L); for (unsigned int ii = 0; ii < (L - 1); ii++) { GTGtp.zeros(); GTGtp.diag(-(T1) (ii+1)) += glsum(ii); GTGtp.diag((T1) (ii+1)) += std::conj(glsum(ii)); GTG = GTG+GTGtp; } T1 rcn = 1/cond(GTG); if (rcn>10*2e-16) { //condition number of GTG iGTGGT = inv(GTG)*G.t(); } else { iGTGGT = pinv(GTG)*G.t(); // pseudo inverse } Mat <CxT1> iGTGGTtp; Mat <CxT1> ftp; Col <CxT1> res, temp; for (unsigned int ii = 0; ii<NOneShot; ii++) { ftp = exp(i*fieldMap*timeVec(ii)); res = iGTGGT*ftp; tempAA.row(ii) = res.t(); } AA = repmat(tempAA, Nshots, 1); } } savemat("aamat.mat", "AA", vectorise(AA)); cout << "Exiting class constructor." << endl; }
//[[Rcpp::export]] List rhierMnlRwMixture_rcpp_loop(List const& lgtdata, mat const& Z, vec const& deltabar, mat const& Ad, mat const& mubar, mat const& Amu, double nu, mat const& V, double s, int R, int keep, int nprint, bool drawdelta, mat olddelta, vec const& a, vec oldprob, mat oldbetas, vec ind, vec const& SignRes){ // Wayne Taylor 10/01/2014 int nlgt = lgtdata.size(); int nvar = V.n_cols; int nz = Z.n_cols; mat rootpi, betabar, ucholinv, incroot; int mkeep; mnlMetropOnceOut metropout_struct; List lgtdatai, nmix; // convert List to std::vector of struct std::vector<moments> lgtdata_vector; moments lgtdatai_struct; for (int lgt = 0; lgt<nlgt; lgt++){ lgtdatai = lgtdata[lgt]; lgtdatai_struct.y = as<vec>(lgtdatai["y"]); lgtdatai_struct.X = as<mat>(lgtdatai["X"]); lgtdatai_struct.hess = as<mat>(lgtdatai["hess"]); lgtdata_vector.push_back(lgtdatai_struct); } // allocate space for draws vec oldll = zeros<vec>(nlgt); cube betadraw(nlgt, nvar, R/keep); mat probdraw(R/keep, oldprob.size()); vec loglike(R/keep); mat Deltadraw(1,1); if(drawdelta) Deltadraw.zeros(R/keep, nz*nvar);//enlarge Deltadraw only if the space is required List compdraw(R/keep); if (nprint>0) startMcmcTimer(); for (int rep = 0; rep<R; rep++){ //first draw comps,ind,p | {beta_i}, delta // ind,p need initialization comps is drawn first in sub-Gibbs List mgout; if(drawdelta) { olddelta.reshape(nvar,nz); mgout = rmixGibbs (oldbetas-Z*trans(olddelta),mubar,Amu,nu,V,a,oldprob,ind); } else { mgout = rmixGibbs(oldbetas,mubar,Amu,nu,V,a,oldprob,ind); } List oldcomp = mgout["comps"]; oldprob = as<vec>(mgout["p"]); //conversion from Rcpp to Armadillo requires explict declaration of variable type using as<> ind = as<vec>(mgout["z"]); //now draw delta | {beta_i}, ind, comps if(drawdelta) olddelta = drawDelta(Z,oldbetas,ind,oldcomp,deltabar,Ad); //loop over all LGT equations drawing beta_i | ind[i],z[i,],mu[ind[i]],rooti[ind[i]] for(int lgt = 0; lgt<nlgt; lgt++){ List oldcomplgt = oldcomp[ind[lgt]-1]; rootpi = as<mat>(oldcomplgt[1]); //note: beta_i = Delta*z_i + u_i Delta is nvar x nz if(drawdelta){ olddelta.reshape(nvar,nz); betabar = as<vec>(oldcomplgt[0])+olddelta*vectorise(Z(lgt,span::all)); } else { betabar = as<vec>(oldcomplgt[0]); } if (rep == 0) oldll[lgt] = llmnl_con(vectorise(oldbetas(lgt,span::all)),lgtdata_vector[lgt].y,lgtdata_vector[lgt].X,SignRes); //compute inc.root ucholinv = solve(trimatu(chol(lgtdata_vector[lgt].hess+rootpi*trans(rootpi))), eye(nvar,nvar)); //trimatu interprets the matrix as upper triangular and makes solve more efficient incroot = chol(ucholinv*trans(ucholinv)); metropout_struct = mnlMetropOnce_con(lgtdata_vector[lgt].y,lgtdata_vector[lgt].X,vectorise(oldbetas(lgt,span::all)), oldll[lgt],s,incroot,betabar,rootpi,SignRes); oldbetas(lgt,span::all) = trans(metropout_struct.betadraw); oldll[lgt] = metropout_struct.oldll; } //print time to completion and draw # every nprint'th draw if (nprint>0) if ((rep+1)%nprint==0) infoMcmcTimer(rep, R); if((rep+1)%keep==0){ mkeep = (rep+1)/keep; betadraw.slice(mkeep-1) = oldbetas; probdraw(mkeep-1, span::all) = trans(oldprob); loglike[mkeep-1] = sum(oldll); if(drawdelta) Deltadraw(mkeep-1, span::all) = trans(vectorise(olddelta)); compdraw[mkeep-1] = oldcomp; } } if (nprint>0) endMcmcTimer(); nmix = List::create(Named("probdraw") = probdraw, Named("zdraw") = R_NilValue, //sets the value to NULL in R Named("compdraw") = compdraw); //ADDED FOR CONSTRAINTS //If there are sign constraints, return f(betadraws) as "betadraws" //conStatus will be set to true if SignRes has any non-zero elements bool conStatus = any(SignRes); if(conStatus){ int SignResSize = SignRes.size(); //loop through each sign constraint for(int i = 0;i < SignResSize; i++){ //if there is a constraint loop through each slice of betadraw if(SignRes[i] != 0){ for(int s = 0;s < R/keep; s++){ betadraw(span(),span(i),span(s)) = SignRes[i] * exp(betadraw(span(),span(i),span(s))); } } }//end loop through SignRes } if(drawdelta){ return(List::create( Named("Deltadraw") = Deltadraw, Named("betadraw") = betadraw, Named("nmix") = nmix, Named("loglike") = loglike, Named("SignRes") = SignRes)); } else { return(List::create( Named("betadraw") = betadraw, Named("nmix") = nmix, Named("loglike") = loglike, Named("SignRes") = SignRes)); } }