Exemplo n.º 1
0
    std::vector<VectorI> enumerate(const VectorI& repetitions) {
        std::vector<VectorI> result;
        const size_t dim = repetitions.size();
        if (dim == 2) {
            for (size_t i=0; i<repetitions[0]; i++) {
                for (size_t j=0; j<repetitions[1]; j++) {
                    result.push_back(Vector2I(i,j));
                }
            }
        } else if (dim == 3) {
            for (size_t i=0; i<repetitions[0]; i++) {
                for (size_t j=0; j<repetitions[1]; j++) {
                    for (size_t k=0; k<repetitions[2]; k++) {
                        result.push_back(Vector3I(i,j,k));
                    }
                }
            }
        } else {
            std::stringstream err_msg;
            err_msg << "Unsupported dim: " << dim;
            throw NotImplementedError(err_msg.str());
        }

        return result;
    }
Exemplo n.º 2
0
void Deform::set_soft_ctrs(const VectorF &T, const VectorI &idx_T)
{
    assert(T.size()/3 == idx_T.size());

    for (int i = 0, i_end = idx_T.size(); i < i_end; ++ i)
    {
        int cid = idx_T[i];

        Eigen::Vector3f ctr; 
        ctr << T[3*i], T[3*i+1], T[3*i+2];

        soft_ctrs.push_back(Constraint(ctr, cid));
    }

    std::sort(soft_ctrs.begin(), soft_ctrs.end(), ConstraintCompare());
}
Exemplo n.º 3
0
ZSparseMatrix Assembler2D::getMassMatrix(bool lumped, int repeats) {
    double p = m_density;

    typedef Eigen::Triplet<double> T;
    std::vector<T> triplets;

    if (lumped) {
        for (size_t i=0; i<m_mesh->getNbrElements(); i++) {
            VectorI idx = m_mesh->getElement(i);
            assert(idx.size() == 3);
            double V = m_mesh->getElementVolume(i);

            for (size_t j=0; j<idx.size(); j++)
                for (size_t l=0; l<repeats; l++)
                    triplets.push_back(T(repeats*idx[j]+l,
                                         repeats*idx[j]+l, p*V/3.0));
        }
    } else {
        double coeff_jj = 1.0 / 6.0,
               coeff_jk = 1.0 / 12.0;
        for (size_t i=0; i<m_mesh->getNbrElements(); ++i) {
            VectorI idx = m_mesh->getElement(i);
            assert(idx.size() == 3);
            double V = m_mesh->getElementVolume(i);

            for (size_t j=0; j<3; ++j) {
                for (size_t k=0; k<3; ++k) {
                    if (idx[j] == idx[k]) {
                        for (size_t l=0; l<repeats; ++l)
                            triplets.push_back(
                                T(repeats*idx[j]+l, repeats*idx[k]+l, p*V*coeff_jj));
                    } else {
                        for (size_t l=0; l<repeats; ++l)
                            triplets.push_back(
                                T(repeats*idx[j]+l, repeats*idx[k]+l, p*V*coeff_jk));
                    }
                }
            }
        }
    }

    Eigen::SparseMatrix<double> M = Eigen::SparseMatrix<double>(
                                        repeats*m_mesh->getNbrNodes(), repeats*m_mesh->getNbrNodes());
    M.setFromTriplets(triplets.begin(), triplets.end());
    return ZSparseMatrix(M);
}
Exemplo n.º 4
0
 VectorI map_indices(const VectorI& face, const VectorI& index_map) {
     const size_t vertex_per_face = face.size();
     VectorI index(vertex_per_face);
     for (size_t i=0; i<vertex_per_face; i++) {
         index[i] = index_map[face[i]];
     }
     return index;
 }
