Exemple #1
0
// m=m-m*v*v'
void sub_m_v_vT(mat &m, const vec &v)
{
  vec v2(m.rows());
  double tmp, *v2p;
  const double *vp;
  int i, j;

  it_assert(v.size() == m.cols(), "sub_m_v_vT()");

  v2p = v2._data();
  for (i = 0; i < m.rows(); i++) {
    tmp = 0.0;
    vp = v._data();
    for (j = 0; j < m.cols(); j++)
      tmp += *(vp++) * m._elem(i, j);
    *(v2p++) = tmp;
  }

  v2p = v2._data();
  for (i = 0; i < m.rows(); i++) {
    vp = v._data();
    for (j = 0; j < m.cols(); j++)
      m._elem(i, j) -= *v2p * *(vp++);
    v2p++;
  }
}
// fonction retournant le produit d'une matrice et d'un vecteur
vec Calculs::produit(mat MM, vec V)
{
       VV.resize(MM.size());
       for(kk=0;kk<MM.size();kk++)
       {
               som = 0;
               for(ll=0;ll<V.size();ll++)
               {
                       som = som+MM[kk][ll]*V[ll];
               }
               VV[kk] = som;
       }
       return VV;
}
Exemple #3
0
inline void update_WtA(mat & WtA, const mat & W, const mat & W1, const mat & H2, const mat & A)
{
	// compute WtA = (W[:, 0:k-1], W1)^T (A - W[, k:end] H2^T)
	if (H2.empty())
		update_WtA(WtA, W, W1, A);
	else
	{
		int k = W.n_cols - H2.n_cols;
		//std::cout << "1.3" << std::endl;
		//A.print("A = ");
		//(W.cols(k, W.n_cols-1) * H2.t()).print("W[, k:] = ");
		update_WtA(WtA, W.cols(0, k-1), W1, A - W.cols(k, W.n_cols-1) * H2.t());
	}
}
//! get gravity and body acc. components of the window
//! @param[in] &window		reference to the window
//! @param[out] &gravity	reference to the gravity comp. extracted from the window
//! @param[out] &body		reference to the body acc. comp. extracted from the window
void Classifier::analyzeWindow(mat &window, mat &gravity, mat &body)
{
	// perform median filtering to reduce the noise
	int n = 3;
	mat clean_window = window.t();
	medianFilter(clean_window, n);
	clean_window = clean_window.t();

	// discriminate between gravity and body acc. components
	mat tempgr = clean_window.t();
	gravity = ChebyshevFilter(tempgr);
	gravity = gravity.t();
	body = clean_window - gravity;
}
Exemple #5
0
// convertion
void mat2Blob(mat& mA, shared_ptr<Blob>& out, int c, int h, int w) {
    int n = mA.n_rows;
    assert(mA.n_cols == c*h*w);

    mA = mA.t();
    if (out) {
        out.reset();
    }
    out.reset(new Blob(n, c, h, w));
    for (int i = 0; i < n; ++i) {
        (*out)[i] = cube(mA.colptr(i), h, w, c);
    }
    return;
}
Exemple #6
0
double Jastrow::getRatio(const int &particleNum, const mat &rNew, const mat &rOld){
    double argument = 0;
    double fNew = 0;
    double fOld = 0;
    double r12 = 0;
    for (int i = 0; i < particleNum; i++){
        r12Vec = rNew.row(particleNum) - rNew.row(i);
        r12 = sqrt(r12Vec(0)*r12Vec(0) + r12Vec(1)*r12Vec(1) + r12Vec(2)*r12Vec(2));
        fNew = f(r12, particleNum, i);

        r12Vec = rOld.row(particleNum) - rOld.row(i);
        r12 = sqrt(r12Vec(0)*r12Vec(0) + r12Vec(1)*r12Vec(1) + r12Vec(2)*r12Vec(2));
        fOld = f(r12, particleNum, i);

        argument += fNew - fOld;
    }
    for (int i = particleNum + 1; i < nParticles; i++){
        r12Vec = rNew.row(particleNum) - rNew.row(i);
        r12 = sqrt(r12Vec(0)*r12Vec(0) + r12Vec(1)*r12Vec(1) + r12Vec(2)*r12Vec(2));
        fNew = f(r12, particleNum, i);

        r12Vec = rOld.row(particleNum) - rOld.row(i);
        r12 = sqrt(r12Vec(0)*r12Vec(0) + r12Vec(1)*r12Vec(1) + r12Vec(2)*r12Vec(2));
        fOld = f(r12, particleNum, i);

        argument += fNew - fOld;
    }
    return exp(argument);
}
//used for both spheric and hybrid multilateration
static
bool generate_meas(vec &meas, const bvec &method, const mat &bs_pos, const vec &ms_pos)
{
  unsigned int method_len = length(method);
  unsigned int nb_bs = bs_pos.cols();
  bool column = true;
  if(3 == nb_bs) {
    nb_bs = bs_pos.rows();
    column = false;
  }
  if((nb_bs < method_len) || (3 != length(ms_pos))) {
    return false;
  }
  meas.set_size(method_len);
  vec pos(3);
  vec pos_ref(3);
  pos_ref = column ? bs_pos.get_col(0) : bs_pos.get_row(0);
  for(unsigned int k = 0; k < method_len; ++k) {
    if(bin(1) == method[k]) {  /* hyperbolic */
      pos = column ? bs_pos.get_col(k + 1) : bs_pos.get_row(k + 1);
      meas[k] = get_dist(pos, ms_pos) - get_dist(pos_ref, ms_pos);
    }
    else { /* spherical */
      pos = column ? bs_pos.get_col(k) : bs_pos.get_row(k);
      meas[k] = get_dist(pos, ms_pos);
    }
  }
  return true;
}
Exemple #8
0
 virtual Vec4f vertex(int iface, int nthvert) {
     Vec2f uv = m_model->uv(iface, nthvert);
     varying_uv.set_col(nthvert, uv);
     varying_nrm.set_col(nthvert, proj<3>(m_invModelMat*embed<4>(m_model->normal(iface, nthvert), 0.f)));
     Vec3f unScaledVert = m_model->vert(iface, nthvert);
     Vec3f scaledVert=Vec3f(unScaledVert[0]*m_localScaling[0],
                            unScaledVert[1]*m_localScaling[1],
                            unScaledVert[2]*m_localScaling[2]);
     Vec4f gl_Vertex = m_projectionMat*m_modelView1*embed<4>(scaledVert);
     varying_tri.set_col(nthvert, gl_Vertex);
     Vec4f gl_VertexLightView = m_projectionMat*m_lightModelView*embed<4>(scaledVert);
     varying_tri_light_view.set_col(nthvert, gl_VertexLightView);
     return gl_Vertex;
 }
