Example #1
0
inline const auto
join_cols(const Base<typename T1::elem_type,T1>& A,
          const Base<typename T1::elem_type,T2>& B,
          const Base<typename T1::elem_type,T3>& C)
{
    return join_cols(join_cols(A, B), C);
}
Example #2
0
/* Conditional on other individual */
double F1(unsigned row, unsigned cause, unsigned indiv, unsigned cond_cause, const DataPairs &data, const gmat &sigma, vec u){

  // Other individual
  unsigned cond_indiv;
  if (indiv==0){
    cond_indiv=1;
  }
  else {
    cond_indiv=0;
  }

  // Alpgam of other individual
  double cond_alp = data.alphaMarg_get(row, cond_cause, cond_indiv);
  double cond_gam = data.gammaMarg_get(row, cond_cause, cond_indiv);
  double cond_alpgam = cond_alp - cond_gam;

  vec vcond_alpgam(1); vcond_alpgam(0) = cond_alpgam;

  // Joining u vector and alpgam from other individual
  vec alpgamu = join_cols(vcond_alpgam, u);

  // Attaining variance covariance matrix etc. (conditional on u and other individual)
  vmat cond_sig = sigma(cause,cond_cause);
  double cond_mean = as_scalar(cond_sig.proj*alpgamu);

  double alp = data.alphaMarg_get(row, cause, indiv);
  double gam = data.gammaMarg_get(row, cause, indiv);
  double alpgam = alp - gam;

  double F1 = data.piMarg_get(row, cause, indiv)*pn(alpgam, cond_mean, as_scalar(cond_sig.vcov));
  return(F1);
};
void ImageProcessor::process(cv::Mat& image) {
    cv::resize(image, image, cv::Size(640,480));
    
    cv::Mat 	inputImgGray;
    cv::Mat 	inputImgRGB;
    inputImgRGB =  image;
    cv::cvtColor( inputImgRGB, inputImgGray, cv::COLOR_BGR2GRAY );
    
    // ======== Matches between reference image and input image =======
    
    timer.start();
    
    // may mistakenly track some points out of the actual image
    matchesAll = keypointMatcher->MatchImages3D2D(inputImgGray); // TODO: Make the input gray image
    
    timer.stop();
    cout << "Number of 3D-2D Fern matches: " << matchesAll.n_rows << endl;
    cout << "Total time for matching: " << timer.getElapsedTimeInMilliSec() << " ms" << endl;
    
    // ================== Track inlier matches ========================
    // make the last frame's inlier matches to be checked to avoid viaration
    
    // if sudden change between two frames, those inliermatches won't exist any more.
    mat trackedMatches = matchTracker.TrackMatches(inputImgGray, matchesInlier);
    matchesAll 		   = join_cols(matchesAll, trackedMatches);
    
    // ============== Reconstruction without constraints ==============
    timer.start();
    // eliminate error matches
    reconstruction->ReconstructPlanarUnconstrIter( matchesAll, resMesh, inlierMatchIdxs );
    
    matchesInlier = matchesAll.rows(inlierMatchIdxs);
    
    timer.stop();
    cout << "Number of inliers in unconstrained recontruction: " << inlierMatchIdxs.n_rows << endl;
    cout << "Unconstrained reconstruction time: " << timer.getElapsedTimeInMilliSec() << " ms" << endl;
    
    // ============== Constrained Optimization =======================
    if (inlierMatchIdxs.n_rows > DETECT_THRES)
    {
        timer.start();
        
        vec cInit = reshape( resMesh.GetCtrlVertices(), resMesh.GetNCtrlPoints()*3, 1 );	// x1 x2..y1 y2..z1 z2..
        
        reconstruction->ReconstructIneqConstr(cInit, resMesh);
        
        timer.stop();
        cout << "Constrained reconstruction time: " << timer.getElapsedTimeInMilliSec() << " ms \n\n";
    }
    
    // Visualization
    if (inlierMatchIdxs.n_rows > DETECT_THRES)
    {
        Visualization::DrawProjectedMesh( image, resMesh, modelCamCamera, MESH_COLOR );
    }
    //if (isDisplayPoints) {
    //Visualization::DrawVectorOfPointsAsPlus(inputImg, matchTracker.GetGoodTrackedPoints(), INLIER_KPT_COLOR);
    Visualization::DrawPointsAsDot( image, matchesAll.cols(6,7), KPT_COLOR );				  // All points
    Visualization::DrawPointsAsDot( image, matchesInlier.cols(6,7), INLIER_KPT_COLOR );// Inlier points
}
Example #4
0
vec sem::update_d(double tol, int max_iter)
{
    int i;
    double conv_crit = 1.0;
    int counter = 0;
    double old_obj, new_obj;
    new_obj = get_objective();

    //pre-allocate memory for gradient, hessian and update
    vec grad(v_ + gamma_indices_.n_elem);
    mat hessian(v_ + gamma_indices_.n_elem, v_ + gamma_indices_.n_elem);
    vec update(v_ + gamma_indices_.n_elem);

    while(conv_crit > tol && counter < max_iter) {
        old_obj = new_obj;

        // build in backtracking if necessary
        set_gradient_hessian(grad, hessian);
        update =  join_cols(lambda_, gamma_) - solve(hessian, grad);

        lambda_ = update(0, v_ - 1);
        gamma_ = update(v_, v_ + gamma_indices_.n_elem);

        new_obj = get_objective();
        conv_crit = fabs((new_obj - old_obj)/old_obj);
        counter++;
    }
}
Example #5
0
//[[Rcpp::export]]
vec breg(vec const& y, mat const& X, vec const& betabar, mat const& A) {

// Keunwoo Kim 06/20/2014

// Purpose: draw from posterior for linear regression, sigmasq=1.0

// Output: draw from posterior
 
// Model: y = Xbeta + e  e ~ N(0,I)

// Prior:  beta ~ N(betabar,A^-1)

  int k = betabar.size();
  mat RA = chol(A);
  mat W = join_cols(X, RA); //same as rbind(X,RA)
  vec z = join_cols(y, RA*betabar);
  mat IR = solve(trimatu(chol(trans(W)*W)), eye(k,k)); //trimatu interprets the matrix as upper triangular and makes solve more efficient
  
  return ((IR*trans(IR))*(trans(W)*z) + IR*vec(rnorm(k)));
} 
Example #6
0
rowvec dF1du(unsigned row, unsigned cause, unsigned indiv, unsigned cond_cause, const DataPairs &data, const gmat &sigma, vec u){

  // Other individual
  unsigned cond_indiv;
  if (indiv==0){
    cond_indiv=1;
  }
  else {
    cond_indiv=0;
  }

  // Alpgam of other individual
  double cond_alp = data.alphaMarg_get(row, cond_cause, cond_indiv);
  double cond_gam = data.gammaMarg_get(row, cond_cause, cond_indiv);
  double cond_alpgam = cond_alp - cond_gam;

  vec vcond_alpgam(1); vcond_alpgam(0) = cond_alpgam;

  // Joining u vector and alpgam from other individual
  vec alpgamu = join_cols(vcond_alpgam, u);

  // Attaining variance covariance matrix etc. (conditional on u and other individual)
  vmat cond_sig = sigma(cause,cond_cause);
  double cond_mean = as_scalar(cond_sig.proj*alpgamu);

  double alp = data.alphaMarg_get(row, cause, indiv);
  double gam = data.gammaMarg_get(row, cause, indiv);
  double alpgam = alp - gam;
  double c_alpgam = alpgam - cond_mean;

  double inner = pow((c_alpgam),2)*as_scalar(cond_sig.inv);

  double cdf = pn(alpgam, cond_mean, as_scalar(cond_sig.vcov));
  double pdf = invsqtwopi*1/sqrt(as_scalar(cond_sig.vcov))*exp(-0.5*inner);

  uvec upos = zeros<uvec>(u.n_rows);
  for (unsigned h=0; h<u.n_rows; h++){
    upos(h) = h + 1;
  };

  mat proj = cond_sig.proj;
  rowvec dcdfdu = pdf*(-proj.cols(upos));
  rowvec dF1du = data.dpiduMarg_get(row, cause, indiv)*cdf + data.piMarg_get(row, cause, indiv)*dcdfdu;

  return(dF1du);
};
Example #7
0
/*
    "getBestStump()" function saves the best decision stump's threshold, weak hypothesis and its error;
*/
void DSC::getBestStump(Threshold &threshold, ivec &hypothesis, double &error)
{
    /* Separating weights by classes: */
    mat class1Weights = weights(find(classes == -1));
    mat class2Weights = weights(find(classes == +1));

    /* Accumulate weights for given thresholds ("number of thresholds" x "number of features"): */
    mat thresholdWeights1 = accumarray(join_rows(class1Thresholds, featureIndexes1),
                                       repmat(class1Weights, features.n_cols, 1),
                                       SizeMat(N_THRESHOLDS, features.n_cols));
    mat thresholdWeights2 = accumarray(join_rows(class2Thresholds, featureIndexes2),
                                       repmat(class2Weights, features.n_cols, 1),
                                       SizeMat(N_THRESHOLDS, features.n_cols));

    /*
        Looking for threshold with minimum error;
        Here we construct cummulative sum of weights for seaprate classes, then we add them;
        In order to find the smallest error, we consider both directions of a threshold;
    */
    mat thresholdErrors = flipud(cumsum(flipud(thresholdWeights1))) + cumsum(thresholdWeights2);
    thresholdErrors = join_cols(thresholdErrors, sum(weights) - thresholdErrors);
    uword index;
    uword featureType;
    error = thresholdErrors.min(index, featureType);
    threshold.featureType = featureType;
    if (index > N_THRESHOLDS - 1)
    {
        threshold.direction = -1;
        index -= N_THRESHOLDS;
    }
    else
    {
        threshold.direction = +1;
    }

    threshold.value = minFeatures(featureType) + (ranges(featureType) / N_THRESHOLDS) * index;

    /* Evaluating hypothesis for derived threshold: */
    classify(threshold, features, hypothesis);

    return;
}
Example #8
0
ArmadilloSolver::ArmadilloSolver(
        float *p_flow_bases_u,
        float *p_flow_bases_v,
        float *p_cov_matrix,
        int p_pc_width,
        int p_pc_height,
        int p_nc,
        int p_nc_max_per,
        double p_sigma,
        double p_lambda,
        int p_debug,
        int n_iters)
{
    // Copy parameters
    this->pc_width = p_pc_width;
    this->pc_height = p_pc_height;
    this->nc = p_nc;
    this->sigma_sq = p_sigma * p_sigma;
    this->lambda = p_lambda;
    this->debug = p_debug;
    this->n_iters = n_iters;
    
    // Copy pointers to raw data of the flow bases.
    //this->flow_bases_u = flow_bases_u;
    //this->flow_bases_v = flow_bases_v;
    
    // These matrices are of size (width*height) x n_bases.
    this->flow_bases_u_t = fmat(p_flow_bases_u, p_pc_width*p_pc_height, p_nc/2);
    this->flow_bases_v_t = fmat(p_flow_bases_v, p_pc_width*p_pc_height, p_nc/2);

    // If we want less cols, remove them here.
    this->flow_bases_u_t = this->flow_bases_u_t.head_cols(p_nc/2);
    this->flow_bases_v_t = this->flow_bases_v_t.head_cols(p_nc/2);
   
    // Generate covariance matrix
    fmat cov(p_cov_matrix, 2*p_nc_max_per,2*p_nc_max_per);
    // Armadillo stores the matrices as column-major. But cov is symmetric, so this is not a problem.

    if (p_nc_max_per == p_nc/2)
    {
      // We use the full covariance matrix
      // Generate Q as inverse of covariance matrix with some slight regularization.
      mat Q_ = this->lambda * (conv_to<mat>::from(cov) + eye<mat>(p_nc,p_nc)).i();
      this->Q = conv_to<fmat>::from(Q_);
    }
    else {
      if (0) { // Old-style inversion
      	mat Q_ = this->lambda * (conv_to<mat>::from(cov) + eye<mat>(2*p_nc_max_per,2*p_nc_max_per)).i();
        uvec inds(p_nc);

        inds.subvec(0,p_nc/2-1) = linspace<uvec>(0,p_nc/2-1,p_nc/2);
        inds.subvec(p_nc/2,p_nc-1) = linspace<uvec>(0,p_nc/2-1,p_nc/2)+p_nc_max_per;

	    this->Q = conv_to<fmat>::from(Q_(inds,inds));
      }
      else { // New style
	    uvec inds = join_cols(linspace<uvec>(0,p_nc/2-1,p_nc/2),
			      linspace<uvec>(p_nc_max_per, p_nc_max_per+p_nc/2-1,p_nc/2));
			    
        fmat cov2 = cov(inds,inds);
      	mat Q_ = this->lambda * (conv_to<mat>::from(cov2) + eye<mat>(p_nc,p_nc)).i();
        this->Q = conv_to<fmat>::from(Q_);
      }
	
    }

      
      // 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->Q = this->lambda * (cov + eye<fmat>(p_nc,p_nc)).i();

    if (this->debug)
    {
        std::cout << "[DEBUG] Initialized ArmadilloSolver." << std::endl;
        std::cout << "[DEBUG] Using " << this->nc << " basis vectors." << std::endl;
    }
}
Example #9
0
/******************************************************************
 * 函数功能:几何校正
 * 
 * 待写:H_final的值也应该返回去
 */