Exemplo n.º 5
0
bool SimpleInflator::belong_to_the_same_loop(
        const VectorI& indices, const VectorI& source_ids) const {
    const size_t size = indices.size();
    assert(size > 0);
    const int id = source_ids[indices[0]];
    for (size_t i=1; i<size; i++) {
        if (id != source_ids[indices[i]]) return false;
    }
    return true;
}
Exemplo n.º 6
0
VectorF Assembler::getDivergence(double* vector_field, int num_vector_field) {
    size_t num_node = m_mesh->getNbrNodes();
    size_t num_elem = m_mesh->getNbrElements();
    size_t dim = m_mesh->getDim();

    assert(num_vector_field == dim*num_node);

    VectorF div(num_elem);
    for (size_t i=0; i<num_elem; i++) {
        div[i] = 0;
        VectorI elem = m_mesh->getElement(i);
        const Eigen::MatrixXd& DN = m_DN[i];
        for (size_t j=0; j<elem.size(); j++) {
            for (size_t k=0; k<dim; k++) {
                div[i] += DN(j,k) * vector_field[elem[j]*dim+k];
            }
        }
    }
    return div;
}
Exemplo n.º 7
0
void Deform::find_share_vertex(int pi, int pj, VectorI &share_vertex)
{
    vector<int> vertices;
    set_intersection(adj_list[pi].begin(), adj_list[pi].end(), adj_list[pj].begin(), adj_list[pj].end(), back_inserter(vertices));
    for (auto &i : vertices) {
        vector<int> f;
        f.push_back(pi);
        f.push_back(pj);
        f.push_back(i);
        sort(f.begin(), f.end());
        vector<Vector3i>::iterator it = find(face_list.begin(), face_list.end(), Map<Vector3i>(&f[0]));
        if (it != face_list.end()) {
            if ((*it)(0) != pi && (*it)(0) != pj) share_vertex.push_back((*it)(0));
            else if ((*it)(1) != pi && (*it)(1) != pj) share_vertex.push_back((*it)(1));
            else share_vertex.push_back((*it)(2));
        }
    }
    if (share_vertex.size() > 2) {
        cout << "share vertices number warning: " << share_vertex.size() << endl;
    }
}
Exemplo n.º 8
0
ZSparseMatrix Assembler2D::getStiffnessMatrix() {
    // Elastic modulii
    //
    Eigen::MatrixXd& D = m_D;
    Eigen::MatrixXd& C = m_C;

    typedef Eigen::Triplet<double> T;
    std::vector<T> triplets;

    for (size_t i=0; i<m_mesh->getNbrElements(); ++i)
    {
        VectorI idx = m_mesh->getElement(i);
        assert(idx.size() == 3);

        Eigen::MatrixXd& dN = m_DN[i];

        // Small strain-displacement matrix
        //
        Eigen::MatrixXd B(3,6);
        B << dN(0,0),    0.0,dN(1,0),    0.0,dN(2,0),    0.0,
        0.0    ,dN(0,1),    0.0,dN(1,1),    0.0,dN(2,1),
        0.5*dN(0,1),0.5*dN(0,0),
        0.5*dN(1,1),0.5*dN(1,0),
        0.5*dN(2,1),0.5*dN(2,0);

        Eigen::MatrixXd k_el = B.transpose() * D * C * B * m_mesh->getElementVolume(i);

        for (size_t j=0; j<3; ++j)
            for (size_t k=0; k<3; ++k)
                for (size_t l=0; l<2; ++l)
                    for (size_t m=0; m<2; ++m)
                        triplets.push_back(T(2*idx[j]+l, 2*idx[k]+m, k_el(2*j+l, 2*k+m)));
    }

    Eigen::SparseMatrix<double> K = Eigen::SparseMatrix<double>(2*m_mesh->getNbrNodes(), 2*m_mesh->getNbrNodes());
    K.setFromTriplets(triplets.begin(), triplets.end());
    ZSparseMatrix tmp = ZSparseMatrix(K);
    return tmp;
}
Exemplo n.º 9
0
ZSparseMatrix Assembler2D::getBdLaplacianMatrix() {
    typedef Eigen::Triplet<double> T;
    std::vector<T> triplets;

    size_t num_bdv = m_mesh->getNbrBoundaryNodes();
    size_t num_bdf = m_mesh->getNbrBoundaryFaces();

    // Compute lumped mass
    VectorF lumped_mass(num_bdv);
    for (size_t i=0; i<num_bdv; i++) {
        VectorI neighbor_faces = m_mesh->getBoundaryNodeAdjacentBoundaryFaces(i);
        assert(neighbor_faces.size() == 2);

        double total_weight =
            m_mesh->getBoundaryFaceArea(neighbor_faces[0]) +
            m_mesh->getBoundaryFaceArea(neighbor_faces[1]);
        lumped_mass[i] = 0.5 * total_weight;
    }

    // Compute laplacian matrix.
    for (size_t i=0; i<num_bdf; i++) {
        VectorI face = m_mesh->getBoundaryFace(i);
        assert(face.size() == 2);

        double l = m_mesh->getBoundaryFaceArea(i);
        size_t v1 = m_mesh->getBoundaryIndex(face[0]);
        size_t v2 = m_mesh->getBoundaryIndex(face[1]);
        double weight = 1.0 / l;
        triplets.push_back(T(v1, v1, -weight / lumped_mass[v1]));
        triplets.push_back(T(v1, v2,  weight / lumped_mass[v1]));
        triplets.push_back(T(v2, v1,  weight / lumped_mass[v2]));
        triplets.push_back(T(v2, v2, -weight / lumped_mass[v2]));
    }

    Eigen::SparseMatrix<double> Lb = Eigen::SparseMatrix<double>(num_bdv, num_bdv);
    Lb.setFromTriplets(triplets.begin(), triplets.end());
    return ZSparseMatrix(Lb);
}
Exemplo n.º 10
0
void MSHWriter::write(const VectorF& vertices, const VectorI& faces, const VectorI& voxels,
        size_t dim, size_t vertex_per_face, size_t vertex_per_voxel) {
    MshSaver saver(m_filename, !m_in_ascii);
    MshSaver::ElementType type;
    if (voxels.size() == 0) {
        type = get_face_type(vertex_per_face);
        saver.save_mesh(vertices, faces, dim, type);
    } else {
        type = get_voxel_type(vertex_per_voxel);
        saver.save_mesh(vertices, voxels, dim, type);
    }
    if (m_attr_names.size() != 0) {
        std::cerr << "Warning: all attributes are ignored." << std::endl;
    }
}
Exemplo n.º 11
0
void OffsetParameters::add(const VectorI& roi,
        const std::string& formula, Float value, size_t axis) {
    const Float tol = 1e-12;
    const size_t dim = m_wire_network->get_dim();
    const size_t num_vertices = m_wire_network->get_num_vertices();
    const VectorF bbox_min = m_wire_network->get_bbox_min();
    const VectorF bbox_max = m_wire_network->get_bbox_max();
    const VectorF bbox_center = 0.5 * (bbox_min + bbox_max);
    const MatrixFr& vertices = m_wire_network->get_vertices();
    assert(axis < dim);

    VectorF roi_min = bbox_max;
    VectorF roi_max = bbox_min;

    const size_t num_roi = roi.size();
    for (size_t i=0; i<num_roi; i++) {
        size_t v_idx = roi[i];
        assert(v_idx < num_vertices);
        const VectorF& v = vertices.row(v_idx);
        roi_min = roi_min.cwiseMin(v);
        roi_max = roi_max.cwiseMax(v);
    }

    if (fabs(roi_max[axis] - bbox_center[axis]) < tol &&
        fabs(roi_min[axis] - bbox_center[axis]) < tol) {
        // No dof in this axis without destroy symmetry.
        return;
    }
    if (roi_min[axis] > bbox_min[axis] + tol &&
            roi_max[axis] < bbox_max[axis] - tol) {
        m_params.emplace_back(PatternParameter::Ptr(
                    new VertexOffsetParameter(m_wire_network, axis)));
        PatternParameter::Ptr param = m_params.back();
        param->set_roi(roi);
        param->set_value(value);
        param->set_formula(formula);
    }
}
Exemplo n.º 12
0
  ALGEB getVector(MKernelVector kv, ALGEB* args)
  {
    // Get the key, declare variables
    int key = MapleToInteger32(kv,args[1]), flag;
    char err[] = "ERROR!  The associated Vector object does not exist!";
    M_INT index, bound[2];
    RTableData d;
    RTableSettings s;
    ALGEB rtable, blank;
    char MapleStatement[100] = "rtable(1..";


    // Check to see if the object pointed to by key is in the type table.  If not, panic
    std::map<int,int>::iterator f_i = typeTable.find(key);
    if(f_i == typeTable.end() ) {
      MapleRaiseError(kv, err);
    }

    // Otherwise, we have our object
    flag = f_i->second;

    // Get a pointer to the actual data
    std::map<int,void*>::iterator h_i = hashTable.find(key);
    if(h_i != hashTable.end() ) {

      // Diverge over whether we are using maple 7 or 8 ( and 5 & 6)
      // in Maple, arg 3 is a flag indicating which method to use
      switch( MapleToInteger32(kv, args[3])) {

	// In this case, Maple 7 is being used, we have to construct a call using "EvalMapleStatement()"
	// to call the RTable constructor
         case 1:

	   switch(flag) {
	   case SmallV:{
	     // Get the vector
	     Vectorl* V = (Vectorl*) h_i->second;
	     Vectorl::const_iterator V_i;

	     // Create the Maple object
	     sprintf(MapleStatement + strlen(MapleStatement), "%d", V->size() );
	     strcat(MapleStatement, ", subtype=Vector[column], storage=sparse)");
	     rtable = kv->evalMapleStatement(MapleStatement);

	     // populate the Maple vector w/ the entries from V above
	     for(index = 1, V_i = V->begin(); V_i != V->end(); ++V_i, ++index) {
	       d.dag = ToMapleInteger(kv, *V_i); // d is a union, dag is the
	                                         // ALGEB union field
	       RTableAssign(kv, rtable, &index, d);
	     }
	   }
	   break;

	   case LargeV: {
	     // This part works the same way as above
	     VectorI* V = (VectorI*) h_i->second;
	     VectorI::const_iterator V_i;
	     sprintf(MapleStatement + strlen(MapleStatement), "%d", V->size() );
	     strcat(MapleStatement, ",subtype=Vector[column], storage=sparse)");
	     rtable = kv->evalMapleStatement(MapleStatement);

	     // Use maple callback to call the procedure from Maple that translates a gmp integer
	     // into a large maple integer.  Then put this into the Maple vector
	     for(index = 1, V_i = V->begin(); V_i != V->end(); ++V_i, ++index) {

	       /* Okay, here's how this line works.  Basically,
		* in order to set the entries of this RTable to
		* multi-precision integers, I have to first use my own conversion
		* method, LiToM, to convert the integer entry to a ALGEB structure,
		* then do a callback into Maple that calls the ExToM procedure,
		* which converts the results of LiToM into a Maple multi-precision
		* integer. At the moment, this is the best idea I've got as to
		* how to convert a GMP integer into a Maple representation in one shot.
		*/

	       d.dag = EvalMapleProc(kv,args[2],1,LiToM(kv, *V_i, blank));
	       RTableAssign(kv, rtable, &index, d);
	     }
	   }
	   break;

	   default:
	     MapleRaiseError(kv, err);
	     break;
	   }
	   break;

	   // In this case, use the simpler RTableCreate function, rather than building a string
	   // that must be parsed by maple

	   case 2:

	     kv->rtableGetDefaults(&s); // Get default settings - set datatype to Maple,
                               // DAGTAG to anything
	     s.subtype = 2; // Subtype set to column vector
	     s.storage = 4; // Storage set to rectangular
	     s.num_dimensions = 1; // What do you think this means :-)
	     bound[0] = 1; // Set the lower bounds of each dimension to 0

	     switch(flag) {// Switch on data type of vector
	     case SmallV:{ // single word integer entry vector
	       Vectorl* V = (Vectorl*) h_i->second;
	       Vectorl::const_iterator V_i;
	       bound[1] = V->size();
	       rtable = kv->rtableCreate(&s, NULL, bound); // Create the Maple vector

	       for(index = 1, V_i = V->begin(); V_i != V->end(); ++V_i, ++index) {
		 d.dag = ToMapleInteger(kv, *V_i); // d is a union, dag is the
	                                        // ALGEB union field
		 RTableAssign(kv, rtable, &index, d);
	       }
	     }
	     break;

	     case LargeV: { // Same as above for multi-word integer entry vector
	       VectorI* V = (VectorI*) h_i->second;
	       VectorI::const_iterator V_i;
	       bound[1] = V->size();
	       rtable = kv->rtableCreate(&s, NULL, bound);

	       for(index = 1, V_i = V->begin(); V_i != V->end(); ++V_i, ++index) {


		 /* Okay, here's how this line works.  Basically,
		  * in order to set the entries of this RTable to
		  * multi-precision integers, I have to first use my own conversion
		  * method, LiToM, to convert the integer entry to a ALGEB structure,
		  * then do a callback into Maple that calls the ExToM procedure,
		  * which converts the results of LiToM into a Maple multi-precision
		  * integer. At the moment, this is the best idea I've got as to
		  * how to convert a GMP integer into a Maple representation in one shot.
		  */

		 d.dag = EvalMapleProc(kv,args[2],1,LiToM(kv, *V_i, blank));
		 RTableAssign(kv, rtable, &index, d);
	       }
	     }
	     break;

	     default:
	       MapleRaiseError(kv, err);
	       break;
	     }
	     break; // breaks case 2.
	     // This was causing a wicked error :-)


      default:
	MapleRaiseError(kv, err);
	break;

      }
    }
    else {
      MapleRaiseError(kv, err);
    }

    return rtable;
  }
