OpenMD 3.2
Molecular Dynamics in the Open
Loading...
Searching...
No Matches
AlphaHull.cpp
1/*
2 * Copyright (c) 2004-present, The University of Notre Dame. All rights
3 * reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 *
15 * 3. Neither the name of the copyright holder nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 *
31 * SUPPORT OPEN SCIENCE! If you use OpenMD or its source code in your
32 * research, please cite the following paper when you publish your work:
33 *
34 * [1] Drisko et al., J. Open Source Softw. 9, 7004 (2024).
35 *
36 * Good starting points for code and simulation methodology are:
37 *
38 * [2] Meineke, et al., J. Comp. Chem. 26, 252-271 (2005).
39 * [3] Fennell & Gezelter, J. Chem. Phys. 124, 234104 (2006).
40 * [4] Sun, Lin & Gezelter, J. Chem. Phys. 128, 234107 (2008).
41 * [5] Vardeman, Stocker & Gezelter, J. Chem. Theory Comput. 7, 834 (2011).
42 * [6] Kuang & Gezelter, Mol. Phys., 110, 691-701 (2012).
43 * [7] Lamichhane, Gezelter & Newman, J. Chem. Phys. 141, 134109 (2014).
44 * [8] Bhattarai, Newman & Gezelter, Phys. Rev. B 99, 094106 (2019).
45 * [9] Drisko & Gezelter, J. Chem. Theory Comput. 20, 4986-4997 (2024).
46 */
47
48#include "math/AlphaHull.hpp"
49
50#include <algorithm>
51#include <fstream>
52#include <iostream>
53#include <iterator>
54#include <list>
55
56#ifdef IS_MPI
57#include <mpi.h>
58#endif
59
60#include "math/qhull.hpp"
61#include "utils/simError.h"
62
63#ifdef HAVE_QHULL
64using namespace std;
65using namespace OpenMD;
66
67double calculate_circumradius(pointT* p0, pointT* p1, pointT* p2, int dim);
68
69AlphaHull::AlphaHull(double alpha) :
70 Hull(), dim_(4), alpha_(alpha), options_("qhull d QJ Tcv Pp") {}
71
72void AlphaHull::computeHull(vector<StuntDouble*> bodydoubles) {
73#ifdef HAVE_QHULL_REENTRANT
74 qhT qh_qh;
75 qhT* qh = &qh_qh;
76 QHULL_LIB_CHECK
77#endif
78
79 int numpoints = bodydoubles.size();
80
81 Triangles_.clear();
82
83 vertexT* vertex;
84 facetT *facet, *neighbor;
85 pointT* interiorPoint;
86 int curlong, totlong;
87
88 vector<double> ptArray(numpoints * dim_);
89
90 // Copy the positon vector into a points vector for qhull.
91 vector<StuntDouble*>::iterator SD;
92 int i = 0;
93
94 for (SD = bodydoubles.begin(); SD != bodydoubles.end(); ++SD) {
95 Vector3d pos = (*SD)->getPos();
96 ptArray[dim_ * i] = pos.x();
97 ptArray[dim_ * i + 1] = pos.y();
98 ptArray[dim_ * i + 2] = pos.z();
99 ptArray[dim_ * i + 3] = pos.lengthSquare();
100 i++;
101 }
102 /* Clean up memory from previous convex hull calculations*/
103 boolT ismalloc = False;
104
105 /* compute the hull for our local points (or all the points for single
106 processor versions) */
107#ifdef HAVE_QHULL_REENTRANT
108 qh_init_A(qh, NULL, NULL, stderr, 0, NULL);
109 int exitcode = setjmp(qh->errexit);
110 if (!exitcode) {
111 qh->NOerrexit = False;
112 qh_initflags(qh, const_cast<char*>(options_.c_str()));
113 qh_init_B(qh, &ptArray[0], numpoints, dim_, ismalloc);
114 qh_qhull(qh);
115 qh_check_output(qh);
116 exitcode = qh_ERRnone;
117 qh->NOerrexit = True;
118 } else {
119 snprintf(painCave.errMsg, MAX_SIM_ERROR_MSG_LENGTH,
120 "AlphaHull: Qhull failed to compute convex hull");
121 painCave.isFatal = 1;
122 simError();
123 }
124#else
125 qh_init_A(NULL, NULL, stderr, 0, NULL);
126 int exitcode = setjmp(qh errexit);
127 if (!exitcode) {
128 qh_initflags(const_cast<char*>(options_.c_str()));
129 qh_init_B(&ptArray[0], numpoints, dim_, ismalloc);
130 qh_qhull();
131 qh_check_output();
132 exitcode = qh_ERRnone;
133 qh NOerrexit = True;
134 } else {
135 snprintf(painCave.errMsg, MAX_SIM_ERROR_MSG_LENGTH,
136 "AlphaHull: Qhull failed to compute convex hull");
137 painCave.isFatal = 1;
138 simError();
139 }
140#endif
141
142#ifdef IS_MPI
143 // If we are doing the mpi version, set up some vectors for data communication
144
145 int nproc;
146 int myrank;
147 MPI_Comm_size(MPI_COMM_WORLD, &nproc);
148 MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
149
150 int localHullSites = 0;
151
152 vector<int> hullSitesOnProc(nproc, 0);
153 vector<int> coordsOnProc(nproc, 0);
154 vector<int> displacements(nproc, 0);
155 vector<int> vectorDisplacements(nproc, 0);
156
157 vector<double> coords;
158 vector<double> vels;
159 vector<int> indexMap;
160 vector<double> masses;
161
162 FORALLvertices {
163 localHullSites++;
164
165#ifdef HAVE_QHULL_REENTRANT
166 int idx = qh_pointid(qh, vertex->point);
167#else
168 int idx = qh_pointid(vertex->point);
169#endif
170
171 indexMap.push_back(idx);
172
173 coords.push_back(ptArray[dim_ * idx]);
174 coords.push_back(ptArray[dim_ * idx + 1]);
175 coords.push_back(ptArray[dim_ * idx + 2]);
176 coords.push_back(ptArray[dim_ * idx + 3]);
177
178 StuntDouble* sd = bodydoubles[idx];
179
180 Vector3d vel = sd->getVel();
181 vels.push_back(vel.x());
182 vels.push_back(vel.y());
183 vels.push_back(vel.z());
184 vels.push_back(0.0);
185
186 masses.push_back(sd->getMass());
187 }
188
189 MPI_Allgather(&localHullSites, 1, MPI_INT, &hullSitesOnProc[0], 1, MPI_INT,
190 MPI_COMM_WORLD);
191
192 int globalHullSites = 0;
193 for (int iproc = 0; iproc < nproc; iproc++) {
194 globalHullSites += hullSitesOnProc[iproc];
195 coordsOnProc[iproc] = dim_ * hullSitesOnProc[iproc];
196 }
197
198 displacements[0] = 0;
199 vectorDisplacements[0] = 0;
200
201 for (int iproc = 1; iproc < nproc; iproc++) {
202 displacements[iproc] =
203 displacements[iproc - 1] + hullSitesOnProc[iproc - 1];
204 vectorDisplacements[iproc] =
205 vectorDisplacements[iproc - 1] + coordsOnProc[iproc - 1];
206 }
207
208 vector<double> globalCoords(dim_ * globalHullSites);
209 vector<double> globalVels(dim_ * globalHullSites);
210 vector<double> globalMasses(globalHullSites);
211
212 int count = coordsOnProc[myrank];
213
214 MPI_Allgatherv(&coords[0], count, MPI_DOUBLE, &globalCoords[0],
215 &coordsOnProc[0], &vectorDisplacements[0], MPI_DOUBLE,
216 MPI_COMM_WORLD);
217
218 MPI_Allgatherv(&vels[0], count, MPI_DOUBLE, &globalVels[0], &coordsOnProc[0],
219 &vectorDisplacements[0], MPI_DOUBLE, MPI_COMM_WORLD);
220
221 MPI_Allgatherv(&masses[0], localHullSites, MPI_DOUBLE, &globalMasses[0],
222 &hullSitesOnProc[0], &displacements[0], MPI_DOUBLE,
223 MPI_COMM_WORLD);
224
225 // Free previous hull
226#ifdef HAVE_QHULL_REENTRANT
227 qh_freeqhull(qh, !qh_ALL);
228 qh_memfreeshort(qh, &curlong, &totlong);
229#else
230 qh_freeqhull(!qh_ALL);
231 qh_memfreeshort(&curlong, &totlong);
232#endif
233 if (curlong || totlong) {
234 snprintf(painCave.errMsg, MAX_SIM_ERROR_MSG_LENGTH,
235 "AlphaHull: qhull internal warning:\n"
236 "\tdid not free %d bytes of long memory (%d pieces)",
237 totlong, curlong);
238 painCave.isFatal = 1;
239 simError();
240 }
241
242#ifdef HAVE_QHULL_REENTRANT
243 qh_init_A(qh, NULL, NULL, stderr, 0, NULL);
244 exitcode = setjmp(qh->errexit);
245 if (!exitcode) {
246 qh->NOerrexit = False;
247 qh_initflags(qh, const_cast<char*>(options_.c_str()));
248 qh_init_B(qh, &globalCoords[0], globalHullSites, dim_, ismalloc);
249 qh_qhull(qh);
250 qh_check_output(qh);
251 exitcode = qh_ERRnone;
252 qh->NOerrexit = True;
253 } else {
254 snprintf(painCave.errMsg, MAX_SIM_ERROR_MSG_LENGTH,
255 "AlphaHull: Qhull failed to compute convex hull");
256 painCave.isFatal = 1;
257 simError();
258 }
259#else
260 qh_init_A(NULL, NULL, stderr, 0, NULL);
261 exitcode = setjmp(qh errexit);
262 if (!exitcode) {
263 qh NOerrexit = False;
264 qh_initflags(const_cast<char*>(options_.c_str()));
265 qh_init_B(&globalCoords[0], globalHullSites, dim_, ismalloc);
266 qh_qhull();
267 qh_check_output();
268 exitcode = qh_ERRnone;
269 qh NOerrexit = True;
270 } else {
271 snprintf(painCave.errMsg, MAX_SIM_ERROR_MSG_LENGTH,
272 "AlphaHull: Qhull failed to compute convex hull");
273 painCave.isFatal = 1;
274 simError();
275 }
276#endif
277
278#endif
279
280 // Set facet->center as the Voronoi center
281#ifdef HAVE_QHULL_REENTRANT
282 qh_setvoronoi_all(qh);
283#else
284 qh_setvoronoi_all();
285#endif
286
287 // Set of alpha complex triangles for alphashape filtering
288 vector<vector<int>> facetlist;
289 int numFacets = 0;
290
291#ifdef HAVE_QHULL_REENTRANT
292 setT* set = qh_settemp(qh, 4 * qh->num_facets);
293 qh->visit_id++;
294 interiorPoint = qh->interior_point;
295#else
296 setT* set = qh_settemp(4 * qh num_facets);
297 qh visit_id++;
298 interiorPoint = qh interior_point;
299#endif
300
301#ifdef HAVE_QHULL_REENTRANT
302 FORALLfacet_(qh->facet_list) {
303#else
304 FORALLfacet_(qh facet_list) {
305#endif
306 numFacets++;
307 if (!facet->upperdelaunay) {
308 // For all facets (that are tetrahedrons)calculate the radius of
309 // the empty circumsphere considering the distance between the
310 // circumcenter and a vertex of the facet
311 vertexT* vertex = (vertexT*)(facet->vertices->e[0].p);
312
313#ifdef HAVE_QHULL_REENTRANT
314 double* center = qh_facetcenter(qh, facet->vertices);
315#else
316 double* center = qh_facetcenter(facet->vertices);
317#endif
318 double radius = qh_pointdist(center, vertex->point, dim_ - 1);
319 // If radius is bigger than alpha, remove the tetrahedron
320
321 if (radius > alpha_) {
322 // if calculating the alphashape, unmark the facet ('good' is
323 // used as 'marked').
324 facet->good = false;
325
326 // Compute each ridge (triangle) once and test the
327 // cironference radius with alpha
328#ifdef HAVE_QHULL_REENTRANT
329 facet->visitid = qh->visit_id;
330 qh_makeridges(qh, facet);
331#else
332 facet->visitid = qh visit_id;
333 qh_makeridges(facet);
334#endif
335 ridgeT *ridge, **ridgep;
336 int goodTriangles = 0;
337 FOREACHridge_(facet->ridges) {
338 neighbor = otherfacet_(ridge, facet);
339#ifdef HAVE_QHULL_REENTRANT
340 if ((neighbor->visitid != qh->visit_id)) {
341#else
342 if ((neighbor->visitid != qh visit_id)) {
343#endif
344 // Calculate the radius of the circumference
345 pointT* p0 = ((vertexT*)(ridge->vertices->e[0].p))->point;
346 pointT* p1 = ((vertexT*)(ridge->vertices->e[1].p))->point;
347 pointT* p2 = ((vertexT*)(ridge->vertices->e[2].p))->point;
348
349 radius = calculate_circumradius(p0, p1, p2, dim_ - 1);
350
351 if (radius <= alpha_) {
352 goodTriangles++;
353 // save the triangle (ridge) for subsequent filtering
354#ifdef HAVE_QHULL_REENTRANT
355 qh_setappend(qh, &set, ridge);
356#else
357 qh_setappend(&set, ridge);
358#endif
359 }
360 }
361 }
362
363 // If calculating the alphashape, mark the facet('good' is
364 // used as 'marked'). This facet will have some triangles
365 // hidden by the facet's neighbor.
366 if (goodTriangles == 4) facet->good = true;
367
368 } else // the facet is good. Put all the triangles of the
369 // tetrahedron in the mesh
370 {
371 // Compute each ridge (triangle) once
372#ifdef HAVE_QHULL_REENTRANT
373 facet->visitid = qh->visit_id;
374#else
375 facet->visitid = qh visit_id;
376#endif
377 // Mark the facet('good' is used as 'marked'). This facet
378 // will have some triangles hidden by the facet's neighbor.
379 facet->good = true;
380#ifdef HAVE_QHULL_REENTRANT
381 qh_makeridges(qh, facet);
382#else
383 qh_makeridges(facet);
384#endif
385 ridgeT *ridge, **ridgep;
386 FOREACHridge_(facet->ridges) {
387 neighbor = otherfacet_(ridge, facet);
388#ifdef HAVE_QHULL_REENTRANT
389 if ((neighbor->visitid != qh->visit_id)) {
390 qh_setappend(qh, &set, ridge);
391 }
392#else
393 if ((neighbor->visitid != qh visit_id)) { qh_setappend(&set, ridge); }
394#endif
395 }
396 }
397 }
398 }
399
400 int ridgesCount = 0;
401
402 ridgeT *ridge, **ridgep;
403 FOREACHridge_(set) {
404 if ((!ridge->top->good || !ridge->bottom->good ||
405 ridge->top->upperdelaunay || ridge->bottom->upperdelaunay)) {
406 ridgesCount++;
407 int vertex_n, vertex_i;
408 Triangle face;
409
410 Vector3d faceVel = V3Zero;
411 Vector3d p[3];
412 RealType faceMass = 0.0;
413
414 int ver = 0;
415 vector<int> vertexlist;
416
417#ifdef HAVE_QHULL_REENTRANT
418 FOREACHvertex_i_(qh, ridge->vertices) {
419#else
420 FOREACHvertex_i_(ridge->vertices) {
421#endif
422#ifdef HAVE_QHULL_REENTRANT
423 int id = qh_pointid(qh, vertex->point);
424#else
425 int id = qh_pointid(vertex->point);
426#endif
427 p[ver][0] = vertex->point[0];
428 p[ver][1] = vertex->point[1];
429 p[ver][2] = vertex->point[2];
430 Vector3d vel;
431 RealType mass;
432 ver++;
433 vertexlist.push_back(id);
434
435 vel = bodydoubles[id]->getVel();
436 mass = bodydoubles[id]->getMass();
437 face.addVertexSD(bodydoubles[id]);
438
439 faceVel = faceVel + vel;
440 faceMass = faceMass + mass;
441 } // FOREACH Vertex
442 facetlist.push_back(vertexlist);
443 face.addVertices(p[0], p[1], p[2]);
444 face.setFacetMass(faceMass);
445 face.setFacetVelocity(faceVel / RealType(3.0));
446
447 RealType area = face.getArea();
448 area_ += area;
449 Vector3d normal = face.getUnitNormal();
450 RealType dist = normal[0] * interiorPoint[0] +
451 normal[1] * interiorPoint[1] +
452 normal[2] * interiorPoint[2];
453#ifdef HAVE_QHULL_REENTRANT
454 volume_ += dist * area / qh->hull_dim;
455#else
456 volume_ += dist * area / qh hull_dim;
457#endif
458
459 Triangles_.push_back(face);
460 }
461 }
462
463#ifdef HAVE_QHULL_REENTRANT
464 qh_freeqhull(qh, !qh_ALL);
465 qh_memfreeshort(qh, &curlong, &totlong);
466#else
467 qh_freeqhull(!qh_ALL);
468 qh_memfreeshort(&curlong, &totlong);
469#endif
470 if (curlong || totlong) {
471 snprintf(painCave.errMsg, MAX_SIM_ERROR_MSG_LENGTH,
472 "AlphaHull: qhull internal warning:\n"
473 "\tdid not free %d bytes of long memory (%d pieces)",
474 totlong, curlong);
475 painCave.isFatal = 1;
476 simError();
477 }
478}
479
480double calculate_circumradius(pointT* p0, pointT* p1, pointT* p2, int dim) {
481 coordT a = qh_pointdist(p0, p1, dim);
482 coordT b = qh_pointdist(p1, p2, dim);
483 coordT c = qh_pointdist(p2, p0, dim);
484
485 coordT sum = (a + b + c) * 0.5;
486 coordT area = sum * (a + b - sum) * (a + c - sum) * (b + c - sum);
487 return (double)(a * b * c) / (4 * sqrt(area));
488}
489
490#endif // QHULL
Vector3d getVel()
Returns the current velocity of this stuntDouble.
RealType getMass()
Returns the mass of this stuntDouble.
Real & z()
Returns reference of the third element of Vector3.
Definition Vector3.hpp:123
Real & x()
Returns reference of the first element of Vector3.
Definition Vector3.hpp:99
Real & y()
Returns reference of the second element of Vector3.
Definition Vector3.hpp:111
Real lengthSquare() const
Returns the squared length of this vector.
Definition Vector.hpp:403
This basic Periodic Table class was originally taken from the data.cpp file in OpenBabel.