source: src/boundary.cpp@ d30402

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

Split VolumeOfConvexEnvelope() into find_convex_border() and remainder.

  • Convex envelope is not working anymore, in the state of fixing it and trying to refactor code a bit.
  • planned to have VolumeOfConvexEnvelope() to be replaced by VolumeOfEnvelope(), which can also do Non-Convex-Envelopes
  • Property mode set to 100755
File size: 125.3 KB
Line 
1#include "boundary.hpp"
2#include "linkedcell.hpp"
3#include "molecules.hpp"
4#include <gsl/gsl_matrix.h>
5#include <gsl/gsl_linalg.h>
6#include <gsl/gsl_multimin.h>
7#include <gsl/gsl_permutation.h>
8
9#define DEBUG 1
10#define DoSingleStepOutput 0
11#define DoTecplotOutput 1
12#define DoRaster3DOutput 1
13#define DoVRMLOutput 1
14#define TecplotSuffix ".dat"
15#define Raster3DSuffix ".r3d"
16#define VRMLSUffix ".wrl"
17#define HULLEPSILON 1e-7
18
19// ======================================== Points on Boundary =================================
20
21BoundaryPointSet::BoundaryPointSet()
22{
23 LinesCount = 0;
24 Nr = -1;
25}
26;
27
28BoundaryPointSet::BoundaryPointSet(atom *Walker)
29{
30 node = Walker;
31 LinesCount = 0;
32 Nr = Walker->nr;
33}
34;
35
36BoundaryPointSet::~BoundaryPointSet()
37{
38 cout << Verbose(5) << "Erasing point nr. " << Nr << "." << endl;
39 if (!lines.empty())
40 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some lines." << endl;
41 node = NULL;
42}
43;
44
45void BoundaryPointSet::AddLine(class BoundaryLineSet *line)
46{
47 cout << Verbose(6) << "Adding " << *this << " to line " << *line << "."
48 << endl;
49 if (line->endpoints[0] == this)
50 {
51 lines.insert(LinePair(line->endpoints[1]->Nr, line));
52 }
53 else
54 {
55 lines.insert(LinePair(line->endpoints[0]->Nr, line));
56 }
57 LinesCount++;
58}
59;
60
61ostream &
62operator <<(ostream &ost, BoundaryPointSet &a)
63{
64 ost << "[" << a.Nr << "|" << a.node->Name << "]";
65 return ost;
66}
67;
68
69// ======================================== Lines on Boundary =================================
70
71BoundaryLineSet::BoundaryLineSet()
72{
73 for (int i = 0; i < 2; i++)
74 endpoints[i] = NULL;
75 TrianglesCount = 0;
76 Nr = -1;
77}
78;
79
80BoundaryLineSet::BoundaryLineSet(class BoundaryPointSet *Point[2], int number)
81{
82 // set number
83 Nr = number;
84 // set endpoints in ascending order
85 SetEndpointsOrdered(endpoints, Point[0], Point[1]);
86 // add this line to the hash maps of both endpoints
87 Point[0]->AddLine(this); //Taken out, to check whether we can avoid unwanted double adding.
88 Point[1]->AddLine(this); //
89 // clear triangles list
90 TrianglesCount = 0;
91 cout << Verbose(5) << "New Line with endpoints " << *this << "." << endl;
92}
93;
94
95BoundaryLineSet::~BoundaryLineSet()
96{
97 int Numbers[2];
98 Numbers[0] = endpoints[1]->Nr;
99 Numbers[1] = endpoints[0]->Nr;
100 for (int i = 0; i < 2; i++) {
101 cout << Verbose(5) << "Erasing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
102 // as there may be multiple lines with same endpoints, we have to go through each and find in the endpoint's line list this line set
103 pair<LineMap::iterator, LineMap::iterator> erasor = endpoints[i]->lines.equal_range(Numbers[i]);
104 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
105 if ((*Runner).second == this) {
106 endpoints[i]->lines.erase(Runner);
107 break;
108 }
109 if (endpoints[i]->lines.empty()) {
110 cout << Verbose(5) << *endpoints[i] << " has no more lines it's attached to, erasing." << endl;
111 if (endpoints[i] != NULL) {
112 delete(endpoints[i]);
113 endpoints[i] = NULL;
114 } else
115 cerr << "ERROR: Endpoint " << i << " has already been free'd." << endl;
116 } else
117 cout << Verbose(5) << *endpoints[i] << " has still lines it's attached to." << endl;
118 }
119 if (!triangles.empty())
120 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some triangles." << endl;
121}
122;
123
124void
125BoundaryLineSet::AddTriangle(class BoundaryTriangleSet *triangle)
126{
127 cout << Verbose(6) << "Add " << triangle->Nr << " to line " << *this << "."
128 << endl;
129 triangles.insert(TrianglePair(triangle->Nr, triangle));
130 TrianglesCount++;
131}
132;
133
134ostream &
135operator <<(ostream &ost, BoundaryLineSet &a)
136{
137 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << ","
138 << a.endpoints[1]->node->Name << "]";
139 return ost;
140}
141;
142
143// ======================================== Triangles on Boundary =================================
144
145
146BoundaryTriangleSet::BoundaryTriangleSet()
147{
148 for (int i = 0; i < 3; i++)
149 {
150 endpoints[i] = NULL;
151 lines[i] = NULL;
152 }
153 Nr = -1;
154}
155;
156
157BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet *line[3], int number)
158{
159 // set number
160 Nr = number;
161 // set lines
162 cout << Verbose(5) << "New triangle " << Nr << ":" << endl;
163 for (int i = 0; i < 3; i++)
164 {
165 lines[i] = line[i];
166 lines[i]->AddTriangle(this);
167 }
168 // get ascending order of endpoints
169 map<int, class BoundaryPointSet *> OrderMap;
170 for (int i = 0; i < 3; i++)
171 // for all three lines
172 for (int j = 0; j < 2; j++)
173 { // for both endpoints
174 OrderMap.insert(pair<int, class BoundaryPointSet *> (
175 line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
176 // and we don't care whether insertion fails
177 }
178 // set endpoints
179 int Counter = 0;
180 cout << Verbose(6) << " with end points ";
181 for (map<int, class BoundaryPointSet *>::iterator runner = OrderMap.begin(); runner
182 != OrderMap.end(); runner++)
183 {
184 endpoints[Counter] = runner->second;
185 cout << " " << *endpoints[Counter];
186 Counter++;
187 }
188 if (Counter < 3)
189 {
190 cerr << "ERROR! We have a triangle with only two distinct endpoints!"
191 << endl;
192 //exit(1);
193 }
194 cout << "." << endl;
195}
196;
197
198BoundaryTriangleSet::~BoundaryTriangleSet()
199{
200 for (int i = 0; i < 3; i++) {
201 cout << Verbose(5) << "Erasing triangle Nr." << Nr << endl;
202 lines[i]->triangles.erase(Nr);
203 if (lines[i]->triangles.empty()) {
204 if (lines[i] != NULL) {
205 cout << Verbose(5) << *lines[i] << " is no more attached to any triangle, erasing." << endl;
206 delete (lines[i]);
207 lines[i] = NULL;
208 } else
209 cerr << "ERROR: This line " << i << " has already been free'd." << endl;
210 } else
211 cout << Verbose(5) << *lines[i] << " is still attached to another triangle." << endl;
212 }
213}
214;
215
216void
217BoundaryTriangleSet::GetNormalVector(Vector &OtherVector)
218{
219 // get normal vector
220 NormalVector.MakeNormalVector(&endpoints[0]->node->x, &endpoints[1]->node->x,
221 &endpoints[2]->node->x);
222
223 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
224 if (NormalVector.Projection(&OtherVector) > 0)
225 NormalVector.Scale(-1.);
226}
227;
228
229ostream &
230operator <<(ostream &ost, BoundaryTriangleSet &a)
231{
232 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << ","
233 << a.endpoints[1]->node->Name << "," << a.endpoints[2]->node->Name << "]";
234 return ost;
235}
236;
237
238
239// ============================ CandidateForTesselation =============================
240
241CandidateForTesselation::CandidateForTesselation(
242 atom *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter
243) {
244 point = candidate;
245 BaseLine = line;
246 OptCenter.CopyVector(&OptCandidateCenter);
247 OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
248}
249
250CandidateForTesselation::~CandidateForTesselation() {
251 point = NULL;
252 BaseLine = NULL;
253}
254
255// ========================================== F U N C T I O N S =================================
256
257/** Finds the endpoint two lines are sharing.
258 * \param *line1 first line
259 * \param *line2 second line
260 * \return point which is shared or NULL if none
261 */
262class BoundaryPointSet *
263GetCommonEndpoint(class BoundaryLineSet * line1, class BoundaryLineSet * line2)
264{
265 class BoundaryLineSet * lines[2] =
266 { line1, line2 };
267 class BoundaryPointSet *node = NULL;
268 map<int, class BoundaryPointSet *> OrderMap;
269 pair<map<int, class BoundaryPointSet *>::iterator, bool> OrderTest;
270 for (int i = 0; i < 2; i++)
271 // for both lines
272 for (int j = 0; j < 2; j++)
273 { // for both endpoints
274 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
275 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
276 if (!OrderTest.second)
277 { // if insertion fails, we have common endpoint
278 node = OrderTest.first->second;
279 cout << Verbose(5) << "Common endpoint of lines " << *line1
280 << " and " << *line2 << " is: " << *node << "." << endl;
281 j = 2;
282 i = 2;
283 break;
284 }
285 }
286 return node;
287}
288;
289
290/** Determines the boundary points of a cluster.
291 * Does a projection per axis onto the orthogonal plane, transforms into spherical coordinates, sorts them by the angle
292 * and looks at triples: if the middle has less a distance than the allowed maximum height of the triangle formed by the plane's
293 * center and first and last point in the triple, it is thrown out.
294 * \param *out output stream for debugging
295 * \param *mol molecule structure representing the cluster
296 */
297Boundaries *
298GetBoundaryPoints(ofstream *out, molecule *mol)
299{
300 atom *Walker = NULL;
301 PointMap PointsOnBoundary;
302 LineMap LinesOnBoundary;
303 TriangleMap TrianglesOnBoundary;
304
305 *out << Verbose(1) << "Finding all boundary points." << endl;
306 Boundaries *BoundaryPoints = new Boundaries[NDIM]; // first is alpha, second is (r, nr)
307 BoundariesTestPair BoundaryTestPair;
308 Vector AxisVector, AngleReferenceVector, AngleReferenceNormalVector;
309 double radius, angle;
310 // 3a. Go through every axis
311 for (int axis = 0; axis < NDIM; axis++)
312 {
313 AxisVector.Zero();
314 AngleReferenceVector.Zero();
315 AngleReferenceNormalVector.Zero();
316 AxisVector.x[axis] = 1.;
317 AngleReferenceVector.x[(axis + 1) % NDIM] = 1.;
318 AngleReferenceNormalVector.x[(axis + 2) % NDIM] = 1.;
319 // *out << Verbose(1) << "Axisvector is ";
320 // AxisVector.Output(out);
321 // *out << " and AngleReferenceVector is ";
322 // AngleReferenceVector.Output(out);
323 // *out << "." << endl;
324 // *out << " and AngleReferenceNormalVector is ";
325 // AngleReferenceNormalVector.Output(out);
326 // *out << "." << endl;
327 // 3b. construct set of all points, transformed into cylindrical system and with left and right neighbours
328 Walker = mol->start;
329 while (Walker->next != mol->end)
330 {
331 Walker = Walker->next;
332 Vector ProjectedVector;
333 ProjectedVector.CopyVector(&Walker->x);
334 ProjectedVector.ProjectOntoPlane(&AxisVector);
335 // correct for negative side
336 //if (Projection(y) < 0)
337 //angle = 2.*M_PI - angle;
338 radius = ProjectedVector.Norm();
339 if (fabs(radius) > MYEPSILON)
340 angle = ProjectedVector.Angle(&AngleReferenceVector);
341 else
342 angle = 0.; // otherwise it's a vector in Axis Direction and unimportant for boundary issues
343
344 //*out << "Checking sign in quadrant : " << ProjectedVector.Projection(&AngleReferenceNormalVector) << "." << endl;
345 if (ProjectedVector.Projection(&AngleReferenceNormalVector) > 0)
346 {
347 angle = 2. * M_PI - angle;
348 }
349 //*out << Verbose(2) << "Inserting " << *Walker << ": (r, alpha) = (" << radius << "," << angle << "): ";
350 //ProjectedVector.Output(out);
351 //*out << endl;
352 BoundaryTestPair = BoundaryPoints[axis].insert(BoundariesPair(angle,
353 DistancePair (radius, Walker)));
354 if (BoundaryTestPair.second)
355 { // successfully inserted
356 }
357 else
358 { // same point exists, check first r, then distance of original vectors to center of gravity
359 *out << Verbose(2)
360 << "Encountered two vectors whose projection onto axis "
361 << axis << " is equal: " << endl;
362 *out << Verbose(2) << "Present vector: ";
363 BoundaryTestPair.first->second.second->x.Output(out);
364 *out << endl;
365 *out << Verbose(2) << "New vector: ";
366 Walker->x.Output(out);
367 *out << endl;
368 double tmp = ProjectedVector.Norm();
369 if (tmp > BoundaryTestPair.first->second.first)
370 {
371 BoundaryTestPair.first->second.first = tmp;
372 BoundaryTestPair.first->second.second = Walker;
373 *out << Verbose(2) << "Keeping new vector." << endl;
374 }
375 else if (tmp == BoundaryTestPair.first->second.first)
376 {
377 if (BoundaryTestPair.first->second.second->x.ScalarProduct(
378 &BoundaryTestPair.first->second.second->x)
379 < Walker->x.ScalarProduct(&Walker->x))
380 { // Norm() does a sqrt, which makes it a lot slower
381 BoundaryTestPair.first->second.second = Walker;
382 *out << Verbose(2) << "Keeping new vector." << endl;
383 }
384 else
385 {
386 *out << Verbose(2) << "Keeping present vector." << endl;
387 }
388 }
389 else
390 {
391 *out << Verbose(2) << "Keeping present vector." << endl;
392 }
393 }
394 }
395 // printing all inserted for debugging
396 // {
397 // *out << Verbose(2) << "Printing list of candidates for axis " << axis << " which we have inserted so far." << endl;
398 // int i=0;
399 // for(Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
400 // if (runner != BoundaryPoints[axis].begin())
401 // *out << ", " << i << ": " << *runner->second.second;
402 // else
403 // *out << i << ": " << *runner->second.second;
404 // i++;
405 // }
406 // *out << endl;
407 // }
408 // 3c. throw out points whose distance is less than the mean of left and right neighbours
409 bool flag = false;
410 do
411 { // do as long as we still throw one out per round
412 *out << Verbose(1)
413 << "Looking for candidates to kick out by convex condition ... "
414 << endl;
415 flag = false;
416 Boundaries::iterator left = BoundaryPoints[axis].end();
417 Boundaries::iterator right = BoundaryPoints[axis].end();
418 for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner
419 != BoundaryPoints[axis].end(); runner++)
420 {
421 // set neighbours correctly
422 if (runner == BoundaryPoints[axis].begin())
423 {
424 left = BoundaryPoints[axis].end();
425 }
426 else
427 {
428 left = runner;
429 }
430 left--;
431 right = runner;
432 right++;
433 if (right == BoundaryPoints[axis].end())
434 {
435 right = BoundaryPoints[axis].begin();
436 }
437 // check distance
438
439 // construct the vector of each side of the triangle on the projected plane (defined by normal vector AxisVector)
440 {
441 Vector SideA, SideB, SideC, SideH;
442 SideA.CopyVector(&left->second.second->x);
443 SideA.ProjectOntoPlane(&AxisVector);
444 // *out << "SideA: ";
445 // SideA.Output(out);
446 // *out << endl;
447
448 SideB.CopyVector(&right->second.second->x);
449 SideB.ProjectOntoPlane(&AxisVector);
450 // *out << "SideB: ";
451 // SideB.Output(out);
452 // *out << endl;
453
454 SideC.CopyVector(&left->second.second->x);
455 SideC.SubtractVector(&right->second.second->x);
456 SideC.ProjectOntoPlane(&AxisVector);
457 // *out << "SideC: ";
458 // SideC.Output(out);
459 // *out << endl;
460
461 SideH.CopyVector(&runner->second.second->x);
462 SideH.ProjectOntoPlane(&AxisVector);
463 // *out << "SideH: ";
464 // SideH.Output(out);
465 // *out << endl;
466
467 // calculate each length
468 double a = SideA.Norm();
469 //double b = SideB.Norm();
470 //double c = SideC.Norm();
471 double h = SideH.Norm();
472 // calculate the angles
473 double alpha = SideA.Angle(&SideH);
474 double beta = SideA.Angle(&SideC);
475 double gamma = SideB.Angle(&SideH);
476 double delta = SideC.Angle(&SideH);
477 double MinDistance = a * sin(beta) / (sin(delta)) * (((alpha
478 < M_PI / 2.) || (gamma < M_PI / 2.)) ? 1. : -1.);
479 // *out << Verbose(2) << " I calculated: a = " << a << ", h = " << h << ", beta(" << left->second.second->Name << "," << left->second.second->Name << "-" << right->second.second->Name << ") = " << beta << ", delta(" << left->second.second->Name << "," << runner->second.second->Name << ") = " << delta << ", Min = " << MinDistance << "." << endl;
480 //*out << Verbose(1) << "Checking CoG distance of runner " << *runner->second.second << " " << h << " against triangle's side length spanned by (" << *left->second.second << "," << *right->second.second << ") of " << MinDistance << "." << endl;
481 if ((fabs(h / fabs(h) - MinDistance / fabs(MinDistance))
482 < MYEPSILON) && (h < MinDistance))
483 {
484 // throw out point
485 //*out << Verbose(1) << "Throwing out " << *runner->second.second << "." << endl;
486 BoundaryPoints[axis].erase(runner);
487 flag = true;
488 }
489 }
490 }
491 }
492 while (flag);
493 }
494 return BoundaryPoints;
495}
496;
497
498/** Determines greatest diameters of a cluster defined by its convex envelope.
499 * Looks at lines parallel to one axis and where they intersect on the projected planes
500 * \param *out output stream for debugging
501 * \param *BoundaryPoints NDIM set of boundary points defining the convex envelope on each projected plane
502 * \param *mol molecule structure representing the cluster
503 * \param IsAngstroem whether we have angstroem or atomic units
504 * \return NDIM array of the diameters
505 */
506double *
507GetDiametersOfCluster(ofstream *out, Boundaries *BoundaryPtr, molecule *mol,
508 bool IsAngstroem)
509{
510 // get points on boundary of NULL was given as parameter
511 bool BoundaryFreeFlag = false;
512 Boundaries *BoundaryPoints = BoundaryPtr;
513 if (BoundaryPoints == NULL)
514 {
515 BoundaryFreeFlag = true;
516 BoundaryPoints = GetBoundaryPoints(out, mol);
517 }
518 else
519 {
520 *out << Verbose(1) << "Using given boundary points set." << endl;
521 }
522 // determine biggest "diameter" of cluster for each axis
523 Boundaries::iterator Neighbour, OtherNeighbour;
524 double *GreatestDiameter = new double[NDIM];
525 for (int i = 0; i < NDIM; i++)
526 GreatestDiameter[i] = 0.;
527 double OldComponent, tmp, w1, w2;
528 Vector DistanceVector, OtherVector;
529 int component, Othercomponent;
530 for (int axis = 0; axis < NDIM; axis++)
531 { // regard each projected plane
532 //*out << Verbose(1) << "Current axis is " << axis << "." << endl;
533 for (int j = 0; j < 2; j++)
534 { // and for both axis on the current plane
535 component = (axis + j + 1) % NDIM;
536 Othercomponent = (axis + 1 + ((j + 1) & 1)) % NDIM;
537 //*out << Verbose(1) << "Current component is " << component << ", Othercomponent is " << Othercomponent << "." << endl;
538 for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner
539 != BoundaryPoints[axis].end(); runner++)
540 {
541 //*out << Verbose(2) << "Current runner is " << *(runner->second.second) << "." << endl;
542 // seek for the neighbours pair where the Othercomponent sign flips
543 Neighbour = runner;
544 Neighbour++;
545 if (Neighbour == BoundaryPoints[axis].end()) // make it wrap around
546 Neighbour = BoundaryPoints[axis].begin();
547 DistanceVector.CopyVector(&runner->second.second->x);
548 DistanceVector.SubtractVector(&Neighbour->second.second->x);
549 do
550 { // seek for neighbour pair where it flips
551 OldComponent = DistanceVector.x[Othercomponent];
552 Neighbour++;
553 if (Neighbour == BoundaryPoints[axis].end()) // make it wrap around
554 Neighbour = BoundaryPoints[axis].begin();
555 DistanceVector.CopyVector(&runner->second.second->x);
556 DistanceVector.SubtractVector(&Neighbour->second.second->x);
557 //*out << Verbose(3) << "OldComponent is " << OldComponent << ", new one is " << DistanceVector.x[Othercomponent] << "." << endl;
558 }
559 while ((runner != Neighbour) && (fabs(OldComponent / fabs(
560 OldComponent) - DistanceVector.x[Othercomponent] / fabs(
561 DistanceVector.x[Othercomponent])) < MYEPSILON)); // as long as sign does not flip
562 if (runner != Neighbour)
563 {
564 OtherNeighbour = Neighbour;
565 if (OtherNeighbour == BoundaryPoints[axis].begin()) // make it wrap around
566 OtherNeighbour = BoundaryPoints[axis].end();
567 OtherNeighbour--;
568 //*out << Verbose(2) << "The pair, where the sign of OtherComponent flips, is: " << *(Neighbour->second.second) << " and " << *(OtherNeighbour->second.second) << "." << endl;
569 // now we have found the pair: Neighbour and OtherNeighbour
570 OtherVector.CopyVector(&runner->second.second->x);
571 OtherVector.SubtractVector(&OtherNeighbour->second.second->x);
572 //*out << Verbose(2) << "Distances to Neighbour and OtherNeighbour are " << DistanceVector.x[component] << " and " << OtherVector.x[component] << "." << endl;
573 //*out << Verbose(2) << "OtherComponents to Neighbour and OtherNeighbour are " << DistanceVector.x[Othercomponent] << " and " << OtherVector.x[Othercomponent] << "." << endl;
574 // do linear interpolation between points (is exact) to extract exact intersection between Neighbour and OtherNeighbour
575 w1 = fabs(OtherVector.x[Othercomponent]);
576 w2 = fabs(DistanceVector.x[Othercomponent]);
577 tmp = fabs((w1 * DistanceVector.x[component] + w2
578 * OtherVector.x[component]) / (w1 + w2));
579 // mark if it has greater diameter
580 //*out << Verbose(2) << "Comparing current greatest " << GreatestDiameter[component] << " to new " << tmp << "." << endl;
581 GreatestDiameter[component] = (GreatestDiameter[component]
582 > tmp) ? GreatestDiameter[component] : tmp;
583 } //else
584 //*out << Verbose(2) << "Saw no sign flip, probably top or bottom node." << endl;
585 }
586 }
587 }
588 *out << Verbose(0) << "RESULT: The biggest diameters are "
589 << GreatestDiameter[0] << " and " << GreatestDiameter[1] << " and "
590 << GreatestDiameter[2] << " " << (IsAngstroem ? "angstrom"
591 : "atomiclength") << "." << endl;
592
593 // free reference lists
594 if (BoundaryFreeFlag)
595 delete[] (BoundaryPoints);
596
597 return GreatestDiameter;
598}
599;
600
601/** Creates the objects in a VRML file.
602 * \param *out output stream for debugging
603 * \param *vrmlfile output stream for tecplot data
604 * \param *Tess Tesselation structure with constructed triangles
605 * \param *mol molecule structure with atom positions
606 */
607void write_vrml_file(ofstream *out, ofstream *vrmlfile, class Tesselation *Tess, class molecule *mol)
608{
609 atom *Walker = mol->start;
610 bond *Binder = mol->first;
611 int i;
612 Vector *center = mol->DetermineCenterOfAll(out);
613 if (vrmlfile != NULL) {
614 //cout << Verbose(1) << "Writing Raster3D file ... ";
615 *vrmlfile << "#VRML V2.0 utf8" << endl;
616 *vrmlfile << "#Created by molecuilder" << endl;
617 *vrmlfile << "#All atoms as spheres" << endl;
618 while (Walker->next != mol->end) {
619 Walker = Walker->next;
620 *vrmlfile << "Sphere {" << endl << " "; // 2 is sphere type
621 for (i=0;i<NDIM;i++)
622 *vrmlfile << Walker->x.x[i]+center->x[i] << " ";
623 *vrmlfile << "\t0.1\t1. 1. 1." << endl; // radius 0.05 and white as colour
624 }
625
626 *vrmlfile << "# All bonds as vertices" << endl;
627 while (Binder->next != mol->last) {
628 Binder = Binder->next;
629 *vrmlfile << "3" << endl << " "; // 2 is round-ended cylinder type
630 for (i=0;i<NDIM;i++)
631 *vrmlfile << Binder->leftatom->x.x[i]+center->x[i] << " ";
632 *vrmlfile << "\t0.03\t";
633 for (i=0;i<NDIM;i++)
634 *vrmlfile << Binder->rightatom->x.x[i]+center->x[i] << " ";
635 *vrmlfile << "\t0.03\t0. 0. 1." << endl; // radius 0.05 and blue as colour
636 }
637
638 *vrmlfile << "# All tesselation triangles" << endl;
639 for (TriangleMap::iterator TriangleRunner = Tess->TrianglesOnBoundary.begin(); TriangleRunner != Tess->TrianglesOnBoundary.end(); TriangleRunner++) {
640 *vrmlfile << "1" << endl << " "; // 1 is triangle type
641 for (i=0;i<3;i++) { // print each node
642 for (int j=0;j<NDIM;j++) // and for each node all NDIM coordinates
643 *vrmlfile << TriangleRunner->second->endpoints[i]->node->x.x[j]+center->x[j] << " ";
644 *vrmlfile << "\t";
645 }
646 *vrmlfile << "1. 0. 0." << endl; // red as colour
647 *vrmlfile << "18" << endl << " 0.5 0.5 0.5" << endl; // 18 is transparency type for previous object
648 }
649 } else {
650 cerr << "ERROR: Given vrmlfile is " << vrmlfile << "." << endl;
651 }
652 delete(center);
653};
654
655/** Creates the objects in a raster3d file (renderable with a header.r3d).
656 * \param *out output stream for debugging
657 * \param *rasterfile output stream for tecplot data
658 * \param *Tess Tesselation structure with constructed triangles
659 * \param *mol molecule structure with atom positions
660 */
661void write_raster3d_file(ofstream *out, ofstream *rasterfile, class Tesselation *Tess, class molecule *mol)
662{
663 atom *Walker = mol->start;
664 bond *Binder = mol->first;
665 int i;
666 Vector *center = mol->DetermineCenterOfAll(out);
667 if (rasterfile != NULL) {
668 //cout << Verbose(1) << "Writing Raster3D file ... ";
669 *rasterfile << "# Raster3D object description, created by MoleCuilder" << endl;
670 *rasterfile << "@header.r3d" << endl;
671 *rasterfile << "# All atoms as spheres" << endl;
672 while (Walker->next != mol->end) {
673 Walker = Walker->next;
674 *rasterfile << "2" << endl << " "; // 2 is sphere type
675 for (i=0;i<NDIM;i++)
676 *rasterfile << Walker->x.x[i]+center->x[i] << " ";
677 *rasterfile << "\t0.1\t1. 1. 1." << endl; // radius 0.05 and white as colour
678 }
679
680 *rasterfile << "# All bonds as vertices" << endl;
681 while (Binder->next != mol->last) {
682 Binder = Binder->next;
683 *rasterfile << "3" << endl << " "; // 2 is round-ended cylinder type
684 for (i=0;i<NDIM;i++)
685 *rasterfile << Binder->leftatom->x.x[i]+center->x[i] << " ";
686 *rasterfile << "\t0.03\t";
687 for (i=0;i<NDIM;i++)
688 *rasterfile << Binder->rightatom->x.x[i]+center->x[i] << " ";
689 *rasterfile << "\t0.03\t0. 0. 1." << endl; // radius 0.05 and blue as colour
690 }
691
692 *rasterfile << "# All tesselation triangles" << endl;
693 *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";
694 for (TriangleMap::iterator TriangleRunner = Tess->TrianglesOnBoundary.begin(); TriangleRunner != Tess->TrianglesOnBoundary.end(); TriangleRunner++) {
695 *rasterfile << "1" << endl << " "; // 1 is triangle type
696 for (i=0;i<3;i++) { // print each node
697 for (int j=0;j<NDIM;j++) // and for each node all NDIM coordinates
698 *rasterfile << TriangleRunner->second->endpoints[i]->node->x.x[j]+center->x[j] << " ";
699 *rasterfile << "\t";
700 }
701 *rasterfile << "1. 0. 0." << endl; // red as colour
702 //*rasterfile << "18" << endl << " 0.5 0.5 0.5" << endl; // 18 is transparency type for previous object
703 }
704 *rasterfile << "9\n terminating special property\n";
705 } else {
706 cerr << "ERROR: Given rasterfile is " << rasterfile << "." << endl;
707 }
708 delete(center);
709};
710
711/** This function creates the tecplot file, displaying the tesselation of the hull.
712 * \param *out output stream for debugging
713 * \param *tecplot output stream for tecplot data
714 * \param N arbitrary number to differentiate various zones in the tecplot format
715 */
716void
717write_tecplot_file(ofstream *out, ofstream *tecplot,
718 class Tesselation *TesselStruct, class molecule *mol, int N)
719{
720 if (tecplot != NULL)
721 {
722 *tecplot << "TITLE = \"3D CONVEX SHELL\"" << endl;
723 *tecplot << "VARIABLES = \"X\" \"Y\" \"Z\"" << endl;
724 *tecplot << "ZONE T=\"TRIANGLES" << N << "\", N="
725 << TesselStruct->PointsOnBoundaryCount << ", E="
726 << TesselStruct->TrianglesOnBoundaryCount
727 << ", DATAPACKING=POINT, ZONETYPE=FETRIANGLE" << endl;
728 int *LookupList = new int[mol->AtomCount];
729 for (int i = 0; i < mol->AtomCount; i++)
730 LookupList[i] = -1;
731
732 // print atom coordinates
733 *out << Verbose(2) << "The following triangles were created:";
734 int Counter = 1;
735 atom *Walker = NULL;
736 for (PointMap::iterator target = TesselStruct->PointsOnBoundary.begin(); target
737 != TesselStruct->PointsOnBoundary.end(); target++)
738 {
739 Walker = target->second->node;
740 LookupList[Walker->nr] = Counter++;
741 *tecplot << Walker->x.x[0] << " " << Walker->x.x[1] << " "
742 << Walker->x.x[2] << " " << endl;
743 }
744 *tecplot << endl;
745 // print connectivity
746 for (TriangleMap::iterator runner =
747 TesselStruct->TrianglesOnBoundary.begin(); runner
748 != TesselStruct->TrianglesOnBoundary.end(); runner++)
749 {
750 *out << " " << runner->second->endpoints[0]->node->Name << "<->"
751 << runner->second->endpoints[1]->node->Name << "<->"
752 << runner->second->endpoints[2]->node->Name;
753 *tecplot << LookupList[runner->second->endpoints[0]->node->nr] << " "
754 << LookupList[runner->second->endpoints[1]->node->nr] << " "
755 << LookupList[runner->second->endpoints[2]->node->nr] << endl;
756 }
757 delete[] (LookupList);
758 *out << endl;
759 }
760}
761
762/** Tesselates the convex boundary by finding all boundary points.
763 * \param *out output stream for debugging
764 * \param *mol molecule structure with Atom's and Bond's
765 * \param *TesselStruct Tesselation filled with points, lines and triangles on boundary on return
766 * \param *LCList atoms in LinkedCell list
767 * \param *filename filename prefix for output of vertex data
768 * \return *TesselStruct is filled with convex boundary and tesselation is stored under \a *filename.
769 */
770void Find_convex_border(ofstream *out, molecule* mol, class Tesselation *&TesselStruct, class LinkedCell *LCList, const char *filename)
771{
772 atom *Walker = NULL;
773 bool BoundaryFreeFlag = false;
774 Boundaries *BoundaryPoints = NULL;
775
776 if (TesselStruct != NULL) // free if allocated
777 delete(TesselStruct);
778 TesselStruct = new class Tesselation;
779
780 // 1. calculate center of gravity
781 *out << endl;
782 Vector *CenterOfGravity = mol->DetermineCenterOfGravity(out);
783
784 // 2. translate all points into CoG
785 *out << Verbose(1) << "Translating system to Center of Gravity." << endl;
786 Walker = mol->start;
787 while (Walker->next != mol->end) {
788 Walker = Walker->next;
789 Walker->x.Translate(CenterOfGravity);
790 }
791
792 // 3. Find all points on the boundary
793 if (BoundaryPoints == NULL) {
794 BoundaryFreeFlag = true;
795 BoundaryPoints = GetBoundaryPoints(out, mol);
796 } else {
797 *out << Verbose(1) << "Using given boundary points set." << endl;
798 }
799
800 // 4. fill the boundary point list
801 for (int axis = 0; axis < NDIM; axis++)
802 for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++)
803 TesselStruct->AddPoint(runner->second.second);
804
805 *out << Verbose(2) << "I found " << TesselStruct->PointsOnBoundaryCount
806 << " points on the convex boundary." << endl;
807 // now we have the whole set of edge points in the BoundaryList
808
809 // listing for debugging
810 // *out << Verbose(1) << "Listing PointsOnBoundary:";
811 // for(PointMap::iterator runner = PointsOnBoundary.begin(); runner != PointsOnBoundary.end(); runner++) {
812 // *out << " " << *runner->second;
813 // }
814 // *out << endl;
815
816 // 5a. guess starting triangle
817 TesselStruct->GuessStartingTriangle(out);
818
819 // 5b. go through all lines, that are not yet part of two triangles (only of one so far)
820 TesselStruct->TesselateOnBoundary(out, mol);
821
822 *out << Verbose(2) << "I created " << TesselStruct->TrianglesOnBoundaryCount
823 << " triangles with " << TesselStruct->LinesOnBoundaryCount
824 << " lines and " << TesselStruct->PointsOnBoundaryCount << " points."
825 << endl;
826
827 // 6. translate all points back from CoG
828 *out << Verbose(1) << "Translating system back from Center of Gravity."
829 << endl;
830 CenterOfGravity->Scale(-1);
831 Walker = mol->start;
832 while (Walker->next != mol->end)
833 {
834 Walker = Walker->next;
835 Walker->x.Translate(CenterOfGravity);
836 }
837
838 // 7. Store triangles in tecplot file
839 if (filename != NULL) {
840 string OutputName(filename);
841 OutputName.append(TecplotSuffix);
842 ofstream *tecplot = new ofstream(OutputName.c_str());
843 write_tecplot_file(out, tecplot, TesselStruct, mol, 0);
844 tecplot->close();
845 delete(tecplot);
846 ofstream *rasterplot = new ofstream(OutputName.c_str());
847 write_raster3d_file(out, rasterplot, TesselStruct, mol);
848 rasterplot->close();
849 delete(rasterplot);
850 }
851
852 // free reference lists
853 if (BoundaryFreeFlag)
854 delete[] (BoundaryPoints);
855
856};
857
858
859/** Determines the volume of a cluster.
860 * Determines first the convex envelope, then tesselates it and calculates its volume.
861 * \param *out output stream for debugging
862 * \param *TesselStruct Tesselation filled with points, lines and triangles on boundary on return
863 * \param *configuration needed for path to store convex envelope file
864 * \return determined volume of the cluster in cubed config:GetIsAngstroem()
865 */
866double
867VolumeOfConvexEnvelope(ofstream *out, class Tesselation *TesselStruct, class config *configuration)
868{
869 bool IsAngstroem = configuration->GetIsAngstroem();
870 double volume = 0.;
871 double PyramidVolume = 0.;
872 double G, h;
873 Vector x, y;
874 double a, b, c;
875
876 // 6a. Every triangle forms a pyramid with the center of gravity as its peak, sum up the volumes
877 *out << Verbose(1)
878 << "Calculating the volume of the pyramids formed out of triangles and center of gravity."
879 << endl;
880 for (TriangleMap::iterator runner = TesselStruct->TrianglesOnBoundary.begin(); runner
881 != TesselStruct->TrianglesOnBoundary.end(); runner++)
882 { // go through every triangle, calculate volume of its pyramid with CoG as peak
883 x.CopyVector(&runner->second->endpoints[0]->node->x);
884 x.SubtractVector(&runner->second->endpoints[1]->node->x);
885 y.CopyVector(&runner->second->endpoints[0]->node->x);
886 y.SubtractVector(&runner->second->endpoints[2]->node->x);
887 a = sqrt(runner->second->endpoints[0]->node->x.DistanceSquared(
888 &runner->second->endpoints[1]->node->x));
889 b = sqrt(runner->second->endpoints[0]->node->x.DistanceSquared(
890 &runner->second->endpoints[2]->node->x));
891 c = sqrt(runner->second->endpoints[2]->node->x.DistanceSquared(
892 &runner->second->endpoints[1]->node->x));
893 G = sqrt(((a + b + c) * (a + b + c) - 2 * (a * a + b * b + c * c)) / 16.); // area of tesselated triangle
894 x.MakeNormalVector(&runner->second->endpoints[0]->node->x,
895 &runner->second->endpoints[1]->node->x,
896 &runner->second->endpoints[2]->node->x);
897 x.Scale(runner->second->endpoints[1]->node->x.Projection(&x));
898 h = x.Norm(); // distance of CoG to triangle
899 PyramidVolume = (1. / 3.) * G * h; // this formula holds for _all_ pyramids (independent of n-edge base or (not) centered peak)
900 *out << Verbose(2) << "Area of triangle is " << G << " "
901 << (IsAngstroem ? "angstrom" : "atomiclength") << "^2, height is "
902 << h << " and the volume is " << PyramidVolume << " "
903 << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
904 volume += PyramidVolume;
905 }
906 *out << Verbose(0) << "RESULT: The summed volume is " << setprecision(10)
907 << volume << " " << (IsAngstroem ? "angstrom" : "atomiclength") << "^3."
908 << endl;
909
910 return volume;
911}
912;
913
914/** Creates multiples of the by \a *mol given cluster and suspends them in water with a given final density.
915 * We get cluster volume by VolumeOfConvexEnvelope() and its diameters by GetDiametersOfCluster()
916 * \param *out output stream for debugging
917 * \param *configuration needed for path to store convex envelope file
918 * \param *mol molecule structure representing the cluster
919 * \param ClusterVolume guesstimated cluster volume, if equal 0 we used VolumeOfConvexEnvelope() instead.
920 * \param celldensity desired average density in final cell
921 */
922void
923PrepareClustersinWater(ofstream *out, config *configuration, molecule *mol,
924 double ClusterVolume, double celldensity)
925{
926 // transform to PAS
927 mol->PrincipalAxisSystem(out, true);
928
929 // some preparations beforehand
930 bool IsAngstroem = configuration->GetIsAngstroem();
931 Boundaries *BoundaryPoints = GetBoundaryPoints(out, mol);
932 class Tesselation *TesselStruct = NULL;
933 LinkedCell LCList(mol, 10.);
934 Find_convex_border(out, mol, TesselStruct, &LCList, NULL);
935 double clustervolume;
936 if (ClusterVolume == 0)
937 clustervolume = VolumeOfConvexEnvelope(out, TesselStruct, configuration);
938 else
939 clustervolume = ClusterVolume;
940 double *GreatestDiameter = GetDiametersOfCluster(out, BoundaryPoints, mol, IsAngstroem);
941 Vector BoxLengths;
942 int repetition[NDIM] =
943 { 1, 1, 1 };
944 int TotalNoClusters = 1;
945 for (int i = 0; i < NDIM; i++)
946 TotalNoClusters *= repetition[i];
947
948 // sum up the atomic masses
949 double totalmass = 0.;
950 atom *Walker = mol->start;
951 while (Walker->next != mol->end)
952 {
953 Walker = Walker->next;
954 totalmass += Walker->type->mass;
955 }
956 *out << Verbose(0) << "RESULT: The summed mass is " << setprecision(10)
957 << totalmass << " atomicmassunit." << endl;
958
959 *out << Verbose(0) << "RESULT: The average density is " << setprecision(10)
960 << totalmass / clustervolume << " atomicmassunit/"
961 << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
962
963 // solve cubic polynomial
964 *out << Verbose(1) << "Solving equidistant suspension in water problem ..."
965 << endl;
966 double cellvolume;
967 if (IsAngstroem)
968 cellvolume = (TotalNoClusters * totalmass / SOLVENTDENSITY_A - (totalmass
969 / clustervolume)) / (celldensity - 1);
970 else
971 cellvolume = (TotalNoClusters * totalmass / SOLVENTDENSITY_a0 - (totalmass
972 / clustervolume)) / (celldensity - 1);
973 *out << Verbose(1) << "Cellvolume needed for a density of " << celldensity
974 << " g/cm^3 is " << cellvolume << " " << (IsAngstroem ? "angstrom"
975 : "atomiclength") << "^3." << endl;
976
977 double minimumvolume = TotalNoClusters * (GreatestDiameter[0]
978 * GreatestDiameter[1] * GreatestDiameter[2]);
979 *out << Verbose(1)
980 << "Minimum volume of the convex envelope contained in a rectangular box is "
981 << minimumvolume << " atomicmassunit/" << (IsAngstroem ? "angstrom"
982 : "atomiclength") << "^3." << endl;
983 if (minimumvolume > cellvolume)
984 {
985 cerr << Verbose(0)
986 << "ERROR: the containing box already has a greater volume than the envisaged cell volume!"
987 << endl;
988 cout << Verbose(0)
989 << "Setting Box dimensions to minimum possible, the greatest diameters."
990 << endl;
991 for (int i = 0; i < NDIM; i++)
992 BoxLengths.x[i] = GreatestDiameter[i];
993 mol->CenterEdge(out, &BoxLengths);
994 }
995 else
996 {
997 BoxLengths.x[0] = (repetition[0] * GreatestDiameter[0] + repetition[1]
998 * GreatestDiameter[1] + repetition[2] * GreatestDiameter[2]);
999 BoxLengths.x[1] = (repetition[0] * repetition[1] * GreatestDiameter[0]
1000 * GreatestDiameter[1] + repetition[0] * repetition[2]
1001 * GreatestDiameter[0] * GreatestDiameter[2] + repetition[1]
1002 * repetition[2] * GreatestDiameter[1] * GreatestDiameter[2]);
1003 BoxLengths.x[2] = minimumvolume - cellvolume;
1004 double x0 = 0., x1 = 0., x2 = 0.;
1005 if (gsl_poly_solve_cubic(BoxLengths.x[0], BoxLengths.x[1],
1006 BoxLengths.x[2], &x0, &x1, &x2) == 1) // either 1 or 3 on return
1007 *out << Verbose(0) << "RESULT: The resulting spacing is: " << x0
1008 << " ." << endl;
1009 else
1010 {
1011 *out << Verbose(0) << "RESULT: The resulting spacings are: " << x0
1012 << " and " << x1 << " and " << x2 << " ." << endl;
1013 x0 = x2; // sorted in ascending order
1014 }
1015
1016 cellvolume = 1;
1017 for (int i = 0; i < NDIM; i++)
1018 {
1019 BoxLengths.x[i] = repetition[i] * (x0 + GreatestDiameter[i]);
1020 cellvolume *= BoxLengths.x[i];
1021 }
1022
1023 // set new box dimensions
1024 *out << Verbose(0) << "Translating to box with these boundaries." << endl;
1025 mol->SetBoxDimension(&BoxLengths);
1026 mol->CenterInBox((ofstream *) &cout);
1027 }
1028 // update Box of atoms by boundary
1029 mol->SetBoxDimension(&BoxLengths);
1030 *out << Verbose(0) << "RESULT: The resulting cell dimensions are: "
1031 << BoxLengths.x[0] << " and " << BoxLengths.x[1] << " and "
1032 << BoxLengths.x[2] << " with total volume of " << cellvolume << " "
1033 << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
1034}
1035;
1036
1037// =========================================================== class TESSELATION ===========================================
1038
1039/** Constructor of class Tesselation.
1040 */
1041Tesselation::Tesselation()
1042{
1043 PointsOnBoundaryCount = 0;
1044 LinesOnBoundaryCount = 0;
1045 TrianglesOnBoundaryCount = 0;
1046 TriangleFilesWritten = 0;
1047}
1048;
1049
1050/** Constructor of class Tesselation.
1051 * We have to free all points, lines and triangles.
1052 */
1053Tesselation::~Tesselation()
1054{
1055 cout << Verbose(1) << "Free'ing TesselStruct ... " << endl;
1056 for (TriangleMap::iterator runner = TrianglesOnBoundary.begin(); runner != TrianglesOnBoundary.end(); runner++) {
1057 if (runner->second != NULL) {
1058 delete (runner->second);
1059 runner->second = NULL;
1060 } else
1061 cerr << "ERROR: The triangle " << runner->first << " has already been free'd." << endl;
1062 }
1063}
1064;
1065
1066/** Gueses first starting triangle of the convex envelope.
1067 * We guess the starting triangle by taking the smallest distance between two points and looking for a fitting third.
1068 * \param *out output stream for debugging
1069 * \param PointsOnBoundary set of boundary points defining the convex envelope of the cluster
1070 */
1071void
1072Tesselation::GuessStartingTriangle(ofstream *out)
1073{
1074 // 4b. create a starting triangle
1075 // 4b1. create all distances
1076 DistanceMultiMap DistanceMMap;
1077 double distance, tmp;
1078 Vector PlaneVector, TrialVector;
1079 PointMap::iterator A, B, C; // three nodes of the first triangle
1080 A = PointsOnBoundary.begin(); // the first may be chosen arbitrarily
1081
1082 // with A chosen, take each pair B,C and sort
1083 if (A != PointsOnBoundary.end())
1084 {
1085 B = A;
1086 B++;
1087 for (; B != PointsOnBoundary.end(); B++)
1088 {
1089 C = B;
1090 C++;
1091 for (; C != PointsOnBoundary.end(); C++)
1092 {
1093 tmp = A->second->node->x.DistanceSquared(&B->second->node->x);
1094 distance = tmp * tmp;
1095 tmp = A->second->node->x.DistanceSquared(&C->second->node->x);
1096 distance += tmp * tmp;
1097 tmp = B->second->node->x.DistanceSquared(&C->second->node->x);
1098 distance += tmp * tmp;
1099 DistanceMMap.insert(DistanceMultiMapPair(distance, pair<
1100 PointMap::iterator, PointMap::iterator> (B, C)));
1101 }
1102 }
1103 }
1104 // // listing distances
1105 // *out << Verbose(1) << "Listing DistanceMMap:";
1106 // for(DistanceMultiMap::iterator runner = DistanceMMap.begin(); runner != DistanceMMap.end(); runner++) {
1107 // *out << " " << runner->first << "(" << *runner->second.first->second << ", " << *runner->second.second->second << ")";
1108 // }
1109 // *out << endl;
1110 // 4b2. pick three baselines forming a triangle
1111 // 1. we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
1112 DistanceMultiMap::iterator baseline = DistanceMMap.begin();
1113 for (; baseline != DistanceMMap.end(); baseline++)
1114 {
1115 // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
1116 // 2. next, we have to check whether all points reside on only one side of the triangle
1117 // 3. construct plane vector
1118 PlaneVector.MakeNormalVector(&A->second->node->x,
1119 &baseline->second.first->second->node->x,
1120 &baseline->second.second->second->node->x);
1121 *out << Verbose(2) << "Plane vector of candidate triangle is ";
1122 PlaneVector.Output(out);
1123 *out << endl;
1124 // 4. loop over all points
1125 double sign = 0.;
1126 PointMap::iterator checker = PointsOnBoundary.begin();
1127 for (; checker != PointsOnBoundary.end(); checker++)
1128 {
1129 // (neglecting A,B,C)
1130 if ((checker == A) || (checker == baseline->second.first) || (checker
1131 == baseline->second.second))
1132 continue;
1133 // 4a. project onto plane vector
1134 TrialVector.CopyVector(&checker->second->node->x);
1135 TrialVector.SubtractVector(&A->second->node->x);
1136 distance = TrialVector.Projection(&PlaneVector);
1137 if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
1138 continue;
1139 *out << Verbose(3) << "Projection of " << checker->second->node->Name
1140 << " yields distance of " << distance << "." << endl;
1141 tmp = distance / fabs(distance);
1142 // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
1143 if ((sign != 0) && (tmp != sign))
1144 {
1145 // 4c. If so, break 4. loop and continue with next candidate in 1. loop
1146 *out << Verbose(2) << "Current candidates: "
1147 << A->second->node->Name << ","
1148 << baseline->second.first->second->node->Name << ","
1149 << baseline->second.second->second->node->Name << " leave "
1150 << checker->second->node->Name << " outside the convex hull."
1151 << endl;
1152 break;
1153 }
1154 else
1155 { // note the sign for later
1156 *out << Verbose(2) << "Current candidates: "
1157 << A->second->node->Name << ","
1158 << baseline->second.first->second->node->Name << ","
1159 << baseline->second.second->second->node->Name << " leave "
1160 << checker->second->node->Name << " inside the convex hull."
1161 << endl;
1162 sign = tmp;
1163 }
1164 // 4d. Check whether the point is inside the triangle (check distance to each node
1165 tmp = checker->second->node->x.DistanceSquared(&A->second->node->x);
1166 int innerpoint = 0;
1167 if ((tmp < A->second->node->x.DistanceSquared(
1168 &baseline->second.first->second->node->x)) && (tmp
1169 < A->second->node->x.DistanceSquared(
1170 &baseline->second.second->second->node->x)))
1171 innerpoint++;
1172 tmp = checker->second->node->x.DistanceSquared(
1173 &baseline->second.first->second->node->x);
1174 if ((tmp < baseline->second.first->second->node->x.DistanceSquared(
1175 &A->second->node->x)) && (tmp
1176 < baseline->second.first->second->node->x.DistanceSquared(
1177 &baseline->second.second->second->node->x)))
1178 innerpoint++;
1179 tmp = checker->second->node->x.DistanceSquared(
1180 &baseline->second.second->second->node->x);
1181 if ((tmp < baseline->second.second->second->node->x.DistanceSquared(
1182 &baseline->second.first->second->node->x)) && (tmp
1183 < baseline->second.second->second->node->x.DistanceSquared(
1184 &A->second->node->x)))
1185 innerpoint++;
1186 // 4e. If so, break 4. loop and continue with next candidate in 1. loop
1187 if (innerpoint == 3)
1188 break;
1189 }
1190 // 5. come this far, all on same side? Then break 1. loop and construct triangle
1191 if (checker == PointsOnBoundary.end())
1192 {
1193 *out << "Looks like we have a candidate!" << endl;
1194 break;
1195 }
1196 }
1197 if (baseline != DistanceMMap.end())
1198 {
1199 BPS[0] = baseline->second.first->second;
1200 BPS[1] = baseline->second.second->second;
1201 BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1202 BPS[0] = A->second;
1203 BPS[1] = baseline->second.second->second;
1204 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1205 BPS[0] = baseline->second.first->second;
1206 BPS[1] = A->second;
1207 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1208
1209 // 4b3. insert created triangle
1210 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1211 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1212 TrianglesOnBoundaryCount++;
1213 for (int i = 0; i < NDIM; i++)
1214 {
1215 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
1216 LinesOnBoundaryCount++;
1217 }
1218
1219 *out << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
1220 }
1221 else
1222 {
1223 *out << Verbose(1) << "No starting triangle found." << endl;
1224 exit(255);
1225 }
1226}
1227;
1228
1229/** Tesselates the convex envelope of a cluster from a single starting triangle.
1230 * The starting triangle is made out of three baselines. Each line in the final tesselated cluster may belong to at most
1231 * 2 triangles. Hence, we go through all current lines:
1232 * -# if the lines contains to only one triangle
1233 * -# We search all points in the boundary
1234 * -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors
1235 * -# if the triangle is in forward direction of the baseline (at most 90 degrees angle between vector orthogonal to
1236 * baseline in triangle plane pointing out of the triangle and normal vector of new triangle)
1237 * -# then we have a new triangle, whose baselines we again add (or increase their TriangleCount)
1238 * \param *out output stream for debugging
1239 * \param *configuration for IsAngstroem
1240 * \param *mol the cluster as a molecule structure
1241 */
1242void
1243Tesselation::TesselateOnBoundary(ofstream *out, molecule *mol)
1244{
1245 bool flag;
1246 PointMap::iterator winner;
1247 class BoundaryPointSet *peak = NULL;
1248 double SmallestAngle, TempAngle;
1249 Vector NormalVector, VirtualNormalVector, CenterVector, TempVector,
1250 PropagationVector;
1251 LineMap::iterator LineChecker[2];
1252 do
1253 {
1254 flag = false;
1255 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline
1256 != LinesOnBoundary.end(); baseline++)
1257 if (baseline->second->TrianglesCount == 1)
1258 {
1259 *out << Verbose(2) << "Current baseline is between "
1260 << *(baseline->second) << "." << endl;
1261 // 5a. go through each boundary point if not _both_ edges between either endpoint of the current line and this point exist (and belong to 2 triangles)
1262 SmallestAngle = M_PI;
1263 BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
1264 // get peak point with respect to this base line's only triangle
1265 for (int i = 0; i < 3; i++)
1266 if ((BTS->endpoints[i] != baseline->second->endpoints[0])
1267 && (BTS->endpoints[i] != baseline->second->endpoints[1]))
1268 peak = BTS->endpoints[i];
1269 *out << Verbose(3) << " and has peak " << *peak << "." << endl;
1270 // normal vector of triangle
1271 BTS->GetNormalVector(NormalVector);
1272 *out << Verbose(4) << "NormalVector of base triangle is ";
1273 NormalVector.Output(out);
1274 *out << endl;
1275 // offset to center of triangle
1276 CenterVector.Zero();
1277 for (int i = 0; i < 3; i++)
1278 CenterVector.AddVector(&BTS->endpoints[i]->node->x);
1279 CenterVector.Scale(1. / 3.);
1280 *out << Verbose(4) << "CenterVector of base triangle is ";
1281 CenterVector.Output(out);
1282 *out << endl;
1283 // vector in propagation direction (out of triangle)
1284 // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
1285 TempVector.CopyVector(&baseline->second->endpoints[0]->node->x);
1286 TempVector.SubtractVector(&baseline->second->endpoints[1]->node->x);
1287 PropagationVector.MakeNormalVector(&TempVector, &NormalVector);
1288 TempVector.CopyVector(&CenterVector);
1289 TempVector.SubtractVector(&baseline->second->endpoints[0]->node->x); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
1290 //*out << Verbose(2) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
1291 if (PropagationVector.Projection(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
1292 PropagationVector.Scale(-1.);
1293 *out << Verbose(4) << "PropagationVector of base triangle is ";
1294 PropagationVector.Output(out);
1295 *out << endl;
1296 winner = PointsOnBoundary.end();
1297 for (PointMap::iterator target = PointsOnBoundary.begin(); target
1298 != PointsOnBoundary.end(); target++)
1299 if ((target->second != baseline->second->endpoints[0])
1300 && (target->second != baseline->second->endpoints[1]))
1301 { // don't take the same endpoints
1302 *out << Verbose(3) << "Target point is " << *(target->second)
1303 << ":";
1304 bool continueflag = true;
1305
1306 VirtualNormalVector.CopyVector(
1307 &baseline->second->endpoints[0]->node->x);
1308 VirtualNormalVector.AddVector(
1309 &baseline->second->endpoints[0]->node->x);
1310 VirtualNormalVector.Scale(-1. / 2.); // points now to center of base line
1311 VirtualNormalVector.AddVector(&target->second->node->x); // points from center of base line to target
1312 TempAngle = VirtualNormalVector.Angle(&PropagationVector);
1313 continueflag = continueflag && (TempAngle < (M_PI/2.)); // no bends bigger than Pi/2 (90 degrees)
1314 if (!continueflag)
1315 {
1316 *out << Verbose(4)
1317 << "Angle between propagation direction and base line to "
1318 << *(target->second) << " is " << TempAngle
1319 << ", bad direction!" << endl;
1320 continue;
1321 }
1322 else
1323 *out << Verbose(4)
1324 << "Angle between propagation direction and base line to "
1325 << *(target->second) << " is " << TempAngle
1326 << ", good direction!" << endl;
1327 LineChecker[0] = baseline->second->endpoints[0]->lines.find(
1328 target->first);
1329 LineChecker[1] = baseline->second->endpoints[1]->lines.find(
1330 target->first);
1331 // if (LineChecker[0] != baseline->second->endpoints[0]->lines.end())
1332 // *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->TrianglesCount << " triangles." << endl;
1333 // else
1334 // *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has no line to " << *(target->second) << " as endpoint." << endl;
1335 // if (LineChecker[1] != baseline->second->endpoints[1]->lines.end())
1336 // *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->TrianglesCount << " triangles." << endl;
1337 // else
1338 // *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has no line to " << *(target->second) << " as endpoint." << endl;
1339 // check first endpoint (if any connecting line goes to target or at least not more than 1)
1340 continueflag = continueflag && (((LineChecker[0]
1341 == baseline->second->endpoints[0]->lines.end())
1342 || (LineChecker[0]->second->TrianglesCount == 1)));
1343 if (!continueflag)
1344 {
1345 *out << Verbose(4) << *(baseline->second->endpoints[0])
1346 << " has line " << *(LineChecker[0]->second)
1347 << " to " << *(target->second)
1348 << " as endpoint with "
1349 << LineChecker[0]->second->TrianglesCount
1350 << " triangles." << endl;
1351 continue;
1352 }
1353 // check second endpoint (if any connecting line goes to target or at least not more than 1)
1354 continueflag = continueflag && (((LineChecker[1]
1355 == baseline->second->endpoints[1]->lines.end())
1356 || (LineChecker[1]->second->TrianglesCount == 1)));
1357 if (!continueflag)
1358 {
1359 *out << Verbose(4) << *(baseline->second->endpoints[1])
1360 << " has line " << *(LineChecker[1]->second)
1361 << " to " << *(target->second)
1362 << " as endpoint with "
1363 << LineChecker[1]->second->TrianglesCount
1364 << " triangles." << endl;
1365 continue;
1366 }
1367 // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
1368 continueflag = continueflag && (!(((LineChecker[0]
1369 != baseline->second->endpoints[0]->lines.end())
1370 && (LineChecker[1]
1371 != baseline->second->endpoints[1]->lines.end())
1372 && (GetCommonEndpoint(LineChecker[0]->second,
1373 LineChecker[1]->second) == peak))));
1374 if (!continueflag)
1375 {
1376 *out << Verbose(4) << "Current target is peak!" << endl;
1377 continue;
1378 }
1379 // in case NOT both were found
1380 if (continueflag)
1381 { // create virtually this triangle, get its normal vector, calculate angle
1382 flag = true;
1383 VirtualNormalVector.MakeNormalVector(
1384 &baseline->second->endpoints[0]->node->x,
1385 &baseline->second->endpoints[1]->node->x,
1386 &target->second->node->x);
1387 // make it always point inward
1388 if (baseline->second->endpoints[0]->node->x.Projection(
1389 &VirtualNormalVector) > 0)
1390 VirtualNormalVector.Scale(-1.);
1391 // calculate angle
1392 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1393 *out << Verbose(4) << "NormalVector is ";
1394 VirtualNormalVector.Output(out);
1395 *out << " and the angle is " << TempAngle << "." << endl;
1396 if (SmallestAngle > TempAngle)
1397 { // set to new possible winner
1398 SmallestAngle = TempAngle;
1399 winner = target;
1400 }
1401 }
1402 }
1403 // 5b. The point of the above whose triangle has the greatest angle with the triangle the current line belongs to (it only belongs to one, remember!): New triangle
1404 if (winner != PointsOnBoundary.end())
1405 {
1406 *out << Verbose(2) << "Winning target point is "
1407 << *(winner->second) << " with angle " << SmallestAngle
1408 << "." << endl;
1409 // create the lins of not yet present
1410 BLS[0] = baseline->second;
1411 // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
1412 LineChecker[0] = baseline->second->endpoints[0]->lines.find(
1413 winner->first);
1414 LineChecker[1] = baseline->second->endpoints[1]->lines.find(
1415 winner->first);
1416 if (LineChecker[0]
1417 == baseline->second->endpoints[0]->lines.end())
1418 { // create
1419 BPS[0] = baseline->second->endpoints[0];
1420 BPS[1] = winner->second;
1421 BLS[1] = new class BoundaryLineSet(BPS,
1422 LinesOnBoundaryCount);
1423 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount,
1424 BLS[1]));
1425 LinesOnBoundaryCount++;
1426 }
1427 else
1428 BLS[1] = LineChecker[0]->second;
1429 if (LineChecker[1]
1430 == baseline->second->endpoints[1]->lines.end())
1431 { // create
1432 BPS[0] = baseline->second->endpoints[1];
1433 BPS[1] = winner->second;
1434 BLS[2] = new class BoundaryLineSet(BPS,
1435 LinesOnBoundaryCount);
1436 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount,
1437 BLS[2]));
1438 LinesOnBoundaryCount++;
1439 }
1440 else
1441 BLS[2] = LineChecker[1]->second;
1442 BTS = new class BoundaryTriangleSet(BLS,
1443 TrianglesOnBoundaryCount);
1444 TrianglesOnBoundary.insert(TrianglePair(
1445 TrianglesOnBoundaryCount, BTS));
1446 TrianglesOnBoundaryCount++;
1447 }
1448 else
1449 {
1450 *out << Verbose(1)
1451 << "I could not determine a winner for this baseline "
1452 << *(baseline->second) << "." << endl;
1453 }
1454
1455 // 5d. If the set of lines is not yet empty, go to 5. and continue
1456 }
1457 else
1458 *out << Verbose(2) << "Baseline candidate " << *(baseline->second)
1459 << " has a triangle count of "
1460 << baseline->second->TrianglesCount << "." << endl;
1461 }
1462 while (flag);
1463
1464}
1465;
1466
1467/** Adds an atom to the tesselation::PointsOnBoundary list.
1468 * \param *Walker atom to add
1469 */
1470void
1471Tesselation::AddPoint(atom *Walker)
1472{
1473 PointTestPair InsertUnique;
1474 BPS[0] = new class BoundaryPointSet(Walker);
1475 InsertUnique = PointsOnBoundary.insert(PointPair(Walker->nr, BPS[0]));
1476 if (InsertUnique.second) // if new point was not present before, increase counter
1477 PointsOnBoundaryCount++;
1478}
1479;
1480
1481/** Adds point to Tesselation::PointsOnBoundary if not yet present.
1482 * Tesselation::TPS is set to either this new BoundaryPointSet or to the existing one of not unique.
1483 * @param Candidate point to add
1484 * @param n index for this point in Tesselation::TPS array
1485 */
1486void
1487Tesselation::AddTrianglePoint(atom* Candidate, int n)
1488{
1489 PointTestPair InsertUnique;
1490 TPS[n] = new class BoundaryPointSet(Candidate);
1491 InsertUnique = PointsOnBoundary.insert(PointPair(Candidate->nr, TPS[n]));
1492 if (InsertUnique.second) { // if new point was not present before, increase counter
1493 PointsOnBoundaryCount++;
1494 } else {
1495 delete TPS[n];
1496 cout << Verbose(3) << "Atom " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl;
1497 TPS[n] = (InsertUnique.first)->second;
1498 }
1499}
1500;
1501
1502/** Function tries to add line from current Points in BPS to BoundaryLineSet.
1503 * If successful it raises the line count and inserts the new line into the BLS,
1504 * if unsuccessful, it writes the line which had been present into the BLS, deleting the new constructed one.
1505 * @param *a first endpoint
1506 * @param *b second endpoint
1507 * @param n index of Tesselation::BLS giving the line with both endpoints
1508 */
1509void Tesselation::AddTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n) {
1510 bool insertNewLine = true;
1511
1512 if (a->lines.find(b->node->nr) != a->lines.end()) {
1513 LineMap::iterator FindLine;
1514 pair<LineMap::iterator,LineMap::iterator> FindPair;
1515 FindPair = a->lines.equal_range(b->node->nr);
1516
1517 for (FindLine = FindPair.first; FindLine != FindPair.second; ++FindLine) {
1518 // If there is a line with less than two attached triangles, we don't need a new line.
1519 if (FindLine->second->TrianglesCount < 2) {
1520 insertNewLine = false;
1521 cout << Verbose(3) << "Using existing line " << *FindLine->second << endl;
1522
1523 BPS[0] = FindLine->second->endpoints[0];
1524 BPS[1] = FindLine->second->endpoints[1];
1525 BLS[n] = FindLine->second;
1526
1527 break;
1528 }
1529 }
1530 }
1531
1532 if (insertNewLine) {
1533 AlwaysAddTriangleLine(a, b, n);
1534 }
1535}
1536;
1537
1538/**
1539 * Adds lines from each of the current points in the BPS to BoundaryLineSet.
1540 * Raises the line count and inserts the new line into the BLS.
1541 *
1542 * @param *a first endpoint
1543 * @param *b second endpoint
1544 * @param n index of Tesselation::BLS giving the line with both endpoints
1545 */
1546void Tesselation::AlwaysAddTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n)
1547{
1548 cout << Verbose(3) << "Adding line between " << *(a->node) << " and " << *(b->node) << "." << endl;
1549 BPS[0] = a;
1550 BPS[1] = b;
1551 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
1552 // add line to global map
1553 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1554 // increase counter
1555 LinesOnBoundaryCount++;
1556};
1557
1558/** Function tries to add Triangle just created to Triangle and remarks if already existent (Failure of algorithm).
1559 * Furthermore it adds the triangle to all of its lines, in order to recognize those which are saturated later.
1560 */
1561void
1562Tesselation::AddTriangle()
1563{
1564 cout << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1565
1566 // add triangle to global map
1567 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1568 TrianglesOnBoundaryCount++;
1569
1570 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1571}
1572;
1573
1574
1575double det_get(gsl_matrix *A, int inPlace) {
1576 /*
1577 inPlace = 1 => A is replaced with the LU decomposed copy.
1578 inPlace = 0 => A is retained, and a copy is used for LU.
1579 */
1580
1581 double det;
1582 int signum;
1583 gsl_permutation *p = gsl_permutation_alloc(A->size1);
1584 gsl_matrix *tmpA;
1585
1586 if (inPlace)
1587 tmpA = A;
1588 else {
1589 gsl_matrix *tmpA = gsl_matrix_alloc(A->size1, A->size2);
1590 gsl_matrix_memcpy(tmpA , A);
1591 }
1592
1593
1594 gsl_linalg_LU_decomp(tmpA , p , &signum);
1595 det = gsl_linalg_LU_det(tmpA , signum);
1596 gsl_permutation_free(p);
1597 if (! inPlace)
1598 gsl_matrix_free(tmpA);
1599
1600 return det;
1601};
1602
1603void get_sphere(Vector *center, Vector &a, Vector &b, Vector &c, double RADIUS)
1604{
1605 gsl_matrix *A = gsl_matrix_calloc(3,3);
1606 double m11, m12, m13, m14;
1607
1608 for(int i=0;i<3;i++) {
1609 gsl_matrix_set(A, i, 0, a.x[i]);
1610 gsl_matrix_set(A, i, 1, b.x[i]);
1611 gsl_matrix_set(A, i, 2, c.x[i]);
1612 }
1613 m11 = det_get(A, 1);
1614
1615 for(int i=0;i<3;i++) {
1616 gsl_matrix_set(A, i, 0, a.x[i]*a.x[i] + b.x[i]*b.x[i] + c.x[i]*c.x[i]);
1617 gsl_matrix_set(A, i, 1, b.x[i]);
1618 gsl_matrix_set(A, i, 2, c.x[i]);
1619 }
1620 m12 = det_get(A, 1);
1621
1622 for(int i=0;i<3;i++) {
1623 gsl_matrix_set(A, i, 0, a.x[i]*a.x[i] + b.x[i]*b.x[i] + c.x[i]*c.x[i]);
1624 gsl_matrix_set(A, i, 1, a.x[i]);
1625 gsl_matrix_set(A, i, 2, c.x[i]);
1626 }
1627 m13 = det_get(A, 1);
1628
1629 for(int i=0;i<3;i++) {
1630 gsl_matrix_set(A, i, 0, a.x[i]*a.x[i] + b.x[i]*b.x[i] + c.x[i]*c.x[i]);
1631 gsl_matrix_set(A, i, 1, a.x[i]);
1632 gsl_matrix_set(A, i, 2, b.x[i]);
1633 }
1634 m14 = det_get(A, 1);
1635
1636 if (fabs(m11) < MYEPSILON)
1637 cerr << "ERROR: three points are colinear." << endl;
1638
1639 center->x[0] = 0.5 * m12/ m11;
1640 center->x[1] = -0.5 * m13/ m11;
1641 center->x[2] = 0.5 * m14/ m11;
1642
1643 if (fabs(a.Distance(center) - RADIUS) > MYEPSILON)
1644 cerr << "ERROR: The given center is further way by " << fabs(a.Distance(center) - RADIUS) << " from a than RADIUS." << endl;
1645
1646 gsl_matrix_free(A);
1647};
1648
1649
1650
1651/**
1652 * Function returns center of sphere with RADIUS, which rests on points a, b, c
1653 * @param Center this vector will be used for return
1654 * @param a vector first point of triangle
1655 * @param b vector second point of triangle
1656 * @param c vector third point of triangle
1657 * @param *Umkreismittelpunkt new cneter point of circumference
1658 * @param Direction vector indicates up/down
1659 * @param AlternativeDirection vecotr, needed in case the triangles have 90 deg angle
1660 * @param Halfplaneindicator double indicates whether Direction is up or down
1661 * @param AlternativeIndicator doube indicates in case of orthogonal triangles which direction of AlternativeDirection is suitable
1662 * @param alpha double angle at a
1663 * @param beta double, angle at b
1664 * @param gamma, double, angle at c
1665 * @param Radius, double
1666 * @param Umkreisradius double radius of circumscribing circle
1667 */
1668void Get_center_of_sphere(Vector* Center, Vector a, Vector b, Vector c, Vector *NewUmkreismittelpunkt, Vector* Direction, Vector* AlternativeDirection,
1669 double HalfplaneIndicator, double AlternativeIndicator, double alpha, double beta, double gamma, double RADIUS, double Umkreisradius)
1670{
1671 Vector TempNormal, helper;
1672 double Restradius;
1673 Vector OtherCenter;
1674 cout << Verbose(3) << "Begin of Get_center_of_sphere.\n";
1675 Center->Zero();
1676 helper.CopyVector(&a);
1677 helper.Scale(sin(2.*alpha));
1678 Center->AddVector(&helper);
1679 helper.CopyVector(&b);
1680 helper.Scale(sin(2.*beta));
1681 Center->AddVector(&helper);
1682 helper.CopyVector(&c);
1683 helper.Scale(sin(2.*gamma));
1684 Center->AddVector(&helper);
1685 //*Center = a * sin(2.*alpha) + b * sin(2.*beta) + c * sin(2.*gamma) ;
1686 Center->Scale(1./(sin(2.*alpha) + sin(2.*beta) + sin(2.*gamma)));
1687 NewUmkreismittelpunkt->CopyVector(Center);
1688 cout << Verbose(4) << "Center of new circumference is " << *NewUmkreismittelpunkt << ".\n";
1689 // Here we calculated center of circumscribing circle, using barycentric coordinates
1690 cout << Verbose(4) << "Center of circumference is " << *Center << " in direction " << *Direction << ".\n";
1691
1692 TempNormal.CopyVector(&a);
1693 TempNormal.SubtractVector(&b);
1694 helper.CopyVector(&a);
1695 helper.SubtractVector(&c);
1696 TempNormal.VectorProduct(&helper);
1697 if (fabs(HalfplaneIndicator) < MYEPSILON)
1698 {
1699 if ((TempNormal.ScalarProduct(AlternativeDirection) <0 and AlternativeIndicator >0) or (TempNormal.ScalarProduct(AlternativeDirection) >0 and AlternativeIndicator <0))
1700 {
1701 TempNormal.Scale(-1);
1702 }
1703 }
1704 else
1705 {
1706 if (TempNormal.ScalarProduct(Direction)<0 && HalfplaneIndicator >0 || TempNormal.ScalarProduct(Direction)>0 && HalfplaneIndicator<0)
1707 {
1708 TempNormal.Scale(-1);
1709 }
1710 }
1711
1712 TempNormal.Normalize();
1713 Restradius = sqrt(RADIUS*RADIUS - Umkreisradius*Umkreisradius);
1714 cout << Verbose(4) << "Height of center of circumference to center of sphere is " << Restradius << ".\n";
1715 TempNormal.Scale(Restradius);
1716 cout << Verbose(4) << "Shift vector to sphere of circumference is " << TempNormal << ".\n";
1717
1718 Center->AddVector(&TempNormal);
1719 cout << Verbose(0) << "Center of sphere of circumference is " << *Center << ".\n";
1720 get_sphere(&OtherCenter, a, b, c, RADIUS);
1721 cout << Verbose(0) << "OtherCenter of sphere of circumference is " << OtherCenter << ".\n";
1722 cout << Verbose(3) << "End of Get_center_of_sphere.\n";
1723};
1724
1725
1726/** Constructs the center of the circumcircle defined by three points \a *a, \a *b and \a *c.
1727 * \param *Center new center on return
1728 * \param *a first point
1729 * \param *b second point
1730 * \param *c third point
1731 */
1732void GetCenterofCircumcircle(Vector *Center, Vector *a, Vector *b, Vector *c)
1733{
1734 Vector helper;
1735 double alpha, beta, gamma;
1736 Vector SideA, SideB, SideC;
1737 SideA.CopyVector(b);
1738 SideA.SubtractVector(c);
1739 SideB.CopyVector(c);
1740 SideB.SubtractVector(a);
1741 SideC.CopyVector(a);
1742 SideC.SubtractVector(b);
1743 alpha = M_PI - SideB.Angle(&SideC);
1744 beta = M_PI - SideC.Angle(&SideA);
1745 gamma = M_PI - SideA.Angle(&SideB);
1746 //cout << Verbose(3) << "INFO: alpha = " << alpha/M_PI*180. << ", beta = " << beta/M_PI*180. << ", gamma = " << gamma/M_PI*180. << "." << endl;
1747 if (fabs(M_PI - alpha - beta - gamma) > HULLEPSILON)
1748 cerr << "GetCenterofCircumcircle: Sum of angles " << (alpha+beta+gamma)/M_PI*180. << " > 180 degrees by " << fabs(M_PI - alpha - beta - gamma)/M_PI*180. << "!" << endl;
1749
1750 Center->Zero();
1751 helper.CopyVector(a);
1752 helper.Scale(sin(2.*alpha));
1753 Center->AddVector(&helper);
1754 helper.CopyVector(b);
1755 helper.Scale(sin(2.*beta));
1756 Center->AddVector(&helper);
1757 helper.CopyVector(c);
1758 helper.Scale(sin(2.*gamma));
1759 Center->AddVector(&helper);
1760 Center->Scale(1./(sin(2.*alpha) + sin(2.*beta) + sin(2.*gamma)));
1761};
1762
1763/** 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.
1764 * Test whether the \a NewSphereCenter is really on the given plane and in distance \a CircleRadius from \a CircleCenter.
1765 * It calculates the angle, making it unique on [0,2.*M_PI) by comparing to SearchDirection.
1766 * 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).
1767 * \param CircleCenter Center of the parameter circle
1768 * \param CirclePlaneNormal normal vector to plane of the parameter circle
1769 * \param CircleRadius radius of the parameter circle
1770 * \param NewSphereCenter new center of a circumcircle
1771 * \param OldSphereCenter old center of a circumcircle, defining the zero "path length" on the parameter circle
1772 * \param NormalVector normal vector
1773 * \param SearchDirection search direction to make angle unique on return.
1774 * \return Angle between \a NewSphereCenter and \a OldSphereCenter relative to \a CircleCenter, 2.*M_PI if one test fails
1775 */
1776double GetPathLengthonCircumCircle(Vector &CircleCenter, Vector &CirclePlaneNormal, double CircleRadius, Vector &NewSphereCenter, Vector &OldSphereCenter, Vector &NormalVector, Vector &SearchDirection)
1777{
1778 Vector helper;
1779 double radius, alpha;
1780
1781 helper.CopyVector(&NewSphereCenter);
1782 // test whether new center is on the parameter circle's plane
1783 if (fabs(helper.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
1784 cerr << "ERROR: Something's very wrong here: NewSphereCenter is not on the band's plane as desired by " <<fabs(helper.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
1785 helper.ProjectOntoPlane(&CirclePlaneNormal);
1786 }
1787 radius = helper.ScalarProduct(&helper);
1788 // test whether the new center vector has length of CircleRadius
1789 if (fabs(radius - CircleRadius) > HULLEPSILON)
1790 cerr << Verbose(1) << "ERROR: The projected center of the new sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
1791 alpha = helper.Angle(&OldSphereCenter);
1792 // make the angle unique by checking the halfplanes/search direction
1793 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON) // acos is not unique on [0, 2.*M_PI), hence extra check to decide between two half intervals
1794 alpha = 2.*M_PI - alpha;
1795 //cout << Verbose(2) << "INFO: RelativeNewSphereCenter is " << helper << ", RelativeOldSphereCenter is " << OldSphereCenter << " and resulting angle is " << alpha << "." << endl;
1796 radius = helper.Distance(&OldSphereCenter);
1797 helper.ProjectOntoPlane(&NormalVector);
1798 // check whether new center is somewhat away or at least right over the current baseline to prevent intersecting triangles
1799 if ((radius > HULLEPSILON) || (helper.Norm() < HULLEPSILON)) {
1800 //cout << Verbose(2) << "INFO: Distance between old and new center is " << radius << " and between new center and baseline center is " << helper.Norm() << "." << endl;
1801 return alpha;
1802 } else {
1803 //cout << Verbose(1) << "INFO: NewSphereCenter " << helper << " is too close to OldSphereCenter" << OldSphereCenter << "." << endl;
1804 return 2.*M_PI;
1805 }
1806};
1807
1808
1809/** Checks whether the triangle consisting of the three atoms is already present.
1810 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1811 * lines. If any of the three edges already has two triangles attached, false is
1812 * returned.
1813 * \param *out output stream for debugging
1814 * \param *Candidates endpoints of the triangle candidate
1815 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
1816 * triangles exist which is the maximum for three points
1817 */
1818int Tesselation::CheckPresenceOfTriangle(ofstream *out, atom *Candidates[3]) {
1819 LineMap::iterator FindLine;
1820 PointMap::iterator FindPoint;
1821 TriangleMap::iterator FindTriangle;
1822 int adjacentTriangleCount = 0;
1823 class BoundaryPointSet *Points[3];
1824
1825 //*out << Verbose(2) << "Begin of CheckPresenceOfTriangle" << endl;
1826 // builds a triangle point set (Points) of the end points
1827 for (int i = 0; i < 3; i++) {
1828 FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1829 if (FindPoint != PointsOnBoundary.end()) {
1830 Points[i] = FindPoint->second;
1831 } else {
1832 Points[i] = NULL;
1833 }
1834 }
1835
1836 // checks lines between the points in the Points for their adjacent triangles
1837 for (int i = 0; i < 3; i++) {
1838 if (Points[i] != NULL) {
1839 for (int j = i; j < 3; j++) {
1840 if (Points[j] != NULL) {
1841 FindLine = Points[i]->lines.find(Points[j]->node->nr);
1842 if (FindLine != Points[i]->lines.end()) {
1843 for (; FindLine->first == Points[j]->node->nr; FindLine++) {
1844 FindTriangle = FindLine->second->triangles.begin();
1845 for (; FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
1846 if ((
1847 (FindTriangle->second->endpoints[0] == Points[0])
1848 || (FindTriangle->second->endpoints[0] == Points[1])
1849 || (FindTriangle->second->endpoints[0] == Points[2])
1850 ) && (
1851 (FindTriangle->second->endpoints[1] == Points[0])
1852 || (FindTriangle->second->endpoints[1] == Points[1])
1853 || (FindTriangle->second->endpoints[1] == Points[2])
1854 ) && (
1855 (FindTriangle->second->endpoints[2] == Points[0])
1856 || (FindTriangle->second->endpoints[2] == Points[1])
1857 || (FindTriangle->second->endpoints[2] == Points[2])
1858 )
1859 ) {
1860 adjacentTriangleCount++;
1861 }
1862 }
1863 }
1864 // Only one of the triangle lines must be considered for the triangle count.
1865 *out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1866 return adjacentTriangleCount;
1867
1868 }
1869 }
1870 }
1871 }
1872 }
1873
1874 *out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1875 return adjacentTriangleCount;
1876};
1877
1878/** This recursive function finds a third point, to form a triangle with two given ones.
1879 * Note that this function is for the starting triangle.
1880 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
1881 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
1882 * the center of the sphere is still fixed up to a single parameter. The band of possible values
1883 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
1884 * us the "null" on this circle, the new center of the candidate point will be some way along this
1885 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
1886 * by the normal vector of the base triangle that always points outwards by construction.
1887 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
1888 * We construct the normal vector that defines the plane this circle lies in, it is just in the
1889 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
1890 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
1891 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
1892 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
1893 * both.
1894 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
1895 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
1896 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
1897 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
1898 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
1899 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
1900 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa Find_starting_triangle())
1901 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
1902 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
1903 * @param BaseLine BoundaryLineSet with the current base line
1904 * @param ThirdNode third atom to avoid in search
1905 * @param candidates list of equally good candidates to return
1906 * @param ShortestAngle the current path length on this circle band for the current Opt_Candidate
1907 * @param RADIUS radius of sphere
1908 * @param *LC LinkedCell structure with neighbouring atoms
1909 */
1910void Find_third_point_for_Tesselation(
1911 Vector NormalVector, Vector SearchDirection, Vector OldSphereCenter,
1912 class BoundaryLineSet *BaseLine, atom *ThirdNode, CandidateList* &candidates,
1913 double *ShortestAngle, const double RADIUS, LinkedCell *LC
1914) {
1915 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
1916 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
1917 Vector SphereCenter;
1918 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
1919 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
1920 Vector NewNormalVector; // normal vector of the Candidate's triangle
1921 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
1922 LinkedAtoms *List = NULL;
1923 double CircleRadius; // radius of this circle
1924 double radius;
1925 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
1926 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
1927 atom *Candidate = NULL;
1928 CandidateForTesselation *optCandidate = NULL;
1929
1930 cout << Verbose(1) << "Begin of Find_third_point_for_Tesselation" << endl;
1931
1932 //cout << Verbose(2) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
1933
1934 // construct center of circle
1935 CircleCenter.CopyVector(&(BaseLine->endpoints[0]->node->x));
1936 CircleCenter.AddVector(&BaseLine->endpoints[1]->node->x);
1937 CircleCenter.Scale(0.5);
1938
1939 // construct normal vector of circle
1940 CirclePlaneNormal.CopyVector(&BaseLine->endpoints[0]->node->x);
1941 CirclePlaneNormal.SubtractVector(&BaseLine->endpoints[1]->node->x);
1942
1943 // calculate squared radius atom *ThirdNode,f circle
1944 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
1945 if (radius/4. < RADIUS*RADIUS) {
1946 CircleRadius = RADIUS*RADIUS - radius/4.;
1947 CirclePlaneNormal.Normalize();
1948 //cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
1949
1950 // test whether old center is on the band's plane
1951 if (fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
1952 cerr << "ERROR: Something's very wrong here: OldSphereCenter is not on the band's plane as desired by " << fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
1953 OldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
1954 }
1955 radius = OldSphereCenter.ScalarProduct(&OldSphereCenter);
1956 if (fabs(radius - CircleRadius) < HULLEPSILON) {
1957
1958 // check SearchDirection
1959 //cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
1960 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
1961 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
1962 }
1963
1964 // get cell for the starting atom
1965 if (LC->SetIndexToVector(&CircleCenter)) {
1966 for(int i=0;i<NDIM;i++) // store indices of this cell
1967 N[i] = LC->n[i];
1968 //cout << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
1969 } else {
1970 cerr << "ERROR: Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
1971 return;
1972 }
1973 // then go through the current and all neighbouring cells and check the contained atoms for possible candidates
1974 //cout << Verbose(2) << "LC Intervals:";
1975 for (int i=0;i<NDIM;i++) {
1976 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
1977 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
1978 //cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
1979 }
1980 //cout << endl;
1981 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
1982 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
1983 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
1984 List = LC->GetCurrentCell();
1985 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1986 if (List != NULL) {
1987 for (LinkedAtoms::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
1988 Candidate = (*Runner);
1989
1990 // check for three unique points
1991 //cout << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " at " << Candidate->x << "." << endl;
1992 if ((Candidate != BaseLine->endpoints[0]->node) && (Candidate != BaseLine->endpoints[1]->node) ){
1993
1994 // construct both new centers
1995 GetCenterofCircumcircle(&NewSphereCenter, &(BaseLine->endpoints[0]->node->x), &(BaseLine->endpoints[1]->node->x), &(Candidate->x));
1996 OtherNewSphereCenter.CopyVector(&NewSphereCenter);
1997
1998 if ((NewNormalVector.MakeNormalVector(&(BaseLine->endpoints[0]->node->x), &(BaseLine->endpoints[1]->node->x), &(Candidate->x)))
1999 && (fabs(NewNormalVector.ScalarProduct(&NewNormalVector)) > HULLEPSILON)
2000 ) {
2001 helper.CopyVector(&NewNormalVector);
2002 //cout << Verbose(2) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
2003 radius = BaseLine->endpoints[0]->node->x.DistanceSquared(&NewSphereCenter);
2004 if (radius < RADIUS*RADIUS) {
2005 helper.Scale(sqrt(RADIUS*RADIUS - radius));
2006 //cout << Verbose(2) << "INFO: Distance of NewCircleCenter to NewSphereCenter is " << helper.Norm() << " with sphere radius " << RADIUS << "." << endl;
2007 NewSphereCenter.AddVector(&helper);
2008 NewSphereCenter.SubtractVector(&CircleCenter);
2009 //cout << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
2010
2011 // OtherNewSphereCenter is created by the same vector just in the other direction
2012 helper.Scale(-1.);
2013 OtherNewSphereCenter.AddVector(&helper);
2014 OtherNewSphereCenter.SubtractVector(&CircleCenter);
2015 //cout << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
2016
2017 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2018 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2019 alpha = min(alpha, Otheralpha);
2020 // if there is a better candidate, drop the current list and add the new candidate
2021 // otherwise ignore the new candidate and keep the list
2022 if (*ShortestAngle > (alpha - HULLEPSILON)) {
2023 optCandidate = new CandidateForTesselation(Candidate, BaseLine, OptCandidateCenter, OtherOptCandidateCenter);
2024 if (fabs(alpha - Otheralpha) > MYEPSILON) {
2025 optCandidate->OptCenter.CopyVector(&NewSphereCenter);
2026 optCandidate->OtherOptCenter.CopyVector(&OtherNewSphereCenter);
2027 } else {
2028 optCandidate->OptCenter.CopyVector(&OtherNewSphereCenter);
2029 optCandidate->OtherOptCenter.CopyVector(&NewSphereCenter);
2030 }
2031 // if there is an equal candidate, add it to the list without clearing the list
2032 if ((*ShortestAngle - HULLEPSILON) < alpha) {
2033 candidates->push_back(optCandidate);
2034 cout << Verbose(2) << "ACCEPT: We have found an equally good candidate: " << *(optCandidate->point) << " with "
2035 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2036 } else {
2037 // remove all candidates from the list and then the list itself
2038 class CandidateForTesselation *remover = NULL;
2039 for (CandidateList::iterator it = candidates->begin(); it != candidates->end(); ++it) {
2040 remover = *it;
2041 delete(remover);
2042 }
2043 candidates->clear();
2044 candidates->push_back(optCandidate);
2045 cout << Verbose(2) << "ACCEPT: We have found a better candidate: " << *(optCandidate->point) << " with "
2046 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2047 }
2048 *ShortestAngle = alpha;
2049 //cout << Verbose(2) << "INFO: There are " << candidates->size() << " candidates in the list now." << endl;
2050 } else {
2051 if ((optCandidate != NULL) && (optCandidate->point != NULL)) {
2052 //cout << Verbose(2) << "REJECT: Old candidate: " << *(optCandidate->point) << " is better than " << alpha << " with " << *ShortestAngle << "." << endl;
2053 } else {
2054 //cout << Verbose(2) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
2055 }
2056 }
2057
2058 } else {
2059 //cout << Verbose(2) << "REJECT: NewSphereCenter " << NewSphereCenter << " is too far away: " << radius << "." << endl;
2060 }
2061 } else {
2062 //cout << Verbose(2) << "REJECT: Three points from " << *BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
2063 }
2064 } else {
2065 if (ThirdNode != NULL) {
2066 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
2067 } else {
2068 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " contains Candidate " << *Candidate << "." << endl;
2069 }
2070 }
2071 }
2072 }
2073 }
2074 } else {
2075 cerr << Verbose(2) << "ERROR: The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
2076 }
2077 } else {
2078 if (ThirdNode != NULL)
2079 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
2080 else
2081 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " is too big!" << endl;
2082 }
2083
2084 //cout << Verbose(2) << "INFO: Sorting candidate list ..." << endl;
2085 if (candidates->size() > 1) {
2086 candidates->unique();
2087 candidates->sort(sortCandidates);
2088 }
2089
2090 cout << Verbose(1) << "End of Find_third_point_for_Tesselation" << endl;
2091};
2092
2093struct Intersection {
2094 Vector x1;
2095 Vector x2;
2096 Vector x3;
2097 Vector x4;
2098};
2099
2100/**
2101 * Intersection calculation function.
2102 *
2103 * @param x to find the result for
2104 * @param function parameter
2105 */
2106double MinIntersectDistance(const gsl_vector * x, void *params) {
2107 double retval = 0;
2108 struct Intersection *I = (struct Intersection *)params;
2109 Vector intersection;
2110 Vector SideA,SideB,HeightA, HeightB;
2111 for (int i=0;i<NDIM;i++)
2112 intersection.x[i] = gsl_vector_get(x, i);
2113
2114 SideA.CopyVector(&(I->x1));
2115 SideA.SubtractVector(&I->x2);
2116 HeightA.CopyVector(&intersection);
2117 HeightA.SubtractVector(&I->x1);
2118 HeightA.ProjectOntoPlane(&SideA);
2119
2120 SideB.CopyVector(&I->x3);
2121 SideB.SubtractVector(&I->x4);
2122 HeightB.CopyVector(&intersection);
2123 HeightB.SubtractVector(&I->x3);
2124 HeightB.ProjectOntoPlane(&SideB);
2125
2126 retval = HeightA.ScalarProduct(&HeightA) + HeightB.ScalarProduct(&HeightB);
2127 //cout << Verbose(2) << "MinIntersectDistance called, result: " << retval << endl;
2128
2129 return retval;
2130};
2131
2132
2133/**
2134 * Calculates whether there is an intersection between two lines. The first line
2135 * always goes through point 1 and point 2 and the second line is given by the
2136 * connection between point 4 and point 5.
2137 *
2138 * @param point 1 of line 1
2139 * @param point 2 of line 1
2140 * @param point 1 of line 2
2141 * @param point 2 of line 2
2142 *
2143 * @return true if there is an intersection between the given lines, false otherwise
2144 */
2145bool existsIntersection(Vector point1, Vector point2, Vector point3, Vector point4) {
2146 bool result;
2147
2148 struct Intersection par;
2149 par.x1.CopyVector(&point1);
2150 par.x2.CopyVector(&point2);
2151 par.x3.CopyVector(&point3);
2152 par.x4.CopyVector(&point4);
2153
2154 const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
2155 gsl_multimin_fminimizer *s = NULL;
2156 gsl_vector *ss, *x;
2157 gsl_multimin_function minex_func;
2158
2159 size_t iter = 0;
2160 int status;
2161 double size;
2162
2163 /* Starting point */
2164 x = gsl_vector_alloc(NDIM);
2165 gsl_vector_set(x, 0, point1.x[0]);
2166 gsl_vector_set(x, 1, point1.x[1]);
2167 gsl_vector_set(x, 2, point1.x[2]);
2168
2169 /* Set initial step sizes to 1 */
2170 ss = gsl_vector_alloc(NDIM);
2171 gsl_vector_set_all(ss, 1.0);
2172
2173 /* Initialize method and iterate */
2174 minex_func.n = NDIM;
2175 minex_func.f = &MinIntersectDistance;
2176 minex_func.params = (void *)&par;
2177
2178 s = gsl_multimin_fminimizer_alloc(T, NDIM);
2179 gsl_multimin_fminimizer_set(s, &minex_func, x, ss);
2180
2181 do {
2182 iter++;
2183 status = gsl_multimin_fminimizer_iterate(s);
2184
2185 if (status) {
2186 break;
2187 }
2188
2189 size = gsl_multimin_fminimizer_size(s);
2190 status = gsl_multimin_test_size(size, 1e-2);
2191
2192 if (status == GSL_SUCCESS) {
2193 cout << Verbose(2) << "converged to minimum" << endl;
2194 }
2195 } while (status == GSL_CONTINUE && iter < 100);
2196
2197 // check whether intersection is in between or not
2198 Vector intersection, SideA, SideB, HeightA, HeightB;
2199 double t1, t2;
2200 for (int i = 0; i < NDIM; i++) {
2201 intersection.x[i] = gsl_vector_get(s->x, i);
2202 }
2203
2204 SideA.CopyVector(&par.x2);
2205 SideA.SubtractVector(&par.x1);
2206 HeightA.CopyVector(&intersection);
2207 HeightA.SubtractVector(&par.x1);
2208
2209 t1 = HeightA.Projection(&SideA)/SideA.ScalarProduct(&SideA);
2210
2211 SideB.CopyVector(&par.x4);
2212 SideB.SubtractVector(&par.x3);
2213 HeightB.CopyVector(&intersection);
2214 HeightB.SubtractVector(&par.x3);
2215
2216 t2 = HeightB.Projection(&SideB)/SideB.ScalarProduct(&SideB);
2217
2218 cout << Verbose(2) << "Intersection " << intersection << " is at "
2219 << t1 << " for (" << point1 << "," << point2 << ") and at "
2220 << t2 << " for (" << point3 << "," << point4 << "): ";
2221
2222 if (((t1 >= 0) && (t1 <= 1)) && ((t2 >= 0) && (t2 <= 1))) {
2223 cout << "true intersection." << endl;
2224 result = true;
2225 } else {
2226 cout << "intersection out of region of interest." << endl;
2227 result = false;
2228 }
2229
2230 // free minimizer stuff
2231 gsl_vector_free(x);
2232 gsl_vector_free(ss);
2233 gsl_multimin_fminimizer_free(s);
2234
2235 return result;
2236}
2237
2238/** Finds the second point of starting triangle.
2239 * \param *a first atom
2240 * \param *Candidate pointer to candidate atom on return
2241 * \param Oben vector indicating the outside
2242 * \param Opt_Candidate reference to recommended candidate on return
2243 * \param Storage[3] array storing angles and other candidate information
2244 * \param RADIUS radius of virtual sphere
2245 * \param *LC LinkedCell structure with neighbouring atoms
2246 */
2247void Find_second_point_for_Tesselation(atom* a, atom* Candidate, Vector Oben, atom*& Opt_Candidate, double Storage[3], double RADIUS, LinkedCell *LC)
2248{
2249 cout << Verbose(2) << "Begin of Find_second_point_for_Tesselation" << endl;
2250 Vector AngleCheck;
2251 double norm = -1., angle;
2252 LinkedAtoms *List = NULL;
2253 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2254
2255 if (LC->SetIndexToAtom(a)) { // get cell for the starting atom
2256 for(int i=0;i<NDIM;i++) // store indices of this cell
2257 N[i] = LC->n[i];
2258 } else {
2259 cerr << "ERROR: Atom " << *a << " is not found in cell " << LC->index << "." << endl;
2260 return;
2261 }
2262 // then go through the current and all neighbouring cells and check the contained atoms for possible candidates
2263 cout << Verbose(3) << "LC Intervals from [";
2264 for (int i=0;i<NDIM;i++) {
2265 cout << " " << N[i] << "<->" << LC->N[i];
2266 }
2267 cout << "] :";
2268 for (int i=0;i<NDIM;i++) {
2269 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2270 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2271 cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2272 }
2273 cout << endl;
2274
2275
2276 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2277 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2278 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2279 List = LC->GetCurrentCell();
2280 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2281 if (List != NULL) {
2282 for (LinkedAtoms::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2283 Candidate = (*Runner);
2284 // check if we only have one unique point yet ...
2285 if (a != Candidate) {
2286 // Calculate center of the circle with radius RADIUS through points a and Candidate
2287 Vector OrthogonalizedOben, a_Candidate, Center;
2288 double distance, scaleFactor;
2289
2290 OrthogonalizedOben.CopyVector(&Oben);
2291 a_Candidate.CopyVector(&(a->x));
2292 a_Candidate.SubtractVector(&(Candidate->x));
2293 OrthogonalizedOben.ProjectOntoPlane(&a_Candidate);
2294 OrthogonalizedOben.Normalize();
2295 distance = 0.5 * a_Candidate.Norm();
2296 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
2297 OrthogonalizedOben.Scale(scaleFactor);
2298
2299 Center.CopyVector(&(Candidate->x));
2300 Center.AddVector(&(a->x));
2301 Center.Scale(0.5);
2302 Center.AddVector(&OrthogonalizedOben);
2303
2304 AngleCheck.CopyVector(&Center);
2305 AngleCheck.SubtractVector(&(a->x));
2306 norm = a_Candidate.Norm();
2307 // second point shall have smallest angle with respect to Oben vector
2308 if (norm < RADIUS*2.) {
2309 angle = AngleCheck.Angle(&Oben);
2310 if (angle < Storage[0]) {
2311 //cout << Verbose(3) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
2312 cout << Verbose(3) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
2313 Opt_Candidate = Candidate;
2314 Storage[0] = angle;
2315 //cout << Verbose(3) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
2316 } else {
2317 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *Opt_Candidate << endl;
2318 }
2319 } else {
2320 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
2321 }
2322 } else {
2323 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
2324 }
2325 }
2326 } else {
2327 cout << Verbose(3) << "Linked cell list is empty." << endl;
2328 }
2329 }
2330 cout << Verbose(2) << "End of Find_second_point_for_Tesselation" << endl;
2331};
2332
2333/** Finds the starting triangle for find_non_convex_border().
2334 * Looks at the outermost atom per axis, then Find_second_point_for_Tesselation()
2335 * for the second and Find_next_suitable_point_via_Angle_of_Sphere() for the third
2336 * point are called.
2337 * \param RADIUS radius of virtual rolling sphere
2338 * \param *LC LinkedCell structure with neighbouring atoms
2339 */
2340void Tesselation::Find_starting_triangle(ofstream *out, molecule *mol, const double RADIUS, LinkedCell *LC)
2341{
2342 cout << Verbose(1) << "Begin of Find_starting_triangle\n";
2343 int i = 0;
2344 LinkedAtoms *List = NULL;
2345 atom* FirstPoint = NULL;
2346 atom* SecondPoint = NULL;
2347 atom* MaxAtom[NDIM];
2348 double max_coordinate[NDIM];
2349 Vector Oben;
2350 Vector helper;
2351 Vector Chord;
2352 Vector SearchDirection;
2353
2354 Oben.Zero();
2355
2356 for (i = 0; i < 3; i++) {
2357 MaxAtom[i] = NULL;
2358 max_coordinate[i] = -1;
2359 }
2360
2361 // 1. searching topmost atom with respect to each axis
2362 for (int i=0;i<NDIM;i++) { // each axis
2363 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
2364 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
2365 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
2366 List = LC->GetCurrentCell();
2367 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2368 if (List != NULL) {
2369 for (LinkedAtoms::iterator Runner = List->begin();Runner != List->end();Runner++) {
2370 if ((*Runner)->x.x[i] > max_coordinate[i]) {
2371 cout << Verbose(2) << "New maximal for axis " << i << " atom is " << *(*Runner) << " at " << (*Runner)->x << "." << endl;
2372 max_coordinate[i] = (*Runner)->x.x[i];
2373 MaxAtom[i] = (*Runner);
2374 }
2375 }
2376 } else {
2377 cerr << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
2378 }
2379 }
2380 }
2381
2382 cout << Verbose(2) << "Found maximum coordinates: ";
2383 for (int i=0;i<NDIM;i++)
2384 cout << i << ": " << *MaxAtom[i] << "\t";
2385 cout << endl;
2386
2387 BTS = NULL;
2388 CandidateList *Opt_Candidates = new CandidateList();
2389 for (int k=0;k<NDIM;k++) {
2390 Oben.x[k] = 1.;
2391 FirstPoint = MaxAtom[k];
2392 cout << Verbose(1) << "Coordinates of start atom " << *FirstPoint << " at " << FirstPoint->x << "." << endl;
2393
2394 double ShortestAngle;
2395 atom* Opt_Candidate = NULL;
2396 ShortestAngle = 999999.; // This will contain the angle, which will be always positive (when looking for second point), when looking for third point this will be the quadrant.
2397
2398 Find_second_point_for_Tesselation(FirstPoint, NULL, Oben, Opt_Candidate, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
2399 SecondPoint = Opt_Candidate;
2400 if (SecondPoint == NULL) // have we found a second point?
2401 continue;
2402 else
2403 cout << Verbose(1) << "Found second point is " << *SecondPoint << " at " << SecondPoint->x << ".\n";
2404
2405 helper.CopyVector(&(FirstPoint->x));
2406 helper.SubtractVector(&(SecondPoint->x));
2407 helper.Normalize();
2408 Oben.ProjectOntoPlane(&helper);
2409 Oben.Normalize();
2410 helper.VectorProduct(&Oben);
2411 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
2412
2413 Chord.CopyVector(&(FirstPoint->x)); // bring into calling function
2414 Chord.SubtractVector(&(SecondPoint->x));
2415 double radius = Chord.ScalarProduct(&Chord);
2416 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
2417 helper.CopyVector(&Oben);
2418 helper.Scale(CircleRadius);
2419 // Now, oben and helper are two orthonormalized vectors in the plane defined by Chord (not normalized)
2420
2421 // look in one direction of baseline for initial candidate
2422 SearchDirection.MakeNormalVector(&Chord, &Oben); // whether we look "left" first or "right" first is not important ...
2423
2424 // adding point 1 and point 2 and the line between them
2425 AddTrianglePoint(FirstPoint, 0);
2426 AddTrianglePoint(SecondPoint, 1);
2427 AddTriangleLine(TPS[0], TPS[1], 0);
2428
2429 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << helper << ".\n";
2430 Find_third_point_for_Tesselation(
2431 Oben, SearchDirection, helper, BLS[0], NULL, *&Opt_Candidates, &ShortestAngle, RADIUS, LC
2432 );
2433 cout << Verbose(1) << "List of third Points is ";
2434 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
2435 cout << " " << *(*it)->point;
2436 }
2437 cout << endl;
2438
2439 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
2440 // add third triangle point
2441 AddTrianglePoint((*it)->point, 2);
2442 // add the second and third line
2443 AddTriangleLine(TPS[1], TPS[2], 1);
2444 AddTriangleLine(TPS[0], TPS[2], 2);
2445 // ... and triangles to the Maps of the Tesselation class
2446 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2447 AddTriangle();
2448 // ... and calculate its normal vector (with correct orientation)
2449 (*it)->OptCenter.Scale(-1.);
2450 cout << Verbose(2) << "Anti-Oben is currently " << (*it)->OptCenter << "." << endl;
2451 BTS->GetNormalVector((*it)->OptCenter); // vector to compare with should point inwards
2452 cout << Verbose(0) << "==> Found starting triangle consists of " << *FirstPoint << ", " << *SecondPoint << " and "
2453 << *(*it)->point << " with normal vector " << BTS->NormalVector << ".\n";
2454
2455 // if we do not reach the end with the next step of iteration, we need to setup a new first line
2456 if (it != Opt_Candidates->end()--) {
2457 FirstPoint = (*it)->BaseLine->endpoints[0]->node;
2458 SecondPoint = (*it)->point;
2459 // adding point 1 and point 2 and the line between them
2460 AddTrianglePoint(FirstPoint, 0);
2461 AddTrianglePoint(SecondPoint, 1);
2462 AddTriangleLine(TPS[0], TPS[1], 0);
2463 }
2464 cout << Verbose(2) << "Projection is " << BTS->NormalVector.Projection(&Oben) << "." << endl;
2465 }
2466 if (BTS != NULL) // we have created one starting triangle
2467 break;
2468 else {
2469 // remove all candidates from the list and then the list itself
2470 class CandidateForTesselation *remover = NULL;
2471 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
2472 remover = *it;
2473 delete(remover);
2474 }
2475 Opt_Candidates->clear();
2476 }
2477 }
2478
2479 // remove all candidates from the list and then the list itself
2480 class CandidateForTesselation *remover = NULL;
2481 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
2482 remover = *it;
2483 delete(remover);
2484 }
2485 delete(Opt_Candidates);
2486 cout << Verbose(1) << "End of Find_starting_triangle\n";
2487};
2488
2489/** Checks for a new special triangle whether one of its edges is already present with one one triangle connected.
2490 * This enforces that special triangles (i.e. degenerated ones) should at last close the open-edge frontier and not
2491 * make it bigger (i.e. closing one (the baseline) and opening two new ones).
2492 * \param TPS[3] nodes of the triangle
2493 * \return true - there is such a line (i.e. creation of degenerated triangle is valid), false - no such line (don't create)
2494 */
2495bool CheckLineCriteriaforDegeneratedTriangle(class BoundaryPointSet *nodes[3])
2496{
2497 bool result = false;
2498 int counter = 0;
2499
2500 // check all three points
2501 for (int i=0;i<3;i++)
2502 for (int j=i+1; j<3; j++) {
2503 if (nodes[i]->lines.find(nodes[j]->node->nr) != nodes[i]->lines.end()) { // there already is a line
2504 LineMap::iterator FindLine;
2505 pair<LineMap::iterator,LineMap::iterator> FindPair;
2506 FindPair = nodes[i]->lines.equal_range(nodes[j]->node->nr);
2507 for (FindLine = FindPair.first; FindLine != FindPair.second; ++FindLine) {
2508 // If there is a line with less than two attached triangles, we don't need a new line.
2509 if (FindLine->second->TrianglesCount < 2) {
2510 counter++;
2511 break; // increase counter only once per edge
2512 }
2513 }
2514 } else { // no line
2515 cout << Verbose(1) << "ERROR: The line between " << nodes[i] << " and " << nodes[j] << " is not yet present, hence no need for a degenerate triangle!" << endl;
2516 result = true;
2517 }
2518 }
2519 if (counter > 1) {
2520 cout << Verbose(2) << "INFO: Degenerate triangle is ok, at least two, here " << counter << ", existing lines are used." << endl;
2521 result = true;
2522 }
2523 return result;
2524};
2525
2526
2527/** This function finds a triangle to a line, adjacent to an existing one.
2528 * @param out output stream for debugging
2529 * @param *mol molecule with Atom's and Bond's
2530 * @param Line current baseline to search from
2531 * @param T current triangle which \a Line is edge of
2532 * @param RADIUS radius of the rolling ball
2533 * @param N number of found triangles
2534 * @param *filename filename base for intermediate envelopes
2535 * @param *LC LinkedCell structure with neighbouring atoms
2536 */
2537bool Tesselation::Find_next_suitable_triangle(ofstream *out,
2538 molecule *mol, BoundaryLineSet &Line, BoundaryTriangleSet &T,
2539 const double& RADIUS, int N, const char *tempbasename, LinkedCell *LC)
2540{
2541 cout << Verbose(0) << "Begin of Find_next_suitable_triangle\n";
2542 ofstream *tempstream = NULL;
2543 char NumberName[255];
2544 bool result = true;
2545 CandidateList *Opt_Candidates = new CandidateList();
2546
2547 Vector CircleCenter;
2548 Vector CirclePlaneNormal;
2549 Vector OldSphereCenter;
2550 Vector SearchDirection;
2551 Vector helper;
2552 atom *ThirdNode = NULL;
2553 LineMap::iterator testline;
2554 double ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
2555 double radius, CircleRadius;
2556
2557 cout << Verbose(1) << "Current baseline is " << Line << " of triangle " << T << "." << endl;
2558 for (int i=0;i<3;i++)
2559 if ((T.endpoints[i]->node != Line.endpoints[0]->node) && (T.endpoints[i]->node != Line.endpoints[1]->node))
2560 ThirdNode = T.endpoints[i]->node;
2561
2562 // construct center of circle
2563 CircleCenter.CopyVector(&Line.endpoints[0]->node->x);
2564 CircleCenter.AddVector(&Line.endpoints[1]->node->x);
2565 CircleCenter.Scale(0.5);
2566
2567 // construct normal vector of circle
2568 CirclePlaneNormal.CopyVector(&Line.endpoints[0]->node->x);
2569 CirclePlaneNormal.SubtractVector(&Line.endpoints[1]->node->x);
2570
2571 // calculate squared radius of circle
2572 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2573 if (radius/4. < RADIUS*RADIUS) {
2574 CircleRadius = RADIUS*RADIUS - radius/4.;
2575 CirclePlaneNormal.Normalize();
2576 cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2577
2578 // construct old center
2579 GetCenterofCircumcircle(&OldSphereCenter, &(T.endpoints[0]->node->x), &(T.endpoints[1]->node->x), &(T.endpoints[2]->node->x));
2580 helper.CopyVector(&T.NormalVector); // normal vector ensures that this is correct center of the two possible ones
2581 radius = Line.endpoints[0]->node->x.DistanceSquared(&OldSphereCenter);
2582 helper.Scale(sqrt(RADIUS*RADIUS - radius));
2583 OldSphereCenter.AddVector(&helper);
2584 OldSphereCenter.SubtractVector(&CircleCenter);
2585 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
2586
2587 // construct SearchDirection
2588 SearchDirection.MakeNormalVector(&T.NormalVector, &CirclePlaneNormal);
2589 helper.CopyVector(&Line.endpoints[0]->node->x);
2590 helper.SubtractVector(&ThirdNode->x);
2591 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
2592 SearchDirection.Scale(-1.);
2593 SearchDirection.ProjectOntoPlane(&OldSphereCenter);
2594 SearchDirection.Normalize();
2595 cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2596 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
2597 // rotated the wrong way!
2598 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
2599 }
2600
2601 // add third point
2602 Find_third_point_for_Tesselation(
2603 T.NormalVector, SearchDirection, OldSphereCenter, &Line, ThirdNode, Opt_Candidates,
2604 &ShortestAngle, RADIUS, LC
2605 );
2606
2607 } else {
2608 cout << Verbose(1) << "Circumcircle for base line " << Line << " and base triangle " << T << " is too big!" << endl;
2609 }
2610
2611 if (Opt_Candidates->begin() == Opt_Candidates->end()) {
2612 cerr << "WARNING: Could not find a suitable candidate." << endl;
2613 return false;
2614 }
2615 cout << Verbose(1) << "Third Points are ";
2616 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
2617 cout << " " << *(*it)->point;
2618 }
2619 cout << endl;
2620
2621 BoundaryLineSet *BaseRay = &Line;
2622 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
2623 cout << Verbose(1) << " Third point candidate is " << *(*it)->point
2624 << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
2625 cout << Verbose(1) << " Baseline is " << *BaseRay << endl;
2626
2627 // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
2628 atom *AtomCandidates[3];
2629 AtomCandidates[0] = (*it)->point;
2630 AtomCandidates[1] = BaseRay->endpoints[0]->node;
2631 AtomCandidates[2] = BaseRay->endpoints[1]->node;
2632 int existentTrianglesCount = CheckPresenceOfTriangle(out, AtomCandidates);
2633
2634 BTS = NULL;
2635 // If there is no triangle, add it regularly.
2636 if (existentTrianglesCount == 0) {
2637 AddTrianglePoint((*it)->point, 0);
2638 AddTrianglePoint(BaseRay->endpoints[0]->node, 1);
2639 AddTrianglePoint(BaseRay->endpoints[1]->node, 2);
2640
2641 AddTriangleLine(TPS[0], TPS[1], 0);
2642 AddTriangleLine(TPS[0], TPS[2], 1);
2643 AddTriangleLine(TPS[1], TPS[2], 2);
2644
2645 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2646 AddTriangle();
2647 (*it)->OptCenter.Scale(-1.);
2648 BTS->GetNormalVector((*it)->OptCenter);
2649 (*it)->OptCenter.Scale(-1.);
2650
2651 cout << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector
2652 << " for this triangle ... " << endl;
2653 //cout << Verbose(1) << "We have "<< TrianglesOnBoundaryCount << " for line " << *BaseRay << "." << endl;
2654 } else if (existentTrianglesCount == 1) { // If there is a planar region within the structure, we need this triangle a second time.
2655 AddTrianglePoint((*it)->point, 0);
2656 AddTrianglePoint(BaseRay->endpoints[0]->node, 1);
2657 AddTrianglePoint(BaseRay->endpoints[1]->node, 2);
2658
2659 // We demand that at most one new degenerate line is created and that this line also already exists (which has to be the case due to existentTrianglesCount == 1)
2660 // i.e. at least one of the three lines must be present with TriangleCount <= 1
2661 if (CheckLineCriteriaforDegeneratedTriangle(TPS)) {
2662 AddTriangleLine(TPS[0], TPS[1], 0);
2663 AddTriangleLine(TPS[0], TPS[2], 1);
2664 AddTriangleLine(TPS[1], TPS[2], 2);
2665
2666 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2667 AddTriangle();
2668
2669 (*it)->OtherOptCenter.Scale(-1.);
2670 BTS->GetNormalVector((*it)->OtherOptCenter);
2671 (*it)->OtherOptCenter.Scale(-1.);
2672
2673 cout << "--> WARNING: Special new triangle with " << *BTS << " and normal vector " << BTS->NormalVector
2674 << " for this triangle ... " << endl;
2675 cout << Verbose(1) << "We have "<< BaseRay->TrianglesCount << " for line " << BaseRay << "." << endl;
2676 } else {
2677 cout << Verbose(1) << "WARNING: This triangle consisting of ";
2678 cout << *(*it)->point << ", ";
2679 cout << *BaseRay->endpoints[0]->node << " and ";
2680 cout << *BaseRay->endpoints[1]->node << " ";
2681 cout << "exists and is not added, as it does not seem helpful!" << endl;
2682 result = false;
2683 }
2684 } else {
2685 cout << Verbose(1) << "This triangle consisting of ";
2686 cout << *(*it)->point << ", ";
2687 cout << *BaseRay->endpoints[0]->node << " and ";
2688 cout << *BaseRay->endpoints[1]->node << " ";
2689 cout << "is invalid!" << endl;
2690 result = false;
2691 }
2692
2693 if ((result) && (existentTrianglesCount < 2) && (DoSingleStepOutput && (TrianglesOnBoundaryCount % 1 == 0))) { // if we have a new triangle and want to output each new triangle configuration
2694 sprintf(NumberName, "-%04d-%s_%s_%s", TriangleFilesWritten, BTS->endpoints[0]->node->Name, BTS->endpoints[1]->node->Name, BTS->endpoints[2]->node->Name);
2695 if (DoTecplotOutput) {
2696 string NameofTempFile(tempbasename);
2697 NameofTempFile.append(NumberName);
2698 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
2699 NameofTempFile.erase(npos, 1);
2700 NameofTempFile.append(TecplotSuffix);
2701 cout << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
2702 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
2703 write_tecplot_file(out, tempstream, this, mol, TriangleFilesWritten);
2704 tempstream->close();
2705 tempstream->flush();
2706 delete(tempstream);
2707 }
2708
2709 if (DoRaster3DOutput) {
2710 string NameofTempFile(tempbasename);
2711 NameofTempFile.append(NumberName);
2712 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
2713 NameofTempFile.erase(npos, 1);
2714 NameofTempFile.append(Raster3DSuffix);
2715 cout << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
2716 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
2717 write_raster3d_file(out, tempstream, this, mol);
2718 // include the current position of the virtual sphere in the temporary raster3d file
2719 // make the circumsphere's center absolute again
2720 helper.CopyVector(&BaseRay->endpoints[0]->node->x);
2721 helper.AddVector(&BaseRay->endpoints[1]->node->x);
2722 helper.Scale(0.5);
2723 (*it)->OptCenter.AddVector(&helper);
2724 Vector *center = mol->DetermineCenterOfAll(out);
2725 (*it)->OptCenter.AddVector(center);
2726 delete(center);
2727 // and add to file plus translucency object
2728 *tempstream << "# current virtual sphere\n";
2729 *tempstream << "8\n 25.0 0.6 -1.0 -1.0 -1.0 0.2 0 0 0 0\n";
2730 *tempstream << "2\n " << (*it)->OptCenter.x[0] << " "
2731 << (*it)->OptCenter.x[1] << " " << (*it)->OptCenter.x[2]
2732 << "\t" << RADIUS << "\t1 0 0\n";
2733 *tempstream << "9\n terminating special property\n";
2734 tempstream->close();
2735 tempstream->flush();
2736 delete(tempstream);
2737 }
2738 if (DoTecplotOutput || DoRaster3DOutput)
2739 TriangleFilesWritten++;
2740 }
2741
2742 // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
2743 BaseRay = BLS[0];
2744 }
2745
2746 // remove all candidates from the list and then the list itself
2747 class CandidateForTesselation *remover = NULL;
2748 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
2749 remover = *it;
2750 delete(remover);
2751 }
2752 delete(Opt_Candidates);
2753 cout << Verbose(0) << "End of Find_next_suitable_triangle\n";
2754 return result;
2755};
2756
2757/**
2758 * Sort function for the candidate list.
2759 */
2760bool sortCandidates(CandidateForTesselation* candidate1, CandidateForTesselation* candidate2) {
2761 Vector BaseLineVector, OrthogonalVector, helper;
2762 if (candidate1->BaseLine != candidate2->BaseLine) { // sanity check
2763 cout << Verbose(0) << "ERROR: sortCandidates was called for two different baselines: " << candidate1->BaseLine << " and " << candidate2->BaseLine << "." << endl;
2764 //return false;
2765 exit(1);
2766 }
2767 // create baseline vector
2768 BaseLineVector.CopyVector(&(candidate1->BaseLine->endpoints[1]->node->x));
2769 BaseLineVector.SubtractVector(&(candidate1->BaseLine->endpoints[0]->node->x));
2770 BaseLineVector.Normalize();
2771
2772 // 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!)
2773 helper.CopyVector(&(candidate1->BaseLine->endpoints[0]->node->x));
2774 helper.SubtractVector(&(candidate1->point->x));
2775 OrthogonalVector.CopyVector(&helper);
2776 helper.VectorProduct(&BaseLineVector);
2777 OrthogonalVector.SubtractVector(&helper);
2778 OrthogonalVector.Normalize();
2779
2780 // calculate both angles and correct with in-plane vector
2781 helper.CopyVector(&(candidate1->point->x));
2782 helper.SubtractVector(&(candidate1->BaseLine->endpoints[0]->node->x));
2783 double phi = BaseLineVector.Angle(&helper);
2784 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
2785 phi = 2.*M_PI - phi;
2786 }
2787 helper.CopyVector(&(candidate2->point->x));
2788 helper.SubtractVector(&(candidate1->BaseLine->endpoints[0]->node->x));
2789 double psi = BaseLineVector.Angle(&helper);
2790 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
2791 psi = 2.*M_PI - psi;
2792 }
2793
2794 cout << Verbose(2) << *candidate1->point << " has angle " << phi << endl;
2795 cout << Verbose(2) << *candidate2->point << " has angle " << psi << endl;
2796
2797 // return comparison
2798 return phi < psi;
2799}
2800
2801/** Tesselates the non convex boundary by rolling a virtual sphere along the surface of the molecule.
2802 * \param *out output stream for debugging
2803 * \param *mol molecule structure with Atom's and Bond's
2804 * \param *Tess Tesselation filled with points, lines and triangles on boundary on return
2805 * \param *LCList atoms in LinkedCell list
2806 * \param *filename filename prefix for output of vertex data
2807 * \para RADIUS radius of the virtual sphere
2808 */
2809void Find_non_convex_border(ofstream *out, molecule* mol, class Tesselation *Tess, class LinkedCell *LCList, const char *filename, const double RADIUS)
2810{
2811 int N = 0;
2812 bool freeTess = false;
2813 bool freeLC = false;
2814 *out << Verbose(1) << "Entering search for non convex hull. " << endl;
2815 if (Tess == NULL) {
2816 *out << Verbose(1) << "Allocating Tesselation struct ..." << endl;
2817 Tess = new Tesselation;
2818 freeTess = true;
2819 }
2820 LineMap::iterator baseline;
2821 LineMap::iterator testline;
2822 *out << Verbose(0) << "Begin of Find_non_convex_border\n";
2823 bool flag = false; // marks whether we went once through all baselines without finding any without two triangles
2824 bool failflag = false;
2825
2826 if (LCList == NULL) {
2827 LCList = new LinkedCell(mol, 2.*RADIUS);
2828 freeLC = true;
2829 }
2830
2831 Tess->Find_starting_triangle(out, mol, RADIUS, LCList);
2832
2833 baseline = Tess->LinesOnBoundary.begin();
2834 while ((baseline != Tess->LinesOnBoundary.end()) || (flag)) {
2835 if (baseline->second->TrianglesCount == 1) {
2836 failflag = Tess->Find_next_suitable_triangle(out, mol, *(baseline->second), *(((baseline->second->triangles.begin()))->second), RADIUS, N, filename, LCList); //the line is there, so there is a triangle, but only one.
2837 flag = flag || failflag;
2838 if (!failflag)
2839 cerr << "WARNING: Find_next_suitable_triangle failed." << endl;
2840 } else {
2841 //cout << Verbose(1) << "Line " << *baseline->second << " has " << baseline->second->TrianglesCount << " triangles adjacent" << endl;
2842 if (baseline->second->TrianglesCount != 2)
2843 cout << Verbose(1) << "ERROR: TESSELATION FINISHED WITH INVALID TRIANGLE COUNT!" << endl;
2844 }
2845
2846 N++;
2847 baseline++;
2848 if ((baseline == Tess->LinesOnBoundary.end()) && (flag)) {
2849 baseline = Tess->LinesOnBoundary.begin(); // restart if we reach end due to newly inserted lines
2850 flag = false;
2851 }
2852 }
2853 if (1) { //failflag) {
2854 *out << Verbose(1) << "Writing final tecplot file\n";
2855 if (DoTecplotOutput) {
2856 string OutputName(filename);
2857 OutputName.append(TecplotSuffix);
2858 ofstream *tecplot = new ofstream(OutputName.c_str());
2859 write_tecplot_file(out, tecplot, Tess, mol, -1);
2860 tecplot->close();
2861 delete(tecplot);
2862 }
2863 if (DoRaster3DOutput) {
2864 string OutputName(filename);
2865 OutputName.append(Raster3DSuffix);
2866 ofstream *raster = new ofstream(OutputName.c_str());
2867 write_raster3d_file(out, raster, Tess, mol);
2868 raster->close();
2869 delete(raster);
2870 }
2871 } else {
2872 cerr << "ERROR: Could definitively not find all necessary triangles!" << endl;
2873 }
2874
2875 cout << Verbose(2) << "Check: List of Baselines with not two connected triangles:" << endl;
2876 int counter = 0;
2877 for (testline = Tess->LinesOnBoundary.begin(); testline != Tess->LinesOnBoundary.end(); testline++) {
2878 if (testline->second->TrianglesCount != 2) {
2879 cout << Verbose(2) << *testline->second << "\t" << testline->second->TrianglesCount << endl;
2880 counter++;
2881 }
2882 }
2883 if (counter == 0)
2884 cout << Verbose(2) << "None." << endl;
2885
2886 if (freeTess)
2887 delete(Tess);
2888 if (freeLC)
2889 delete(LCList);
2890 *out << Verbose(0) << "End of Find_non_convex_border\n";
2891};
2892
2893/** Finds a hole of sufficient size in \a this molecule to embed \a *srcmol into it.
2894 * \param *out output stream for debugging
2895 * \param *srcmol molecule to embed into
2896 * \return *Vector new center of \a *srcmol for embedding relative to \a this
2897 */
2898Vector* molecule::FindEmbeddingHole(ofstream *out, molecule *srcmol)
2899{
2900 Vector *Center = new Vector;
2901 Center->Zero();
2902 // calculate volume/shape of \a *srcmol
2903
2904 // find embedding holes
2905
2906 // if more than one, let user choose
2907
2908 // return embedding center
2909 return Center;
2910};
2911
Note: See TracBrowser for help on using the repository browser.