Exemplo n.º 13
0
  ALGEB getMatrix(MKernelVector kv, ALGEB* args)
  {
    // Get the key
    int key = MapleToInteger32(kv,args[1]), flag;
    char err[] = "ERROR!  The associated BlackBox object does not exist!";
    M_INT index[2], bound[4];
    RTableData d;
    ALGEB rtable, blank;
    RTableSettings s;
    std::vector<size_t> Row, Col;
    std::vector<size_t>::const_iterator r_i, c_i;
    char MapleStatement[100] = "rtable(1..";


    // Get the data type of the blackbox
    std::map<int,int>::iterator f_i = typeTable.find(key);
    if( f_i == typeTable.end() ) // In case the blackbox isn't there
      MapleRaiseError(kv,err);
    flag = f_i->second; // Otherwise, get the blackbox type

    // Check that the data is there
    std::map<int,void*>::iterator h_i = hashTable.find(key);
    if(h_i != hashTable.end() ) {

      // Switch according to mode - regular or "special fix" mode
      switch( MapleToInteger32(kv, args[3])) {

      case 1: // This is the Maple 7 case, "special fix" mode
	      // Use the EvalMapleStatement() to call the rtable constructor in the
	      // Maple environment

	   // Switch according to the type
	   switch(flag) {
	   case BlackBoxi:{ // For single word entry matrices

	     // Extract the necessary data
	     TriplesBBi* BB = (TriplesBBi*) h_i->second;
	     Vectorl Data = BB->getData();
	     Row = BB->getRows();
	     Col = BB->getCols();
	     Vectorl::const_iterator d_i;

	     // Builds the statement that will be used in the Maple 7 callback

	     sprintf(MapleStatement + strlen(MapleStatement), "%d", BB->rowdim() );
	     strcat(MapleStatement, ",1..");

	     sprintf(MapleStatement + strlen(MapleStatement), "%d", BB->coldim() );
	     strcat(MapleStatement, ", subtype=Matrix, storage=sparse);");

	     // Perform the callback
	     rtable = kv->evalMapleStatement(MapleStatement);

	     // Insert each non-zero entry
	     for(d_i = Data.begin(), r_i = Row.begin(), c_i = Col.begin(); r_i != Row.end(); ++d_i, ++c_i, ++r_i) {
	       index[0] = *r_i; index[1] = *c_i;
	       d.dag = ToMapleInteger(kv, *d_i); // d is a union, dag is the
	                                        // ALGEB union field
	       RTableAssign(kv, rtable, index, d);
	     }
	   }
	   break;

	   case BlackBoxI: { // For multi-word size matrix types
	     TriplesBBI* BB = (TriplesBBI*) h_i->second;
	     VectorI Data = BB->getData();
	     VectorI::const_iterator d_i;

	     // Build and execute the Maple callback
	     sprintf(MapleStatement + strlen(MapleStatement), "%d", BB->rowdim() );
	     strcat(MapleStatement, ", 1..");
	     sprintf(MapleStatement + strlen(MapleStatement), "%d", BB->coldim() );
	     strcat(MapleStatement, ", subtype=Matrix, storage=sparse);");
	     rtable = kv->evalMapleStatement(MapleStatement);

	     for(d_i = Data.begin(), r_i = Row.begin(), c_i = Col.begin(); r_i != Row.end(); ++d_i, ++r_i, ++c_i) {
	       index[0] = *r_i; index[1] = *c_i;

	       //    * Okay, here's how this line works.  Basically,
	       //    * in order to set the entries of this RTable to
	       //    * multi-precision integers, I have to first use my own conversion
	       //    * method, LiToM, to convert the integer entry to a ALGEB structure,
	       //    * then do a callback into Maple that calls the ExToM procedure,
	       //    * which converts the results of LiToM into a Maple multi-precision
	       //    * integer. At the moment, this is the best idea I've got as to
	       //    * how to convert a GMP integer into a Maple representation in one shot.
	       //    *

	       d.dag = EvalMapleProc(kv,args[2],1,LiToM(kv, *d_i, blank));
	       RTableAssign(kv, rtable, index, d);
             }
	   }
	   break;

	   // In this case the object is not a BlackBox type
	   default:
	     MapleRaiseError(kv,err);
	     break;
	   }
	break;

      case 2: // Okay, here is the normal case.
	      // Use RTableCreate to create a Maple rtable object

	    kv->rtableGetDefaults(&s);
	    // Get default settings - set datatype to Maple,
	    // DAGTAG to anything

	    s.subtype = RTABLE_MATRIX; // Subtype set to Matrix
	    s.storage = RTABLE_SPARSE; // Storage set to sparse
	    s.num_dimensions = 2; // What do you think this means :-)
	    bound[0] = bound[2] = 1; // Set the lower bounds of each dimension to 0, which for maple is 1

	    switch(flag) { // Switch on data type

	    case BlackBoxi:{ // word size entry Matrix
		TriplesBBi* BB = (TriplesBBi*) h_i->second;
		Vectorl Data = BB->getData();
		Row = BB->getRows();
		Col = BB->getCols();
		Vectorl::const_iterator d_i;

		bound[1] = BB->rowdim();
		bound[3] = BB->coldim();
		rtable = kv->rtableCreate(&s, NULL, bound); // This is the RTableCreate function, it's
		                                            // just the one that works

		// Assign all the non-zero rows
		for( d_i = Data.begin(), r_i = Row.begin(), c_i = Col.begin(); r_i != Row.end(); ++d_i, ++c_i, ++r_i) {
		  index[0] = *r_i; index[1] = *c_i;
		  d.dag = ToMapleInteger(kv, *d_i); // d is a union, dag is the
	                                        // ALGEB union field
		  RTableAssign(kv, rtable, index, d);
		}
	      }
	      break;

	    case BlackBoxI: { // For multi-word entry Matrices
	      TriplesBBI* BB = (TriplesBBI*) h_i->second;
	      VectorI Data = BB->getData();

	      // Setup the Create() call
	      VectorI::const_iterator d_i;
	      Row = BB->getRows();
	      Col = BB->getCols();
	      bound[1] = BB->rowdim();
	      bound[3] = BB->coldim();
	      rtable = kv->rtableCreate(&s, NULL, bound); // Create an empty RTable

	      // Populate the RTable using the callback method described below
	      for(d_i = Data.begin(), r_i = Row.begin(), c_i = Col.begin(); r_i != Row.end(); ++d_i, ++r_i, ++c_i) {
		index[0] = *r_i; index[1] = *c_i;

	    //    * Okay, here's how this line works.  Basically,
	   //    * in order to set the entries of this RTable to
	   //    * multi-precision integers, I have to first use my own conversion
	   //    * method, LiToM, to convert the integer entry to a ALGEB structure,
	   //    * then do a callback into Maple that calls the ExToM procedure,
	   //    * which converts the results of LiToM into a Maple multi-precision
	   //    * integer. At the moment, this is the best idea I've got as to
	   //    * how to convert a GMP integer into a Maple representation in one shot.

	      d.dag = EvalMapleProc(kv,args[2],1,LiToM(kv, *d_i, blank));
	      RTableAssign(kv, rtable, index, d);
	      }
	    }
	  break;
       }
      }
    }
    else
      MapleRaiseError(kv,err);

    return rtable;
  }
