source: src/boundary.cpp@ 70c333f

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

fixed compiler warning by changing int to size_t because C++ STL set.size() returns size_t.

  • Property mode set to 100755
File size: 123.1 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/** Constructs the center of the circumcircle defined by three points \a *a, \a *b and \a *c.
1713 * \param *Center new center on return
1714 * \param *a first point
1715 * \param *b second point
1716 * \param *c third point
1717 */
1718void GetCenterofCircumcircle(Vector *Center, Vector *a, Vector *b, Vector *c)
1719{
1720 Vector helper;
1721 double alpha, beta, gamma;
1722 Vector SideA, SideB, SideC;
1723 SideA.CopyVector(b);
1724 SideA.SubtractVector(c);
1725 SideB.CopyVector(c);
1726 SideB.SubtractVector(a);
1727 SideC.CopyVector(a);
1728 SideC.SubtractVector(b);
1729 alpha = M_PI - SideB.Angle(&SideC);
1730 beta = M_PI - SideC.Angle(&SideA);
1731 gamma = M_PI - SideA.Angle(&SideB);
1732 cout << Verbose(3) << "INFO: alpha = " << alpha/M_PI*180. << ", beta = " << beta/M_PI*180. << ", gamma = " << gamma/M_PI*180. << "." << endl;
1733 if (fabs(M_PI - alpha - beta - gamma) > HULLEPSILON)
1734 cerr << "Sum of angles " << (alpha+beta+gamma)/M_PI*180. << " > 180 degrees by " << fabs(M_PI - alpha - beta - gamma)/M_PI*180. << "!" << endl;
1735
1736 Center->Zero();
1737 helper.CopyVector(a);
1738 helper.Scale(sin(2.*alpha));
1739 Center->AddVector(&helper);
1740 helper.CopyVector(b);
1741 helper.Scale(sin(2.*beta));
1742 Center->AddVector(&helper);
1743 helper.CopyVector(c);
1744 helper.Scale(sin(2.*gamma));
1745 Center->AddVector(&helper);
1746 Center->Scale(1./(sin(2.*alpha) + sin(2.*beta) + sin(2.*gamma)));
1747};
1748
1749/** 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.
1750 * Test whether the \a NewSphereCenter is really on the given plane and in distance \a CircleRadius from \a CircleCenter.
1751 * It calculates the angle, making it unique on [0,2.*M_PI) by comparing to SearchDirection.
1752 * 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).
1753 * \param CircleCenter Center of the parameter circle
1754 * \param CirclePlaneNormal normal vector to plane of the parameter circle
1755 * \param CircleRadius radius of the parameter circle
1756 * \param NewSphereCenter new center of a circumcircle
1757 * \param OldSphereCenter old center of a circumcircle, defining the zero "path length" on the parameter circle
1758 * \param NormalVector normal vector
1759 * \param SearchDirection search direction to make angle unique on return.
1760 * \return Angle between \a NewSphereCenter and \a OldSphereCenter relative to \a CircleCenter, 2.*M_PI if one test fails
1761 */
1762double GetPathLengthonCircumCircle(Vector &CircleCenter, Vector &CirclePlaneNormal, double CircleRadius, Vector &NewSphereCenter, Vector &OldSphereCenter, Vector &NormalVector, Vector &SearchDirection)
1763{
1764 Vector helper;
1765 double radius, alpha;
1766
1767 helper.CopyVector(&NewSphereCenter);
1768 // test whether new center is on the parameter circle's plane
1769 if (fabs(helper.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
1770 cerr << "ERROR: Something's very wrong here: NewSphereCenter is not on the band's plane as desired by " <<fabs(helper.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
1771 helper.ProjectOntoPlane(&CirclePlaneNormal);
1772 }
1773 radius = helper.ScalarProduct(&helper);
1774 // test whether the new center vector has length of CircleRadius
1775 if (fabs(radius - CircleRadius) > HULLEPSILON)
1776 cerr << Verbose(1) << "ERROR: The projected center of the new sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
1777 alpha = helper.Angle(&OldSphereCenter);
1778 // make the angle unique by checking the halfplanes/search direction
1779 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON) // acos is not unique on [0, 2.*M_PI), hence extra check to decide between two half intervals
1780 alpha = 2.*M_PI - alpha;
1781 cout << Verbose(2) << "INFO: RelativeNewSphereCenter is " << helper << ", RelativeOldSphereCenter is " << OldSphereCenter << " and resulting angle is " << alpha << "." << endl;
1782 radius = helper.Distance(&OldSphereCenter);
1783 helper.ProjectOntoPlane(&NormalVector);
1784 // check whether new center is somewhat away or at least right over the current baseline to prevent intersecting triangles
1785 if ((radius > HULLEPSILON) || (helper.Norm() < HULLEPSILON)) {
1786 cout << Verbose(2) << "INFO: Distance between old and new center is " << radius << " and between new center and baseline center is " << helper.Norm() << "." << endl;
1787 return alpha;
1788 } else {
1789 cout << Verbose(1) << "INFO: NewSphereCenter " << helper << " is too close to OldSphereCenter" << OldSphereCenter << "." << endl;
1790 return 2.*M_PI;
1791 }
1792};
1793
1794
1795/** Checks whether the triangle consisting of the three atoms is already present.
1796 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1797 * lines. If any of the three edges already has two triangles attached, false is
1798 * returned.
1799 * \param *out output stream for debugging
1800 * \param *Candidates endpoints of the triangle candidate
1801 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
1802 * triangles exist which is the maximum for three points
1803 */
1804int Tesselation::CheckPresenceOfTriangle(ofstream *out, atom *Candidates[3]) {
1805 LineMap::iterator FindLine;
1806 PointMap::iterator FindPoint;
1807 TriangleMap::iterator FindTriangle;
1808 int adjacentTriangleCount = 0;
1809 class BoundaryPointSet *Points[3];
1810
1811 *out << Verbose(2) << "Begin of CheckPresenceOfTriangle" << endl;
1812 // builds a triangle point set (Points) of the end points
1813 for (int i = 0; i < 3; i++) {
1814 FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1815 if (FindPoint != PointsOnBoundary.end()) {
1816 Points[i] = FindPoint->second;
1817 } else {
1818 Points[i] = NULL;
1819 }
1820 }
1821
1822 // checks lines between the points in the Points for their adjacent triangles
1823 for (int i = 0; i < 3; i++) {
1824 if (Points[i] != NULL) {
1825 for (int j = i; j < 3; j++) {
1826 if (Points[j] != NULL) {
1827 FindLine = Points[i]->lines.find(Points[j]->node->nr);
1828 if (FindLine != Points[i]->lines.end()) {
1829 for (; FindLine->first == Points[j]->node->nr; FindLine++) {
1830 FindTriangle = FindLine->second->triangles.begin();
1831 for (; FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
1832 if ((
1833 (FindTriangle->second->endpoints[0] == Points[0])
1834 || (FindTriangle->second->endpoints[0] == Points[1])
1835 || (FindTriangle->second->endpoints[0] == Points[2])
1836 ) && (
1837 (FindTriangle->second->endpoints[1] == Points[0])
1838 || (FindTriangle->second->endpoints[1] == Points[1])
1839 || (FindTriangle->second->endpoints[1] == Points[2])
1840 ) && (
1841 (FindTriangle->second->endpoints[2] == Points[0])
1842 || (FindTriangle->second->endpoints[2] == Points[1])
1843 || (FindTriangle->second->endpoints[2] == Points[2])
1844 )
1845 ) {
1846 adjacentTriangleCount++;
1847 }
1848 }
1849 }
1850 // Only one of the triangle lines must be considered for the triangle count.
1851 *out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1852 return adjacentTriangleCount;
1853
1854 }
1855 }
1856 }
1857 }
1858 }
1859
1860 *out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1861 return adjacentTriangleCount;
1862};
1863
1864/** This recursive function finds a third point, to form a triangle with two given ones.
1865 * Note that this function is for the starting triangle.
1866 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
1867 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
1868 * the center of the sphere is still fixed up to a single parameter. The band of possible values
1869 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
1870 * us the "null" on this circle, the new center of the candidate point will be some way along this
1871 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
1872 * by the normal vector of the base triangle that always points outwards by construction.
1873 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
1874 * We construct the normal vector that defines the plane this circle lies in, it is just in the
1875 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
1876 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
1877 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
1878 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
1879 * both.
1880 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
1881 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
1882 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
1883 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
1884 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
1885 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
1886 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa Find_starting_triangle())
1887 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
1888 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
1889 * @param BaseLine BoundaryLineSet with the current base line
1890 * @param ThirdNode third atom to avoid in search
1891 * @param candidates list of equally good candidates to return
1892 * @param ShortestAngle the current path length on this circle band for the current Opt_Candidate
1893 * @param RADIUS radius of sphere
1894 * @param *LC LinkedCell structure with neighbouring atoms
1895 */
1896void Find_third_point_for_Tesselation(
1897 Vector NormalVector, Vector SearchDirection, Vector OldSphereCenter,
1898 class BoundaryLineSet *BaseLine, atom *ThirdNode, CandidateList* &candidates,
1899 double *ShortestAngle, const double RADIUS, LinkedCell *LC
1900) {
1901 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
1902 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
1903 Vector SphereCenter;
1904 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
1905 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
1906 Vector NewNormalVector; // normal vector of the Candidate's triangle
1907 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
1908 LinkedAtoms *List = NULL;
1909 double CircleRadius; // radius of this circle
1910 double radius;
1911 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
1912 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
1913 atom *Candidate = NULL;
1914 CandidateForTesselation *optCandidate;
1915
1916 cout << Verbose(1) << "Begin of Find_third_point_for_Tesselation" << endl;
1917
1918 cout << Verbose(2) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
1919
1920 // construct center of circle
1921 CircleCenter.CopyVector(&(BaseLine->endpoints[0]->node->x));
1922 CircleCenter.AddVector(&BaseLine->endpoints[1]->node->x);
1923 CircleCenter.Scale(0.5);
1924
1925 // construct normal vector of circle
1926 CirclePlaneNormal.CopyVector(&BaseLine->endpoints[0]->node->x);
1927 CirclePlaneNormal.SubtractVector(&BaseLine->endpoints[1]->node->x);
1928
1929 // calculate squared radius atom *ThirdNode,f circle
1930 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
1931 if (radius/4. < RADIUS*RADIUS) {
1932 CircleRadius = RADIUS*RADIUS - radius/4.;
1933 CirclePlaneNormal.Normalize();
1934 cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
1935
1936 // test whether old center is on the band's plane
1937 if (fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
1938 cerr << "ERROR: Something's very wrong here: OldSphereCenter is not on the band's plane as desired by " << fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
1939 OldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
1940 }
1941 radius = OldSphereCenter.ScalarProduct(&OldSphereCenter);
1942 if (fabs(radius - CircleRadius) < HULLEPSILON) {
1943
1944 // check SearchDirection
1945 cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
1946 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
1947 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
1948 }
1949
1950 // get cell for the starting atom
1951 if (LC->SetIndexToVector(&CircleCenter)) {
1952 for(int i=0;i<NDIM;i++) // store indices of this cell
1953 N[i] = LC->n[i];
1954 cout << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
1955 } else {
1956 cerr << "ERROR: Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
1957 return;
1958 }
1959 // then go through the current and all neighbouring cells and check the contained atoms for possible candidates
1960 cout << Verbose(2) << "LC Intervals:";
1961 for (int i=0;i<NDIM;i++) {
1962 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
1963 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
1964 cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
1965 }
1966 cout << endl;
1967 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
1968 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
1969 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
1970 List = LC->GetCurrentCell();
1971 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1972 if (List != NULL) {
1973 for (LinkedAtoms::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
1974 Candidate = (*Runner);
1975
1976 // check for three unique points
1977 cout << Verbose(1) << "INFO: Current Candidate is " << *Candidate << " at " << Candidate->x << "." << endl;
1978 if ((Candidate != BaseLine->endpoints[0]->node) && (Candidate != BaseLine->endpoints[1]->node) ){
1979
1980 // construct both new centers
1981 GetCenterofCircumcircle(&NewSphereCenter, &(BaseLine->endpoints[0]->node->x), &(BaseLine->endpoints[1]->node->x), &(Candidate->x));
1982 OtherNewSphereCenter.CopyVector(&NewSphereCenter);
1983
1984 if ((NewNormalVector.MakeNormalVector(&(BaseLine->endpoints[0]->node->x), &(BaseLine->endpoints[1]->node->x), &(Candidate->x)))
1985 && (fabs(NewNormalVector.ScalarProduct(&NewNormalVector)) > HULLEPSILON)
1986 ) {
1987 helper.CopyVector(&NewNormalVector);
1988 cout << Verbose(2) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
1989 radius = BaseLine->endpoints[0]->node->x.DistanceSquared(&NewSphereCenter);
1990 if (radius < RADIUS*RADIUS) {
1991 helper.Scale(sqrt(RADIUS*RADIUS - radius));
1992 cout << Verbose(2) << "INFO: Distance of NewCircleCenter to NewSphereCenter is " << helper.Norm() << " with sphere radius " << RADIUS << "." << endl;
1993 NewSphereCenter.AddVector(&helper);
1994 NewSphereCenter.SubtractVector(&CircleCenter);
1995 cout << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
1996
1997 // OtherNewSphereCenter is created by the same vector just in the other direction
1998 helper.Scale(-1.);
1999 OtherNewSphereCenter.AddVector(&helper);
2000 OtherNewSphereCenter.SubtractVector(&CircleCenter);
2001 cout << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
2002
2003 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2004 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2005 alpha = min(alpha, Otheralpha);
2006 // if there is a better candidate, drop the current list and add the new candidate
2007 // otherwise ignore the new candidate and keep the list
2008 if (*ShortestAngle > (alpha - HULLEPSILON)) {
2009 optCandidate = new CandidateForTesselation(Candidate, BaseLine, OptCandidateCenter, OtherOptCandidateCenter);
2010 if (fabs(alpha - Otheralpha) > MYEPSILON) {
2011 optCandidate->OptCenter.CopyVector(&NewSphereCenter);
2012 optCandidate->OtherOptCenter.CopyVector(&OtherNewSphereCenter);
2013 } else {
2014 optCandidate->OptCenter.CopyVector(&OtherNewSphereCenter);
2015 optCandidate->OtherOptCenter.CopyVector(&NewSphereCenter);
2016 }
2017 // if there is an equal candidate, add it to the list without clearing the list
2018 if ((*ShortestAngle - HULLEPSILON) < alpha) {
2019 candidates->push_back(optCandidate);
2020 cout << Verbose(1) << "ACCEPT: We have found an equally good candidate: " << *(optCandidate->point) << " with "
2021 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2022 } else {
2023 candidates->clear();
2024 candidates->push_back(optCandidate);
2025 cout << Verbose(1) << "ACCEPT: We have found a better candidate: " << *(optCandidate->point) << " with "
2026 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2027 }
2028 *ShortestAngle = alpha;
2029 cout << Verbose(2) << "INFO: There are " << candidates->size() << " candidates in the list now." << endl;
2030 } else {
2031 if ((optCandidate != NULL) && (optCandidate->point != NULL))
2032 cout << Verbose(1) << "REJECT: Old candidate: " << *(optCandidate->point) << " is better than " << alpha << " with " << *ShortestAngle << "." << endl;
2033 else
2034 cout << Verbose(2) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
2035 }
2036
2037 } else {
2038 cout << Verbose(1) << "REJECT: NewSphereCenter " << NewSphereCenter << " is too far away: " << radius << "." << endl;
2039 }
2040 } else {
2041 cout << Verbose(1) << "REJECT: Three points from " << *BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
2042 }
2043 } else {
2044 if (ThirdNode != NULL)
2045 cout << Verbose(1) << "REJECT: Base triangle " << *BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
2046 else
2047 cout << Verbose(1) << "REJECT: Base triangle " << *BaseLine << " contains Candidate " << *Candidate << "." << endl;
2048 }
2049 }
2050 }
2051 }
2052 } else {
2053 cerr << Verbose(1) << "ERROR: The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
2054 }
2055 } else {
2056 if (ThirdNode != NULL)
2057 cout << Verbose(1) << "Circumcircle for base line " << *BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
2058 else
2059 cout << Verbose(1) << "Circumcircle for base line " << *BaseLine << " is too big!" << endl;
2060 }
2061
2062 cout << Verbose(1) << "INFO: Sorting candidate list ..." << endl;
2063 if (candidates->size() > 1) {
2064 candidates->unique();
2065 candidates->sort(sortCandidates);
2066 }
2067
2068 cout << Verbose(1) << "End of Find_third_point_for_Tesselation" << endl;
2069};
2070
2071struct Intersection {
2072 Vector x1;
2073 Vector x2;
2074 Vector x3;
2075 Vector x4;
2076};
2077
2078/**
2079 * Intersection calculation function.
2080 *
2081 * @param x to find the result for
2082 * @param function parameter
2083 */
2084double MinIntersectDistance(const gsl_vector * x, void *params) {
2085 double retval = 0;
2086 struct Intersection *I = (struct Intersection *)params;
2087 Vector intersection;
2088 Vector SideA,SideB,HeightA, HeightB;
2089 for (int i=0;i<NDIM;i++)
2090 intersection.x[i] = gsl_vector_get(x, i);
2091
2092 SideA.CopyVector(&(I->x1));
2093 SideA.SubtractVector(&I->x2);
2094 HeightA.CopyVector(&intersection);
2095 HeightA.SubtractVector(&I->x1);
2096 HeightA.ProjectOntoPlane(&SideA);
2097
2098 SideB.CopyVector(&I->x3);
2099 SideB.SubtractVector(&I->x4);
2100 HeightB.CopyVector(&intersection);
2101 HeightB.SubtractVector(&I->x3);
2102 HeightB.ProjectOntoPlane(&SideB);
2103
2104 retval = HeightA.ScalarProduct(&HeightA) + HeightB.ScalarProduct(&HeightB);
2105 //cout << Verbose(2) << "MinIntersectDistance called, result: " << retval << endl;
2106
2107 return retval;
2108};
2109
2110
2111/**
2112 * Calculates whether there is an intersection between two lines. The first line
2113 * always goes through point 1 and point 2 and the second line is given by the
2114 * connection between point 4 and point 5.
2115 *
2116 * @param point 1 of line 1
2117 * @param point 2 of line 1
2118 * @param point 1 of line 2
2119 * @param point 2 of line 2
2120 *
2121 * @return true if there is an intersection between the given lines, false otherwise
2122 */
2123bool existsIntersection(Vector point1, Vector point2, Vector point3, Vector point4) {
2124 bool result;
2125
2126 struct Intersection par;
2127 par.x1.CopyVector(&point1);
2128 par.x2.CopyVector(&point2);
2129 par.x3.CopyVector(&point3);
2130 par.x4.CopyVector(&point4);
2131
2132 const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
2133 gsl_multimin_fminimizer *s = NULL;
2134 gsl_vector *ss, *x;
2135 gsl_multimin_function minex_func;
2136
2137 size_t iter = 0;
2138 int status;
2139 double size;
2140
2141 /* Starting point */
2142 x = gsl_vector_alloc(NDIM);
2143 gsl_vector_set(x, 0, point1.x[0]);
2144 gsl_vector_set(x, 1, point1.x[1]);
2145 gsl_vector_set(x, 2, point1.x[2]);
2146
2147 /* Set initial step sizes to 1 */
2148 ss = gsl_vector_alloc(NDIM);
2149 gsl_vector_set_all(ss, 1.0);
2150
2151 /* Initialize method and iterate */
2152 minex_func.n = NDIM;
2153 minex_func.f = &MinIntersectDistance;
2154 minex_func.params = (void *)&par;
2155
2156 s = gsl_multimin_fminimizer_alloc(T, NDIM);
2157 gsl_multimin_fminimizer_set(s, &minex_func, x, ss);
2158
2159 do {
2160 iter++;
2161 status = gsl_multimin_fminimizer_iterate(s);
2162
2163 if (status) {
2164 break;
2165 }
2166
2167 size = gsl_multimin_fminimizer_size(s);
2168 status = gsl_multimin_test_size(size, 1e-2);
2169
2170 if (status == GSL_SUCCESS) {
2171 cout << Verbose(2) << "converged to minimum" << endl;
2172 }
2173 } while (status == GSL_CONTINUE && iter < 100);
2174
2175 // check whether intersection is in between or not
2176 Vector intersection, SideA, SideB, HeightA, HeightB;
2177 double t1, t2;
2178 for (int i = 0; i < NDIM; i++) {
2179 intersection.x[i] = gsl_vector_get(s->x, i);
2180 }
2181
2182 SideA.CopyVector(&par.x2);
2183 SideA.SubtractVector(&par.x1);
2184 HeightA.CopyVector(&intersection);
2185 HeightA.SubtractVector(&par.x1);
2186
2187 t1 = HeightA.Projection(&SideA)/SideA.ScalarProduct(&SideA);
2188
2189 SideB.CopyVector(&par.x4);
2190 SideB.SubtractVector(&par.x3);
2191 HeightB.CopyVector(&intersection);
2192 HeightB.SubtractVector(&par.x3);
2193
2194 t2 = HeightB.Projection(&SideB)/SideB.ScalarProduct(&SideB);
2195
2196 cout << Verbose(2) << "Intersection " << intersection << " is at "
2197 << t1 << " for (" << point1 << "," << point2 << ") and at "
2198 << t2 << " for (" << point3 << "," << point4 << "): ";
2199
2200 if (((t1 >= 0) && (t1 <= 1)) && ((t2 >= 0) && (t2 <= 1))) {
2201 cout << "true intersection." << endl;
2202 result = true;
2203 } else {
2204 cout << "intersection out of region of interest." << endl;
2205 result = false;
2206 }
2207
2208 // free minimizer stuff
2209 gsl_vector_free(x);
2210 gsl_vector_free(ss);
2211 gsl_multimin_fminimizer_free(s);
2212
2213 return result;
2214}
2215
2216/** Finds the second point of starting triangle.
2217 * \param *a first atom
2218 * \param *Candidate pointer to candidate atom on return
2219 * \param Oben vector indicating the outside
2220 * \param Opt_Candidate reference to recommended candidate on return
2221 * \param Storage[3] array storing angles and other candidate information
2222 * \param RADIUS radius of virtual sphere
2223 * \param *LC LinkedCell structure with neighbouring atoms
2224 */
2225void Find_second_point_for_Tesselation(atom* a, atom* Candidate, Vector Oben, atom*& Opt_Candidate, double Storage[3], double RADIUS, LinkedCell *LC)
2226{
2227 cout << Verbose(2) << "Begin of Find_second_point_for_Tesselation" << endl;
2228 Vector AngleCheck;
2229 double norm = -1., angle;
2230 LinkedAtoms *List = NULL;
2231 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2232
2233 if (LC->SetIndexToAtom(a)) { // get cell for the starting atom
2234 for(int i=0;i<NDIM;i++) // store indices of this cell
2235 N[i] = LC->n[i];
2236 } else {
2237 cerr << "ERROR: Atom " << *a << " is not found in cell " << LC->index << "." << endl;
2238 return;
2239 }
2240 // then go through the current and all neighbouring cells and check the contained atoms for possible candidates
2241 cout << Verbose(2) << "LC Intervals from [";
2242 for (int i=0;i<NDIM;i++) {
2243 cout << " " << N[i] << "<->" << LC->N[i];
2244 }
2245 cout << "] :";
2246 for (int i=0;i<NDIM;i++) {
2247 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2248 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2249 cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2250 }
2251 cout << endl;
2252
2253
2254 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2255 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2256 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2257 List = LC->GetCurrentCell();
2258 cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2259 if (List != NULL) {
2260 for (LinkedAtoms::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2261 Candidate = (*Runner);
2262 cout << Verbose(2) << "Current candidate is " << *Candidate << ": ";
2263 // check if we only have one unique point yet ...
2264 if (a != Candidate) {
2265 // Calculate center of the circle with radius RADIUS through points a and Candidate
2266 Vector OrthogonalizedOben, a_Candidate, Center;
2267 double distance, scaleFactor;
2268
2269 OrthogonalizedOben.CopyVector(&Oben);
2270 a_Candidate.CopyVector(&(a->x));
2271 a_Candidate.SubtractVector(&(Candidate->x));
2272 OrthogonalizedOben.ProjectOntoPlane(&a_Candidate);
2273 OrthogonalizedOben.Normalize();
2274 distance = 0.5 * a_Candidate.Norm();
2275 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
2276 OrthogonalizedOben.Scale(scaleFactor);
2277
2278 Center.CopyVector(&(Candidate->x));
2279 Center.AddVector(&(a->x));
2280 Center.Scale(0.5);
2281 Center.AddVector(&OrthogonalizedOben);
2282
2283 AngleCheck.CopyVector(&Center);
2284 AngleCheck.SubtractVector(&(a->x));
2285 norm = a_Candidate.Norm();
2286 // second point shall have smallest angle with respect to Oben vector
2287 if (norm < RADIUS*2.) {
2288 angle = AngleCheck.Angle(&Oben);
2289 if (angle < Storage[0]) {
2290 //cout << Verbose(1) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
2291 cout << "Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
2292 Opt_Candidate = Candidate;
2293 Storage[0] = angle;
2294 //cout << Verbose(1) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
2295 } else {
2296 cout << "Looses with angle " << angle << " to a better candidate " << *Opt_Candidate << endl;
2297 }
2298 } else {
2299 cout << "Refused due to Radius " << norm << endl;
2300 }
2301 } else {
2302 cout << " Candidate is equal to first endpoint " << *a << "." << endl;
2303 }
2304 }
2305 } else {
2306 cout << "Linked cell list is empty." << endl;
2307 }
2308 }
2309 cout << Verbose(2) << "End of Find_second_point_for_Tesselation" << endl;
2310};
2311
2312/** Finds the starting triangle for find_non_convex_border().
2313 * Looks at the outermost atom per axis, then Find_second_point_for_Tesselation()
2314 * for the second and Find_next_suitable_point_via_Angle_of_Sphere() for the third
2315 * point are called.
2316 * \param RADIUS radius of virtual rolling sphere
2317 * \param *LC LinkedCell structure with neighbouring atoms
2318 */
2319void Tesselation::Find_starting_triangle(ofstream *out, molecule *mol, const double RADIUS, LinkedCell *LC)
2320{
2321 cout << Verbose(1) << "Begin of Find_starting_triangle\n";
2322 int i = 0;
2323 LinkedAtoms *List = NULL;
2324 atom* FirstPoint = NULL;
2325 atom* SecondPoint = NULL;
2326 atom* MaxAtom[NDIM];
2327 double max_coordinate[NDIM];
2328 Vector Oben;
2329 Vector helper;
2330 Vector Chord;
2331 Vector SearchDirection;
2332
2333 Oben.Zero();
2334
2335 for (i = 0; i < 3; i++) {
2336 MaxAtom[i] = NULL;
2337 max_coordinate[i] = -1;
2338 }
2339
2340 // 1. searching topmost atom with respect to each axis
2341 for (int i=0;i<NDIM;i++) { // each axis
2342 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
2343 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
2344 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
2345 List = LC->GetCurrentCell();
2346 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2347 if (List != NULL) {
2348 for (LinkedAtoms::iterator Runner = List->begin();Runner != List->end();Runner++) {
2349 cout << Verbose(2) << "Current atom is " << *(*Runner) << "." << endl;
2350 if ((*Runner)->x.x[i] > max_coordinate[i]) {
2351 max_coordinate[i] = (*Runner)->x.x[i];
2352 MaxAtom[i] = (*Runner);
2353 }
2354 }
2355 } else {
2356 cerr << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
2357 }
2358 }
2359 }
2360
2361 cout << Verbose(2) << "Found maximum coordinates: ";
2362 for (int i=0;i<NDIM;i++)
2363 cout << i << ": " << *MaxAtom[i] << "\t";
2364 cout << endl;
2365 const int k = 1; // arbitrary choice
2366 Oben.x[k] = 1.;
2367 FirstPoint = MaxAtom[k];
2368 cout << Verbose(1) << "Coordinates of start atom " << *FirstPoint << " at " << FirstPoint->x << "." << endl;
2369
2370 double ShortestAngle;
2371 atom* Opt_Candidate = NULL;
2372 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.
2373
2374 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_...
2375 SecondPoint = Opt_Candidate;
2376 cout << Verbose(1) << "Found second point is " << *SecondPoint << " at " << SecondPoint->x << ".\n";
2377
2378 helper.CopyVector(&(FirstPoint->x));
2379 helper.SubtractVector(&(SecondPoint->x));
2380 helper.Normalize();
2381 Oben.ProjectOntoPlane(&helper);
2382 Oben.Normalize();
2383 helper.VectorProduct(&Oben);
2384 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
2385
2386 Chord.CopyVector(&(FirstPoint->x)); // bring into calling function
2387 Chord.SubtractVector(&(SecondPoint->x));
2388 double radius = Chord.ScalarProduct(&Chord);
2389 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
2390 helper.CopyVector(&Oben);
2391 helper.Scale(CircleRadius);
2392 // Now, oben and helper are two orthonormalized vectors in the plane defined by Chord (not normalized)
2393
2394 cout << Verbose(2) << "Looking for third point candidates \n";
2395 // look in one direction of baseline for initial candidate
2396 CandidateList *Opt_Candidates = new CandidateList();
2397 SearchDirection.MakeNormalVector(&Chord, &Oben); // whether we look "left" first or "right" first is not important ...
2398
2399 // adding point 1 and point 2 and the line between them
2400 AddTrianglePoint(FirstPoint, 0);
2401 AddTrianglePoint(SecondPoint, 1);
2402 AddTriangleLine(TPS[0], TPS[1], 0);
2403
2404 cout << Verbose(1) << "Looking for third point candidates ...\n";
2405 cout << Verbose(2) << "INFO: OldSphereCenter is at " << helper << ".\n";
2406 Find_third_point_for_Tesselation(
2407 Oben, SearchDirection, helper, BLS[0], NULL, *&Opt_Candidates, &ShortestAngle, RADIUS, LC
2408 );
2409 cout << Verbose(1) << "Third Points are ";
2410 CandidateList::iterator it;
2411 for (it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
2412 cout << " " << *(*it)->point;
2413 }
2414 cout << endl;
2415
2416 for (it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
2417 // add third triangle point
2418 AddTrianglePoint((*it)->point, 2);
2419 // add the second and third line
2420 AddTriangleLine(TPS[1], TPS[2], 1);
2421 AddTriangleLine(TPS[0], TPS[2], 2);
2422 // ... and triangles to the Maps of the Tesselation class
2423 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2424 AddTriangle();
2425 // ... and calculate its normal vector (with correct orientation)
2426 (*it)->OptCenter.Scale(-1.);
2427 cout << Verbose(2) << "Anti-Oben is currently " << (*it)->OptCenter << "." << endl;
2428 BTS->GetNormalVector((*it)->OptCenter); // vector to compare with should point inwards
2429 cout << Verbose(0) << "==> Found starting triangle consists of " << *FirstPoint << ", " << *SecondPoint << " and "
2430 << *(*it)->point << " with normal vector " << BTS->NormalVector << ".\n";
2431
2432 // if we do not reach the end with the next step of iteration, we need to setup a new first line
2433 if (it != Opt_Candidates->end()--) {
2434 FirstPoint = (*it)->BaseLine->endpoints[0]->node;
2435 SecondPoint = (*it)->point;
2436 // adding point 1 and point 2 and the line between them
2437 AddTrianglePoint(FirstPoint, 0);
2438 AddTrianglePoint(SecondPoint, 1);
2439 AddTriangleLine(TPS[0], TPS[1], 0);
2440 }
2441 }
2442 cout << Verbose(2) << "Projection is " << BTS->NormalVector.Projection(&Oben) << "." << endl;
2443 cout << Verbose(1) << "End of Find_starting_triangle\n";
2444};
2445
2446/** Checks for a new special triangle whether one of its edges is already present with one one triangle connected.
2447 * This enforces that special triangles (i.e. degenerated ones) should at last close the open-edge frontier and not
2448 * make it bigger (i.e. closing one (the baseline) and opening two new ones).
2449 * \param TPS[3] nodes of the triangle
2450 * \return true - there is such a line (i.e. creation of degenerated triangle is valid), false - no such line (don't create)
2451 */
2452bool CheckLineCriteriaforDegeneratedTriangle(class BoundaryPointSet *nodes[3])
2453{
2454 bool result = false;
2455 int counter = 0;
2456
2457 // check all three points
2458 for (int i=0;i<3;i++)
2459 for (int j=i+1; j<3; j++) {
2460 if (nodes[i]->lines.find(nodes[j]->node->nr) != nodes[i]->lines.end()) { // there already is a line
2461 LineMap::iterator FindLine;
2462 pair<LineMap::iterator,LineMap::iterator> FindPair;
2463 FindPair = nodes[i]->lines.equal_range(nodes[j]->node->nr);
2464 for (FindLine = FindPair.first; FindLine != FindPair.second; ++FindLine) {
2465 // If there is a line with less than two attached triangles, we don't need a new line.
2466 if (FindLine->second->TrianglesCount < 2) {
2467 counter++;
2468 break; // increase counter only once per edge
2469 }
2470 }
2471 } else { // no line
2472 cout << Verbose(1) << "ERROR: The line between " << nodes[i] << " and " << nodes[j] << " is not yet present, hence no need for a degenerate triangle!" << endl;
2473 result = true;
2474 }
2475 }
2476 if (counter > 1) {
2477 cout << Verbose(2) << "INFO: Degenerate triangle is ok, at least two, here " << counter << ", existing lines are used." << endl;
2478 result = true;
2479 }
2480 return result;
2481};
2482
2483
2484/** This function finds a triangle to a line, adjacent to an existing one.
2485 * @param out output stream for debugging
2486 * @param *mol molecule with Atom's and Bond's
2487 * @param Line current baseline to search from
2488 * @param T current triangle which \a Line is edge of
2489 * @param RADIUS radius of the rolling ball
2490 * @param N number of found triangles
2491 * @param *filename filename base for intermediate envelopes
2492 * @param *LC LinkedCell structure with neighbouring atoms
2493 */
2494bool Tesselation::Find_next_suitable_triangle(ofstream *out,
2495 molecule *mol, BoundaryLineSet &Line, BoundaryTriangleSet &T,
2496 const double& RADIUS, int N, const char *tempbasename, LinkedCell *LC)
2497{
2498 cout << Verbose(1) << "Begin of Find_next_suitable_triangle\n";
2499 ofstream *tempstream = NULL;
2500 char NumberName[255];
2501 bool result = true;
2502 CandidateList *Opt_Candidates = new CandidateList();
2503
2504 Vector CircleCenter;
2505 Vector CirclePlaneNormal;
2506 Vector OldSphereCenter;
2507 Vector SearchDirection;
2508 Vector helper;
2509 atom *ThirdNode = NULL;
2510 LineMap::iterator testline;
2511 double ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
2512 double radius, CircleRadius;
2513
2514 cout << Verbose(1) << "Current baseline is " << Line << " of triangle " << T << "." << endl;
2515 for (int i=0;i<3;i++)
2516 if ((T.endpoints[i]->node != Line.endpoints[0]->node) && (T.endpoints[i]->node != Line.endpoints[1]->node))
2517 ThirdNode = T.endpoints[i]->node;
2518
2519 // construct center of circle
2520 CircleCenter.CopyVector(&Line.endpoints[0]->node->x);
2521 CircleCenter.AddVector(&Line.endpoints[1]->node->x);
2522 CircleCenter.Scale(0.5);
2523
2524 // construct normal vector of circle
2525 CirclePlaneNormal.CopyVector(&Line.endpoints[0]->node->x);
2526 CirclePlaneNormal.SubtractVector(&Line.endpoints[1]->node->x);
2527
2528 // calculate squared radius of circle
2529 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2530 if (radius/4. < RADIUS*RADIUS) {
2531 CircleRadius = RADIUS*RADIUS - radius/4.;
2532 CirclePlaneNormal.Normalize();
2533 cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2534
2535 // construct old center
2536 GetCenterofCircumcircle(&OldSphereCenter, &(T.endpoints[0]->node->x), &(T.endpoints[1]->node->x), &(T.endpoints[2]->node->x));
2537 helper.CopyVector(&T.NormalVector); // normal vector ensures that this is correct center of the two possible ones
2538 radius = Line.endpoints[0]->node->x.DistanceSquared(&OldSphereCenter);
2539 helper.Scale(sqrt(RADIUS*RADIUS - radius));
2540 OldSphereCenter.AddVector(&helper);
2541 OldSphereCenter.SubtractVector(&CircleCenter);
2542 cout << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
2543
2544 // construct SearchDirection
2545 SearchDirection.MakeNormalVector(&T.NormalVector, &CirclePlaneNormal);
2546 helper.CopyVector(&Line.endpoints[0]->node->x);
2547 helper.SubtractVector(&ThirdNode->x);
2548 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
2549 SearchDirection.Scale(-1.);
2550 SearchDirection.ProjectOntoPlane(&OldSphereCenter);
2551 SearchDirection.Normalize();
2552 cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2553 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
2554 // rotated the wrong way!
2555 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
2556 }
2557
2558 // add third point
2559 cout << Verbose(1) << "Looking for third point candidates for triangle ... " << endl;
2560 Find_third_point_for_Tesselation(
2561 T.NormalVector, SearchDirection, OldSphereCenter, &Line, ThirdNode, Opt_Candidates,
2562 &ShortestAngle, RADIUS, LC
2563 );
2564
2565 } else {
2566 cout << Verbose(1) << "Circumcircle for base line " << Line << " and base triangle " << T << " is too big!" << endl;
2567 }
2568
2569 if (Opt_Candidates->begin() == Opt_Candidates->end()) {
2570 cerr << "WARNING: Could not find a suitable candidate." << endl;
2571 return false;
2572 }
2573 cout << Verbose(1) << "Third Points are ";
2574 CandidateList::iterator it;
2575 for (it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
2576 cout << " " << *(*it)->point;
2577 }
2578 cout << endl;
2579
2580 BoundaryLineSet *BaseRay = &Line;
2581 for (it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
2582 cout << Verbose(1) << " Third point candidate is " << *(*it)->point
2583 << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
2584 cout << Verbose(1) << " Baseline is " << *BaseRay << endl;
2585
2586 // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
2587 atom *AtomCandidates[3];
2588 AtomCandidates[0] = (*it)->point;
2589 AtomCandidates[1] = BaseRay->endpoints[0]->node;
2590 AtomCandidates[2] = BaseRay->endpoints[1]->node;
2591 int existentTrianglesCount = CheckPresenceOfTriangle(out, AtomCandidates);
2592
2593 BTS = NULL;
2594 // If there is no triangle, add it regularly.
2595 if (existentTrianglesCount == 0) {
2596 AddTrianglePoint((*it)->point, 0);
2597 AddTrianglePoint(BaseRay->endpoints[0]->node, 1);
2598 AddTrianglePoint(BaseRay->endpoints[1]->node, 2);
2599
2600 AddTriangleLine(TPS[0], TPS[1], 0);
2601 AddTriangleLine(TPS[0], TPS[2], 1);
2602 AddTriangleLine(TPS[1], TPS[2], 2);
2603
2604 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2605 AddTriangle();
2606 (*it)->OptCenter.Scale(-1.);
2607 BTS->GetNormalVector((*it)->OptCenter);
2608 (*it)->OptCenter.Scale(-1.);
2609
2610 cout << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector
2611 << " for this triangle ... " << endl;
2612 cout << Verbose(1) << "We have "<< TrianglesOnBoundaryCount << " for line " << BaseRay << "." << endl;
2613 } else if (existentTrianglesCount == 1) { // If there is a planar region within the structure, we need this triangle a second time.
2614 AddTrianglePoint((*it)->point, 0);
2615 AddTrianglePoint(BaseRay->endpoints[0]->node, 1);
2616 AddTrianglePoint(BaseRay->endpoints[1]->node, 2);
2617
2618 // 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)
2619 // i.e. at least one of the three lines must be present with TriangleCount <= 1
2620 if (CheckLineCriteriaforDegeneratedTriangle(TPS)) {
2621 AddTriangleLine(TPS[0], TPS[1], 0);
2622 AddTriangleLine(TPS[0], TPS[2], 1);
2623 AddTriangleLine(TPS[1], TPS[2], 2);
2624
2625 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2626 AddTriangle();
2627
2628 (*it)->OtherOptCenter.Scale(-1.);
2629 BTS->GetNormalVector((*it)->OtherOptCenter);
2630 (*it)->OtherOptCenter.Scale(-1.);
2631
2632 cout << "--> WARNING: Special new triangle with " << *BTS << " and normal vector " << BTS->NormalVector
2633 << " for this triangle ... " << endl;
2634 cout << Verbose(1) << "We have "<< BaseRay->TrianglesCount << " for line " << BaseRay << "." << endl;
2635 } else {
2636 cout << Verbose(1) << "WARNING: This triangle consisting of ";
2637 cout << *(*it)->point << ", ";
2638 cout << *BaseRay->endpoints[0]->node << " and ";
2639 cout << *BaseRay->endpoints[1]->node << " ";
2640 cout << "exists and is not added, as it does not seem helpful!" << endl;
2641 result = false;
2642 }
2643 } else {
2644 cout << Verbose(1) << "This triangle consisting of ";
2645 cout << *(*it)->point << ", ";
2646 cout << *BaseRay->endpoints[0]->node << " and ";
2647 cout << *BaseRay->endpoints[1]->node << " ";
2648 cout << "is invalid!" << endl;
2649 result = false;
2650 }
2651
2652 if ((result) && (existentTrianglesCount < 2) && (DoSingleStepOutput && (TrianglesOnBoundaryCount % 1 == 0))) { // if we have a new triangle and want to output each new triangle configuration
2653 sprintf(NumberName, "-%04d-%s_%s_%s", TriangleFilesWritten, BTS->endpoints[0]->node->Name, BTS->endpoints[1]->node->Name, BTS->endpoints[2]->node->Name);
2654 if (DoTecplotOutput) {
2655 string NameofTempFile(tempbasename);
2656 NameofTempFile.append(NumberName);
2657 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
2658 NameofTempFile.erase(npos, 1);
2659 NameofTempFile.append(TecplotSuffix);
2660 cout << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
2661 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
2662 write_tecplot_file(out, tempstream, this, mol, TriangleFilesWritten);
2663 tempstream->close();
2664 tempstream->flush();
2665 delete(tempstream);
2666 }
2667
2668 if (DoRaster3DOutput) {
2669 string NameofTempFile(tempbasename);
2670 NameofTempFile.append(NumberName);
2671 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
2672 NameofTempFile.erase(npos, 1);
2673 NameofTempFile.append(Raster3DSuffix);
2674 cout << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
2675 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
2676 write_raster3d_file(out, tempstream, this, mol);
2677 // include the current position of the virtual sphere in the temporary raster3d file
2678 // make the circumsphere's center absolute again
2679 helper.CopyVector(&BaseRay->endpoints[0]->node->x);
2680 helper.AddVector(&BaseRay->endpoints[1]->node->x);
2681 helper.Scale(0.5);
2682 (*it)->OptCenter.AddVector(&helper);
2683 Vector *center = mol->DetermineCenterOfAll(out);
2684 (*it)->OptCenter.AddVector(center);
2685 delete(center);
2686 // and add to file plus translucency object
2687 *tempstream << "# current virtual sphere\n";
2688 *tempstream << "8\n 25.0 0.6 -1.0 -1.0 -1.0 0.2 0 0 0 0\n";
2689 *tempstream << "2\n " << (*it)->OptCenter.x[0] << " "
2690 << (*it)->OptCenter.x[1] << " " << (*it)->OptCenter.x[2]
2691 << "\t" << RADIUS << "\t1 0 0\n";
2692 *tempstream << "9\n terminating special property\n";
2693 tempstream->close();
2694 tempstream->flush();
2695 delete(tempstream);
2696 }
2697 if (DoTecplotOutput || DoRaster3DOutput)
2698 TriangleFilesWritten++;
2699 }
2700
2701 // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
2702 BaseRay = BLS[0];
2703// LineMap::iterator LineIterator = Line.endpoints[0]->lines.find((*it)->point->nr);
2704// for (; LineIterator != Line.endpoints[0]->lines.end(); LineIterator++) {
2705// if ((*LineIterator->second).TrianglesCount != 2)
2706// break;
2707// }
2708// if (LineIterator == Line.endpoints[0]->lines.end())
2709// cout << Verbose(1) << "ERROR: I could not find a suitable line with less than two triangles connected!" << endl;
2710 }
2711
2712 cout << Verbose(1) << "End of Find_next_suitable_triangle\n";
2713 return result;
2714};
2715
2716/**
2717 * Sort function for the candidate list.
2718 */
2719bool sortCandidates(CandidateForTesselation* candidate1, CandidateForTesselation* candidate2) {
2720 Vector BaseLineVector, OrthogonalVector, helper;
2721 if (candidate1->BaseLine != candidate2->BaseLine) { // sanity check
2722 cout << Verbose(0) << "ERROR: sortCandidates was called for two different baselines: " << candidate1->BaseLine << " and " << candidate2->BaseLine << "." << endl;
2723 //return false;
2724 exit(1);
2725 }
2726 // create baseline vector
2727 BaseLineVector.CopyVector(&(candidate1->BaseLine->endpoints[1]->node->x));
2728 BaseLineVector.SubtractVector(&(candidate1->BaseLine->endpoints[0]->node->x));
2729 BaseLineVector.Normalize();
2730
2731 // 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!)
2732 helper.CopyVector(&(candidate1->BaseLine->endpoints[0]->node->x));
2733 helper.SubtractVector(&(candidate1->point->x));
2734 OrthogonalVector.CopyVector(&helper);
2735 helper.VectorProduct(&BaseLineVector);
2736 OrthogonalVector.SubtractVector(&helper);
2737 OrthogonalVector.Normalize();
2738
2739 // calculate both angles and correct with in-plane vector
2740 helper.CopyVector(&(candidate1->point->x));
2741 helper.SubtractVector(&(candidate1->BaseLine->endpoints[0]->node->x));
2742 double phi = BaseLineVector.Angle(&helper);
2743 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
2744 phi = 2.*M_PI - phi;
2745 }
2746 helper.CopyVector(&(candidate2->point->x));
2747 helper.SubtractVector(&(candidate1->BaseLine->endpoints[0]->node->x));
2748 double psi = BaseLineVector.Angle(&helper);
2749 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
2750 psi = 2.*M_PI - psi;
2751 }
2752
2753 cout << Verbose(2) << *candidate1->point << " has angle " << phi << endl;
2754 cout << Verbose(2) << *candidate2->point << " has angle " << psi << endl;
2755
2756 // return comparison
2757 return phi < psi;
2758}
2759
2760/** Tesselates the non convex boundary by rolling a virtual sphere along the surface of the molecule.
2761 * \param *out output stream for debugging
2762 * \param *mol molecule structure with Atom's and Bond's
2763 * \param *Tess Tesselation filled with points, lines and triangles on boundary on return
2764 * \param *filename filename prefix for output of vertex data
2765 * \para RADIUS radius of the virtual sphere
2766 */
2767void Find_non_convex_border(ofstream *out, molecule* mol, class Tesselation *Tess, class LinkedCell *LCList, const char *filename, const double RADIUS)
2768{
2769 int N = 0;
2770 bool freeTess = false;
2771 bool freeLC = false;
2772 *out << Verbose(1) << "Entering search for non convex hull. " << endl;
2773 if (Tess == NULL) {
2774 *out << Verbose(1) << "Allocating Tesselation struct ..." << endl;
2775 Tess = new Tesselation;
2776 freeTess = true;
2777 }
2778 LineMap::iterator baseline;
2779 LineMap::iterator testline;
2780 *out << Verbose(0) << "Begin of Find_non_convex_border\n";
2781 bool flag = false; // marks whether we went once through all baselines without finding any without two triangles
2782 bool failflag = false;
2783
2784 if (LCList == NULL) {
2785 LCList = new LinkedCell(mol, 2.*RADIUS);
2786 freeLC = true;
2787 }
2788
2789 Tess->Find_starting_triangle(out, mol, RADIUS, LCList);
2790
2791 baseline = Tess->LinesOnBoundary.begin();
2792 while ((baseline != Tess->LinesOnBoundary.end()) || (flag)) {
2793 if (baseline->second->TrianglesCount == 1) {
2794 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.
2795 flag = flag || failflag;
2796 if (!failflag)
2797 cerr << "WARNING: Find_next_suitable_triangle failed." << endl;
2798
2799 // we inserted new lines, hence show list with connected triangles
2800 cout << Verbose(1) << "List of Baselines with connected triangles so far:" << endl;
2801 for (testline = Tess->LinesOnBoundary.begin(); testline != Tess->LinesOnBoundary.end(); testline++) {
2802 cout << Verbose(1) << *testline->second << "\t" << testline->second->TrianglesCount << endl;
2803 }
2804 } else {
2805 cout << Verbose(1) << "Line " << *baseline->second << " has " << baseline->second->TrianglesCount << " triangles adjacent" << endl;
2806 if (baseline->second->TrianglesCount != 2)
2807 cout << Verbose(1) << "ERROR: TESSELATION FINISHED WITH INVALID TRIANGLE COUNT!" << endl;
2808 }
2809
2810 N++;
2811 baseline++;
2812 if ((baseline == Tess->LinesOnBoundary.end()) && (flag)) {
2813 baseline = Tess->LinesOnBoundary.begin(); // restart if we reach end due to newly inserted lines
2814 flag = false;
2815 }
2816 }
2817 if (1) { //failflag) {
2818 *out << Verbose(1) << "Writing final tecplot file\n";
2819 if (DoTecplotOutput) {
2820 string OutputName(filename);
2821 OutputName.append(TecplotSuffix);
2822 ofstream *tecplot = new ofstream(OutputName.c_str());
2823 write_tecplot_file(out, tecplot, Tess, mol, -1);
2824 tecplot->close();
2825 delete(tecplot);
2826 }
2827 if (DoRaster3DOutput) {
2828 string OutputName(filename);
2829 OutputName.append(Raster3DSuffix);
2830 ofstream *raster = new ofstream(OutputName.c_str());
2831 write_raster3d_file(out, raster, Tess, mol);
2832 raster->close();
2833 delete(raster);
2834 }
2835 } else {
2836 cerr << "ERROR: Could definitively not find all necessary triangles!" << endl;
2837 }
2838 if (freeTess)
2839 delete(Tess);
2840 if (freeLC)
2841 delete(LCList);
2842 *out << Verbose(0) << "End of Find_non_convex_border\n";
2843};
2844
2845/** Finds a hole of sufficient size in \a this molecule to embed \a *srcmol into it.
2846 * \param *out output stream for debugging
2847 * \param *srcmol molecule to embed into
2848 * \return *Vector new center of \a *srcmol for embedding relative to \a this
2849 */
2850Vector* molecule::FindEmbeddingHole(ofstream *out, molecule *srcmol)
2851{
2852 Vector *Center = new Vector;
2853 Center->Zero();
2854 // calculate volume/shape of \a *srcmol
2855
2856 // find embedding holes
2857
2858 // if more than one, let user choose
2859
2860 // return embedding center
2861 return Center;
2862};
2863
Note: See TracBrowser for help on using the repository browser.