source: src/tesselationhelpers.cpp@ 717e0c

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 717e0c was 717e0c, checked in by Frederik Heber <heber@…>, 15 years ago

Verbosity corrected for ERROR and WARNING

  • present ERROR and WARNING prefixes removed and placed by eLog() and respective Verbosity().
  • -v... is scanned for number of 'v's and verbosity is set accordingly
  • standard verbosity is now 0.

Signed-off-by: Frederik Heber <heber@…>

  • Property mode set to 100644
File size: 36.2 KB
Line 
1/*
2 * TesselationHelpers.cpp
3 *
4 * Created on: Aug 3, 2009
5 * Author: heber
6 */
7
8#include <fstream>
9
10#include "linkedcell.hpp"
11#include "log.hpp"
12#include "tesselation.hpp"
13#include "tesselationhelpers.hpp"
14#include "vector.hpp"
15#include "verbose.hpp"
16
17double DetGet(gsl_matrix * const A, const int inPlace) {
18 /*
19 inPlace = 1 => A is replaced with the LU decomposed copy.
20 inPlace = 0 => A is retained, and a copy is used for LU.
21 */
22
23 double det;
24 int signum;
25 gsl_permutation *p = gsl_permutation_alloc(A->size1);
26 gsl_matrix *tmpA;
27
28 if (inPlace)
29 tmpA = A;
30 else {
31 gsl_matrix *tmpA = gsl_matrix_alloc(A->size1, A->size2);
32 gsl_matrix_memcpy(tmpA , A);
33 }
34
35
36 gsl_linalg_LU_decomp(tmpA , p , &signum);
37 det = gsl_linalg_LU_det(tmpA , signum);
38 gsl_permutation_free(p);
39 if (! inPlace)
40 gsl_matrix_free(tmpA);
41
42 return det;
43};
44
45void GetSphere(Vector * const center, const Vector &a, const Vector &b, const Vector &c, const double RADIUS)
46{
47 gsl_matrix *A = gsl_matrix_calloc(3,3);
48 double m11, m12, m13, m14;
49
50 for(int i=0;i<3;i++) {
51 gsl_matrix_set(A, i, 0, a.x[i]);
52 gsl_matrix_set(A, i, 1, b.x[i]);
53 gsl_matrix_set(A, i, 2, c.x[i]);
54 }
55 m11 = DetGet(A, 1);
56
57 for(int i=0;i<3;i++) {
58 gsl_matrix_set(A, i, 0, a.x[i]*a.x[i] + b.x[i]*b.x[i] + c.x[i]*c.x[i]);
59 gsl_matrix_set(A, i, 1, b.x[i]);
60 gsl_matrix_set(A, i, 2, c.x[i]);
61 }
62 m12 = DetGet(A, 1);
63
64 for(int i=0;i<3;i++) {
65 gsl_matrix_set(A, i, 0, a.x[i]*a.x[i] + b.x[i]*b.x[i] + c.x[i]*c.x[i]);
66 gsl_matrix_set(A, i, 1, a.x[i]);
67 gsl_matrix_set(A, i, 2, c.x[i]);
68 }
69 m13 = DetGet(A, 1);
70
71 for(int i=0;i<3;i++) {
72 gsl_matrix_set(A, i, 0, a.x[i]*a.x[i] + b.x[i]*b.x[i] + c.x[i]*c.x[i]);
73 gsl_matrix_set(A, i, 1, a.x[i]);
74 gsl_matrix_set(A, i, 2, b.x[i]);
75 }
76 m14 = DetGet(A, 1);
77
78 if (fabs(m11) < MYEPSILON)
79 eLog() << Verbose(1) << "three points are colinear." << endl;
80
81 center->x[0] = 0.5 * m12/ m11;
82 center->x[1] = -0.5 * m13/ m11;
83 center->x[2] = 0.5 * m14/ m11;
84
85 if (fabs(a.Distance(center) - RADIUS) > MYEPSILON)
86 eLog() << Verbose(1) << "The given center is further way by " << fabs(a.Distance(center) - RADIUS) << " from a than RADIUS." << endl;
87
88 gsl_matrix_free(A);
89};
90
91
92
93/**
94 * Function returns center of sphere with RADIUS, which rests on points a, b, c
95 * @param Center this vector will be used for return
96 * @param a vector first point of triangle
97 * @param b vector second point of triangle
98 * @param c vector third point of triangle
99 * @param *Umkreismittelpunkt new center point of circumference
100 * @param Direction vector indicates up/down
101 * @param AlternativeDirection Vector, needed in case the triangles have 90 deg angle
102 * @param Halfplaneindicator double indicates whether Direction is up or down
103 * @param AlternativeIndicator double indicates in case of orthogonal triangles which direction of AlternativeDirection is suitable
104 * @param alpha double angle at a
105 * @param beta double, angle at b
106 * @param gamma, double, angle at c
107 * @param Radius, double
108 * @param Umkreisradius double radius of circumscribing circle
109 */
110void GetCenterOfSphere(Vector* const & Center, const Vector &a, const Vector &b, const Vector &c, Vector * const NewUmkreismittelpunkt, const Vector* const Direction, const Vector* const AlternativeDirection,
111 const double HalfplaneIndicator, const double AlternativeIndicator, const double alpha, const double beta, const double gamma, const double RADIUS, const double Umkreisradius)
112{
113 Vector TempNormal, helper;
114 double Restradius;
115 Vector OtherCenter;
116 Log() << Verbose(3) << "Begin of GetCenterOfSphere.\n";
117 Center->Zero();
118 helper.CopyVector(&a);
119 helper.Scale(sin(2.*alpha));
120 Center->AddVector(&helper);
121 helper.CopyVector(&b);
122 helper.Scale(sin(2.*beta));
123 Center->AddVector(&helper);
124 helper.CopyVector(&c);
125 helper.Scale(sin(2.*gamma));
126 Center->AddVector(&helper);
127 //*Center = a * sin(2.*alpha) + b * sin(2.*beta) + c * sin(2.*gamma) ;
128 Center->Scale(1./(sin(2.*alpha) + sin(2.*beta) + sin(2.*gamma)));
129 NewUmkreismittelpunkt->CopyVector(Center);
130 Log() << Verbose(4) << "Center of new circumference is " << *NewUmkreismittelpunkt << ".\n";
131 // Here we calculated center of circumscribing circle, using barycentric coordinates
132 Log() << Verbose(4) << "Center of circumference is " << *Center << " in direction " << *Direction << ".\n";
133
134 TempNormal.CopyVector(&a);
135 TempNormal.SubtractVector(&b);
136 helper.CopyVector(&a);
137 helper.SubtractVector(&c);
138 TempNormal.VectorProduct(&helper);
139 if (fabs(HalfplaneIndicator) < MYEPSILON)
140 {
141 if ((TempNormal.ScalarProduct(AlternativeDirection) <0 and AlternativeIndicator >0) or (TempNormal.ScalarProduct(AlternativeDirection) >0 and AlternativeIndicator <0))
142 {
143 TempNormal.Scale(-1);
144 }
145 }
146 else
147 {
148 if (TempNormal.ScalarProduct(Direction)<0 && HalfplaneIndicator >0 || TempNormal.ScalarProduct(Direction)>0 && HalfplaneIndicator<0)
149 {
150 TempNormal.Scale(-1);
151 }
152 }
153
154 TempNormal.Normalize();
155 Restradius = sqrt(RADIUS*RADIUS - Umkreisradius*Umkreisradius);
156 Log() << Verbose(4) << "Height of center of circumference to center of sphere is " << Restradius << ".\n";
157 TempNormal.Scale(Restradius);
158 Log() << Verbose(4) << "Shift vector to sphere of circumference is " << TempNormal << ".\n";
159
160 Center->AddVector(&TempNormal);
161 Log() << Verbose(0) << "Center of sphere of circumference is " << *Center << ".\n";
162 GetSphere(&OtherCenter, a, b, c, RADIUS);
163 Log() << Verbose(0) << "OtherCenter of sphere of circumference is " << OtherCenter << ".\n";
164 Log() << Verbose(3) << "End of GetCenterOfSphere.\n";
165};
166
167
168/** Constructs the center of the circumcircle defined by three points \a *a, \a *b and \a *c.
169 * \param *Center new center on return
170 * \param *a first point
171 * \param *b second point
172 * \param *c third point
173 */
174void GetCenterofCircumcircle(Vector * const Center, const Vector &a, const Vector &b, const Vector &c)
175{
176 Vector helper;
177 double alpha, beta, gamma;
178 Vector SideA, SideB, SideC;
179 SideA.CopyVector(b);
180 SideA.SubtractVector(&c);
181 SideB.CopyVector(c);
182 SideB.SubtractVector(&a);
183 SideC.CopyVector(a);
184 SideC.SubtractVector(&b);
185 alpha = M_PI - SideB.Angle(&SideC);
186 beta = M_PI - SideC.Angle(&SideA);
187 gamma = M_PI - SideA.Angle(&SideB);
188 //Log() << Verbose(3) << "INFO: alpha = " << alpha/M_PI*180. << ", beta = " << beta/M_PI*180. << ", gamma = " << gamma/M_PI*180. << "." << endl;
189 if (fabs(M_PI - alpha - beta - gamma) > HULLEPSILON)
190 eLog() << Verbose(0) << "GetCenterofCircumcircle: Sum of angles " << (alpha+beta+gamma)/M_PI*180. << " > 180 degrees by " << fabs(M_PI - alpha - beta - gamma)/M_PI*180. << "!" << endl;
191
192 Center->Zero();
193 helper.CopyVector(a);
194 helper.Scale(sin(2.*alpha));
195 Center->AddVector(&helper);
196 helper.CopyVector(b);
197 helper.Scale(sin(2.*beta));
198 Center->AddVector(&helper);
199 helper.CopyVector(c);
200 helper.Scale(sin(2.*gamma));
201 Center->AddVector(&helper);
202 Center->Scale(1./(sin(2.*alpha) + sin(2.*beta) + sin(2.*gamma)));
203};
204
205/** Returns the parameter "path length" for a given \a NewSphereCenter relative to \a OldSphereCenter on a circle on the plane \a CirclePlaneNormal with center \a CircleCenter and radius \a CircleRadius.
206 * Test whether the \a NewSphereCenter is really on the given plane and in distance \a CircleRadius from \a CircleCenter.
207 * It calculates the angle, making it unique on [0,2.*M_PI) by comparing to SearchDirection.
208 * Also the new center is invalid if it the same as the old one and does not lie right above (\a NormalVector) the base line (\a CircleCenter).
209 * \param CircleCenter Center of the parameter circle
210 * \param CirclePlaneNormal normal vector to plane of the parameter circle
211 * \param CircleRadius radius of the parameter circle
212 * \param NewSphereCenter new center of a circumcircle
213 * \param OldSphereCenter old center of a circumcircle, defining the zero "path length" on the parameter circle
214 * \param NormalVector normal vector
215 * \param SearchDirection search direction to make angle unique on return.
216 * \return Angle between \a NewSphereCenter and \a OldSphereCenter relative to \a CircleCenter, 2.*M_PI if one test fails
217 */
218double GetPathLengthonCircumCircle(const Vector &CircleCenter, const Vector &CirclePlaneNormal, const double CircleRadius, const Vector &NewSphereCenter, const Vector &OldSphereCenter, const Vector &NormalVector, const Vector &SearchDirection)
219{
220 Vector helper;
221 double radius, alpha;
222
223 helper.CopyVector(&NewSphereCenter);
224 // test whether new center is on the parameter circle's plane
225 if (fabs(helper.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
226 eLog() << Verbose(1) << "Something's very wrong here: NewSphereCenter is not on the band's plane as desired by " <<fabs(helper.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
227 helper.ProjectOntoPlane(&CirclePlaneNormal);
228 }
229 radius = helper.ScalarProduct(&helper);
230 // test whether the new center vector has length of CircleRadius
231 if (fabs(radius - CircleRadius) > HULLEPSILON)
232 eLog() << Verbose(1) << "The projected center of the new sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
233 alpha = helper.Angle(&OldSphereCenter);
234 // make the angle unique by checking the halfplanes/search direction
235 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON) // acos is not unique on [0, 2.*M_PI), hence extra check to decide between two half intervals
236 alpha = 2.*M_PI - alpha;
237 //Log() << Verbose(2) << "INFO: RelativeNewSphereCenter is " << helper << ", RelativeOldSphereCenter is " << OldSphereCenter << " and resulting angle is " << alpha << "." << endl;
238 radius = helper.Distance(&OldSphereCenter);
239 helper.ProjectOntoPlane(&NormalVector);
240 // check whether new center is somewhat away or at least right over the current baseline to prevent intersecting triangles
241 if ((radius > HULLEPSILON) || (helper.Norm() < HULLEPSILON)) {
242 //Log() << Verbose(2) << "INFO: Distance between old and new center is " << radius << " and between new center and baseline center is " << helper.Norm() << "." << endl;
243 return alpha;
244 } else {
245 //Log() << Verbose(1) << "INFO: NewSphereCenter " << helper << " is too close to OldSphereCenter" << OldSphereCenter << "." << endl;
246 return 2.*M_PI;
247 }
248};
249
250struct Intersection {
251 Vector x1;
252 Vector x2;
253 Vector x3;
254 Vector x4;
255};
256
257/**
258 * Intersection calculation function.
259 *
260 * @param x to find the result for
261 * @param function parameter
262 */
263double MinIntersectDistance(const gsl_vector * x, void *params)
264{
265 double retval = 0;
266 struct Intersection *I = (struct Intersection *)params;
267 Vector intersection;
268 Vector SideA,SideB,HeightA, HeightB;
269 for (int i=0;i<NDIM;i++)
270 intersection.x[i] = gsl_vector_get(x, i);
271
272 SideA.CopyVector(&(I->x1));
273 SideA.SubtractVector(&I->x2);
274 HeightA.CopyVector(&intersection);
275 HeightA.SubtractVector(&I->x1);
276 HeightA.ProjectOntoPlane(&SideA);
277
278 SideB.CopyVector(&I->x3);
279 SideB.SubtractVector(&I->x4);
280 HeightB.CopyVector(&intersection);
281 HeightB.SubtractVector(&I->x3);
282 HeightB.ProjectOntoPlane(&SideB);
283
284 retval = HeightA.ScalarProduct(&HeightA) + HeightB.ScalarProduct(&HeightB);
285 //Log() << Verbose(2) << "MinIntersectDistance called, result: " << retval << endl;
286
287 return retval;
288};
289
290
291/**
292 * Calculates whether there is an intersection between two lines. The first line
293 * always goes through point 1 and point 2 and the second line is given by the
294 * connection between point 4 and point 5.
295 *
296 * @param point 1 of line 1
297 * @param point 2 of line 1
298 * @param point 1 of line 2
299 * @param point 2 of line 2
300 *
301 * @return true if there is an intersection between the given lines, false otherwise
302 */
303bool existsIntersection(const Vector &point1, const Vector &point2, const Vector &point3, const Vector &point4)
304{
305 bool result;
306
307 struct Intersection par;
308 par.x1.CopyVector(&point1);
309 par.x2.CopyVector(&point2);
310 par.x3.CopyVector(&point3);
311 par.x4.CopyVector(&point4);
312
313 const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
314 gsl_multimin_fminimizer *s = NULL;
315 gsl_vector *ss, *x;
316 gsl_multimin_function minexFunction;
317
318 size_t iter = 0;
319 int status;
320 double size;
321
322 /* Starting point */
323 x = gsl_vector_alloc(NDIM);
324 gsl_vector_set(x, 0, point1.x[0]);
325 gsl_vector_set(x, 1, point1.x[1]);
326 gsl_vector_set(x, 2, point1.x[2]);
327
328 /* Set initial step sizes to 1 */
329 ss = gsl_vector_alloc(NDIM);
330 gsl_vector_set_all(ss, 1.0);
331
332 /* Initialize method and iterate */
333 minexFunction.n = NDIM;
334 minexFunction.f = &MinIntersectDistance;
335 minexFunction.params = (void *)&par;
336
337 s = gsl_multimin_fminimizer_alloc(T, NDIM);
338 gsl_multimin_fminimizer_set(s, &minexFunction, x, ss);
339
340 do {
341 iter++;
342 status = gsl_multimin_fminimizer_iterate(s);
343
344 if (status) {
345 break;
346 }
347
348 size = gsl_multimin_fminimizer_size(s);
349 status = gsl_multimin_test_size(size, 1e-2);
350
351 if (status == GSL_SUCCESS) {
352 Log() << Verbose(2) << "converged to minimum" << endl;
353 }
354 } while (status == GSL_CONTINUE && iter < 100);
355
356 // check whether intersection is in between or not
357 Vector intersection, SideA, SideB, HeightA, HeightB;
358 double t1, t2;
359 for (int i = 0; i < NDIM; i++) {
360 intersection.x[i] = gsl_vector_get(s->x, i);
361 }
362
363 SideA.CopyVector(&par.x2);
364 SideA.SubtractVector(&par.x1);
365 HeightA.CopyVector(&intersection);
366 HeightA.SubtractVector(&par.x1);
367
368 t1 = HeightA.ScalarProduct(&SideA)/SideA.ScalarProduct(&SideA);
369
370 SideB.CopyVector(&par.x4);
371 SideB.SubtractVector(&par.x3);
372 HeightB.CopyVector(&intersection);
373 HeightB.SubtractVector(&par.x3);
374
375 t2 = HeightB.ScalarProduct(&SideB)/SideB.ScalarProduct(&SideB);
376
377 Log() << Verbose(2) << "Intersection " << intersection << " is at "
378 << t1 << " for (" << point1 << "," << point2 << ") and at "
379 << t2 << " for (" << point3 << "," << point4 << "): ";
380
381 if (((t1 >= 0) && (t1 <= 1)) && ((t2 >= 0) && (t2 <= 1))) {
382 Log() << Verbose(0) << "true intersection." << endl;
383 result = true;
384 } else {
385 Log() << Verbose(0) << "intersection out of region of interest." << endl;
386 result = false;
387 }
388
389 // free minimizer stuff
390 gsl_vector_free(x);
391 gsl_vector_free(ss);
392 gsl_multimin_fminimizer_free(s);
393
394 return result;
395};
396
397/** Gets the angle between a point and a reference relative to the provided center.
398 * We have two shanks point and reference between which the angle is calculated
399 * and by scalar product with OrthogonalVector we decide the interval.
400 * @param point to calculate the angle for
401 * @param reference to which to calculate the angle
402 * @param OrthogonalVector points in direction of [pi,2pi] interval
403 *
404 * @return angle between point and reference
405 */
406double GetAngle(const Vector &point, const Vector &reference, const Vector &OrthogonalVector)
407{
408 if (reference.IsZero())
409 return M_PI;
410
411 // calculate both angles and correct with in-plane vector
412 if (point.IsZero())
413 return M_PI;
414 double phi = point.Angle(&reference);
415 if (OrthogonalVector.ScalarProduct(&point) > 0) {
416 phi = 2.*M_PI - phi;
417 }
418
419 Log() << Verbose(4) << "INFO: " << point << " has angle " << phi << " with respect to reference " << reference << "." << endl;
420
421 return phi;
422}
423
424
425/** Calculates the volume of a general tetraeder.
426 * \param *a first vector
427 * \param *a first vector
428 * \param *a first vector
429 * \param *a first vector
430 * \return \f$ \frac{1}{6} \cdot ((a-d) \times (a-c) \cdot (a-b)) \f$
431 */
432double CalculateVolumeofGeneralTetraeder(const Vector &a, const Vector &b, const Vector &c, const Vector &d)
433{
434 Vector Point, TetraederVector[3];
435 double volume;
436
437 TetraederVector[0].CopyVector(a);
438 TetraederVector[1].CopyVector(b);
439 TetraederVector[2].CopyVector(c);
440 for (int j=0;j<3;j++)
441 TetraederVector[j].SubtractVector(&d);
442 Point.CopyVector(&TetraederVector[0]);
443 Point.VectorProduct(&TetraederVector[1]);
444 volume = 1./6. * fabs(Point.ScalarProduct(&TetraederVector[2]));
445 return volume;
446};
447
448
449/** Checks for a new special triangle whether one of its edges is already present with one one triangle connected.
450 * This enforces that special triangles (i.e. degenerated ones) should at last close the open-edge frontier and not
451 * make it bigger (i.e. closing one (the baseline) and opening two new ones).
452 * \param TPS[3] nodes of the triangle
453 * \return true - there is such a line (i.e. creation of degenerated triangle is valid), false - no such line (don't create)
454 */
455bool CheckLineCriteriaForDegeneratedTriangle(const BoundaryPointSet * const nodes[3])
456{
457 bool result = false;
458 int counter = 0;
459
460 // check all three points
461 for (int i=0;i<3;i++)
462 for (int j=i+1; j<3; j++) {
463 if (nodes[i] == NULL) {
464 Log() << Verbose(1) << "Node nr. " << i << " is not yet present." << endl;
465 result = true;
466 } else if (nodes[i]->lines.find(nodes[j]->node->nr) != nodes[i]->lines.end()) { // there already is a line
467 LineMap::const_iterator FindLine;
468 pair<LineMap::const_iterator,LineMap::const_iterator> FindPair;
469 FindPair = nodes[i]->lines.equal_range(nodes[j]->node->nr);
470 for (FindLine = FindPair.first; FindLine != FindPair.second; ++FindLine) {
471 // If there is a line with less than two attached triangles, we don't need a new line.
472 if (FindLine->second->triangles.size() < 2) {
473 counter++;
474 break; // increase counter only once per edge
475 }
476 }
477 } else { // no line
478 Log() << Verbose(1) << "The line between " << *nodes[i] << " and " << *nodes[j] << " is not yet present, hence no need for a degenerate triangle." << endl;
479 result = true;
480 }
481 }
482 if ((!result) && (counter > 1)) {
483 Log() << Verbose(2) << "INFO: Degenerate triangle is ok, at least two, here " << counter << ", existing lines are used." << endl;
484 result = true;
485 }
486 return result;
487};
488
489
490/** Sort function for the candidate list.
491 */
492bool SortCandidates(const CandidateForTesselation* candidate1, const CandidateForTesselation* candidate2)
493{
494 Vector BaseLineVector, OrthogonalVector, helper;
495 if (candidate1->BaseLine != candidate2->BaseLine) { // sanity check
496 eLog() << Verbose(1) << "sortCandidates was called for two different baselines: " << candidate1->BaseLine << " and " << candidate2->BaseLine << "." << endl;
497 //return false;
498 exit(1);
499 }
500 // create baseline vector
501 BaseLineVector.CopyVector(candidate1->BaseLine->endpoints[1]->node->node);
502 BaseLineVector.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
503 BaseLineVector.Normalize();
504
505 // create normal in-plane vector to cope with acos() non-uniqueness on [0,2pi] (note that is pointing in the "right" direction already, hence ">0" test!)
506 helper.CopyVector(candidate1->BaseLine->endpoints[0]->node->node);
507 helper.SubtractVector(candidate1->point->node);
508 OrthogonalVector.CopyVector(&helper);
509 helper.VectorProduct(&BaseLineVector);
510 OrthogonalVector.SubtractVector(&helper);
511 OrthogonalVector.Normalize();
512
513 // calculate both angles and correct with in-plane vector
514 helper.CopyVector(candidate1->point->node);
515 helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
516 double phi = BaseLineVector.Angle(&helper);
517 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
518 phi = 2.*M_PI - phi;
519 }
520 helper.CopyVector(candidate2->point->node);
521 helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
522 double psi = BaseLineVector.Angle(&helper);
523 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
524 psi = 2.*M_PI - psi;
525 }
526
527 Log() << Verbose(2) << *candidate1->point << " has angle " << phi << endl;
528 Log() << Verbose(2) << *candidate2->point << " has angle " << psi << endl;
529
530 // return comparison
531 return phi < psi;
532};
533
534/**
535 * Finds the point which is second closest to the provided one.
536 *
537 * @param Point to which to find the second closest other point
538 * @param linked cell structure
539 *
540 * @return point which is second closest to the provided one
541 */
542TesselPoint* FindSecondClosestPoint(const Vector* Point, const LinkedCell* const LC)
543{
544 TesselPoint* closestPoint = NULL;
545 TesselPoint* secondClosestPoint = NULL;
546 double distance = 1e16;
547 double secondDistance = 1e16;
548 Vector helper;
549 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
550
551 LC->SetIndexToVector(Point); // ignore status as we calculate bounds below sensibly
552 for(int i=0;i<NDIM;i++) // store indices of this cell
553 N[i] = LC->n[i];
554 Log() << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
555
556 LC->GetNeighbourBounds(Nlower, Nupper);
557 //Log() << Verbose(0) << endl;
558 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
559 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
560 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
561 const LinkedNodes *List = LC->GetCurrentCell();
562 //Log() << Verbose(3) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
563 if (List != NULL) {
564 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
565 helper.CopyVector(Point);
566 helper.SubtractVector((*Runner)->node);
567 double currentNorm = helper. Norm();
568 if (currentNorm < distance) {
569 // remember second point
570 secondDistance = distance;
571 secondClosestPoint = closestPoint;
572 // mark down new closest point
573 distance = currentNorm;
574 closestPoint = (*Runner);
575 //Log() << Verbose(2) << "INFO: New Second Nearest Neighbour is " << *secondClosestPoint << "." << endl;
576 }
577 }
578 } else {
579 eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << ","
580 << LC->n[2] << " is invalid!" << endl;
581 }
582 }
583
584 return secondClosestPoint;
585};
586
587/**
588 * Finds the point which is closest to the provided one.
589 *
590 * @param Point to which to find the closest other point
591 * @param SecondPoint the second closest other point on return, NULL if none found
592 * @param linked cell structure
593 *
594 * @return point which is closest to the provided one, NULL if none found
595 */
596TesselPoint* FindClosestPoint(const Vector* Point, TesselPoint *&SecondPoint, const LinkedCell* const LC)
597{
598 TesselPoint* closestPoint = NULL;
599 SecondPoint = NULL;
600 double distance = 1e16;
601 double secondDistance = 1e16;
602 Vector helper;
603 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
604
605 LC->SetIndexToVector(Point); // ignore status as we calculate bounds below sensibly
606 for(int i=0;i<NDIM;i++) // store indices of this cell
607 N[i] = LC->n[i];
608 Log() << Verbose(3) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
609
610 LC->GetNeighbourBounds(Nlower, Nupper);
611 //Log() << Verbose(0) << endl;
612 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
613 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
614 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
615 const LinkedNodes *List = LC->GetCurrentCell();
616 //Log() << Verbose(3) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
617 if (List != NULL) {
618 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
619 helper.CopyVector(Point);
620 helper.SubtractVector((*Runner)->node);
621 double currentNorm = helper. Norm();
622 if (currentNorm < distance) {
623 secondDistance = distance;
624 SecondPoint = closestPoint;
625 distance = currentNorm;
626 closestPoint = (*Runner);
627 //Log() << Verbose(2) << "INFO: New Nearest Neighbour is " << *closestPoint << "." << endl;
628 } else if (currentNorm < secondDistance) {
629 secondDistance = currentNorm;
630 SecondPoint = (*Runner);
631 //Log() << Verbose(2) << "INFO: New Second Nearest Neighbour is " << *SecondPoint << "." << endl;
632 }
633 }
634 } else {
635 eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << ","
636 << LC->n[2] << " is invalid!" << endl;
637 }
638 }
639 // output
640 if (closestPoint != NULL) {
641 Log() << Verbose(2) << "Closest point is " << *closestPoint;
642 if (SecondPoint != NULL)
643 Log() << Verbose(0) << " and second closest is " << *SecondPoint;
644 Log() << Verbose(0) << "." << endl;
645 }
646 return closestPoint;
647};
648
649/** Returns the closest point on \a *Base with respect to \a *OtherBase.
650 * \param *out output stream for debugging
651 * \param *Base reference line
652 * \param *OtherBase other base line
653 * \return Vector on reference line that has closest distance
654 */
655Vector * GetClosestPointBetweenLine(const BoundaryLineSet * const Base, const BoundaryLineSet * const OtherBase)
656{
657 // construct the plane of the two baselines (i.e. take both their directional vectors)
658 Vector Normal;
659 Vector Baseline, OtherBaseline;
660 Baseline.CopyVector(Base->endpoints[1]->node->node);
661 Baseline.SubtractVector(Base->endpoints[0]->node->node);
662 OtherBaseline.CopyVector(OtherBase->endpoints[1]->node->node);
663 OtherBaseline.SubtractVector(OtherBase->endpoints[0]->node->node);
664 Normal.CopyVector(&Baseline);
665 Normal.VectorProduct(&OtherBaseline);
666 Normal.Normalize();
667 Log() << Verbose(4) << "First direction is " << Baseline << ", second direction is " << OtherBaseline << ", normal of intersection plane is " << Normal << "." << endl;
668
669 // project one offset point of OtherBase onto this plane (and add plane offset vector)
670 Vector NewOffset;
671 NewOffset.CopyVector(OtherBase->endpoints[0]->node->node);
672 NewOffset.SubtractVector(Base->endpoints[0]->node->node);
673 NewOffset.ProjectOntoPlane(&Normal);
674 NewOffset.AddVector(Base->endpoints[0]->node->node);
675 Vector NewDirection;
676 NewDirection.CopyVector(&NewOffset);
677 NewDirection.AddVector(&OtherBaseline);
678
679 // calculate the intersection between this projected baseline and Base
680 Vector *Intersection = new Vector;
681 Intersection->GetIntersectionOfTwoLinesOnPlane(Base->endpoints[0]->node->node, Base->endpoints[1]->node->node, &NewOffset, &NewDirection, &Normal);
682 Normal.CopyVector(Intersection);
683 Normal.SubtractVector(Base->endpoints[0]->node->node);
684 Log() << Verbose(3) << "Found closest point on " << *Base << " at " << *Intersection << ", factor in line is " << fabs(Normal.ScalarProduct(&Baseline)/Baseline.NormSquared()) << "." << endl;
685
686 return Intersection;
687};
688
689/** Returns the distance to the plane defined by \a *triangle
690 * \param *out output stream for debugging
691 * \param *x Vector to calculate distance to
692 * \param *triangle triangle defining plane
693 * \return distance between \a *x and plane defined by \a *triangle, -1 - if something went wrong
694 */
695double DistanceToTrianglePlane(const Vector *x, const BoundaryTriangleSet * const triangle)
696{
697 double distance = 0.;
698 if (x == NULL) {
699 return -1;
700 }
701 distance = x->DistanceToPlane(&triangle->NormalVector, triangle->endpoints[0]->node->node);
702 return distance;
703};
704
705/** Creates the objects in a VRML file.
706 * \param *out output stream for debugging
707 * \param *vrmlfile output stream for tecplot data
708 * \param *Tess Tesselation structure with constructed triangles
709 * \param *mol molecule structure with atom positions
710 */
711void WriteVrmlFile(ofstream * const vrmlfile, const Tesselation * const Tess, const PointCloud * const cloud)
712{
713 TesselPoint *Walker = NULL;
714 int i;
715 Vector *center = cloud->GetCenter();
716 if (vrmlfile != NULL) {
717 //Log() << Verbose(1) << "Writing Raster3D file ... ";
718 *vrmlfile << "#VRML V2.0 utf8" << endl;
719 *vrmlfile << "#Created by molecuilder" << endl;
720 *vrmlfile << "#All atoms as spheres" << endl;
721 cloud->GoToFirst();
722 while (!cloud->IsEnd()) {
723 Walker = cloud->GetPoint();
724 *vrmlfile << "Sphere {" << endl << " "; // 2 is sphere type
725 for (i=0;i<NDIM;i++)
726 *vrmlfile << Walker->node->x[i]-center->x[i] << " ";
727 *vrmlfile << "\t0.1\t1. 1. 1." << endl; // radius 0.05 and white as colour
728 cloud->GoToNext();
729 }
730
731 *vrmlfile << "# All tesselation triangles" << endl;
732 for (TriangleMap::const_iterator TriangleRunner = Tess->TrianglesOnBoundary.begin(); TriangleRunner != Tess->TrianglesOnBoundary.end(); TriangleRunner++) {
733 *vrmlfile << "1" << endl << " "; // 1 is triangle type
734 for (i=0;i<3;i++) { // print each node
735 for (int j=0;j<NDIM;j++) // and for each node all NDIM coordinates
736 *vrmlfile << TriangleRunner->second->endpoints[i]->node->node->x[j]-center->x[j] << " ";
737 *vrmlfile << "\t";
738 }
739 *vrmlfile << "1. 0. 0." << endl; // red as colour
740 *vrmlfile << "18" << endl << " 0.5 0.5 0.5" << endl; // 18 is transparency type for previous object
741 }
742 } else {
743 eLog() << Verbose(1) << "Given vrmlfile is " << vrmlfile << "." << endl;
744 }
745 delete(center);
746};
747
748/** Writes additionally the current sphere (i.e. the last triangle to file).
749 * \param *out output stream for debugging
750 * \param *rasterfile output stream for tecplot data
751 * \param *Tess Tesselation structure with constructed triangles
752 * \param *mol molecule structure with atom positions
753 */
754void IncludeSphereinRaster3D(ofstream * const rasterfile, const Tesselation * const Tess, const PointCloud * const cloud)
755{
756 Vector helper;
757 // include the current position of the virtual sphere in the temporary raster3d file
758 Vector *center = cloud->GetCenter();
759 // make the circumsphere's center absolute again
760 helper.CopyVector(Tess->LastTriangle->endpoints[0]->node->node);
761 helper.AddVector(Tess->LastTriangle->endpoints[1]->node->node);
762 helper.AddVector(Tess->LastTriangle->endpoints[2]->node->node);
763 helper.Scale(1./3.);
764 helper.SubtractVector(center);
765 // and add to file plus translucency object
766 *rasterfile << "# current virtual sphere\n";
767 *rasterfile << "8\n 25.0 0.6 -1.0 -1.0 -1.0 0.2 0 0 0 0\n";
768 *rasterfile << "2\n " << helper.x[0] << " " << helper.x[1] << " " << helper.x[2] << "\t" << 5. << "\t1 0 0\n";
769 *rasterfile << "9\n terminating special property\n";
770 delete(center);
771};
772
773/** Creates the objects in a raster3d file (renderable with a header.r3d).
774 * \param *out output stream for debugging
775 * \param *rasterfile output stream for tecplot data
776 * \param *Tess Tesselation structure with constructed triangles
777 * \param *mol molecule structure with atom positions
778 */
779void WriteRaster3dFile(ofstream * const rasterfile, const Tesselation * const Tess, const PointCloud * const cloud)
780{
781 TesselPoint *Walker = NULL;
782 int i;
783 Vector *center = cloud->GetCenter();
784 if (rasterfile != NULL) {
785 //Log() << Verbose(1) << "Writing Raster3D file ... ";
786 *rasterfile << "# Raster3D object description, created by MoleCuilder" << endl;
787 *rasterfile << "@header.r3d" << endl;
788 *rasterfile << "# All atoms as spheres" << endl;
789 cloud->GoToFirst();
790 while (!cloud->IsEnd()) {
791 Walker = cloud->GetPoint();
792 *rasterfile << "2" << endl << " "; // 2 is sphere type
793 for (i=0;i<NDIM;i++)
794 *rasterfile << Walker->node->x[i]-center->x[i] << " ";
795 *rasterfile << "\t0.1\t1. 1. 1." << endl; // radius 0.05 and white as colour
796 cloud->GoToNext();
797 }
798
799 *rasterfile << "# All tesselation triangles" << endl;
800 *rasterfile << "8\n 25. -1. 1. 1. 1. 0.0 0 0 0 2\n SOLID 1.0 0.0 0.0\n BACKFACE 0.3 0.3 1.0 0 0\n";
801 for (TriangleMap::const_iterator TriangleRunner = Tess->TrianglesOnBoundary.begin(); TriangleRunner != Tess->TrianglesOnBoundary.end(); TriangleRunner++) {
802 *rasterfile << "1" << endl << " "; // 1 is triangle type
803 for (i=0;i<3;i++) { // print each node
804 for (int j=0;j<NDIM;j++) // and for each node all NDIM coordinates
805 *rasterfile << TriangleRunner->second->endpoints[i]->node->node->x[j]-center->x[j] << " ";
806 *rasterfile << "\t";
807 }
808 *rasterfile << "1. 0. 0." << endl; // red as colour
809 //*rasterfile << "18" << endl << " 0.5 0.5 0.5" << endl; // 18 is transparency type for previous object
810 }
811 *rasterfile << "9\n# terminating special property\n";
812 } else {
813 eLog() << Verbose(1) << "Given rasterfile is " << rasterfile << "." << endl;
814 }
815 IncludeSphereinRaster3D(rasterfile, Tess, cloud);
816 delete(center);
817};
818
819/** This function creates the tecplot file, displaying the tesselation of the hull.
820 * \param *out output stream for debugging
821 * \param *tecplot output stream for tecplot data
822 * \param N arbitrary number to differentiate various zones in the tecplot format
823 */
824void WriteTecplotFile(ofstream * const tecplot, const Tesselation * const TesselStruct, const PointCloud * const cloud, const int N)
825{
826 if ((tecplot != NULL) && (TesselStruct != NULL)) {
827 // write header
828 *tecplot << "TITLE = \"3D CONVEX SHELL\"" << endl;
829 *tecplot << "VARIABLES = \"X\" \"Y\" \"Z\" \"U\"" << endl;
830 *tecplot << "ZONE T=\"" << N << "-";
831 for (int i=0;i<3;i++)
832 *tecplot << (i==0 ? "" : "_") << TesselStruct->LastTriangle->endpoints[i]->node->Name;
833 *tecplot << "\", N=" << TesselStruct->PointsOnBoundary.size() << ", E=" << TesselStruct->TrianglesOnBoundary.size() << ", DATAPACKING=POINT, ZONETYPE=FETRIANGLE" << endl;
834 int i=0;
835 for (cloud->GoToFirst(); !cloud->IsEnd(); cloud->GoToNext(), i++);
836 int *LookupList = new int[i];
837 for (cloud->GoToFirst(), i=0; !cloud->IsEnd(); cloud->GoToNext(), i++)
838 LookupList[i] = -1;
839
840 // print atom coordinates
841 Log() << Verbose(2) << "The following triangles were created:";
842 int Counter = 1;
843 TesselPoint *Walker = NULL;
844 for (PointMap::const_iterator target = TesselStruct->PointsOnBoundary.begin(); target != TesselStruct->PointsOnBoundary.end(); target++) {
845 Walker = target->second->node;
846 LookupList[Walker->nr] = Counter++;
847 *tecplot << Walker->node->x[0] << " " << Walker->node->x[1] << " " << Walker->node->x[2] << " " << target->second->value << endl;
848 }
849 *tecplot << endl;
850 // print connectivity
851 for (TriangleMap::const_iterator runner = TesselStruct->TrianglesOnBoundary.begin(); runner != TesselStruct->TrianglesOnBoundary.end(); runner++) {
852 Log() << Verbose(0) << " " << runner->second->endpoints[0]->node->Name << "<->" << runner->second->endpoints[1]->node->Name << "<->" << runner->second->endpoints[2]->node->Name;
853 *tecplot << LookupList[runner->second->endpoints[0]->node->nr] << " " << LookupList[runner->second->endpoints[1]->node->nr] << " " << LookupList[runner->second->endpoints[2]->node->nr] << endl;
854 }
855 delete[] (LookupList);
856 Log() << Verbose(0) << endl;
857 }
858};
859
860/** Calculates the concavity for each of the BoundaryPointSet's in a Tesselation.
861 * Sets BoundaryPointSet::value equal to the number of connected lines that are not convex.
862 * \param *out output stream for debugging
863 * \param *TesselStruct pointer to Tesselation structure
864 */
865void CalculateConcavityPerBoundaryPoint(const Tesselation * const TesselStruct)
866{
867 class BoundaryPointSet *point = NULL;
868 class BoundaryLineSet *line = NULL;
869
870 //Log() << Verbose(2) << "Begin of CalculateConcavityPerBoundaryPoint" << endl;
871 // calculate remaining concavity
872 for (PointMap::const_iterator PointRunner = TesselStruct->PointsOnBoundary.begin(); PointRunner != TesselStruct->PointsOnBoundary.end(); PointRunner++) {
873 point = PointRunner->second;
874 Log() << Verbose(1) << "INFO: Current point is " << *point << "." << endl;
875 point->value = 0;
876 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
877 line = LineRunner->second;
878 //Log() << Verbose(2) << "INFO: Current line of point " << *point << " is " << *line << "." << endl;
879 if (!line->CheckConvexityCriterion())
880 point->value += 1;
881 }
882 }
883 //Log() << Verbose(2) << "End of CalculateConcavityPerBoundaryPoint" << endl;
884};
885
886
887/** Checks whether each BoundaryLineSet in the Tesselation has two triangles.
888 * \param *out output stream for debugging
889 * \param *TesselStruct
890 * \return true - all have exactly two triangles, false - some not, list is printed to screen
891 */
892bool CheckListOfBaselines(const Tesselation * const TesselStruct)
893{
894 LineMap::const_iterator testline;
895 bool result = false;
896 int counter = 0;
897
898 Log() << Verbose(1) << "Check: List of Baselines with not two connected triangles:" << endl;
899 for (testline = TesselStruct->LinesOnBoundary.begin(); testline != TesselStruct->LinesOnBoundary.end(); testline++) {
900 if (testline->second->triangles.size() != 2) {
901 Log() << Verbose(1) << *testline->second << "\t" << testline->second->triangles.size() << endl;
902 counter++;
903 }
904 }
905 if (counter == 0) {
906 Log() << Verbose(1) << "None." << endl;
907 result = true;
908 }
909 return result;
910}
911
Note: See TracBrowser for help on using the repository browser.