mat bb_shift_relative(mat bb,pair<double,double>shift)
{
	bb.row(1) = bb.row(1)+(bb.row(3)-bb.row(1)+1)*shift.first;
	bb.row(2) = bb.row(2)+(bb.row(4)-bb.row(2)+1)*shift.second;
	bb.row(3) = bb.row(3)+(bb.row(3)-bb.row(1)+1)*shift.first;
	bb.row(4) = bb.row(4)+(bb.row(4)-bb.row(2)+1)*shift.second;
}
Exemple #10
0
void updateStateThread() {

	while(0 == lcm1.handle()) {

		x0.at(0,0) = current_state.position[0]/1000.0;
		x0.at(3,0) = current_state.position[1]/1000.0;
		x0.at(6,0) = -(current_state.position[2]/1000.0 + simu_height) + better_height;

		x0.at(1,0) = current_state.velocity[0];
		x0.at(4,0) = current_state.velocity[1];
		x0.at(7,0) = -current_state.velocity[2];

		accumu_err_x = accumu_err_x + x0.at(0,0) * dT;
		accumu_err_y = accumu_err_y + x0.at(3,0) * dT;
		accumu_err_z = accumu_err_z + x0.at(6,0) * dT;

		x0.at(2,0) = accumu_err_x;
		x0.at(5,0) = accumu_err_y;
		x0.at(8,0) = accumu_err_z;

		usleep(5e4);

		// cout <<__LINE__<<endl;
	
	}

}
void forward_substitution(const mat &L, int p, const vec &b, vec &x)
{
    assert( L.rows() == L.cols() && L.cols() == b.size() && b.size() == x.size() && p <= L.rows()/2 );
    int n = L.rows(), i, j;

    x=b;
  
    for (j=0;j<n;j++) {
	x(j)/=L(j,j);
	for (i=j+1;i<MIN(j+p+1,n);i++) {
	    x(i)-=L(i,j)*x(j);
	}
    }
}
mat backslash(const mat &A, const mat &B)
{
  mat ls_solve(const mat &A, const mat &b);
  mat ls_solve_od(const mat &A, const mat &b);
    int m=A.rows(), n=A.cols();

    if (m == n)
	return ls_solve(A,B);
    else if (m > n)
	return ls_solve_od(A,B);
    
    //it_error("Cannot solve under-determined linear equation systems!");
    return vec(0);
}
//Beregning av enkeltderiverte til orbitalene
rowvec3 Wavefunction::Gradient(const mat &r, const int number_particle, const int &Orbital_number, double alpha, int atom_nr)
{
    double Sum_I_Eksponenten = 0;
    rowvec3 Gradienten;
    Gradienten(0)=0; Gradienten(1)=0; Gradienten(2)=0;

    for (int k = 0; k < dimension; k++)
    {
        Sum_I_Eksponenten += (r(number_particle, k) - R(atom_nr, k)) * (r(number_particle, k) - R(atom_nr, k));
    }

    Sum_I_Eksponenten = sqrt(Sum_I_Eksponenten);

    if (Orbital_number == 0)
    {
        Gradienten = -(alpha * (r.row(number_particle)-R.row(atom_nr)) / Sum_I_Eksponenten) * exp(-alpha*Sum_I_Eksponenten);
    }

    if (Orbital_number == 1)
    {
        Gradienten = (alpha*(r.row(number_particle) - R.row(atom_nr))*(alpha*Sum_I_Eksponenten-4) / (4*Sum_I_Eksponenten)) * exp(-alpha*Sum_I_Eksponenten/2);
    }

    if (Orbital_number == 2)
    {
        Gradienten(0) = -alpha*(r(number_particle, 0)-R(atom_nr, 0)) * (r(number_particle ,0)-R(atom_nr, 0)) + 2*Sum_I_Eksponenten;
        Gradienten(1) = -alpha*(r(number_particle, 0)-R(atom_nr,0)) * (r(number_particle ,1)-R(atom_nr,1));
        Gradienten(2) = -alpha*(r(number_particle, 0)-R(atom_nr,0)) * (r(number_particle ,2)-R(atom_nr,2));
        Gradienten = Gradienten * exp(-alpha*Sum_I_Eksponenten / 2) / (2*Sum_I_Eksponenten);
    }

    if (Orbital_number == 3)
    {
        Gradienten(0) = -alpha*(r(number_particle, 1)-R(atom_nr,1)) * (r(number_particle ,0)-R(atom_nr, 0));
        Gradienten(1) = -alpha*(r(number_particle, 1)-R(atom_nr,1)) * (r(number_particle ,1)-R(atom_nr,1)) + 2*Sum_I_Eksponenten;
        Gradienten(2) = -alpha*(r(number_particle, 1)-R(atom_nr,1)) * (r(number_particle ,2)-R(atom_nr,2));
        Gradienten = Gradienten * exp(-alpha*Sum_I_Eksponenten / 2) / (2*Sum_I_Eksponenten);
    }

    if (Orbital_number == 4)
    {
        Gradienten(0) = -alpha*(r(number_particle, 2)-R(atom_nr,2)) * (r(number_particle ,0)-R(atom_nr, 0));
        Gradienten(1) = -alpha*(r(number_particle, 2)-R(atom_nr,2)) * (r(number_particle ,1)-R(atom_nr,1));
        Gradienten(2) = -alpha*(r(number_particle, 1)-R(atom_nr,1)) * (r(number_particle ,2)-R(atom_nr,2)) + 2*Sum_I_Eksponenten;
        Gradienten = Gradienten * exp(-alpha*Sum_I_Eksponenten / 2) / (2*Sum_I_Eksponenten);
    }

    return Gradienten;
}
Exemple #14
0
void randselect(mat X, mat y, int n, mat &outX, mat &outy) {
  std::vector<int> indeces;
	for (int i = 0; i < (int)X.n_rows; i++) {
		indeces.push_back(i);
	}
	random_shuffle(indeces.begin(), indeces.end());
	mat _X_ = X;
	mat _y_ = y;
	outX = mat(n, X.n_cols);
	outy = mat(n, 1);
	for (int i = 0; i < n; i++) {
		outX.row(i) = _X_.row(indeces[i]);
		outy.row(i) = _y_.row(indeces[i]);
	}
}
mat mul(mat &A, mat &B) //A: m*n, B: n*p
{
    mat C(A.size(), vec(B[0].size())); //C: m:p
    for (int i = 0; i < A.size(); i++)
    {
        for (int k = 0; k < B.size(); k++)
        {
            for (int j = 0; j < B[0].size(); j++)
            {
                C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % M;
            }
        }
    }
    return C;
}
mat pow(mat A, ll n)
{
	mat B(A.size(),vec(A.size()));
	for(int i=0;i<A.size();i++)
	{
		B[i][i]=1ll;
	}
	while(n>0)
	{
		if(n&1)B = mul(B,A);
		A = mul(A,A);
		n >>= 1;
	}
	return B;
}
mat mul(mat &A,mat &B)
{
	mat C(A.size(),vec(B[0].size()));
	for(int i=0;i<A.size();i++)
	{
		for(int k=0;k<B.size();k++)
		{
			for(int j=0;j<B[0].size();j++)
			{
				C[i][j]=(C[i][j]+A[i][k]*B[k][j])%MOD;
			}
		}
	}
	return C;
}
Exemple #18
0
mat pow(mat A, LL n)
{
     int i, j;
     mat B(A.size(), vec(A.size()));
     for(i = 0; i < A.size(); i++)
          B[i][i] = 1;
     while(n > 0)
     {
          if(n&1)
               B = mul(B, A);
          A = mul(A, A);
          n = n >> 1;
     }
     return B;
}
Exemple #19
0
mat FMRLasso::GenoStd(mat& geno)
{
    assert(geno.n_rows == mN);
    assert(geno.n_cols == mP);
    
    double q;
    for ( unsigned int j = 0; j < mP; j++)
    {
        q = sum(geno.col(j)) / (2.0 * mN); // BE CAREFUL FOR A VECTOR 0 INDEX
        //cout << q << endl;
        geno.col(j) = (geno.col(j) - 2.0 * q) / sqrt(2.0 * q * (1.0 - q));
    }
    
    return geno;
}
void ConstantCF::covarianceGradient(mat& grad, const int parameterNumber, const mat& X) const
{
	assert(parameterNumber == 0);

	Transform* t = getTransform(parameterNumber);
	double gradientTransform = t->gradientTransform(getParameter(parameterNumber));

	switch(parameterNumber)
	{
		case 0 :
		{
		    grad = gradientTransform * ones(X.rows(), X.rows());
		}
	}
}
void tlin::traduceD(const mat &m, SuperMatrix *&A)
{
	int rows = m.rows(), cols = m.cols();

	if (!A)
		allocD(A, rows, cols);

	int lda;
	double *Avalues = 0;
	readDN(A, lda, Avalues);

	assert(A->nrow == rows && A->ncol == cols && lda == rows);

	memcpy(Avalues, m.values(), rows * cols * sizeof(double));
}
Exemple #22
0
void SeqOls::useObservations(mat X, mat Y  // A n x p matrix with n responses,
                             // one response per row
                            ) {
    if (X.size() != Y.size()) {
        cout << " The predictor/response matrices should have the same size";
        cout << endl;
    }

    n = X.n_rows;
    p = X.n_cols;
    X = join_rows(X, ones(n, 1));
    P = inv((X.t()) * X);
    B = P * (X.t() * Y);
    G = inv(B.rows(0, p - 1));
}
Exemple #23
0
//' C++ Wrapper to Check Stability of Two-sided Matching
//'
//' This function checks if a given matching is stable for a particular set of
//' preferences. This function provides an R wrapper for the C++ backend. Users
//' should not call this function directly and instead use
//' \code{\link{galeShapley.checkStability}}.
//'
//' @param proposerUtils is a matrix with cardinal utilities of the proposing
//'   side of the market. If there are \code{n} proposers and \code{m} reviewers,
//'   then this matrix will be of dimension \code{m} by \code{n}. The
//'   \code{i,j}th element refers to the payoff that individual \code{j} receives
//'   from being matched to individual \code{i}.
//' @param reviewerUtils is a matrix with cardinal utilities of the courted side
//'   of the market. If there are \code{n} proposers and \code{m} reviewers, then
//'   this matrix will be of dimension \code{n} by \code{m}. The \code{i,j}th
//'   element refers to the payoff that individual \code{j} receives from being
//'   matched to individual \code{i}.
//' @param proposals is a matrix that contains the number of the reviewer that a
//'   given proposer is matched to: the first row contains the number of the
//'   reviewer that is matched with the first proposer (using C++ indexing), the
//'   second row contains the id of the reviewer that is matched with the second
//'   proposer, etc. The column dimension accommodates proposers with multiple
//'   slots.
//' @param engagements is a matrix that contains the number of the proposer that
//'   a given reviewer is matched to (using C++ indexing). The column dimension
//'   accommodates reviewers with multiple slots.
//' @return true if the matching is stable, false otherwise
// [[Rcpp::export]]
bool cpp_wrapper_galeshapley_check_stability(mat proposerUtils, mat reviewerUtils, umat proposals, umat engagements) {

    // number of workers
    const int M = proposerUtils.n_cols;
    
    // number of firms
    const int N = proposerUtils.n_rows;
    
    // number of slots per firm
    const int slotsReviewers = engagements.n_cols;
    
    // number of slots per worker
    const int slotsProposers = proposals.n_cols;

    // more jobs than workers (add utility from being unmatched to firms' preferences)
    if(N*slotsReviewers>M*slotsProposers) {
        reviewerUtils.insert_rows(M, 1);
        reviewerUtils.row(M).fill(-1e10);
    }
    // more workers than jobs (add utility from being unmatched to workers' preferences)
    if(M*slotsProposers>N*slotsReviewers) {
        proposerUtils.insert_rows(N, 1);
        proposerUtils.row(N).fill(-1e10);
    }
    
    // loop over workers
    for(int wX=0; wX<M; wX++) {
    
        // loop over firms
        for(int fX=0; fX<N; fX++) {
    
            // loop over multiple "slots" at the same worker
            for(int swX=0;swX<slotsProposers;swX++) {
    
                // loop over multiple slots at the same firm
                for(int sfX=0;sfX<slotsReviewers;sfX++) {
    
                    // check if wX and fX would rather be matched with each other than with their actual matches
                    if(reviewerUtils(wX, fX) > reviewerUtils(engagements(fX, sfX), fX) && proposerUtils(fX, wX) > proposerUtils(proposals(wX, swX), wX)) {
                        ::Rf_warning("matching is not stable; worker %d would rather be matched to firm %d and vice versa.\n", wX, fX);
                        return false;
                    }
                }
            }
        }
    }
    return true;
}
Exemple #24
0
void add_vector(float * a, mat b, int dim){
  petuum::RowAccessor row_acc;
  b.Get(0, &row_acc);
  const petuum::DenseRow<float>& r = row_acc.Get<petuum::DenseRow<float> >();
  for(int i=0;i<dim;i++)
    a[i]+=r[i];
}
Exemple #25
0
// Maximum Down-Sampling
mat maxDownSample(mat source, int stride, mat& retnMask){
 
    dbg_assert(source.n_rows == source.n_cols);
    dbg_assert(stride <= source.n_rows);
    dbg_assert((source.n_rows % stride) == 0);

    int source_size  = source.n_rows;

    int result_size = source_size / stride;
    mat result      = zeros<mat>(result_size, result_size);

    retnMask = zeros<mat>(source_size, source_size);

    for(int row=0; row < result_size; row++){
        for(int col=0; col < result_size; col++){
            int row_start = row * stride;
            int col_start = col * stride;
            uword retn_row;
            uword retn_col;
            result(row, col) = source.submat(
                                    row_start, 
                                    col_start, 
                                    row_start + stride - 1,
                                    col_start + stride - 1
                               ).max(retn_row, retn_col);
            retnMask(retn_row + row_start,
                     retn_col + col_start) = 1;
        }
    }
    
    return(result);
       
}
Exemple #26
0
///
/// \brief PLSData::Discriminate
/// \param data
/// \param labels
/// \return
/// Perform PLS-DA
bool PLSData::Discriminate(const mat &data, const mat &labels)
{
    //data (usually, but not necessarly spectra) is X
    //labels are Y;
    if (labels.n_rows != data.n_cols) return false;
    mat X_loadings, Y_loadings, X_scores, Y_scores, coefficients, percent_variance, fitted;
    bool success = Vespucci::Math::DimensionReduction::plsregress(data.t(), labels, labels.n_cols,
                                                                  X_loadings, Y_loadings,
                                                                  X_scores, Y_scores,
                                                                  coefficients, percent_variance,
                                                                  fitted);
    mat residuals = fitted - labels;

    if (success){
        AddMetadata("Type", "Calibration");
        AddMetadata("Components calculated", QString::number(labels.n_cols));
        AddMatrix("Percent Variance", percent_variance);
        AddMatrix("Predictor Loadings", X_loadings);
        AddMatrix("Response Loadings", Y_loadings);
        AddMatrix("Predictor Scores", X_scores);
        AddMatrix("Response Scores", Y_scores);
        AddMatrix("Coefficients", coefficients);
        AddMatrix("Fitted Data", fitted);
        AddMatrix("Residuals", residuals);
    }

    return success;
}
Exemple #27
0
// операции над обычными матрицами
vec operator * (const mat & a, const vec & b)
{
    vec res(b.size());
    for (size_t i = 0; i < a.size(); ++i)
        res[i] = a[i] * b;
    return res;
}
double scoreFunc(vec &f_q, vector<unsigned> &a_indices, mat &Ws){
	vec g_a = zeros<vec>(f_q.n_rows);
	for (auto i : a_indices) {
		g_a += Ws.col(i);
	}
	return norm_dot(g_a, f_q);
}
Exemple #29
0
void load(mat &x, mat &y) {
  std::ifstream input("/home/joseph/C/data/house.dat", std::ios::in);
  std::string line;

  if (input.is_open()) {
    x = mat(datasize, n);
    y = mat(datasize, o);
    y.zeros();

    for (; std::getline(input, line) ;) {
      if (strcmp(line.substr(0, 5).c_str(), "@data") == 0) {
        cout << "reading data..." << endl;
        break;
      }
    }

    for (uint32_t i = 0 ; i < datasize ; ++i) {
      for (int j = 0 ; j < n ; ++j) {
        double xi = 0;
        char c;
        input >> xi;
        if (j == 0) xi /= (7322564.0 / 10.0);

        x(i, j) = xi;

        // read ,
        input >> c;
      }

      double val = 0;
      input >> val;
      y(i, 0) = val / scale;
    }
  }
Exemple #30
0
mat MaxPoolLayer::forwardprop(const mat& pa) {
  a = mat(pa.n_rows, outputsize * nfilter, arma::fill::zeros);
  images = cube(inputheight + 2*padding, inputwidth + 2*padding, pa.n_rows);
  indexes = mat(pa.n_rows, outputsize*2);

  for (uint32_t i = 0 ; i < pa.n_rows ; ++i) {
    // reshape input sample
    mat sample = pa.row(i);
    for (int j = 0 ; j < pnfilter ; ++j) {
      const mat img = toimage(pa, j, inputwidth, inputheight);
      images.slice(i) = addzeropadding(img);

#ifdef HAVE_OPENMP
#pragma omp parallel for default(none) shared(j,i) if (nfilter >= 16)
#endif
      for (int k = 0 ; k < nfilter ; ++k) {
        mat partialoutput;
        mat index;

        maxpool(images.slice(i), partialoutput, index);
        a.submat(i, k*outputsize, i, (k+1)*outputsize-1) += partialoutput;
        indexes.submat(i, 0, i, outputsize*2-1) = index;
      }
    }
  }
  return funcop(a, actfunc.act);
}