source: src/Tesselation/tesselationhelpers.cpp@ 41a467

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 41a467 was 47d041, checked in by Frederik Heber <heber@…>, 13 years ago

HUGE: Removed all calls to Log(), eLog(), replaced by LOG() and ELOG().

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