source: src/tesselationhelpers.cpp@ b32dbb

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 Candidate_v1.7.0 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 b32dbb was b32dbb, checked in by Frederik Heber <heber@…>, 15 years ago

Fixes and changes to tesselation and concavity measurements.

Here, we implement two attempts for a concavity measure:

  1. Measure concavity per point by looking at neighbouring triangles
    • BoundaryLineSet::CheckConvexityCriterion() split up (calculation of angle outsourced to CalculateConvexity())
    • CHANGE: CalculateConcavityPerBoundaryPoint() uses new concavity measure per BoundaryPointSet containing:
      • concavity per line uses angle instead of +/-1 for line, averaged by number of lines
      • also concavity over all attached triangles uses area of triangle and only in case of concavity, averaged by total area
    • new functions
      • BoundaryLineSet::CalculateConvexity() - calculates the angle between two triangles.
      • BoundaryLineSet::GetOtherTriangle() - for a closed line returns the other triangle for a given one
      • BoundaryTriangleSet::GetThirdLine() - for a given boundary point returns the line of the three which does not contain it (opposite line to a point)
      • CalculateAreaofGeneralTriangle() - calculates area of arbitrary triangle
  1. Measure concavity by the distance to a more convex envelope (i.e. created with bigger sphere radius)

Other unrelated stuff:

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

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