arma::uvec geometricVerification(const arma::mat &frames1, const arma::mat &frames2, 
	const arma::mat &matches, const superluOpts &opts){
	// 测试载入是否准确
    /*std::cout<< "element测试: " << " x: " << frames1(0,1) << " y: " << frames1(1,1) << std::endl;
    std::cout << " 行数: " << frames1.n_rows << " 列数:" << frames1.n_cols << std::endl;
    std::cout << "==========================================================" << std::endl;*/

	int numMatches = matches.n_cols;
	// 测试匹配数目是否准确
    /*std::cout << "没有RANSAC前匹配数目: " << numMatches << std::endl;
    std::cout << "==========================================================" << std::endl;*/

	arma::field<arma::uvec> inliers(1, numMatches);
	arma::field<arma::mat> H(1, numMatches);

	arma::uvec v = arma::linspace<arma::uvec>(0,1,2);
    arma::mat onesVector = arma::ones(1, matches.n_cols);
	arma::uvec matchedIndex_Query = arma::conv_to<arma::uvec>::from(matches.row(0)-1);
	arma::uvec matchedIndex_Object = arma::conv_to<arma::uvec>::from(matches.row(1)-1);

	arma::mat x1 = frames1(v, matchedIndex_Query) ;
	arma::mat x2 = frames2(v, matchedIndex_Object);
    /*std::cout << " x1查询图像匹配行数: " << x1.n_rows << " 查询图像匹配列数:" << x1.n_cols << std::endl;
    std::cout << " x2目标图像匹配行数: " << x2.n_rows << " 目标图像匹配列数:" << x2.n_cols << std::endl;
    std::cout<< "x1 element测试: " << " x: " << x1(0,1) << " y: " << x1(1,1) << std::endl;
    std::cout<< "x2 element测试: " << " x: " << x2(0,1) << " y: " << x2(1,1) << std::endl;
    std::cout << "==========================================================" << std::endl;*/

	arma::mat x1hom = arma::join_cols(x1, arma::ones<arma::mat>(1, numMatches));  //在下面添加一行,注意和join_rows的区别
	arma::mat x2hom = arma::join_cols(x2, arma::ones<arma::mat>(1, numMatches));
    /*std::cout << " x1hom查询图像匹配行数: " << x1hom.n_rows << " 查询图像匹配列数:" << x1hom.n_cols << std::endl;
    std::cout<< "x1hom element测试: " << " x: " << x1hom(0,1) << " y: " << x1hom(1,1) << " z: " << x1hom(2,1) << std::endl;
    std::cout << "==========================================================" << std::endl;*/

	arma::mat x1p, H21;  //作用域
	double tol;
	for(int m = 0; m < numMatches; ++m){
		//cout << "m: " << m << endl;
		for(unsigned int t = 0; t < opts.numRefinementIterations; ++t){
			//cout << "t: " << t << endl;
			if (t == 0){
				arma::mat tmp1 = frames1.col(matches(0, m)-1);
				arma::mat A1 = toAffinity(tmp1);
				//A1.print("A1 =");
				arma::mat tmp2 = frames2.col(matches(1, m)-1);
				arma::mat A2 = toAffinity(tmp2);
				//A2.print("A2 =");
				H21 = A2 * inv(A1);
				//H21.print("H21 =");
				x1p = H21.rows(0, 1) * x1hom ;
				//x1p.print("x1p =");
				tol = opts.tolerance1;
			}else if(t !=0 && t <= 3){
				arma::mat A1 = x1hom.cols(inliers(0, m));
				arma::mat A2 = x2.cols(inliers(0, m));
				//A1.print("A1 =");
				//A2.print("A2 =");
		        H21 = A2*pinv(A1);
				//H21.print("H21 =");
				x1p = H21.rows(0, 1) * x1hom ;
				//x1p.print("x1p =");
				arma::mat v;
				v << 0 << 0 << 1 << arma::endr;
				H21 = join_vert(H21, v);
				//H21.print("H21 =");
				//x1p.print("x1p =");
				tol = opts.tolerance2;
			}else{
				arma::mat x1in = x1hom.cols(inliers(0, m));
				arma::mat x2in = x2hom.cols(inliers(0, m));
				arma::mat S1 = centering(x1in);
				arma::mat S2 = centering(x2in);
				arma::mat x1c = S1 * x1in;
				//x1c.print("x1c =");
				arma::mat x2c = S2 * x2in;
				//x2c.print("x2c =");
				arma::mat A1 = arma::randu<arma::mat>(x1c.n_rows ,x1c.n_cols);
				A1.zeros();
				arma::mat A2 = arma::randu<arma::mat>(x1c.n_rows ,x1c.n_cols);
				A2.zeros();
				arma::mat A3 = arma::randu<arma::mat>(x1c.n_rows ,x1c.n_cols);
				A3.zeros();
				for(unsigned int i = 0; i < x1c.n_cols; ++i){
					A2.col(i) = x1c.col(i)*(-x2c.row(0).col(i));
					A3.col(i) = x1c.col(i)*(-x2c.row(1).col(i));
				}
				arma::mat T1 = join_cols(join_horiz(x1c, A1), join_horiz(A1, x1c));
				arma::mat T2 = join_cols(T1, join_horiz(A2, A3));
				//T2.print("T2 =");
				arma::mat U;
				arma::vec s;
				arma::mat V;
				svd_econ(U, s, V, T2);
				//U.print("U =");
				//V.print("V =");
				arma::vec tmm = U.col(U.n_cols-1);
				H21 = reshape(tmm, 3, 3).t();
				H21 = inv(S2) * H21 * S1;
				H21 = H21 / H21(H21.n_rows-1, H21.n_cols-1) ;
				//H21.print("H21 =");
				arma::mat x1phom = H21 * x1hom ;
				arma::mat cc1 = x1phom.row(0) / x1phom.row(2);
				arma::mat cc2 = x1phom.row(1) / x1phom.row(2);
				arma::mat x1p = join_cols(cc1, cc2);
				//x1p.print("x1p =");
				tol = opts.tolerance3;
			}
			arma::mat tmp = arma::square(x2 - x1p); //精度跟matlab相比更高?
			//tmp.print("tmp =");
			arma::mat dist2 = tmp.row(0) + tmp.row(1);
			//dist2.print("dist2 =");
			inliers(0, m) = arma::find(dist2 < pow(tol, 2));
			H(0, m) = H21;
			//H(0, m).print("H(0, m) =");
			//inliers(0, m).print("inliers(0, m) =");
			//cout << inliers(0, m).size() << endl;
			//cout << "==========================================================" << endl;
			if (inliers(0, m).size() < opts.minInliers) break;
			if (inliers(0, m).size() > 0.7 * numMatches) break;
		}
	}
	arma::uvec scores(numMatches);
	for(int i = 0; i < numMatches; ++i){
		scores.at(i) = inliers(0, i).n_rows;
	}
	//scores.print("scores = ");
	arma::uword index;
	scores.max(index);
	//cout << index << endl;
	arma::mat H_final = inv(H(0, index));
	//H_final.print("H_final = ");
	arma::uvec inliers_final = inliers(0, index);
	//inliers_final.print("inliers_final = ");
	return inliers_final;
}
Example #10
0
void Device2D::matrixDiff_2D() {
	int numBlock = dev1DList.size();
	// initialize the matrixC2D;
	mat matrixC2D(dev1DList[0].getMatrixC()); // has to make it dense mat to use join_rows/join_cols
	// TODO: was j= 0
	for (int j = 0; j < numBlock; j++) {
		std::cout << "Constructing differential matrix @ Block #" << j+1 << "; sumPoint = " << dev1DList[j].getSumPoint()
				<< " * " << nxList[j] << std::endl;
		dev1DList[j].matrixDiff();
		mat matrixC1D(dev1DList[j].getMatrixC());
		// std::cout << matrixC1D.size() << std::endl;
		for (int i=0; i < nxList[j]; i++) {
			matrixC2D=join_cols( join_rows(matrixC2D, zeros(matrixC2D.n_rows, dev1DList[j].getSumPoint())),
					join_rows(zeros(dev1DList[j].getSumPoint(), matrixC2D.n_cols), matrixC1D) );
		}
	}

	// initialize the C_L
	// was sumPointLateral * unitSize, here sumPoint = sumPointLateral * unitSize
	mat C_L = zeros(sumPoint, sumPoint);
	// similar to Device1D 1 => unitSize
    for ( int i=unitSize; i< sumPoint + unitSize; i++) {
        for ( int j=unitSize; j< sumPoint + unitSize; j++) {
            if (i==j) {
                C_L(i-unitSize,j-unitSize)= - 2*dieleArrayIP[i]/( spacingArrayIP[i]*( spacingArrayIP[i]+spacingArrayIP[i-unitSize] ) )
                 - 2*dieleArrayIP[i-unitSize]/( spacingArrayIP[i]*( spacingArrayIP[i]+spacingArrayIP[i-unitSize] ) );
            } else if (j==i-unitSize) {
                C_L(i-unitSize,j-unitSize)=2*dieleArrayIP[i-unitSize]/( spacingArrayIP[i]*( spacingArrayIP[i]+spacingArrayIP[i-unitSize] ) );
            } else if (j==i+unitSize) {
                C_L(i-unitSize,j-unitSize)=2*dieleArrayIP[i]/( spacingArrayIP[i]*( spacingArrayIP[i]+spacingArrayIP[i-unitSize] ) );
            }
        }
    }
    // Lateral boundary
    // boundary condition can differ at the semi and at the dielectric, apply point by point at right and left edge.

    /* IMPORTANT: Ohmic -> Neumann; Schottchy -> Dirichlet
     *
     * TODO: implement Schottchy: 1. add workfucntion for contact metal in input file;
     * 							  2. add this workfunction to boundary;
     * 							  3. Vds apply to boundary condition array instead of VdsArray (see notebook IV)
    */

    for (int i = 0; i < unitSize; i++) {
    	// left boundary
    	if ( leftBTArray[i] == Dirichlet ) {
    		C_L(i,unitSize + i)=LARGE;
    	} else if ( leftBTArray[i] == Neumann) {
    		C_L(i,unitSize + i)= - C_L(i,i);
    	} else {
    		std::cerr << "Error: left boundary type not found." << std::endl;
    	}
    	// right boundary
    	if ( rightBTArray[i] == Dirichlet ) {
    		C_L(i + sumPoint - unitSize, i + sumPoint - 2*unitSize) = LARGE;
    	} else if ( rightBTArray[i] == Neumann) {
    		C_L(i + sumPoint - unitSize, i + sumPoint - 2*unitSize) = -C_L(i + sumPoint - unitSize, i + sumPoint - unitSize);
    	} else {
    		std::cerr << "Error: right boundary type not found." << std::endl;
    	}
    }
    // std::cout << matrixC2D.size() << ", " << C_L.size() << std::endl;
    sp_mat tempMatrixC(matrixC2D + C_L);
    matrixC = tempMatrixC;
}
Example #11
0
void electrodeDeterminer(mat pos, imat& xp1Electrodes, imat& xn1Electrodes, imat& yp1Electrodes, imat& yn1Electrodes, imat& xp2Electrodes, imat& xn2Electrodes, imat& yp2Electrodes, imat& yn2Electrodes, int& numberOfElectrodes, double& xpElecWallMod, double& xnElecWallMod, double& ypElecWallMod, double& ynElecWallMod) {
    //find our cutoffs for what is and and isn't an electrode.
    double xp1CutOff;
    double xn1CutOff;
    double xp2CutOff;
    double xn2CutOff;
    if (numberOfElectrodes >= 2) {
        mat xValues = pos.col(0);
        xp1CutOff = xValues.max() + xpElecWallMod;
        xp2CutOff = xValues.max() + xpElecWallMod * 2;
        xn1CutOff = xValues.min() + xnElecWallMod;
        xn2CutOff = xValues.min() + xnElecWallMod * 2;
    }

    double yp1CutOff;
    double yn1CutOff;
    double yp2CutOff;
    double yn2CutOff;
    if (numberOfElectrodes == 4) {
        mat yValues = pos.col(1);
        yp1CutOff = yValues.max() + ypElecWallMod;
        yp2CutOff = yValues.max() + ypElecWallMod * 2;
        yn1CutOff = yValues.min() + ynElecWallMod;
        yn2CutOff = yValues.min() + ynElecWallMod * 2;
    }

    //cout << "CUTOFFS XP XN YP YN " << xpCutOff << " " << xnCutOff << " " << ypCutOff << " " << ynCutOff << endl;
    ///system("read  -p \"Number of electrodes changed! Push enter to unpause.\" key");


    //initialize matrixes with junk values.
    imat newxp1;
    newxp1 << -1 << endr;
    imat newxn1;
    newxn1 << -1 << endr;
    imat newyp1;
    newyp1 << -1 << endr;
    imat newyn1;
    newyn1 << -1 << endr;
    imat newxp2;
    newxp2 << -1 << endr;
    imat newxn2;
    newxn2 << -1 << endr;
    imat newyp2;
    newyp2 << -1 << endr;
    imat newyn2;
    newyn2 << -1 << endr;

    // loop over atoms to see if they can be electrodes.
    for (int i = 0; i < pos.n_rows; i++) {

        if (numberOfElectrodes >= 2) {
            if (pos(i, 0) > xp1CutOff) {
                imat toBeAdded;
                toBeAdded << i << endr;
                newxp1 = join_cols(newxp1, toBeAdded);
            }
            if (pos(i, 0) > xp2CutOff && pos(i, 0) < xp1CutOff) {
                imat toBeAdded;
                toBeAdded << i << endr;
                newxp2 = join_cols(newxp2, toBeAdded);
            }
            if (pos(i, 0) < xn1CutOff) {
                imat toBeAdded;
                toBeAdded << i << endr;
                newxn1 = join_cols(newxn1, toBeAdded);
            }
            if (pos(i, 0) < xn2CutOff && pos(i, 0) > xn1CutOff) {
                imat toBeAdded;
                toBeAdded << i << endr;
                newxn2 = join_cols(newxn2, toBeAdded);
            }
        }
        if (numberOfElectrodes == 4) {
            if (pos(i, 1) > yp1CutOff) {
                imat toBeAdded;
                toBeAdded << i << endr;
                newyp1 = join_cols(newyp1, toBeAdded);
                //cout << "YP1";
            }
            if (pos(i, 1) > yp2CutOff && pos(i, 1) < yp1CutOff) {
                imat toBeAdded;
                toBeAdded << i << endr;
                newyp2 = join_cols(newyp2, toBeAdded);
                //              cout << "YP2";
            }
            if (pos(i, 1) < yn1CutOff) {
                imat toBeAdded;
                toBeAdded << i << endr;
                newyn1 = join_cols(newyn1, toBeAdded);
                //            cout << "YN1";
            }
            if (pos(i, 1) < yn2CutOff && pos(i, 1) > yn1CutOff) {
                imat toBeAdded;
                toBeAdded << i << endr;
                newyn2 = join_cols(newyn2, toBeAdded);
                //          cout << "YN2";
            }
        }
    }
    //shave junk values.
    newxp1.shed_row(0);
    newxn1.shed_row(0);
    newyp1.shed_row(0);
    newyn1.shed_row(0);
    newxp2.shed_row(0);
    newxn2.shed_row(0);
    newyp2.shed_row(0);
    newyn2.shed_row(0);

    //We need to compare our newly derived electrode atoms with the old ones;
    //they should not have changed.

    //check if this is the first run, i.e. the arrays are null
    if (xp1Electrodes.is_empty()) {
        //simple initilization.
        if (numberOfElectrodes >= 2) {
            xp1Electrodes = newxp1;
            xn1Electrodes = newxn1;
            xp2Electrodes = newxp2;
            xn2Electrodes = newxn2;
        }
        if (numberOfElectrodes == 4) {
            yp1Electrodes = newyp1;
            yn1Electrodes = newyn1;
            yp2Electrodes = newyp2;
            yn2Electrodes = newyn2;
        }
    } else {
        //check that there are the same number of new and the old electrode atoms
        if (numberOfElectrodes >= 2) {
            if ((newxp1.size() != xp1Electrodes.size()) || (newxn1.size() != xn1Electrodes.size())
                    ) {
                //cout << "NUMBER OF X ELECTRODES CHANGED!!!!!!!!!!!!!!!!!! " << endl;
                system("read  -p \"Number x1 of electrodes changed! Push enter to unpause.\" key");
            }
            if ((newxp2.size() != xp2Electrodes.size()) || (newxn2.size() != xn2Electrodes.size())
                    ) {
                //cout << "NUMBER OF X ELECTRODES CHANGED!!!!!!!!!!!!!!!!!! " << endl;
                system("read  -p \"Number x2 of electrodes changed! Push enter to unpause.\" key");
            }

        }
        if (numberOfElectrodes == 4) {
            if ((newyp1.size() != yp1Electrodes.size()) || (newyn1.size() != yn1Electrodes.size())) {
                //cout << "NUMBER OF Y ELECTRODES CHANGED!!!!!!!!!!!!!!!!!! " << endl;
                system("read  -p \"Number of y1 electrodes changed! Push enter to unpause.\" key");
            }
            if ((newyp2.size() != yp2Electrodes.size()) || (newyn2.size() != yn2Electrodes.size())) {
                //cout << "NUMBER OF Y ELECTRODES CHANGED!!!!!!!!!!!!!!!!!! " << endl;
                system("read  -p \"Number of y2 electrodes changed! Push enter to unpause.\" key");
            }
        }
        //number of electrodes the same, fairly ok to assume they did not change.
        if (numberOfElectrodes >= 2) {
            xp1Electrodes = newxp1;
            xp2Electrodes = newxp2;
            xn1Electrodes = newxn1;
            xn2Electrodes = newxn2;
        }
        if (numberOfElectrodes == 4) {
            yp1Electrodes = newyp1;
            yp2Electrodes = newyp2;
            yn1Electrodes = newyn1;
            yn2Electrodes = newyn2;
        }
    }


}
Example #12
0
//' Generate Autoregressive Order P - Moving Average Order Q (ARMA(P,Q)) Model
//' 
//' Generate an ARMA(P,Q) process with supplied vector of Autoregressive Coefficients (\eqn{\phi}), Moving Average Coefficients (\eqn{\theta}), and \eqn{\sigma^2}.
//' @param N       An \code{integer} for signal length.
//' @param ar      A \code{vec} that contains the AR coefficients.
//' @param ma      A \code{vec} that contains the MA coefficients.
//' @param sigma2  A \code{double} that contains process variance.
//' @param n_start An \code{unsigned int} that indicates the amount of observations to be used for the burn in period. 
//' @return A \code{vec} that contains the generated observations.
//' @details 
//' The innovations are generated from a normal distribution.
//' The \eqn{\sigma^2} parameter is indeed a variance parameter. 
//' This differs from R's use of the standard deviation, \eqn{\sigma}.
//' 
//' For AR(1), MA(1), and ARMA(1,1) please use their functions if speed is important.
//' @backref src/gen_process.cpp
//' @backref src/gen_process.h
//' @keywords internal
//' @examples
//' gen_arma(10, c(.3,.5), c(.1), 1, 0)
// [[Rcpp::export]]
arma::vec gen_arma(const unsigned int N,
                   const arma::vec& ar, const arma::vec& ma,
                   const double sigma2 = 1.5, 
                   unsigned int n_start = 0){
  
  // P = AR1 coefs, Q = MA coefs
  unsigned int p = ar.n_elem, q = ma.n_elem;

  // Need to append 1 to vectors.
  arma::vec one = arma::ones<arma::vec>(1);
  
  // What is the minimum root?
  double min_root = 1;
  
  // SD
  double sd = sqrt(sigma2);
  
  // Innovation save
  arma::vec innov(N);
  
  // Start Innovation
  arma::vec start_innov;
  
  // Store data
  arma::vec x;
  
  // Loop counter
  unsigned int i;
  
  // AR terms present? 
  if(p != 0){
    
    // Obtain the smallest root of the AR coefs.
    min_root = minroot(arma::conv_to<arma::cx_vec>::from(
                                      arma::join_cols(one, -ar)
                                    )
        
                      );
    
    // Check to see if the smallest root is not invertible (e.g. in unit circle)
    if(min_root <= 1){
      throw std::runtime_error("Supplied model's AR component is NOT invertible!");
    }
  }
  
  
  // Determine starting values
  if(n_start == 0){
    n_start = p + q + ( p > 0 ? ceil(6/log(min_root)) : 0 );
  }
  
  if(n_start < p + q){
    throw std::runtime_error("burn-in 'n.start' must be as long as 'ar + ma'");
  }
  
  // Generate Innovations
  for(i = 0; i < N; i++){
    innov(i) = R::rnorm(0,sd);
  }
  
  // Generate Starting Innovations
  start_innov = arma::vec(n_start);
  
  for(i = 0; i < n_start; i++){
    start_innov(i) = R::rnorm(0,sd);
  }
  
  // Combine
  x = join_cols(start_innov, innov);
  
  // Handle the MA part of ARMA
  if(q > 0){
    // Apply a convolution filter 
    // data, filter, sides, circular
    x = cfilter(x, join_cols(one,ma), 1, false);
    x.rows(0, q-1).fill(0);
  }
  
  // Handle the AR part of ARMA
  if(p > 0){
    // Apply recursive filter
    // data, filter, init value 
    // see comment in rfilter docs for init values (different than normal R)
    x = rfilter(x, ar, arma::zeros<arma::vec>(p));
  }
  
  // Remove starting innovations
  if(n_start > 0){
    // need -1 for C++ oob error 
    x = x.rows(n_start, x.n_elem - 1);
  }
  
  return x;
}
Example #13
0
//------------------------------------------------------------------------------
void Grid::createGrid()
{
    double x_len = m_boundaryLength[0];
    double y_len = m_boundaryLength[1];
    double z_len = m_boundaryLength[2];

    // Finding the optimal length
    int nx = floor(x_len/m_gridspacing) > 0 ? floor(x_len/m_gridspacing) : 1;
    int ny = floor(y_len/m_gridspacing) > 0 ? floor(y_len/m_gridspacing) : 1;
    int nz = floor(z_len/m_gridspacing) > 0 ? floor(z_len/m_gridspacing) : 1;

    m_gridSpacing = {x_len/nx, y_len/ny, z_len/nz };
    m_nGrid = {nx, ny, nz};
    vector<ivec> inner_points;
    vector<ivec> boundary_points;

    for(int d=0;d<3; d++)
    {
        if(m_periodicBoundaries[d])
        {
            inner_points.push_back(linspace<ivec>(1, m_nGrid(d), m_nGrid(d)));
            boundary_points.push_back({0, m_nGrid(d) + 1});
            m_nGrid(d) += 2;
            m_boundary[d].first -= m_gridSpacing(d);
            m_boundary[d].second += m_gridSpacing(d);
        }
        else
        {
            inner_points.push_back(linspace<ivec>(0, m_nGrid(d)-1, m_nGrid(d)));
            boundary_points.push_back({});
        }
    }

    // Setting the grid
    for(int x:inner_points[X])
    {
        for(int y:inner_points[Y])
        {
            for(int z:inner_points[Z])
            {
                // id = x + nx*y + nx*ny*z;
                // Center of gridpoint
                vec3 center = {
                    m_boundary[X].first + m_gridSpacing(X)*(x + 0.5)
                    ,m_boundary[Y].first + m_gridSpacing(Y)*(y + 0.5)
                    ,m_boundary[Z].first + m_gridSpacing(Z)*(z + 0.5)};

                int id = gridId(center);
                m_gridpoints[id] = new GridPoint(id, center, false);
                m_myGridPoints.push_back(id);
            }
        }
    }

    // Boundary conditions
    for(int d=0; d<3; d++)
    {
        ivec3 xyz = {0, 0, 0};

        for(int point_0:boundary_points[d])
        {
            vector<int> inn_p = {0, 1, 2};
            inn_p.erase(inn_p.begin() + d);

            ivec p1 = join_cols(inner_points[inn_p[0]], boundary_points[inn_p[0]]);
            for(int point_1:p1)
            {
                ivec p2 = join_cols(inner_points[inn_p[1]], boundary_points[inn_p[1]]);

                for(int point_2:p2)
                {
                    xyz(d) = point_0;
                    xyz(inn_p[0]) = point_1;
                    xyz(inn_p[1]) = point_2;

                    // Center of gridpoint
                    vec3 center = {
                        m_boundary[X].first + m_gridSpacing(X)*(xyz(X) + 0.5)
                        ,m_boundary[Y].first + m_gridSpacing(Y)*(xyz(Y) + 0.5)
                        ,m_boundary[Z].first + m_gridSpacing(Z)*(xyz(Z) + 0.5)};

                    int id = gridId(center);
                    m_gridpoints[id] = new GridPoint(id, center, true);
                }
            }
        }
    }
}