示例#1
0
IGL_INLINE void igl::cat(
    const int dim, 
    const Eigen::SparseMatrix<Scalar> & A, 
    const Eigen::SparseMatrix<Scalar> & B, 
    Eigen::SparseMatrix<Scalar> & C)
{
  assert(dim == 1 || dim == 2);
  using namespace Eigen;
  // Special case if B or A is empty
  if(A.size() == 0)
  {
    C = B;
    return;
  }
  if(B.size() == 0)
  {
    C = A;
    return;
  }

  DynamicSparseMatrix<Scalar, RowMajor> dyn_C;
  if(dim == 1)
  {
    assert(A.cols() == B.cols());
    dyn_C.resize(A.rows()+B.rows(),A.cols());
  }else if(dim == 2)
  {
    assert(A.rows() == B.rows());
    dyn_C.resize(A.rows(),A.cols()+B.cols());
  }else
  {
    fprintf(stderr,"cat.h: Error: Unsupported dimension %d\n",dim);
  }

  dyn_C.reserve(A.nonZeros()+B.nonZeros());

  // Iterate over outside of A
  for(int k=0; k<A.outerSize(); ++k)
  {
    // Iterate over inside
    for(typename SparseMatrix<Scalar>::InnerIterator it (A,k); it; ++it)
    {
      dyn_C.coeffRef(it.row(),it.col()) += it.value();
    }
  }

  // Iterate over outside of B
  for(int k=0; k<B.outerSize(); ++k)
  {
    // Iterate over inside
    for(typename SparseMatrix<Scalar>::InnerIterator it (B,k); it; ++it)
    {
      int r = (dim == 1 ? A.rows()+it.row() : it.row());
      int c = (dim == 2 ? A.cols()+it.col() : it.col());
      dyn_C.coeffRef(r,c) += it.value();
    }
  }

  C = SparseMatrix<Scalar>(dyn_C);
}
示例#2
0
Eigen::VectorXd KronProdSPMat2(
    Eigen::SparseMatrix<double, Eigen::RowMajor> a0,
    Eigen::SparseMatrix<double, Eigen::RowMajor> a1,
    Eigen::VectorXd y) {

    signal(SIGSEGV, handler);   // install our handler
    Eigen::VectorXd retvec;
    retvec.setZero( a0.rows() * a1.rows()  );

    //loop rows a0
    for (int row_idx0=0; row_idx0<a0.outerSize(); ++row_idx0) {
        int row_offset1 = row_idx0;
        row_offset1    *= a1.rows();

        // loop rows a1
        for (int row_idx1=0; row_idx1<a1.outerSize(); ++row_idx1) {

            // loop cols a0 (non-zero elements only)
            for (Eigen::SparseMatrix<double,RowMajor>::InnerIterator it0(a0,row_idx0); it0; ++it0) {
                int col_offset1 = it0.index();
                col_offset1    *= a1.innerSize();
                double factor1 = it0.value();

                for (Eigen::SparseMatrix<double,RowMajor>::InnerIterator it1(a1,row_idx1); it1; ++it1) {
                    retvec( row_offset1 + row_idx1 ) += factor1 * it1.value() * y( col_offset1 + it1.index() );
                }
            }
        }
    }
    return retvec;
}
示例#3
0
IGL_INLINE void igl::matlab::prepare_lhs_double(
    const Eigen::SparseMatrix<Vtype> & M,
    mxArray *plhs[])
{
    using namespace std;
    const int m = M.rows();
    const int n = M.cols();
    // THIS WILL NOT WORK FOR ROW-MAJOR
    assert(n==M.outerSize());
    const int nzmax = M.nonZeros();
    plhs[0] = mxCreateSparse(m, n, nzmax, mxREAL);
    mxArray * mx_data = plhs[0];
    // Copy data immediately
    double * pr = mxGetPr(mx_data);
    mwIndex * ir = mxGetIr(mx_data);
    mwIndex * jc = mxGetJc(mx_data);

    // Iterate over outside
    int k = 0;
    for(int j=0; j<M.outerSize(); j++)
    {
        jc[j] = k;
        // Iterate over inside
        for(typename Eigen::SparseMatrix<Vtype>::InnerIterator it (M,j); it; ++it)
        {
            // copy (cast to double)
            pr[k] = it.value();
            ir[k] = it.row();
            k++;
        }
    }
    jc[M.outerSize()] = k;

}
示例#4
0
Eigen::VectorXd KronProdSPMat4(
    Eigen::SparseMatrix<double, Eigen::RowMajor> a0,
    Eigen::SparseMatrix<double, Eigen::RowMajor> a1,
    Eigen::SparseMatrix<double, Eigen::RowMajor> a2,
    Eigen::SparseMatrix<double, Eigen::RowMajor> a3,
    Eigen::VectorXd y) {

    signal(SIGSEGV, handler);   // install our handler
    Eigen::VectorXd retvec;
    retvec.setZero( a0.rows() * a1.rows() * a2.rows() * a3.rows()  );

    //loop rows a0
    for (int row_idx0=0; row_idx0<a0.outerSize(); ++row_idx0) {
        int row_offset1 = row_idx0;
        row_offset1    *= a1.rows();

        // loop rows a1
        for (int row_idx1=0; row_idx1<a1.outerSize(); ++row_idx1) {
            int row_offset2 = row_offset1 + row_idx1;
            row_offset2    *= a2.rows();

            // loop rows a2
            for (int row_idx2=0; row_idx2<a2.outerSize(); ++row_idx2) {
                int row_offset3 = row_offset2 + row_idx2;
                row_offset3    *= a3.rows();

                // loop rows a3
                for (int row_idx3=0; row_idx3<a3.outerSize(); ++row_idx3) {

                    // loop cols a0 (non-zero elements only)
                    for (Eigen::SparseMatrix<double,RowMajor>::InnerIterator it0(a0,row_idx0); it0; ++it0) {
                        int col_offset1 = it0.index();
                        col_offset1    *= a1.innerSize();
                        double factor1 = it0.value();

                        // loop cols a1
                        for (Eigen::SparseMatrix<double,RowMajor>::InnerIterator it1(a1,row_idx1); it1; ++it1) {
                            int col_offset2 = col_offset1 + it1.index();
                            col_offset2    *= a2.innerSize();
                            double factor2  = factor1 * it1.value();

                            //loop cols a2
                            for (Eigen::SparseMatrix<double,RowMajor>::InnerIterator it2(a2,row_idx2); it2; ++it2) {
                                int col_offset3 = col_offset2 + it2.index();
                                col_offset3    *= a3.innerSize();
                                double factor3  = factor2 * it2.value();

                                for (Eigen::SparseMatrix<double,RowMajor>::InnerIterator it3(a3,row_idx3); it3; ++it3) {
                                    retvec( row_offset3 + row_idx3 ) += factor3 * it3.value() * y( col_offset3 + it3.index() );
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return retvec;
}
示例#5
0
文件: find.cpp 项目: bbrrck/libigl
IGL_INLINE void igl::find(
  const Eigen::SparseMatrix<T>& X,
  Eigen::DenseBase<DerivedI> & I,
  Eigen::DenseBase<DerivedJ> & J,
  Eigen::DenseBase<DerivedV> & V)
{
  // Resize outputs to fit nonzeros
  I.derived().resize(X.nonZeros(),1);
  J.derived().resize(X.nonZeros(),1);
  V.derived().resize(X.nonZeros(),1);

  int i = 0;
  // Iterate over outside
  for(int k=0; k<X.outerSize(); ++k)
  {
    // Iterate over inside
    for(typename Eigen::SparseMatrix<T>::InnerIterator it (X,k); it; ++it)
    {
      V(i) = it.value();
      I(i) = it.row();
      J(i) = it.col();
      i++;
    }
  }
}
示例#6
0
void ProbitNoise::evalModel(Eigen::SparseMatrix<double> & Ytest, const int n, Eigen::VectorXd & predictions, Eigen::VectorXd & predictions_var, const Eigen::MatrixXd &cols, const Eigen::MatrixXd &rows, double mean_rating) {
  const unsigned N = Ytest.nonZeros();
  Eigen::VectorXd pred(N);
  Eigen::VectorXd test(N);

// #pragma omp parallel for schedule(dynamic,8) reduction(+:se, se_avg) <- dark magic :)
  for (int k = 0; k < Ytest.outerSize(); ++k) {
    int idx = Ytest.outerIndexPtr()[k];
    for (Eigen::SparseMatrix<double>::InnerIterator it(Ytest,k); it; ++it) {
     pred[idx] = nCDF(cols.col(it.col()).dot(rows.col(it.row())));
     test[idx] = it.value();

      // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm
      double pred_avg;
      if (n == 0) {
        pred_avg = pred[idx];
      } else {
        double delta = pred[idx] - predictions[idx];
        pred_avg = (predictions[idx] + delta / (n + 1));
        predictions_var[idx] += delta * (pred[idx] - pred_avg);
      }
      predictions[idx++] = pred_avg;

   }
  }
  auc_test_onesample = auc(pred,test);
  auc_test = auc(predictions, test);
}
示例#7
0
void ApplyConstraints(Eigen::SparseMatrix<float>& K, const std::vector<Constraint>& constraints)
{
	std::vector<int> indicesToConstraint;

	for (std::vector<Constraint>::const_iterator it = constraints.begin(); it != constraints.end(); ++it)
	{
		if (it->type & Constraint::UX)
		{
			indicesToConstraint.push_back(2 * it->node + 0);
		}
		if (it->type & Constraint::UY)
		{
			indicesToConstraint.push_back(2 * it->node + 1);
		}
	}

	for (int k = 0; k < K.outerSize(); ++k)
	{
		for (Eigen::SparseMatrix<float>::InnerIterator it(K, k); it; ++it)
		{
			for (std::vector<int>::iterator idit = indicesToConstraint.begin(); idit != indicesToConstraint.end(); ++idit)
			{
				SetConstraints(it, *idit);
			}
		}
	}
}
示例#8
0
文件: slice_into.cpp 项目: azer89/BBW
IGL_INLINE void igl::slice_into(
  const Eigen::SparseMatrix<T>& X,
  const Eigen::Matrix<int,Eigen::Dynamic,1> & R,
  const Eigen::Matrix<int,Eigen::Dynamic,1> & C,
  Eigen::SparseMatrix<T>& Y)
{

  int xm = X.rows();
  int xn = X.cols();
  assert(R.size() == xm);
  assert(C.size() == xn);
#ifndef NDEBUG
  int ym = Y.size();
  int yn = Y.size();
  assert(R.minCoeff() >= 0);
  assert(R.maxCoeff() < ym);
  assert(C.minCoeff() >= 0);
  assert(C.maxCoeff() < yn);
#endif

  // create temporary dynamic sparse matrix
  Eigen::DynamicSparseMatrix<T, Eigen::RowMajor>  dyn_Y(Y);
  // Iterate over outside
  for(int k=0; k<X.outerSize(); ++k)
  {
    // Iterate over inside
    for(typename Eigen::SparseMatrix<T>::InnerIterator it (X,k); it; ++it)
    {
      dyn_Y.coeffRef(R(it.row()),C(it.col())) = it.value();
    }
  }
  Y = Eigen::SparseMatrix<T>(dyn_Y);
}
// inserts the sparse matrix 'ins' into the sparse matrix 'original' in the place given by 'row' and 'col' integers
void insertSparseBlock(const Eigen::SparseMatrix<Scalar>& ins, Eigen::SparseMatrix<Scalar>& original, const unsigned int& row, const unsigned int& col)
{
  for (int k=0; k<ins.outerSize(); ++k)
    for (Eigen::SparseMatrix<Scalar>::InnerIterator iti(ins,k); iti; ++iti)
      original.coeffRef(iti.row() + row, iti.col() + col) = iti.value();

  original.makeCompressed();
}
示例#10
0
文件: util.hpp 项目: ALPSCore/CT-HYB
double maxAbsCoeff(const Eigen::SparseMatrix<T> &mat) {
  double maxval;
  int count = 0;
  for (int k = 0; k < mat.outerSize(); ++k) {
    for (typename Eigen::SparseMatrix<T>::InnerIterator it(mat, k); it; ++it) {
      maxval = count == 0 ? std::abs(it.value()) : std::max(std::abs(it.value()), maxval);
    }
  }
  return maxval;
}
示例#11
0
IGL_INLINE void igl::components(
  const Eigen::SparseMatrix<AScalar> & A,
  Eigen::PlainObjectBase<DerivedC> & C,
  Eigen::PlainObjectBase<Derivedcounts> & counts)
{
  using namespace Eigen;
  using namespace std;
  assert(A.rows() == A.cols() && "A should be square.");
  const size_t n = A.rows();
  Array<bool,Dynamic,1> seen = Array<bool,Dynamic,1>::Zero(n,1);
  C.resize(n,1);
  typename DerivedC::Scalar id = 0;
  vector<typename Derivedcounts::Scalar> vcounts;
  // breadth first search
  for(int k=0; k<A.outerSize(); ++k)
  {
    if(seen(k))
    {
      continue;
    }
    queue<int> Q;
    Q.push(k);
    vcounts.push_back(0);
    while(!Q.empty())
    {
      const int f = Q.front();
      Q.pop();
      if(seen(f))
      {
        continue;
      }
      seen(f) = true;
      C(f,0) = id;
      vcounts[id]++;
      // Iterate over inside
      for(typename SparseMatrix<AScalar>::InnerIterator it (A,f); it; ++it)
      {
        const int g = it.index();
        if(!seen(g) && it.value())
        {
          Q.push(g);
        }
      }
    }
    id++;
  }
  assert((size_t) id == vcounts.size());
  const size_t ncc = vcounts.size();
  assert((size_t)C.maxCoeff()+1 == ncc);
  counts.resize(ncc,1);
  for(size_t i = 0;i<ncc;i++)
  {
    counts(i) = vcounts[i];
  }
}
示例#12
0
IGL_INLINE void igl::repdiag(
  const Eigen::SparseMatrix<T>& A,
  const int d,
  Eigen::SparseMatrix<T>& B)
{
  using namespace std;
  using namespace Eigen;
  int m = A.rows();
  int n = A.cols();

  vector<Triplet<T> > IJV;
  IJV.reserve(A.nonZeros()*d);
  // Loop outer level
  for (int k=0; k<A.outerSize(); ++k)
  {
    // loop inner level
    for (typename Eigen::SparseMatrix<T>::InnerIterator it(A,k); it; ++it)
    {
      for(int i = 0;i<d;i++)
      {
        IJV.push_back(Triplet<T>(i*m+it.row(),i*n+it.col(),it.value()));
      }
    }
  }
  B.resize(m*d,n*d);
  B.setFromTriplets(IJV.begin(),IJV.end());
  

  // Q: Why is this **Very** slow?

  //int m = A.rows();
  //int n = A.cols();

  //B.resize(m*d,n*d);
  //// Reserve enough space for new non zeros
  //B.reserve(d*A.nonZeros());

  //// loop over reps
  //for(int i=0;i<d;i++)
  //{
  //  // Loop outer level
  //  for (int k=0; k<A.outerSize(); ++k)
  //  {
  //    // loop inner level
  //    for (typename Eigen::SparseMatrix<T>::InnerIterator it(A,k); it; ++it)
  //    {
  //      B.insert(i*m+it.row(),i*n+it.col()) = it.value();
  //    }
  //  }
  //}
  //B.makeCompressed();
}
示例#13
0
IGL_INLINE void igl::adjacency_matrix(
  const Eigen::PlainObjectBase<DerivedF> & F, 
  Eigen::SparseMatrix<T>& A)
{
  using namespace std;
  using namespace Eigen;
  typedef typename DerivedF::Scalar Index;

  typedef Triplet<T> IJV;
  vector<IJV > ijv;
  ijv.reserve(F.size()*2);
  // Loop over faces
  for(int i = 0;i<F.rows();i++)
  {
    // Loop over this face
    for(int j = 0;j<F.cols();j++)
    {
      // Get indices of edge: s --> d
      Index s = F(i,j);
      Index d = F(i,(j+1)%F.cols());
      ijv.push_back(IJV(s,d,1));
      ijv.push_back(IJV(d,s,1));
    }
  }

  const Index n = F.maxCoeff()+1;
  A.resize(n,n);
  switch(F.cols())
  {
    case 3:
      A.reserve(6*(F.maxCoeff()+1));
      break;
    case 4:
      A.reserve(26*(F.maxCoeff()+1));
      break;
  }
  A.setFromTriplets(ijv.begin(),ijv.end());

  // Force all non-zeros to be one

  // Iterate over outside
  for(int k=0; k<A.outerSize(); ++k)
  {
    // Iterate over inside
    for(typename Eigen::SparseMatrix<T>::InnerIterator it (A,k); it; ++it)
    {
      assert(it.value() != 0);
      A.coeffRef(it.row(),it.col()) = 1;
    }
  }
}
示例#14
0
IGL_INLINE void igl::harwell_boeing(
  const Eigen::SparseMatrix<Scalar> & A,
  int & num_rows,
  std::vector<Scalar> & V,
  std::vector<Index> & R,
  std::vector<Index> & C)
{
  num_rows = A.rows();
  int num_cols = A.cols();
  int nnz = A.nonZeros();
  V.resize(nnz);
  R.resize(nnz);
  C.resize(num_cols+1);

  // Assumes outersize is columns
  assert(A.cols() == A.outerSize());
  int column_pointer = 0;
  int i = 0;
  int k = 0;
  // Iterate over outside
  for(; k<A.outerSize(); ++k)
  {
    C[k] = column_pointer;
    // Iterate over inside
    for(typename Eigen::SparseMatrix<Scalar>::InnerIterator it (A,k); it; ++it)
    {
      V[i] = it.value();
      R[i] = it.row();
      i++;
      // Also increment column pointer
      column_pointer++; 
    }
  }
  // by convention C[num_cols] = nnz
  C[k] = column_pointer;
}
示例#15
0
Eigen::SparseMatrix<Type> kronecker(Eigen::SparseMatrix<Type> x,
				    Eigen::SparseMatrix<Type> y){
  typedef Eigen::Triplet<Type> T;
  typedef typename Eigen::SparseMatrix<Type>::InnerIterator Iterator;
  std::vector<T> tripletList;
  int n1=x.rows(),n2=x.cols(),n3=y.rows(),n4=y.cols();
  int i,j,k,l;
  // Loop over nonzeros of x
  for (int cx=0; cx<x.outerSize(); cx++)
    for (Iterator itx(x,cx); itx; ++itx)
      // Loop over nonzeros of y
      for (int cy=0; cy<y.outerSize(); cy++)
  	for (Iterator ity(y,cy); ity; ++ity)
  	  {
  	    i=itx.row();
  	    j=itx.col();
  	    k=ity.row();
  	    l=ity.col();
  	    tripletList.push_back(T(i*n3+k,j*n4+l, itx.value()*ity.value() ));
   	  }
  Eigen::SparseMatrix<Type> mat(n1*n3,n2*n4);
  mat.setFromTriplets(tripletList.begin(), tripletList.end());
  return mat;
}
示例#16
0
文件: full.cpp 项目: azer89/BBW
IGL_INLINE void igl::full(
  const Eigen::SparseMatrix<T> & A,
  Eigen::PlainObjectBase<DerivedB>& B)
{
  assert(false && "Obsolete. Just call B = Matrix(A)");
  using namespace Eigen;
  B = PlainObjectBase<DerivedB >::Zero(A.rows(),A.cols());
  // Iterate over outside
  for(int k=0; k<A.outerSize(); ++k)
  {
    // Iterate over inside
    for(typename SparseMatrix<T>::InnerIterator it (A,k); it; ++it)
    {
      B(it.row(),it.col()) = it.value();
    }
  }
}
void Dirichlet_LIMSolver3D::prepareProblemData(std::vector<int>& hessRowIdx, std::vector<int>& hessColIdx)
{
  const int numNodes = mesh->InitalVertices->rows();
  const int numTets = mesh->Tetrahedra->rows();

  Eigen::SparseMatrix<double> tempL;
  Eigen::SparseMatrix<double> M;
  igl::massmatrix(*mesh->InitalVertices,*mesh->Tetrahedra,igl::MASSMATRIX_TYPE_BARYCENTRIC, M);
  igl::cotmatrix(*mesh->InitalVertices, *mesh->Tetrahedra,tempL);
  tempL *= -1;

  // Create L matrix
  L.resize(numVariables,numVariables);
  std::vector<Eigen::Triplet<double> > triplets;
  for (int k=0;k<tempL.outerSize();++k)
  {
    for (Eigen::SparseMatrix<double>::InnerIterator it(tempL,k);it;++it)
    {
      int row = 3*it.row();
      int col = 3*it.col();
      triplets.push_back(Eigen::Triplet<double>(row,col,it.value()));
      triplets.push_back(Eigen::Triplet<double>(row+1,col+1,it.value()));
      triplets.push_back(Eigen::Triplet<double>(row+2,col+2,it.value()));
    }
  }
  L.setFromTriplets(triplets.begin(), triplets.end());

  TetrahedronVertexIdx.resize(12,mesh->Tetrahedra->rows());

  for (int k=0;k<L.outerSize();++k)
  {
    for (Eigen::SparseMatrix<double>::InnerIterator it(L,k);it;++it)
    {
      int row = it.row();
      int col = it.col();
      
      // std::sort for upper triangule matrix				
      if(row <= col)
      {
        hessRowIdx.push_back(row);
        hessColIdx.push_back(col);
      }
    }
  }
}
示例#18
0
inline std::unique_ptr<giss::VectorSparseMatrix> Eigen_to_giss(
    Eigen::SparseMatrix<double> const &mat)
{
    std::unique_ptr<giss::VectorSparseMatrix> ret(
        new giss::VectorSparseMatrix(giss::SparseDescr(
                                         mat.rows(), mat.cols())));

    int nz = mat.nonZeros();
    ret->reserve(nz);

    for (int k=0; k<mat.outerSize(); ++k) {
        for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it) {
            ret->set(it.row(), it.col(), it.value(), SparseMatrix::DuplicatePolicy::ADD);
        }
    }

    return ret;
}
示例#19
0
////  AdaptiveGaussianNoise  ////
void AdaptiveGaussianNoise::init(const Eigen::SparseMatrix<double> &train, double mean_value) {
  double se = 0.0;

#pragma omp parallel for schedule(dynamic, 4) reduction(+:se)
  for (int k = 0; k < train.outerSize(); ++k) {
    for (SparseMatrix<double>::InnerIterator it(train,k); it; ++it) {
      se += square(it.value() - mean_value);
    }
  }

  var_total = se / train.nonZeros();
  if (var_total <= 0.0 || std::isnan(var_total)) {
    // if var cannot be computed using 1.0
    var_total = 1.0;
  }
  // Var(noise) = Var(total) / (SN + 1)
  alpha     = (sn_init + 1.0) / var_total;
  alpha_max = (sn_max + 1.0) / var_total;
}
void Dirichlet_LIMSolver2D::prepareProblemData(std::vector<int>& hessRowIdx, std::vector<int>& hessColIdx)
{
  const int numNodes = mesh->InitalVertices->rows();
  const int numTriangles = mesh->Triangles->rows();
  
  // create sparse laplacian matrix L
  Eigen::SparseMatrix<double> tempL;
  igl::cotmatrix(*mesh->InitalVertices, *mesh->Triangles,tempL);
  tempL *= -1;

  // Create L matrix
  L.resize(numVariables,numVariables);
  std::vector<Eigen::Triplet<double> > triplets;
  for (int k=0;k<tempL.outerSize();++k)
  {
    for (Eigen::SparseMatrix<double>::InnerIterator it(tempL,k);it;++it)
    {
      int row = 2*it.row();
      int col = 2*it.col();
      triplets.push_back(Eigen::Triplet<double>(row,col,it.value()));
      triplets.push_back(Eigen::Triplet<double>(row+1,col+1,it.value()));
    }
  }
  L.setFromTriplets(triplets.begin(), triplets.end());

  for (int k=0;k<L.outerSize();++k)
  {
    for (Eigen::SparseMatrix<double>::InnerIterator it(L,k);it;++it)
    {
      int row = it.row();
      int col = it.col();
      
      // std::sort for upper triangule matrix
      if(row <= col)
      {
        hessRowIdx.push_back(row);
        hessColIdx.push_back(col);
      }
    }
  }
}
void compare(const Physika::SparseMatrix<mytype> &a, const Eigen::SparseMatrix<mytype> &b)
{
    /*if (a.nonZeros() != b.nonZeros())
    {
        cout<<"a.nonzeros:"<<a.nonZeros()<<endl;
        cout << "b.nonZeros:" << b.nonZeros() << endl;
        cout << "correctness bad!" << endl;
        return;
    }*/
        std::vector<Physika::Trituple<mytype>> v;
        bool correctness = true;
        for(unsigned int i = 0;i<a.rows();++i)
        {
            v = a.getRowElements(i);
            for(unsigned int j=0;j<v.size();++j)
            {
                int row = v[j].row(), col = v[j].col();
                mytype value = v[j].value();
                if(b.coeff(row,col) != value)
                {
                    cout<<"eror: "<<row<<' '<<col<<" value: psm "<<value<<" "<<b.coeff(row,col)<<endl;
                    correctness = false;
                    break;
                }
            }
        }
		for (unsigned int i = 0; i < b.outerSize();++i)
           for (Eigen::SparseMatrix<mytype>::InnerIterator it(b, i); it; ++it)
            {
                if (it.value() != a(it.row(), it.col()))
                {
                    cout << "eror: " << it.row() << ' ' << it.col() << " value: psm " << a(it.row(),it.col()) << " " << it.value() << endl;
                    correctness = false;
                    break;
                }
            }
        if(correctness) cout<<"correctness OK!"<<endl;
        else cout<<"correctness bad!"<<endl;
}
示例#22
0
IGL_INLINE void igl::components(
  const Eigen::SparseMatrix<AScalar> & A,
  Eigen::PlainObjectBase<DerivedC> & C)
{
  assert(A.rows() == A.cols());
  using namespace Eigen;
  // THIS IS DENSE:
  //boost::adjacency_matrix<boost::undirectedS> bA(A.rows());
  boost::adjacency_list<boost::vecS,boost::vecS,boost::undirectedS> bA(A.rows());
  for(int j=0; j<A.outerSize();j++)
  {
    // Iterate over inside
    for(typename SparseMatrix<AScalar>::InnerIterator it (A,j); it; ++it)
    {
      if(0 != it.value())
      {
        boost::add_edge(it.row(),it.col(),bA);
      }
    }
  }
  C.resize(A.rows(),1);
  boost::connected_components(bA,C.data());
}
示例#23
0
inline void igl::PlanarizerShapeUp<DerivedV, DerivedF>::assembleQ()
{
  std::vector<Eigen::Triplet<typename DerivedV::Scalar> > tripletList;
  
  // assemble the Ni matrix
  assembleNi();
  
  for (int fi = 0; fi< numF; fi++)
  {
    Eigen::SparseMatrix<typename DerivedV::Scalar > Sfi;
    assembleSelector(fi, Sfi);
    
    // the final matrix per face
    Eigen::SparseMatrix<typename DerivedV::Scalar > Qi = weightsSqrt(fi)*Ni*Sfi;
    // put it in the correct block of Q
    // todo: this can be made faster by omitting the selector matrix
    for (int k=0; k<Qi.outerSize(); ++k)
      for (typename Eigen::SparseMatrix<typename DerivedV::Scalar >::InnerIterator it(Qi,k); it; ++it)
      {
        typename DerivedV::Scalar val = it.value();
        int row = it.row();
        int col = it.col();
        tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(row+3*ni*fi,col,val));
      }
  }
  
  Q.resize(3*ni*numF,3*numV);
  Q.setFromTriplets(tripletList.begin(), tripletList.end());
  // the actual lhs matrix is Q'*Q
  // prefactor that matrix
  solver.compute(Q.transpose()*Q);
  if(solver.info()!=Eigen::Success)
  {
    std::cerr << "Cholesky failed - PlanarizerShapeUp.cpp" << std::endl;
    assert(0);
  }
}
示例#24
0
文件: sum.cpp 项目: azer89/BBW
IGL_INLINE void igl::sum(
  const Eigen::SparseMatrix<T>& X, 
  const int dim,
  Eigen::SparseVector<T>& S)
{
  // dim must be 2 or 1
  assert(dim == 1 || dim == 2);
  // Get size of input
  int m = X.rows();
  int n = X.cols();
  // resize output
  if(dim==1)
  {
    S = Eigen::SparseVector<T>(n);
  }else
  {
    S = Eigen::SparseVector<T>(m);
  }

  // Iterate over outside
  for(int k=0; k<X.outerSize(); ++k)
  {
    // Iterate over inside
    for(typename Eigen::SparseMatrix<T>::InnerIterator it (X,k); it; ++it)
    {
      if(dim == 1)
      {
        S.coeffRef(it.col()) += it.value();
      }else
      {
        S.coeffRef(it.row()) += it.value();
      }
    }
  }

}
示例#25
0
void AdaptiveGaussianNoise::update(const Eigen::SparseMatrix<double> &train, double mean_value, std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples)
{
  double sumsq = 0.0;
  MatrixXd & U = *samples[0];
  MatrixXd & V = *samples[1];

#pragma omp parallel for schedule(dynamic, 4) reduction(+:sumsq)
  for (int j = 0; j < train.outerSize(); j++) {
    auto Vj = V.col(j);
    for (SparseMatrix<double>::InnerIterator it(train, j); it; ++it) {
      double Yhat = Vj.dot( U.col(it.row()) ) + mean_value;
      sumsq += square(Yhat - it.value());
    }
  }
  // (a0, b0) correspond to a prior of 1 sample of noise with full variance
  double a0 = 0.5;
  double b0 = 0.5 * var_total;
  double aN = a0 + train.nonZeros() / 2.0;
  double bN = b0 + sumsq / 2.0;
  alpha = rgamma(aN, 1.0 / bN);
  if (alpha > alpha_max) {
    alpha = alpha_max;
  }
}
void LSConformal_LIMSolver2D::prepareProblemData(std::vector<int>& hessRowIdx, std::vector<int>& hessColIdx)
{
  const int numNodes = mesh->InitalVertices->rows();
  const int numTriangles = mesh->Triangles->rows();

  // create sparse laplacian matrix L
  Eigen::SparseMatrix<double> tempL;//(numNodes,numNodes);
  igl::cotmatrix(*mesh->InitalVertices, *mesh->Triangles,tempL);
  tempL *= -1;

  // Create L matrix
  L.resize(numVariables,numVariables);
  std::vector<Eigen::Triplet<double> > triplets;
  for (int k=0;k<tempL.outerSize();++k)
  {
    for (Eigen::SparseMatrix<double>::InnerIterator it(tempL,k);it;++it)
    {
      int row = 2*it.row();
      int col = 2*it.col();
      triplets.push_back(Eigen::Triplet<double>(row,col,it.value()));
      triplets.push_back(Eigen::Triplet<double>(row+1,col+1,it.value()));
    }
  }
  L.setFromTriplets(triplets.begin(), triplets.end());

  // Create A matrix
  int numBorderVertices = mesh->BorderVertices->rows();
  
  Eigen::SparseMatrix<double> B, C, BNonZero, CNonZero;
  A.resize(2*numNodes,2*numNodes);
  B.resize(2*numBorderVertices, 2*numNodes);
  C.resize(2*numBorderVertices, 2*numNodes);
  
  std::vector<Eigen::Triplet<double> > tripletsB, tripletsC;
  for(int i=0,j=numBorderVertices-1;i<mesh->BorderVertices->rows();j=i,i++)
  {
    int rIdx = 2*i;
    int iIdx = 2*mesh->BorderVertices->coeff(i); 	
    int jIdx = 2*mesh->BorderVertices->coeff(j);

    tripletsB.push_back(Eigen::Triplet<double>(rIdx,jIdx,1));
    tripletsB.push_back(Eigen::Triplet<double>(rIdx+1,jIdx+1,-1));
    tripletsC.push_back(Eigen::Triplet<double>(rIdx,iIdx+1,1));
    tripletsC.push_back(Eigen::Triplet<double>(rIdx+1,iIdx,1));
  }
  B.setFromTriplets(tripletsB.begin(), tripletsB.end());
  C.setFromTriplets(tripletsC.begin(), tripletsC.end());

  A = B.transpose()*C;
  Eigen::SparseMatrix<double> AT = A.transpose();
  L = L - 0.5*(A+AT);

  for (int k=0;k<L.outerSize();++k)
  {
    for (Eigen::SparseMatrix<double>::InnerIterator it(L,k);it;++it)
    {
      int row = it.row();
      int col = it.col();
      
      // std::sort for upper triangule matrix				
      if(row <= col)
      {
        hessRowIdx.push_back(row);
        hessColIdx.push_back(col);
      }
    }
  }
}
IGL_INLINE void igl::slice(
  const Eigen::SparseMatrix<TX>& X,
  const Eigen::Matrix<int,Eigen::Dynamic,1> & R,
  const Eigen::Matrix<int,Eigen::Dynamic,1> & C,
  Eigen::SparseMatrix<TY>& Y)
{
#if 1
  int xm = X.rows();
  int xn = X.cols();
  int ym = R.size();
  int yn = C.size();

  // special case when R or C is empty
  if(ym == 0 || yn == 0)
  {
    Y.resize(ym,yn);
    return;
  }

  assert(R.minCoeff() >= 0);
  assert(R.maxCoeff() < xm);
  assert(C.minCoeff() >= 0);
  assert(C.maxCoeff() < xn);

  // Build reindexing maps for columns and rows, -1 means not in map
  std::vector<std::vector<int> > RI;
  RI.resize(xm);
  for(int i = 0;i<ym;i++)
  {
    RI[R(i)].push_back(i);
  }
  std::vector<std::vector<int> > CI;
  CI.resize(xn);
  // initialize to -1
  for(int i = 0;i<yn;i++)
  {
    CI[C(i)].push_back(i);
  }
  // Resize output
  Eigen::DynamicSparseMatrix<TY, Eigen::RowMajor> dyn_Y(ym,yn);
  // Take a guess at the number of nonzeros (this assumes uniform distribution
  // not banded or heavily diagonal)
  dyn_Y.reserve((X.nonZeros()/(X.rows()*X.cols())) * (ym*yn));
  // Iterate over outside
  for(int k=0; k<X.outerSize(); ++k)
  {
    // Iterate over inside
    for(typename Eigen::SparseMatrix<TX>::InnerIterator it (X,k); it; ++it)
    {
      std::vector<int>::iterator rit, cit;
      for(rit = RI[it.row()].begin();rit != RI[it.row()].end(); rit++)
      {
        for(cit = CI[it.col()].begin();cit != CI[it.col()].end(); cit++)
        {
          dyn_Y.coeffRef(*rit,*cit) = it.value();
        }
      }
    }
  }
  Y = Eigen::SparseMatrix<TY>(dyn_Y);
#else

  // Alec: This is _not_ valid for arbitrary R,C since they don't necessary
  // representation a strict permutation of the rows and columns: rows or
  // columns could be removed or replicated. The removal of rows seems to be
  // handled here (although it's not clear if there is a performance gain when
  // the #removals >> #remains). If this is sufficiently faster than the
  // correct code above, one could test whether all entries in R and C are
  // unique and apply the permutation version if appropriate.
  //

  int xm = X.rows();
  int xn = X.cols();
  int ym = R.size();
  int yn = C.size();

  // special case when R or C is empty
  if(ym == 0 || yn == 0)
  {
    Y.resize(ym,yn);
    return;
  }

  assert(R.minCoeff() >= 0);
  assert(R.maxCoeff() < xm);
  assert(C.minCoeff() >= 0);
  assert(C.maxCoeff() < xn);

  // initialize row and col permutation vectors
  Eigen::VectorXi rowIndexVec = Eigen::VectorXi::LinSpaced(xm,0,xm-1);
  Eigen::VectorXi rowPermVec  = Eigen::VectorXi::LinSpaced(xm,0,xm-1);
  for(int i=0;i<ym;i++)
  {
    int pos = rowIndexVec.coeffRef(R(i));
    if(pos != i)
    {
      int& val = rowPermVec.coeffRef(i);
      std::swap(rowIndexVec.coeffRef(val),rowIndexVec.coeffRef(R(i)));
      std::swap(rowPermVec.coeffRef(i),rowPermVec.coeffRef(pos));
    }
  }
  Eigen::PermutationMatrix<Eigen::Dynamic,Eigen::Dynamic,int> rowPerm(rowIndexVec);

  Eigen::VectorXi colIndexVec = Eigen::VectorXi::LinSpaced(xn,0,xn-1);
  Eigen::VectorXi colPermVec =  Eigen::VectorXi::LinSpaced(xn,0,xn-1);
  for(int i=0;i<yn;i++)
  {
    int pos = colIndexVec.coeffRef(C(i));
    if(pos != i)
    {
      int& val = colPermVec.coeffRef(i);
      std::swap(colIndexVec.coeffRef(val),colIndexVec.coeffRef(C(i)));
      std::swap(colPermVec.coeffRef(i),colPermVec.coeffRef(pos));
    }
  }
  Eigen::PermutationMatrix<Eigen::Dynamic,Eigen::Dynamic,int> colPerm(colPermVec);

  Eigen::SparseMatrix<T> M = (rowPerm * X);
  Y = (M * colPerm).block(0,0,ym,yn);
#endif
}
示例#28
0
IGL_INLINE void igl::orientable_patches(
  const Eigen::PlainObjectBase<DerivedF> & F,
  Eigen::PlainObjectBase<DerivedC> & C,
  Eigen::SparseMatrix<AScalar> & A)
{
  using namespace Eigen;
  using namespace std;

  // simplex size
  assert(F.cols() == 3);

  // List of all "half"-edges: 3*#F by 2
  Matrix<typename DerivedF::Scalar, Dynamic, 2> allE,sortallE,uE;
  allE.resize(F.rows()*3,2);
  Matrix<int,Dynamic,2> IX;
  VectorXi IA,IC;
  allE.block(0*F.rows(),0,F.rows(),1) = F.col(1);
  allE.block(0*F.rows(),1,F.rows(),1) = F.col(2);
  allE.block(1*F.rows(),0,F.rows(),1) = F.col(2);
  allE.block(1*F.rows(),1,F.rows(),1) = F.col(0);
  allE.block(2*F.rows(),0,F.rows(),1) = F.col(0);
  allE.block(2*F.rows(),1,F.rows(),1) = F.col(1);
  // Sort each row
  sort(allE,2,true,sortallE,IX);
  //IC(i) tells us where to find sortallE(i,:) in uE: 
  // so that sortallE(i,:) = uE(IC(i),:)
  unique_rows(sortallE,uE,IA,IC);
  // uE2FT(e,f) = 1 means face f is adjacent to unique edge e
  vector<Triplet<AScalar> > uE2FTijv(IC.rows());
  for(int e = 0;e<IC.rows();e++)
  {
    uE2FTijv[e] = Triplet<AScalar>(e%F.rows(),IC(e),1);
  }
  SparseMatrix<AScalar> uE2FT(F.rows(),uE.rows());
  uE2FT.setFromTriplets(uE2FTijv.begin(),uE2FTijv.end());
  // kill non-manifold edges
  for(int j=0; j<(int)uE2FT.outerSize();j++)
  {
    int degree = 0;
    for(typename SparseMatrix<AScalar>::InnerIterator it (uE2FT,j); it; ++it)
    {
      degree++;
    }
    // Iterate over inside
    if(degree > 2)
    {
      for(typename SparseMatrix<AScalar>::InnerIterator it (uE2FT,j); it; ++it)
      {
        uE2FT.coeffRef(it.row(),it.col()) = 0;
      }
    }
  }
  // Face-face Adjacency matrix
  SparseMatrix<AScalar> uE2F;
  uE2F = uE2FT.transpose().eval();
  A = uE2FT*uE2F;
  // All ones
  for(int j=0; j<A.outerSize();j++)
  {
    // Iterate over inside
    for(typename SparseMatrix<AScalar>::InnerIterator it (A,j); it; ++it)
    {
      if(it.value() > 1)
      {
        A.coeffRef(it.row(),it.col()) = 1;
      }
    }
  }
  //% Connected components are patches
  //%C = components(A); % alternative to graphconncomp from matlab_bgl
  //[~,C] = graphconncomp(A);
  // graph connected components using boost
  components(A,C);

}
void Poisson_LIMSolver2D::prepareProblemData(std::vector<int>& hessRowIdx, std::vector<int>& hessColIdx)
{
  const int numNodes = mesh->InitalVertices->rows();

  // create sparse gradient operator matrix
  Eigen::SparseMatrix<double> tempG;
  Eigen::VectorXd dAreas,dAreasTemp;
  Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> vertices(*mesh->DeformedVertices);
  Eigen::Matrix<int,Eigen::Dynamic,Eigen::Dynamic> faces(*mesh->Triangles);
  
  igl::grad(vertices,faces,tempG);

  // Only get x and y derivatives of elements as z is zero
  int newRowSize = 2.0/3.0*tempG.rows();
  std::vector<Eigen::Triplet<double> > triplets;
  for (int k=0;k<tempG.outerSize();++k)
  {
    for (Eigen::SparseMatrix<double>::InnerIterator it(tempG,k);it;++it)
    {
      int row = it.row();
      int col = it.col();
      if(row < newRowSize)
      {
        triplets.push_back(Eigen::Triplet<double>(row,col,it.value()));
      }
    }
  }
  tempG.setZero();
  tempG.resize(newRowSize,tempG.cols());
  tempG.setFromTriplets(triplets.begin(), triplets.end());

  // Extend gradient operator matrix for x and y scalar function
  triplets.clear();
  G.resize(newRowSize*2,tempG.cols()*2);
  for (int k=0;k<tempG.outerSize();++k)
  {
    for (Eigen::SparseMatrix<double>::InnerIterator it(tempG,k);it;++it)
    {
      int row = it.row()*2;
      int col = it.col()*2;
      triplets.push_back(Eigen::Triplet<double>(row,col,it.value()));
      triplets.push_back(Eigen::Triplet<double>(row+1,col+1,it.value()));
    }
  }
  G.setFromTriplets(triplets.begin(), triplets.end());

  // Compute area weights
  Eigen::SparseMatrix<double> M;
  igl::doublearea(vertices,faces,dAreas);
  triplets.clear();
  M.resize(dAreas.rows()*4,dAreas.rows()*4);
  for(int r=0;r<dAreas.rows();r++)
  {
    int id = 4*r;
    triplets.push_back(Eigen::Triplet<double>(id,id,dAreas(r)));
    triplets.push_back(Eigen::Triplet<double>(id+1,id+1,dAreas(r)));
    triplets.push_back(Eigen::Triplet<double>(id+2,id+2,dAreas(r)));
    triplets.push_back(Eigen::Triplet<double>(id+3,id+3,dAreas(r)));
  }
  M.setFromTriplets(triplets.begin(),triplets.end());

  // Compute laplacian
  L = 0.5*G.transpose()*M*G;

  for (int k=0;k<L.outerSize();++k)
  {
    for (Eigen::SparseMatrix<double>::InnerIterator it(L,k);it;++it)
    {
      int row = it.row();
      int col = it.col();
      
      // std::sort for upper triangule matrix				
      if(row <= col)
      {
        hessRowIdx.push_back(row);
        hessColIdx.push_back(col);
      }
    }
  }

  GTb = 0.5*G.transpose()*M*b;
  constantEnergyPart = b.transpose()*b;
}
	void exportTriplets(const char* filename) {ofstream f; f.open(filename);
		for (int k=0; k<A.outerSize(); ++k)
		  	for (Eigen::SparseMatrix<double>::InnerIterator it(A,k); it; ++it) f<< it.row()<<" "<< it.col()<<" "<<it.value()<<endl; f.close();};