Exemplo n.º 14
0
size_t DuplicatedVertexRemoval::run(Float tol) {
    const size_t dim = m_vertices.cols();
    HashGrid::Ptr grid = HashGrid::create(tol, dim);
    const size_t num_vertices = m_vertices.rows();
    const size_t num_faces = m_faces.rows();
    const size_t vertex_per_face = m_faces.cols();
    m_index_map.resize(num_vertices);
    std::vector<size_t> source_index;

    size_t count = 0;
    size_t num_duplications = 0;
    for (size_t i=0; i<num_vertices; i++) {
        int curr_importance_level = m_importance_level[i];
        if (curr_importance_level < 0) {
            m_index_map[i] = count;
            source_index.push_back(i);
            count++;
            continue;
        }
        const VectorF& v = m_vertices.row(i);
        VectorI candidates = grid->get_items_near_point(v);
        const size_t num_candidates = candidates.size();
        if (num_candidates > 0) {
            VectorF dists(num_candidates);
            for (size_t j=0; j<num_candidates; j++) {
                dists[j] = (m_vertices.row(candidates[j]) - v.transpose()).norm();
            }
            size_t min_idx;
            Float min_dist = dists.minCoeff(&min_idx);
            if (min_dist < tol) {
                size_t best_match_idx = candidates[min_idx];
                size_t output_idx = m_index_map[best_match_idx];
                m_index_map[i] = output_idx;

                int matched_importance_level =
                    m_importance_level[source_index[output_idx]];
                if (curr_importance_level > matched_importance_level) {
                    source_index[output_idx] = i;
                }

                num_duplications++;
                continue;
            }
        }

        // No match, add this vertex in the book.
        grid->insert(i, v);
        m_index_map[i] = count;
        source_index.push_back(i);
        count++;
    }

    assert(source_index.size() == count);
    MatrixFr vertices(count, dim);
    for (size_t i=0; i<count; i++) {
        assert(m_index_map[source_index[i]] == i);
        vertices.row(i) = m_vertices.row(source_index[i]);
    }
    m_vertices = vertices;

    for (size_t i=0; i<num_faces; i++) {
        for (size_t j=0; j<vertex_per_face; j++) {
            size_t v_index = m_faces(i,j);
            m_faces(i,j) = m_index_map[v_index];
        }
    }
    return num_duplications;
}