--- trunk/src/math/ConvexHull.cpp 2008/06/18 17:03:30 1261 +++ trunk/src/math/ConvexHull.cpp 2008/10/07 17:12:48 1302 @@ -1,4 +1,4 @@ -/* Copyright (c) 2006 The University of Notre Dame. All Rights Reserved. +/* Copyright (c) 2008 The University of Notre Dame. All Rights Reserved. * * The University of Notre Dame grants you ("Licensee") a * non-exclusive, royalty free, license to use, modify and @@ -44,7 +44,7 @@ * * Created by Charles F. Vardeman II on 11 Dec 2006. * @author Charles F. Vardeman II - * @version $Id: ConvexHull.cpp,v 1.7 2008-06-18 17:03:30 chuckv Exp $ + * @version $Id: ConvexHull.cpp,v 1.9 2008-10-07 17:12:48 chuckv Exp $ * */ @@ -56,41 +56,126 @@ #include #include "math/ConvexHull.hpp" #include "utils/simError.h" + + using namespace oopse; /* CGAL version of convex hull first then QHULL */ #ifdef HAVE_CGAL - +//#include #include -#include +//#include +#include +#include +#include #include #include +#include +#include #include +#include -#include + +//#include #include -#include +//#include -typedef double RT; -typedef CGAL::Simple_cartesian K; -typedef CGAL::Convex_hull_traits_3 Traits; -typedef Traits::Polyhedron_3 Polyhedron_3; + + +typedef CGAL::MP_Float RT; +//typedef double RT; +//typedef CGAL::Homogeneous K; +typedef CGAL::Exact_predicates_exact_constructions_kernel K; +typedef K::Vector_3 Vector_3; +//typedef CGAL::Convex_hull_traits_3 Traits; +typedef CGAL::Polyhedron_traits_with_normals_3 Traits; +//typedef Traits::Polyhedron_3 Polyhedron_3; +typedef CGAL::Polyhedron_3 Polyhedron_3; typedef K::Point_3 Point_3; -ConvexHull::ConvexHull(){} +typedef Polyhedron_3::HalfedgeDS HalfedgeDS; +typedef Polyhedron_3::Facet_iterator Facet_iterator; +typedef Polyhedron_3::Halfedge_around_facet_circulator Halfedge_facet_circulator; +typedef Polyhedron_3::Halfedge_handle Halfedge_handle; +typedef Polyhedron_3::Facet_iterator Facet_iterator; +typedef Polyhedron_3::Plane_iterator Plane_iterator; +typedef Polyhedron_3::Vertex_iterator Vertex_iterator; +typedef Polyhedron_3::Vertex_handle Vertex_handle; +typedef Polyhedron_3::Point_iterator Point_iterator; + -bool ConvexHull::genHull(std::vector pos) + +class Enriched_Point_3 : public K::Point_3{ +public: + Enriched_Point_3(double x,double y,double z) : K::Point_3(x,y,z), yupMyPoint(false), mySD(NULL) {} + + bool isMyPoint() const{ return yupMyPoint; } + void myPoint(){ yupMyPoint = true; } + void setSD(StuntDouble* SD){mySD = SD;} + StuntDouble* getStuntDouble(){return mySD;} +private: + bool yupMyPoint; + StuntDouble* mySD; + +}; + + + + + + // compare Point_3's... used in setting up the STL map from points to indices +template +struct Point_3_comp { + bool operator() (const Pt3 & p, const Pt3 & q) const { + return CGAL::lexicographically_xyz_smaller(p,q); // this is defined inline & hence we had to create fn object & not ptrfun + } +}; + +// coordinate-based hashing inefficient but can we do better if pts are copied? +typedef std::map > ptMapType; + +#ifdef IS_MPI +struct { + double x,y,z; +} surfacePt; +#endif + +ConvexHull::ConvexHull() : Hull(){ + //If we are doing the mpi version, set up some vectors for data communication +#ifdef IS_MPI + + + nproc_ = MPI::COMM_WORLD.Get_size(); + myrank_ = MPI::COMM_WORLD.Get_rank(); + NstoProc_ = new int[nproc_]; + displs_ = new int[nproc_]; + + // Create a surface point type in MPI to send + surfacePtType = MPI::DOUBLE.Create_contiguous(3); + surfacePtType.Commit(); + + +#endif +} + +void ConvexHull::computeHull(std::vector bodydoubles) { + + std::vector points; + ptMapType myMap; + Point_iterator hc; - std::vector points; - - // Copy the positon vector into a points vector for cgal. - for (int i = 0; i < pos.size(); ++i) + std::vector::iterator SD; + + for (SD =bodydoubles.begin(); SD != bodydoubles.end(); ++SD) { - Point_3 pt(pos[i][0],pos[i][1],pos[i][2]); - points.push_back(pt); + Vector3d pos = (*SD)->getPos(); + Enriched_Point_3* pt = new Enriched_Point_3(pos.x(),pos.y(),pos.z()); + pt->setSD(*SD); + points.push_back(*pt); + // myMap[pt]=(*SD); } // define object to hold convex hull @@ -98,206 +183,487 @@ bool ConvexHull::genHull(std::vector pos) Polyhedron_3 polyhedron; // compute convex hull - std::cerr << "Creating hull" << std::endl; - CGAL::convex_hull_3(points.begin(), points.end(), ch_object_); - std::cerr << "Done Creating hull" << std::endl; - std::vector::const_iterator p_it; + + std::vector::iterator testpt; + + + + CGAL::convex_hull_3(points.begin(), points.end(), polyhedron); + - for (p_it = points.begin(); p_it != points.end(); p_it++) - { - std::cerr << (*p_it).x() << std::endl; + + Ns_ = polyhedron.size_of_vertices(); + +#ifdef IS_MPI + /* Gather an array of the number of verticies on each processor */ + + + surfacePtsGlobal_.clear(); + surfacePtsLocal_.clear(); + + MPI::COMM_WORLD.Allgather(&Ns_,1,MPI::INT,&NstoProc_[0],1,MPI::INT); + + for (int i = 0; i < nproc_; i++){ + Nsglobal_ += NstoProc_[i]; + } + /*Reminder ideally, we would like to reserve size for the vectors here*/ + surfacePtsLocal_.reserve(Ns_); + surfacePtsGlobal_.resize(Nsglobal_); + // std::fill(surfacePtsGlobal_.begin(),surfacePtsGlobal_.end(),0); + + /* Build a displacements array */ + for (int i = 1; i < nproc_; i++){ + displs_[i] = displs_[i-1] + NstoProc_[i-1]; + } + + int noffset = displs_[myrank_]; + /* gather the potential hull */ + + + for (hc =polyhedron.points_begin();hc != polyhedron.points_end(); ++hc){ + Point_3 mypoint = *hc; + surfacePt_ mpiSurfacePt; + mpiSurfacePt.x = CGAL::to_double(mypoint.x()); + mpiSurfacePt.y = CGAL::to_double(mypoint.y()); + mpiSurfacePt.z = CGAL::to_double(mypoint.z()); + surfacePtsLocal_.push_back(mpiSurfacePt); + } + + MPI::COMM_WORLD.Allgatherv(&surfacePtsLocal_[0],Ns_,surfacePtType,&surfacePtsGlobal_[0],NstoProc_,displs_,surfacePtType); + std::vector::iterator spt; + std::vector gblpoints; + + int mine = 0; + int pointidx = 0; + for (spt = surfacePtsGlobal_.begin(); spt != surfacePtsGlobal_.end(); ++spt) + { + surfacePt_ thispos = *spt; + Enriched_Point_3 ept(thispos.x,thispos.y,thispos.z); + if (mine >= noffset && mine < noffset + Ns_){ + ept.myPoint(); + ept.setSD(points[pointidx].getStuntDouble()); + pointidx++; + } + gblpoints.push_back(ept); + + mine++; } + /* Compute the global hull */ + polyhedron.clear(); + CGAL::convex_hull_3(gblpoints.begin(), gblpoints.end(), polyhedron); + + +#endif + + + + /* Loop over all of the surface triangles and build data structures for atoms and normals*/ + Facet_iterator j; + area_ = 0; + for ( j = polyhedron.facets_begin(); j !=polyhedron.facets_end(); ++j) { + Halfedge_handle h = j->halfedge(); + + Point_3 r0=h->vertex()->point(); + Point_3 r1=h->next()->vertex()->point(); + Point_3 r2=h->next()->next()->vertex()->point(); + + Point_3* pr0 = &r0; + Point_3* pr1 = &r1; + Point_3* pr2 = &r2; + + Enriched_Point_3* er0 = static_cast(pr0); + Enriched_Point_3* er1 = static_cast(pr1); + Enriched_Point_3* er2 = static_cast(pr2); + + // StuntDouble* sd = er0->getStuntDouble(); + std::cerr << "sd globalIndex = " << to_double(er0->x()) << "\n"; + + Point_3 thisCentroid = CGAL::centroid(r0,r1,r2); + + Vector_3 normal = CGAL::cross_product(r1-r0,r2-r0); + + Triangle* face = new Triangle(); + Vector3d V3dNormal(CGAL::to_double(normal.x()),CGAL::to_double(normal.y()),CGAL::to_double(normal.z())); + Vector3d V3dCentroid(CGAL::to_double(thisCentroid.x()),CGAL::to_double(thisCentroid.y()),CGAL::to_double(thisCentroid.z())); + face->setNormal(V3dNormal); + face->setCentroid(V3dCentroid); + RealType faceArea = 0.5*V3dNormal.length(); + face->setArea(faceArea); + area_ += faceArea; + Triangles_.push_back(face); + // ptMapType::const_iterator locn=myMap.find(mypoint); + // int myIndex = locn->second; + + } + + std::cout << "Number of surface atoms is: " << Ns_ << std::endl; + + + +} +void ConvexHull::printHull(const std::string& geomFileName) +{ /* - for (Polyhedron_3::Vertex_iterator v = ch_object_.vertices_begin(); - ch_object_.vertices_end(); ++v){ - std::cout<< v.point()<( newGeomFile, "\n")); + for ( Facet_iterator i = polyhedron.facets_begin(); i != polyhedron.facets_end(); ++i) { + Halfedge_facet_circulator j = i->facet_begin(); + // Facets in polyhedral surfaces are at least triangles. + CGAL_assertion( CGAL::circulator_size(j) >= 3); + newGeomFile << CGAL::circulator_size(j) << ' '; + do { + newGeomFile << ' ' << std::distance(polyhedron.vertices_begin(), j->vertex()); + } while ( ++j != i->facet_begin()); + newGeomFile << std::endl; } + + newGeomFile.close(); */ +/* + std::ofstream newGeomFile; + + //create new .md file based on old .md file + newGeomFile.open(geomFileName.c_str()); + + // Write polyhedron in Object File Format (OFF). + CGAL::set_ascii_mode( std::cout); + newGeomFile << "OFF" << std::endl << ch_polyhedron.size_of_vertices() << ' ' + << ch_polyhedron.size_of_facets() << " 0" << std::endl; + std::copy( ch_polyhedron.points_begin(), ch_polyhedron.points_end(), + std::ostream_iterator( newGeomFile, "\n")); + for ( Facet_iterator i = ch_polyhedron.facets_begin(); i != ch_polyhedron.facets_end(); ++i) + { + Halfedge_facet_circulator j = i->facet_begin(); + // Facets in polyhedral surfaces are at least triangles. + CGAL_assertion( CGAL::circulator_size(j) >= 3); + newGeomFile << CGAL::circulator_size(j) << ' '; + do + { + newGeomFile << ' ' << std::distance(ch_polyhedron.vertices_begin(), j->vertex()); + } + while ( ++j != i->facet_begin()); + newGeomFile << std::endl; + } + + newGeomFile.close(); +*/ + } + + + + #else #ifdef HAVE_QHULL /* Old options Qt Qu Qg QG0 FA */ -ConvexHull::ConvexHull() : dim_(3), options_("qhull Qt Qci Tcv Pp") - //ConvexHull::ConvexHull() : dim_(3), options_("qhull d Qbb Qt i") -{} +ConvexHull::ConvexHull() : Hull(), dim_(3), options_("qhull Qt Qci Tcv Pp"), Ns_(200) { + //If we are doing the mpi version, set up some vectors for data communication +#ifdef IS_MPI -bool ConvexHull::genHull(std::vector pos) + + nproc_ = MPI::COMM_WORLD.Get_size(); + myrank_ = MPI::COMM_WORLD.Get_rank(); + NstoProc_ = new int[nproc_]; + displs_ = new int[nproc_]; + + // Create a surface point type in MPI to send + //surfacePtType = MPI::DOUBLE.Create_contiguous(3); + // surfacePtType.Commit(); + + +#endif +} + + + +void ConvexHull::computeHull(std::vector bodydoubles) { - - int numpoints = pos.size(); - coordT* pt_array; + std::vector surfaceIDs; + std::vector surfaceIDsGlobal; + std::vector localPtsMap; + int numpoints = bodydoubles.size(); + + //coordT* pt_array; coordT* surfpt_array; - std::list surface_atoms; + vertexT *vertex, **vertexp; + facetT *facet; + setT *vertices; + int curlong,totlong; + int id; + + coordT *point,**pointp; + + FILE *outdummy = NULL; FILE *errdummy = NULL; - pt_array = (coordT*) malloc(sizeof(coordT) * (numpoints * dim_)); + //pt_array = (coordT*) malloc(sizeof(coordT) * (numpoints * dim_)); + +// double* ptArray = new double[numpoints * 3]; + std::vector ptArray(numpoints*3); + std::vector isSurfaceID(numpoints); + + // Copy the positon vector into a points vector for qhull. + std::vector::iterator SD; + int i = 0; + for (SD =bodydoubles.begin(); SD != bodydoubles.end(); ++SD) + { + Vector3d pos = (*SD)->getPos(); + + ptArray[dim_ * i] = pos.x(); + ptArray[dim_ * i + 1] = pos.y(); + ptArray[dim_ * i + 2] = pos.z(); + i++; + } + - for (int i = 0; i < numpoints; i++) { - pt_array[dim_ * i] = pos[i][0]; - pt_array[dim_ * i + 1] = pos[i][1]; - pt_array[dim_ * i + 2] = pos[i][2]; - } - - /* - qh_initflags(const_cast(options_.c_str())); - qh_init_B(pospoints, numpoints, dim_, ismalloc); - qh_qhull(); - qh_check_output(); - - qh_produce_output(); - */ boolT ismalloc = False; + /* Clean up memory from previous convex hull calculations*/ + Triangles_.clear(); + surfaceSDs_.clear(); + surfaceSDs_.reserve(Ns_); + + if (qh_new_qhull(dim_, numpoints, &ptArray[0], ismalloc, + const_cast(options_.c_str()), NULL, stderr)) { + + sprintf(painCave.errMsg, "ConvexHull: Qhull failed to compute convex hull"); + painCave.isFatal = 0; + simError(); + + } //qh_new_qhull + + +#ifdef IS_MPI + std::vector localPts; + int localPtArraySize; - if (!qh_new_qhull(dim_, numpoints, pt_array, ismalloc, - const_cast(options_.c_str()), NULL, stderr)) { + + std::fill(isSurfaceID.begin(),isSurfaceID.end(),false); + + + FORALLfacets { - vertexT *vertex, **vertexp; - facetT *facet; - setT *vertices; - unsigned int nf = qh num_facets; - - //Matrix idx(nf, dim); - /* - int j, i = 0, id = 0; - - int id2 = 0; - coordT *point,**pointp; - realT dist; - FORALLfacets { - j = 0; - - if (!facet->simplicial){ + if (!facet->simplicial){ // should never happen with Qt sprintf(painCave.errMsg, "ConvexHull: non-simplicaial facet detected"); painCave.isFatal = 0; simError(); - } - - vertices = qh_facet3vertex(facet); - FOREACHvertex_(vertices){ + } + + + vertices = qh_facet3vertex(facet); + FOREACHvertex_(vertices){ id = qh_pointid(vertex->point); - surface_atoms.push_back(id); - //std::cout << "Ag " << pos[id][0] << " " << pos[id][1] << " " << pos[id][2]<< std::endl; + + if( !isSurfaceID[id] ){ + isSurfaceID[id] = true; } - qh_settempfree(&vertices); + } + qh_settempfree(&vertices); - FOREACHpoint_(facet->coplanarset){ - vertex= qh_nearvertex (facet, point, &dist); - //id= qh_pointid (vertex->point); - id2= qh_pointid (point); - surface_atoms.push_back(id2); - //std::cout << "Ag " << pos[id2][0] << " " << pos[id2][1] << " " << pos[id2][2]<< std::endl; - //printf ("%d %d %d " qh_REAL_1 "\n", id, id2, facet->id, dist); - //std::cout << "Neighbors are: %d $d %d\n" << id << id2 << facet->id; - - } - - } - -*/ - - + } //FORALLfacets + + + + /* + std::sort(surfaceIDs.begin(),surfaceIDs.end()); + surfaceIDs.erase(std::unique(surfaceIDs.begin(), surfaceIDs.end()), surfaceIDs.end()); + int localPtArraySize = surfaceIDs.size() * 3; + */ + + //localPts.resize(localPtArraySize); + //std::fill(localPts.begin(),localPts.end(),0.0); + + + int idx = 0; + int nIsIts = 0; +/* + // Copy the surface points into an array. + for(std::vector::iterator list_iter = isSurfaceID.begin(); + list_iter != isSurfaceID.end(); list_iter++) + { + bool isIt = *list_iter; + if (isIt){ + localPts.push_back(ptArray[dim_ * idx]); + localPts.push_back(ptArray[dim_ * idx + 1]); + localPts.push_back(ptArray[dim_ * idx + 2]); + localPtsMap.push_back(idx); + nIsIts++; + } //Isit + idx++; + } //isSurfaceID + */ + FORALLvertices { + idx = qh_pointid(vertex->point); + localPts.push_back(ptArray[dim_ * idx]); + localPts.push_back(ptArray[dim_ * idx + 1]); + localPts.push_back(ptArray[dim_ * idx + 2]); + localPtsMap.push_back(idx); } + localPtArraySize = localPts.size(); + + MPI::COMM_WORLD.Allgather(&localPtArraySize,1,MPI::INT,&NstoProc_[0],1,MPI::INT); - qh_getarea(qh facet_list); - volume_ = qh totvol; - area_ = qh totarea; - // FILE *newGeomFile; + Nsglobal_=0; + for (int i = 0; i < nproc_; i++){ + Nsglobal_ += NstoProc_[i]; + } + + int nglobalPts = int(Nsglobal_/3); + + + std::vector globalPts; + globalPts.resize(Nsglobal_); + + isSurfaceID.resize(nglobalPts); + + + std::fill(globalPts.begin(),globalPts.end(),0.0); + + displs_[0] = 0; + /* Build a displacements array */ + for (int i = 1; i < nproc_; i++){ + displs_[i] = displs_[i-1] + NstoProc_[i-1]; + } + + int noffset = displs_[myrank_]; + /* gather the potential hull */ + + MPI::COMM_WORLD.Allgatherv(&localPts[0],localPtArraySize,MPI::DOUBLE,&globalPts[0],&NstoProc_[0],&displs_[0],MPI::DOUBLE); + /* - FORALLfacets { - for (int k=0; k < qh hull_dim; k++) - printf ("%6.2g ", facet->normal[k]); - printf ("\n"); + if (myrank_ == 0){ + for (i = 0; i < globalPts.size(); i++){ + std::cout << globalPts[i] << std::endl; } + } */ - - int curlong,totlong; - // geomviewHull("junk.off"); + // Free previous hull qh_freeqhull(!qh_ALL); qh_memfreeshort(&curlong, &totlong); if (curlong || totlong) std::cerr << "qhull internal warning (main): did not free %d bytes of long memory (%d pieces) " << totlong << curlong << std::endl; - free(pt_array); - /* - int j = 0; - surface_atoms.sort(); - surface_atoms.unique(); - surfpt_array = (coordT*) malloc(sizeof(coordT) * (surface_atoms.size() * dim_)); - for(std::list::iterator list_iter = surface_atoms.begin(); - list_iter != surface_atoms.end(); list_iter++) - { - int i = *list_iter; - //surfpt_array[dim_ * j] = pos[i][0]; - //surfpt_array[dim_ * j + 1] = pos[i][1]; - //surfpt_array[dim_ * j + 2] = pos[i][2]; - std::cout << "Ag " << pos[i][0] << " " << pos[i][1] << " "<< pos[i][2] << std::endl; - j++; - } - */ - - /* - std::string deloptions_ = "qhull d Qt"; - facetT *facet, *neighbor; - ridgeT *ridge, **ridgep; - - if (!qh_new_qhull(dim_, surface_atoms.size(), surfpt_array, ismalloc, - const_cast(deloptions_.c_str()), NULL, stderr)) { - - qh visit_id++; - FORALLfacets { - if (!facet->upperdelaunay) { - facet->visitid= qh visit_id; - qh_makeridges(facet); - FOREACHridge_(facet->ridges) { - neighbor= otherfacet_(ridge, facet); - if (neighbor->visitid != qh visit_id) { - - FOREACHvertex_(ridge->vertices) - int id2 = qh_pointid (vertex->point); - std::cout << "Ag " << pos[id2][0] << " " << pos[id2][1] << " " << pos[id2][2]<< std::endl; - } - } - } - + if (qh_new_qhull(dim_, nglobalPts, &globalPts[0], ismalloc, + const_cast(options_.c_str()), NULL, stderr)){ + sprintf(painCave.errMsg, "ConvexHull: Qhull failed to compute global convex hull"); + painCave.isFatal = 1; + simError(); + + } //qh_new_qhull + +#endif + + + + + + + unsigned int nf = qh num_facets; + + /* Build Surface SD list first */ + + std::fill(isSurfaceID.begin(),isSurfaceID.end(),false); + + FORALLfacets { + + if (!facet->simplicial){ + // should never happen with Qt + sprintf(painCave.errMsg, "ConvexHull: non-simplicaial facet detected"); + painCave.isFatal = 1; + simError(); + } //simplicical + + Triangle* face = new Triangle(); + Vector3d V3dNormal(facet->normal[0],facet->normal[1],facet->normal[2]); + face->setNormal(V3dNormal); + //face->setCentroid(V3dCentroid); + RealType faceArea = 0.5*V3dNormal.length(); + //face->setArea(faceArea); + + + vertices = qh_facet3vertex(facet); + FOREACHvertex_(vertices){ + id = qh_pointid(vertex->point); + int localindex = id; +#ifdef IS_MPI - } + if (id >= noffset/3 && id < (noffset + localPtArraySize)/3 ){ + localindex = localPtsMap[id-noffset/3]; +#endif + face->addVertex(bodydoubles[localindex]); + if( !isSurfaceID[id] ){ + isSurfaceID[id] = true; +#ifdef IS_MPI + +#endif + + surfaceSDs_.push_back(bodydoubles[localindex]); + + } //IF isSurfaceID - qh_freeqhull(!qh_ALL); - qh_memfreeshort(&curlong, &totlong); - if (curlong || totlong) - std::cerr << "qhull internal warning (main): did not free %d bytes of long memory (%d pieces) " - << totlong << curlong << std::endl; - free(surfpt_array); - */ - return true; -} +#ifdef IS_MPI + + }else{ + face->addVertex(NULL); + } +#endif + } //Foreachvertex + Triangles_.push_back(face); + qh_settempfree(&vertices); + + } //FORALLfacets + -RealType ConvexHull::getVolume() -{ - return volume_; + Ns_ = surfaceSDs_.size(); + + + qh_getarea(qh facet_list); + volume_ = qh totvol; + area_ = qh totarea; + + + + qh_freeqhull(!qh_ALL); + qh_memfreeshort(&curlong, &totlong); + if (curlong || totlong) + std::cerr << "qhull internal warning (main): did not free %d bytes of long memory (%d pieces) " + << totlong << curlong << std::endl; + + + } -void ConvexHull::geomviewHull(const std::string& geomFileName) + + +void ConvexHull::printHull(const std::string& geomFileName) { FILE *newGeomFile;