source: src/tesselationhelpers.cpp@ 13892b

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 13892b was bdb143, checked in by Frederik Heber <heber@…>, 15 years ago

Merge branch 'StructureRefactoring' into stable

Conflicts:

molecuilder/src/analysis_bonds.cpp
molecuilder/src/analysis_bonds.hpp
molecuilder/src/builder.cpp
molecuilder/src/unittests/Makefile.am
molecuilder/src/unittests/TestRunnerMain.cpp

  • TESTFIX: Tesselations/heptan - Due to different implementations of GetCircumCenter() sequence of triangles nodes has changed in degenerate case
  • TESTFIX: Tesselation/1-3 - Due to convexity criterion fourth argument (i.e. the value at the node) has changed.

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

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