source: src/boundary.cpp@ 86234b

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

BUGFIX: Memory leak due to special triangles and similar lines in BoundaryPointSet::lines multimap, corrected some output messages, AddTriangleToLines()->AddTriangle()

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