source: src/boundary.cpp@ 12298c

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

Now we also produce Raster3D output files additionally to TecPlot ones ...

  • Property mode set to 100644
File size: 101.5 KB
Line 
1#include "molecules.hpp"
2#include "boundary.hpp"
3
4#define DEBUG 1
5#define DoTecplotOutput 0
6#define DoRaster3DOutput 1
7#define TecplotSuffix ".dat"
8#define Raster3DSuffix ".r3d"
9
10// ======================================== Points on Boundary =================================
11
12BoundaryPointSet::BoundaryPointSet()
13{
14 LinesCount = 0;
15 Nr = -1;
16}
17;
18
19BoundaryPointSet::BoundaryPointSet(atom *Walker)
20{
21 node = Walker;
22 LinesCount = 0;
23 Nr = Walker->nr;
24}
25;
26
27BoundaryPointSet::~BoundaryPointSet()
28{
29 cout << Verbose(5) << "Erasing point nr. " << Nr << "." << endl;
30 node = NULL;
31}
32;
33
34void
35BoundaryPointSet::AddLine(class BoundaryLineSet *line)
36{
37 cout << Verbose(6) << "Adding " << *this << " to line " << *line << "."
38 << endl;
39 if (line->endpoints[0] == this)
40 {
41 lines.insert(LinePair(line->endpoints[1]->Nr, line));
42 }
43 else
44 {
45 lines.insert(LinePair(line->endpoints[0]->Nr, line));
46 }
47 LinesCount++;
48}
49;
50
51ostream &
52operator <<(ostream &ost, BoundaryPointSet &a)
53{
54 ost << "[" << a.Nr << "|" << a.node->Name << "]";
55 return ost;
56}
57;
58
59// ======================================== Lines on Boundary =================================
60
61BoundaryLineSet::BoundaryLineSet()
62{
63 for (int i = 0; i < 2; i++)
64 endpoints[i] = NULL;
65 TrianglesCount = 0;
66 Nr = -1;
67}
68;
69
70BoundaryLineSet::BoundaryLineSet(class BoundaryPointSet *Point[2], int number)
71{
72 // set number
73 Nr = number;
74 // set endpoints in ascending order
75 SetEndpointsOrdered(endpoints, Point[0], Point[1]);
76 // add this line to the hash maps of both endpoints
77 Point[0]->AddLine(this); //Taken out, to check whether we can avoid unwanted double adding.
78 Point[1]->AddLine(this); //
79 // clear triangles list
80 TrianglesCount = 0;
81 cout << Verbose(5) << "New Line with endpoints " << *this << "." << endl;
82}
83;
84
85BoundaryLineSet::~BoundaryLineSet()
86{
87 for (int i = 0; i < 2; i++)
88 {
89 cout << Verbose(5) << "Erasing Line Nr. " << Nr << " in boundary point "
90 << *endpoints[i] << "." << endl;
91 endpoints[i]->lines.erase(Nr);
92 LineMap::iterator tester = endpoints[i]->lines.begin();
93 tester++;
94 if (tester == endpoints[i]->lines.end())
95 {
96 cout << Verbose(5) << *endpoints[i]
97 << " has no more lines it's attached to, erasing." << endl;
98 //delete(endpoints[i]);
99 }
100 else
101 cout << Verbose(5) << *endpoints[i]
102 << " has still lines it's attached to." << endl;
103 }
104}
105;
106
107void
108BoundaryLineSet::AddTriangle(class BoundaryTriangleSet *triangle)
109{
110 cout << Verbose(6) << "Add " << triangle->Nr << " to line " << *this << "."
111 << endl;
112 triangles.insert(TrianglePair(TrianglesCount, triangle));
113 TrianglesCount++;
114}
115;
116
117ostream &
118operator <<(ostream &ost, BoundaryLineSet &a)
119{
120 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << ","
121 << a.endpoints[1]->node->Name << "]";
122 return ost;
123}
124;
125
126// ======================================== Triangles on Boundary =================================
127
128
129BoundaryTriangleSet::BoundaryTriangleSet()
130{
131 for (int i = 0; i < 3; i++)
132 {
133 endpoints[i] = NULL;
134 lines[i] = NULL;
135 }
136 Nr = -1;
137}
138;
139
140BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet *line[3],
141 int number)
142{
143 // set number
144 Nr = number;
145 // set lines
146 cout << Verbose(5) << "New triangle " << Nr << ":" << endl;
147 for (int i = 0; i < 3; i++)
148 {
149 lines[i] = line[i];
150 lines[i]->AddTriangle(this);
151 }
152 // get ascending order of endpoints
153 map<int, class BoundaryPointSet *> OrderMap;
154 for (int i = 0; i < 3; i++)
155 // for all three lines
156 for (int j = 0; j < 2; j++)
157 { // for both endpoints
158 OrderMap.insert(pair<int, class BoundaryPointSet *> (
159 line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
160 // and we don't care whether insertion fails
161 }
162 // set endpoints
163 int Counter = 0;
164 cout << Verbose(6) << " with end points ";
165 for (map<int, class BoundaryPointSet *>::iterator runner = OrderMap.begin(); runner
166 != OrderMap.end(); runner++)
167 {
168 endpoints[Counter] = runner->second;
169 cout << " " << *endpoints[Counter];
170 Counter++;
171 }
172 if (Counter < 3)
173 {
174 cerr << "ERROR! We have a triangle with only two distinct endpoints!"
175 << endl;
176 //exit(1);
177 }
178 cout << "." << endl;
179}
180;
181
182BoundaryTriangleSet::~BoundaryTriangleSet()
183{
184 for (int i = 0; i < 3; i++)
185 {
186 cout << Verbose(5) << "Erasing triangle Nr." << Nr << endl;
187 lines[i]->triangles.erase(Nr);
188 TriangleMap::iterator tester = lines[i]->triangles.begin();
189 tester++;
190 if (tester == lines[i]->triangles.end())
191 {
192 cout << Verbose(5) << *lines[i]
193 << " is no more attached to any triangle, erasing." << endl;
194 delete (lines[i]);
195 }
196 else
197 cout << Verbose(5) << *lines[i] << " is still attached to a triangle."
198 << endl;
199 }
200}
201;
202
203void
204BoundaryTriangleSet::GetNormalVector(Vector &OtherVector)
205{
206 // get normal vector
207 NormalVector.MakeNormalVector(&endpoints[0]->node->x, &endpoints[1]->node->x,
208 &endpoints[2]->node->x);
209
210 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
211 if (endpoints[0]->node->x.Projection(&OtherVector) > 0)
212 NormalVector.Scale(-1.);
213}
214;
215
216ostream &
217operator <<(ostream &ost, BoundaryTriangleSet &a)
218{
219 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << ","
220 << a.endpoints[1]->node->Name << "," << a.endpoints[2]->node->Name << "]";
221 return ost;
222}
223;
224
225// ========================================== F U N C T I O N S =================================
226
227/** Finds the endpoint two lines are sharing.
228 * \param *line1 first line
229 * \param *line2 second line
230 * \return point which is shared or NULL if none
231 */
232class BoundaryPointSet *
233GetCommonEndpoint(class BoundaryLineSet * line1, class BoundaryLineSet * line2)
234{
235 class BoundaryLineSet * lines[2] =
236 { line1, line2 };
237 class BoundaryPointSet *node = NULL;
238 map<int, class BoundaryPointSet *> OrderMap;
239 pair<map<int, class BoundaryPointSet *>::iterator, bool> OrderTest;
240 for (int i = 0; i < 2; i++)
241 // for both lines
242 for (int j = 0; j < 2; j++)
243 { // for both endpoints
244 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
245 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
246 if (!OrderTest.second)
247 { // if insertion fails, we have common endpoint
248 node = OrderTest.first->second;
249 cout << Verbose(5) << "Common endpoint of lines " << *line1
250 << " and " << *line2 << " is: " << *node << "." << endl;
251 j = 2;
252 i = 2;
253 break;
254 }
255 }
256 return node;
257}
258;
259
260/** Determines the boundary points of a cluster.
261 * Does a projection per axis onto the orthogonal plane, transforms into spherical coordinates, sorts them by the angle
262 * and looks at triples: if the middle has less a distance than the allowed maximum height of the triangle formed by the plane's
263 * center and first and last point in the triple, it is thrown out.
264 * \param *out output stream for debugging
265 * \param *mol molecule structure representing the cluster
266 */
267Boundaries *
268GetBoundaryPoints(ofstream *out, molecule *mol)
269{
270 atom *Walker = NULL;
271 PointMap PointsOnBoundary;
272 LineMap LinesOnBoundary;
273 TriangleMap TrianglesOnBoundary;
274
275 *out << Verbose(1) << "Finding all boundary points." << endl;
276 Boundaries *BoundaryPoints = new Boundaries[NDIM]; // first is alpha, second is (r, nr)
277 BoundariesTestPair BoundaryTestPair;
278 Vector AxisVector, AngleReferenceVector, AngleReferenceNormalVector;
279 double radius, angle;
280 // 3a. Go through every axis
281 for (int axis = 0; axis < NDIM; axis++)
282 {
283 AxisVector.Zero();
284 AngleReferenceVector.Zero();
285 AngleReferenceNormalVector.Zero();
286 AxisVector.x[axis] = 1.;
287 AngleReferenceVector.x[(axis + 1) % NDIM] = 1.;
288 AngleReferenceNormalVector.x[(axis + 2) % NDIM] = 1.;
289 // *out << Verbose(1) << "Axisvector is ";
290 // AxisVector.Output(out);
291 // *out << " and AngleReferenceVector is ";
292 // AngleReferenceVector.Output(out);
293 // *out << "." << endl;
294 // *out << " and AngleReferenceNormalVector is ";
295 // AngleReferenceNormalVector.Output(out);
296 // *out << "." << endl;
297 // 3b. construct set of all points, transformed into cylindrical system and with left and right neighbours
298 Walker = mol->start;
299 while (Walker->next != mol->end)
300 {
301 Walker = Walker->next;
302 Vector ProjectedVector;
303 ProjectedVector.CopyVector(&Walker->x);
304 ProjectedVector.ProjectOntoPlane(&AxisVector);
305 // correct for negative side
306 //if (Projection(y) < 0)
307 //angle = 2.*M_PI - angle;
308 radius = ProjectedVector.Norm();
309 if (fabs(radius) > MYEPSILON)
310 angle = ProjectedVector.Angle(&AngleReferenceVector);
311 else
312 angle = 0.; // otherwise it's a vector in Axis Direction and unimportant for boundary issues
313
314 //*out << "Checking sign in quadrant : " << ProjectedVector.Projection(&AngleReferenceNormalVector) << "." << endl;
315 if (ProjectedVector.Projection(&AngleReferenceNormalVector) > 0)
316 {
317 angle = 2. * M_PI - angle;
318 }
319 //*out << Verbose(2) << "Inserting " << *Walker << ": (r, alpha) = (" << radius << "," << angle << "): ";
320 //ProjectedVector.Output(out);
321 //*out << endl;
322 BoundaryTestPair = BoundaryPoints[axis].insert(BoundariesPair(angle,
323 DistancePair (radius, Walker)));
324 if (BoundaryTestPair.second)
325 { // successfully inserted
326 }
327 else
328 { // same point exists, check first r, then distance of original vectors to center of gravity
329 *out << Verbose(2)
330 << "Encountered two vectors whose projection onto axis "
331 << axis << " is equal: " << endl;
332 *out << Verbose(2) << "Present vector: ";
333 BoundaryTestPair.first->second.second->x.Output(out);
334 *out << endl;
335 *out << Verbose(2) << "New vector: ";
336 Walker->x.Output(out);
337 *out << endl;
338 double tmp = ProjectedVector.Norm();
339 if (tmp > BoundaryTestPair.first->second.first)
340 {
341 BoundaryTestPair.first->second.first = tmp;
342 BoundaryTestPair.first->second.second = Walker;
343 *out << Verbose(2) << "Keeping new vector." << endl;
344 }
345 else if (tmp == BoundaryTestPair.first->second.first)
346 {
347 if (BoundaryTestPair.first->second.second->x.ScalarProduct(
348 &BoundaryTestPair.first->second.second->x)
349 < Walker->x.ScalarProduct(&Walker->x))
350 { // Norm() does a sqrt, which makes it a lot slower
351 BoundaryTestPair.first->second.second = Walker;
352 *out << Verbose(2) << "Keeping new vector." << endl;
353 }
354 else
355 {
356 *out << Verbose(2) << "Keeping present vector." << endl;
357 }
358 }
359 else
360 {
361 *out << Verbose(2) << "Keeping present vector." << endl;
362 }
363 }
364 }
365 // printing all inserted for debugging
366 // {
367 // *out << Verbose(2) << "Printing list of candidates for axis " << axis << " which we have inserted so far." << endl;
368 // int i=0;
369 // for(Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
370 // if (runner != BoundaryPoints[axis].begin())
371 // *out << ", " << i << ": " << *runner->second.second;
372 // else
373 // *out << i << ": " << *runner->second.second;
374 // i++;
375 // }
376 // *out << endl;
377 // }
378 // 3c. throw out points whose distance is less than the mean of left and right neighbours
379 bool flag = false;
380 do
381 { // do as long as we still throw one out per round
382 *out << Verbose(1)
383 << "Looking for candidates to kick out by convex condition ... "
384 << endl;
385 flag = false;
386 Boundaries::iterator left = BoundaryPoints[axis].end();
387 Boundaries::iterator right = BoundaryPoints[axis].end();
388 for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner
389 != BoundaryPoints[axis].end(); runner++)
390 {
391 // set neighbours correctly
392 if (runner == BoundaryPoints[axis].begin())
393 {
394 left = BoundaryPoints[axis].end();
395 }
396 else
397 {
398 left = runner;
399 }
400 left--;
401 right = runner;
402 right++;
403 if (right == BoundaryPoints[axis].end())
404 {
405 right = BoundaryPoints[axis].begin();
406 }
407 // check distance
408
409 // construct the vector of each side of the triangle on the projected plane (defined by normal vector AxisVector)
410 {
411 Vector SideA, SideB, SideC, SideH;
412 SideA.CopyVector(&left->second.second->x);
413 SideA.ProjectOntoPlane(&AxisVector);
414 // *out << "SideA: ";
415 // SideA.Output(out);
416 // *out << endl;
417
418 SideB.CopyVector(&right->second.second->x);
419 SideB.ProjectOntoPlane(&AxisVector);
420 // *out << "SideB: ";
421 // SideB.Output(out);
422 // *out << endl;
423
424 SideC.CopyVector(&left->second.second->x);
425 SideC.SubtractVector(&right->second.second->x);
426 SideC.ProjectOntoPlane(&AxisVector);
427 // *out << "SideC: ";
428 // SideC.Output(out);
429 // *out << endl;
430
431 SideH.CopyVector(&runner->second.second->x);
432 SideH.ProjectOntoPlane(&AxisVector);
433 // *out << "SideH: ";
434 // SideH.Output(out);
435 // *out << endl;
436
437 // calculate each length
438 double a = SideA.Norm();
439 //double b = SideB.Norm();
440 //double c = SideC.Norm();
441 double h = SideH.Norm();
442 // calculate the angles
443 double alpha = SideA.Angle(&SideH);
444 double beta = SideA.Angle(&SideC);
445 double gamma = SideB.Angle(&SideH);
446 double delta = SideC.Angle(&SideH);
447 double MinDistance = a * sin(beta) / (sin(delta)) * (((alpha
448 < M_PI / 2.) || (gamma < M_PI / 2.)) ? 1. : -1.);
449 // *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;
450 //*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;
451 if ((fabs(h / fabs(h) - MinDistance / fabs(MinDistance))
452 < MYEPSILON) && (h < MinDistance))
453 {
454 // throw out point
455 //*out << Verbose(1) << "Throwing out " << *runner->second.second << "." << endl;
456 BoundaryPoints[axis].erase(runner);
457 flag = true;
458 }
459 }
460 }
461 }
462 while (flag);
463 }
464 return BoundaryPoints;
465}
466;
467
468/** Determines greatest diameters of a cluster defined by its convex envelope.
469 * Looks at lines parallel to one axis and where they intersect on the projected planes
470 * \param *out output stream for debugging
471 * \param *BoundaryPoints NDIM set of boundary points defining the convex envelope on each projected plane
472 * \param *mol molecule structure representing the cluster
473 * \param IsAngstroem whether we have angstroem or atomic units
474 * \return NDIM array of the diameters
475 */
476double *
477GetDiametersOfCluster(ofstream *out, Boundaries *BoundaryPtr, molecule *mol,
478 bool IsAngstroem)
479{
480 // get points on boundary of NULL was given as parameter
481 bool BoundaryFreeFlag = false;
482 Boundaries *BoundaryPoints = BoundaryPtr;
483 if (BoundaryPoints == NULL)
484 {
485 BoundaryFreeFlag = true;
486 BoundaryPoints = GetBoundaryPoints(out, mol);
487 }
488 else
489 {
490 *out << Verbose(1) << "Using given boundary points set." << endl;
491 }
492 // determine biggest "diameter" of cluster for each axis
493 Boundaries::iterator Neighbour, OtherNeighbour;
494 double *GreatestDiameter = new double[NDIM];
495 for (int i = 0; i < NDIM; i++)
496 GreatestDiameter[i] = 0.;
497 double OldComponent, tmp, w1, w2;
498 Vector DistanceVector, OtherVector;
499 int component, Othercomponent;
500 for (int axis = 0; axis < NDIM; axis++)
501 { // regard each projected plane
502 //*out << Verbose(1) << "Current axis is " << axis << "." << endl;
503 for (int j = 0; j < 2; j++)
504 { // and for both axis on the current plane
505 component = (axis + j + 1) % NDIM;
506 Othercomponent = (axis + 1 + ((j + 1) & 1)) % NDIM;
507 //*out << Verbose(1) << "Current component is " << component << ", Othercomponent is " << Othercomponent << "." << endl;
508 for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner
509 != BoundaryPoints[axis].end(); runner++)
510 {
511 //*out << Verbose(2) << "Current runner is " << *(runner->second.second) << "." << endl;
512 // seek for the neighbours pair where the Othercomponent sign flips
513 Neighbour = runner;
514 Neighbour++;
515 if (Neighbour == BoundaryPoints[axis].end()) // make it wrap around
516 Neighbour = BoundaryPoints[axis].begin();
517 DistanceVector.CopyVector(&runner->second.second->x);
518 DistanceVector.SubtractVector(&Neighbour->second.second->x);
519 do
520 { // seek for neighbour pair where it flips
521 OldComponent = DistanceVector.x[Othercomponent];
522 Neighbour++;
523 if (Neighbour == BoundaryPoints[axis].end()) // make it wrap around
524 Neighbour = BoundaryPoints[axis].begin();
525 DistanceVector.CopyVector(&runner->second.second->x);
526 DistanceVector.SubtractVector(&Neighbour->second.second->x);
527 //*out << Verbose(3) << "OldComponent is " << OldComponent << ", new one is " << DistanceVector.x[Othercomponent] << "." << endl;
528 }
529 while ((runner != Neighbour) && (fabs(OldComponent / fabs(
530 OldComponent) - DistanceVector.x[Othercomponent] / fabs(
531 DistanceVector.x[Othercomponent])) < MYEPSILON)); // as long as sign does not flip
532 if (runner != Neighbour)
533 {
534 OtherNeighbour = Neighbour;
535 if (OtherNeighbour == BoundaryPoints[axis].begin()) // make it wrap around
536 OtherNeighbour = BoundaryPoints[axis].end();
537 OtherNeighbour--;
538 //*out << Verbose(2) << "The pair, where the sign of OtherComponent flips, is: " << *(Neighbour->second.second) << " and " << *(OtherNeighbour->second.second) << "." << endl;
539 // now we have found the pair: Neighbour and OtherNeighbour
540 OtherVector.CopyVector(&runner->second.second->x);
541 OtherVector.SubtractVector(&OtherNeighbour->second.second->x);
542 //*out << Verbose(2) << "Distances to Neighbour and OtherNeighbour are " << DistanceVector.x[component] << " and " << OtherVector.x[component] << "." << endl;
543 //*out << Verbose(2) << "OtherComponents to Neighbour and OtherNeighbour are " << DistanceVector.x[Othercomponent] << " and " << OtherVector.x[Othercomponent] << "." << endl;
544 // do linear interpolation between points (is exact) to extract exact intersection between Neighbour and OtherNeighbour
545 w1 = fabs(OtherVector.x[Othercomponent]);
546 w2 = fabs(DistanceVector.x[Othercomponent]);
547 tmp = fabs((w1 * DistanceVector.x[component] + w2
548 * OtherVector.x[component]) / (w1 + w2));
549 // mark if it has greater diameter
550 //*out << Verbose(2) << "Comparing current greatest " << GreatestDiameter[component] << " to new " << tmp << "." << endl;
551 GreatestDiameter[component] = (GreatestDiameter[component]
552 > tmp) ? GreatestDiameter[component] : tmp;
553 } //else
554 //*out << Verbose(2) << "Saw no sign flip, probably top or bottom node." << endl;
555 }
556 }
557 }
558 *out << Verbose(0) << "RESULT: The biggest diameters are "
559 << GreatestDiameter[0] << " and " << GreatestDiameter[1] << " and "
560 << GreatestDiameter[2] << " " << (IsAngstroem ? "angstrom"
561 : "atomiclength") << "." << endl;
562
563 // free reference lists
564 if (BoundaryFreeFlag)
565 delete[] (BoundaryPoints);
566
567 return GreatestDiameter;
568}
569;
570
571/** Creates the objects in a raster3d file (renderable with a header.r3d)
572 * \param *out output stream for debugging
573 * \param *tecplot output stream for tecplot data
574 * \param *Tess Tesselation structure with constructed triangles
575 * \param *mol molecule structure with atom positions
576 */
577void write_raster3d_file(ofstream *out, ofstream *rasterfile, class Tesselation *Tess, class molecule *mol)
578{
579 atom *Walker = mol->start;
580 bond *Binder = mol->first;
581 int i;
582 Vector *center = mol->DetermineCenterOfAll(out);
583 if (rasterfile != NULL) {
584 //cout << Verbose(1) << "Writing Raster3D file ... ";
585 *rasterfile << "# Raster3D object description, created by MoleCuilder" << endl;
586 *rasterfile << "@header.r3d" << endl;
587 *rasterfile << "# All atoms as spheres" << endl;
588 while (Walker->next != mol->end) {
589 Walker = Walker->next;
590 *rasterfile << "2" << endl << " "; // 2 is sphere type
591 for (i=0;i<NDIM;i++)
592 *rasterfile << Walker->x.x[i]+center->x[i] << " ";
593 *rasterfile << "\t0.1\t1. 1. 1." << endl; // radius 0.05 and white as colour
594 }
595
596 *rasterfile << "# All bonds as vertices" << endl;
597 while (Binder->next != mol->last) {
598 Binder = Binder->next;
599 *rasterfile << "3" << endl << " "; // 2 is round-ended cylinder type
600 for (i=0;i<NDIM;i++)
601 *rasterfile << Binder->leftatom->x.x[i]+center->x[i] << " ";
602 *rasterfile << "\t0.03\t";
603 for (i=0;i<NDIM;i++)
604 *rasterfile << Binder->rightatom->x.x[i]+center->x[i] << " ";
605 *rasterfile << "\t0.03\t0. 0. 1." << endl; // radius 0.05 and blue as colour
606 }
607
608 *rasterfile << "# All tesselation triangles" << endl;
609 for (TriangleMap::iterator TriangleRunner = Tess->TrianglesOnBoundary.begin(); TriangleRunner != Tess->TrianglesOnBoundary.end(); TriangleRunner++) {
610 *rasterfile << "1" << endl << " "; // 1 is triangle type
611 for (i=0;i<3;i++) { // print each node
612 for (int j=0;j<NDIM;j++) // and for each node all NDIM coordinates
613 *rasterfile << TriangleRunner->second->endpoints[i]->node->x.x[j]+center->x[j] << " ";
614 *rasterfile << "\t";
615 }
616 *rasterfile << "1. 0. 0." << endl; // red as colour
617 *rasterfile << "18" << endl << " 0.5 0.5 0.5" << endl; // 18 is transparency type for previous object
618 }
619 } else {
620 cerr << "ERROR: Given rasterfile is " << rasterfile << "." << endl;
621 }
622 delete(center);
623};
624
625/*
626 * This function creates the tecplot file, displaying the tesselation of the hull.
627 * \param *out output stream for debugging
628 * \param *tecplot output stream for tecplot data
629 * \param N arbitrary number to differentiate various zones in the tecplot format
630 */
631void
632write_tecplot_file(ofstream *out, ofstream *tecplot,
633 class Tesselation *TesselStruct, class molecule *mol, int N)
634{
635 if (tecplot != NULL)
636 {
637 *tecplot << "TITLE = \"3D CONVEX SHELL\"" << endl;
638 *tecplot << "VARIABLES = \"X\" \"Y\" \"Z\"" << endl;
639 *tecplot << "ZONE T=\"TRIANGLES" << N << "\", N="
640 << TesselStruct->PointsOnBoundaryCount << ", E="
641 << TesselStruct->TrianglesOnBoundaryCount
642 << ", DATAPACKING=POINT, ZONETYPE=FETRIANGLE" << endl;
643 int *LookupList = new int[mol->AtomCount];
644 for (int i = 0; i < mol->AtomCount; i++)
645 LookupList[i] = -1;
646
647 // print atom coordinates
648 *out << Verbose(2) << "The following triangles were created:";
649 int Counter = 1;
650 atom *Walker = NULL;
651 for (PointMap::iterator target = TesselStruct->PointsOnBoundary.begin(); target
652 != TesselStruct->PointsOnBoundary.end(); target++)
653 {
654 Walker = target->second->node;
655 LookupList[Walker->nr] = Counter++;
656 *tecplot << Walker->x.x[0] << " " << Walker->x.x[1] << " "
657 << Walker->x.x[2] << " " << endl;
658 }
659 *tecplot << endl;
660 // print connectivity
661 for (TriangleMap::iterator runner =
662 TesselStruct->TrianglesOnBoundary.begin(); runner
663 != TesselStruct->TrianglesOnBoundary.end(); runner++)
664 {
665 *out << " " << runner->second->endpoints[0]->node->Name << "<->"
666 << runner->second->endpoints[1]->node->Name << "<->"
667 << runner->second->endpoints[2]->node->Name;
668 *tecplot << LookupList[runner->second->endpoints[0]->node->nr] << " "
669 << LookupList[runner->second->endpoints[1]->node->nr] << " "
670 << LookupList[runner->second->endpoints[2]->node->nr] << endl;
671 }
672 delete[] (LookupList);
673 *out << endl;
674 }
675}
676
677/** Determines the volume of a cluster.
678 * Determines first the convex envelope, then tesselates it and calculates its volume.
679 * \param *out output stream for debugging
680 * \param *tecplot output stream for tecplot data
681 * \param *configuration needed for path to store convex envelope file
682 * \param *BoundaryPoints NDIM set of boundary points on the projected plane per axis, on return if desired
683 * \param *mol molecule structure representing the cluster
684 * \return determined volume of the cluster in cubed config:GetIsAngstroem()
685 */
686double
687VolumeOfConvexEnvelope(ofstream *out, ofstream *tecplot, config *configuration,
688 Boundaries *BoundaryPtr, molecule *mol)
689{
690 bool IsAngstroem = configuration->GetIsAngstroem();
691 atom *Walker = NULL;
692 struct Tesselation *TesselStruct = new Tesselation;
693 bool BoundaryFreeFlag = false;
694 Boundaries *BoundaryPoints = BoundaryPtr;
695 double volume = 0.;
696 double PyramidVolume = 0.;
697 double G, h;
698 Vector x, y;
699 double a, b, c;
700
701 //Find_non_convex_border(out, tecplot, *TesselStruct, mol); // Is now called from command line.
702
703 // 1. calculate center of gravity
704 *out << endl;
705 Vector *CenterOfGravity = mol->DetermineCenterOfGravity(out);
706
707 // 2. translate all points into CoG
708 *out << Verbose(1) << "Translating system to Center of Gravity." << endl;
709 Walker = mol->start;
710 while (Walker->next != mol->end)
711 {
712 Walker = Walker->next;
713 Walker->x.Translate(CenterOfGravity);
714 }
715
716 // 3. Find all points on the boundary
717 if (BoundaryPoints == NULL)
718 {
719 BoundaryFreeFlag = true;
720 BoundaryPoints = GetBoundaryPoints(out, mol);
721 }
722 else
723 {
724 *out << Verbose(1) << "Using given boundary points set." << endl;
725 }
726
727 // 4. fill the boundary point list
728 for (int axis = 0; axis < NDIM; axis++)
729 for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner
730 != BoundaryPoints[axis].end(); runner++)
731 {
732 TesselStruct->AddPoint(runner->second.second);
733 }
734
735 *out << Verbose(2) << "I found " << TesselStruct->PointsOnBoundaryCount
736 << " points on the convex boundary." << endl;
737 // now we have the whole set of edge points in the BoundaryList
738
739 // listing for debugging
740 // *out << Verbose(1) << "Listing PointsOnBoundary:";
741 // for(PointMap::iterator runner = PointsOnBoundary.begin(); runner != PointsOnBoundary.end(); runner++) {
742 // *out << " " << *runner->second;
743 // }
744 // *out << endl;
745
746 // 5a. guess starting triangle
747 TesselStruct->GuessStartingTriangle(out);
748
749 // 5b. go through all lines, that are not yet part of two triangles (only of one so far)
750 TesselStruct->TesselateOnBoundary(out, configuration, mol);
751
752 *out << Verbose(2) << "I created " << TesselStruct->TrianglesOnBoundaryCount
753 << " triangles with " << TesselStruct->LinesOnBoundaryCount
754 << " lines and " << TesselStruct->PointsOnBoundaryCount << " points."
755 << endl;
756
757 // 6a. Every triangle forms a pyramid with the center of gravity as its peak, sum up the volumes
758 *out << Verbose(1)
759 << "Calculating the volume of the pyramids formed out of triangles and center of gravity."
760 << endl;
761 for (TriangleMap::iterator runner = TesselStruct->TrianglesOnBoundary.begin(); runner
762 != TesselStruct->TrianglesOnBoundary.end(); runner++)
763 { // go through every triangle, calculate volume of its pyramid with CoG as peak
764 x.CopyVector(&runner->second->endpoints[0]->node->x);
765 x.SubtractVector(&runner->second->endpoints[1]->node->x);
766 y.CopyVector(&runner->second->endpoints[0]->node->x);
767 y.SubtractVector(&runner->second->endpoints[2]->node->x);
768 a = sqrt(runner->second->endpoints[0]->node->x.Distance(
769 &runner->second->endpoints[1]->node->x));
770 b = sqrt(runner->second->endpoints[0]->node->x.Distance(
771 &runner->second->endpoints[2]->node->x));
772 c = sqrt(runner->second->endpoints[2]->node->x.Distance(
773 &runner->second->endpoints[1]->node->x));
774 G = sqrt(((a * a + b * b + c * c) * (a * a + b * b + c * c) - 2 * (a * a
775 * a * a + b * b * b * b + c * c * c * c)) / 16.); // area of tesselated triangle
776 x.MakeNormalVector(&runner->second->endpoints[0]->node->x,
777 &runner->second->endpoints[1]->node->x,
778 &runner->second->endpoints[2]->node->x);
779 x.Scale(runner->second->endpoints[1]->node->x.Projection(&x));
780 h = x.Norm(); // distance of CoG to triangle
781 PyramidVolume = (1. / 3.) * G * h; // this formula holds for _all_ pyramids (independent of n-edge base or (not) centered peak)
782 *out << Verbose(2) << "Area of triangle is " << G << " "
783 << (IsAngstroem ? "angstrom" : "atomiclength") << "^2, height is "
784 << h << " and the volume is " << PyramidVolume << " "
785 << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
786 volume += PyramidVolume;
787 }
788 *out << Verbose(0) << "RESULT: The summed volume is " << setprecision(10)
789 << volume << " " << (IsAngstroem ? "angstrom" : "atomiclength") << "^3."
790 << endl;
791
792 // 7. translate all points back from CoG
793 *out << Verbose(1) << "Translating system back from Center of Gravity."
794 << endl;
795 CenterOfGravity->Scale(-1);
796 Walker = mol->start;
797 while (Walker->next != mol->end)
798 {
799 Walker = Walker->next;
800 Walker->x.Translate(CenterOfGravity);
801 }
802
803 // 8. Store triangles in tecplot file
804 write_tecplot_file(out, tecplot, TesselStruct, mol, 0);
805
806 // free reference lists
807 if (BoundaryFreeFlag)
808 delete[] (BoundaryPoints);
809
810 return volume;
811}
812;
813
814/** Creates multiples of the by \a *mol given cluster and suspends them in water with a given final density.
815 * We get cluster volume by VolumeOfConvexEnvelope() and its diameters by GetDiametersOfCluster()
816 * \param *out output stream for debugging
817 * \param *configuration needed for path to store convex envelope file
818 * \param *mol molecule structure representing the cluster
819 * \param ClusterVolume guesstimated cluster volume, if equal 0 we used VolumeOfConvexEnvelope() instead.
820 * \param celldensity desired average density in final cell
821 */
822void
823PrepareClustersinWater(ofstream *out, config *configuration, molecule *mol,
824 double ClusterVolume, double celldensity)
825{
826 // transform to PAS
827 mol->PrincipalAxisSystem(out, true);
828
829 // some preparations beforehand
830 bool IsAngstroem = configuration->GetIsAngstroem();
831 Boundaries *BoundaryPoints = GetBoundaryPoints(out, mol);
832 double clustervolume;
833 if (ClusterVolume == 0)
834 clustervolume = VolumeOfConvexEnvelope(out, NULL, configuration,
835 BoundaryPoints, mol);
836 else
837 clustervolume = ClusterVolume;
838 double *GreatestDiameter = GetDiametersOfCluster(out, BoundaryPoints, mol,
839 IsAngstroem);
840 Vector BoxLengths;
841 int repetition[NDIM] =
842 { 1, 1, 1 };
843 int TotalNoClusters = 1;
844 for (int i = 0; i < NDIM; i++)
845 TotalNoClusters *= repetition[i];
846
847 // sum up the atomic masses
848 double totalmass = 0.;
849 atom *Walker = mol->start;
850 while (Walker->next != mol->end)
851 {
852 Walker = Walker->next;
853 totalmass += Walker->type->mass;
854 }
855 *out << Verbose(0) << "RESULT: The summed mass is " << setprecision(10)
856 << totalmass << " atomicmassunit." << endl;
857
858 *out << Verbose(0) << "RESULT: The average density is " << setprecision(10)
859 << totalmass / clustervolume << " atomicmassunit/"
860 << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
861
862 // solve cubic polynomial
863 *out << Verbose(1) << "Solving equidistant suspension in water problem ..."
864 << endl;
865 double cellvolume;
866 if (IsAngstroem)
867 cellvolume = (TotalNoClusters * totalmass / SOLVENTDENSITY_A - (totalmass
868 / clustervolume)) / (celldensity - 1);
869 else
870 cellvolume = (TotalNoClusters * totalmass / SOLVENTDENSITY_a0 - (totalmass
871 / clustervolume)) / (celldensity - 1);
872 *out << Verbose(1) << "Cellvolume needed for a density of " << celldensity
873 << " g/cm^3 is " << cellvolume << " " << (IsAngstroem ? "angstrom"
874 : "atomiclength") << "^3." << endl;
875
876 double minimumvolume = TotalNoClusters * (GreatestDiameter[0]
877 * GreatestDiameter[1] * GreatestDiameter[2]);
878 *out << Verbose(1)
879 << "Minimum volume of the convex envelope contained in a rectangular box is "
880 << minimumvolume << " atomicmassunit/" << (IsAngstroem ? "angstrom"
881 : "atomiclength") << "^3." << endl;
882 if (minimumvolume > cellvolume)
883 {
884 cerr << Verbose(0)
885 << "ERROR: the containing box already has a greater volume than the envisaged cell volume!"
886 << endl;
887 cout << Verbose(0)
888 << "Setting Box dimensions to minimum possible, the greatest diameters."
889 << endl;
890 for (int i = 0; i < NDIM; i++)
891 BoxLengths.x[i] = GreatestDiameter[i];
892 mol->CenterEdge(out, &BoxLengths);
893 }
894 else
895 {
896 BoxLengths.x[0] = (repetition[0] * GreatestDiameter[0] + repetition[1]
897 * GreatestDiameter[1] + repetition[2] * GreatestDiameter[2]);
898 BoxLengths.x[1] = (repetition[0] * repetition[1] * GreatestDiameter[0]
899 * GreatestDiameter[1] + repetition[0] * repetition[2]
900 * GreatestDiameter[0] * GreatestDiameter[2] + repetition[1]
901 * repetition[2] * GreatestDiameter[1] * GreatestDiameter[2]);
902 BoxLengths.x[2] = minimumvolume - cellvolume;
903 double x0 = 0., x1 = 0., x2 = 0.;
904 if (gsl_poly_solve_cubic(BoxLengths.x[0], BoxLengths.x[1],
905 BoxLengths.x[2], &x0, &x1, &x2) == 1) // either 1 or 3 on return
906 *out << Verbose(0) << "RESULT: The resulting spacing is: " << x0
907 << " ." << endl;
908 else
909 {
910 *out << Verbose(0) << "RESULT: The resulting spacings are: " << x0
911 << " and " << x1 << " and " << x2 << " ." << endl;
912 x0 = x2; // sorted in ascending order
913 }
914
915 cellvolume = 1;
916 for (int i = 0; i < NDIM; i++)
917 {
918 BoxLengths.x[i] = repetition[i] * (x0 + GreatestDiameter[i]);
919 cellvolume *= BoxLengths.x[i];
920 }
921
922 // set new box dimensions
923 *out << Verbose(0) << "Translating to box with these boundaries." << endl;
924 mol->CenterInBox((ofstream *) &cout, &BoxLengths);
925 }
926 // update Box of atoms by boundary
927 mol->SetBoxDimension(&BoxLengths);
928 *out << Verbose(0) << "RESULT: The resulting cell dimensions are: "
929 << BoxLengths.x[0] << " and " << BoxLengths.x[1] << " and "
930 << BoxLengths.x[2] << " with total volume of " << cellvolume << " "
931 << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
932}
933;
934
935// =========================================================== class TESSELATION ===========================================
936
937/** Constructor of class Tesselation.
938 */
939Tesselation::Tesselation()
940{
941 PointsOnBoundaryCount = 0;
942 LinesOnBoundaryCount = 0;
943 TrianglesOnBoundaryCount = 0;
944 TriangleFilesWritten = 0;
945}
946;
947
948/** Constructor of class Tesselation.
949 * We have to free all points, lines and triangles.
950 */
951Tesselation::~Tesselation()
952{
953 cout << Verbose(1) << "Free'ing TesselStruct ... " << endl;
954 for (TriangleMap::iterator runner = TrianglesOnBoundary.begin(); runner
955 != TrianglesOnBoundary.end(); runner++)
956 {
957 delete (runner->second);
958 }
959}
960;
961
962/** Gueses first starting triangle of the convex envelope.
963 * We guess the starting triangle by taking the smallest distance between two points and looking for a fitting third.
964 * \param *out output stream for debugging
965 * \param PointsOnBoundary set of boundary points defining the convex envelope of the cluster
966 */
967void
968Tesselation::GuessStartingTriangle(ofstream *out)
969{
970 // 4b. create a starting triangle
971 // 4b1. create all distances
972 DistanceMultiMap DistanceMMap;
973 double distance, tmp;
974 Vector PlaneVector, TrialVector;
975 PointMap::iterator A, B, C; // three nodes of the first triangle
976 A = PointsOnBoundary.begin(); // the first may be chosen arbitrarily
977
978 // with A chosen, take each pair B,C and sort
979 if (A != PointsOnBoundary.end())
980 {
981 B = A;
982 B++;
983 for (; B != PointsOnBoundary.end(); B++)
984 {
985 C = B;
986 C++;
987 for (; C != PointsOnBoundary.end(); C++)
988 {
989 tmp = A->second->node->x.Distance(&B->second->node->x);
990 distance = tmp * tmp;
991 tmp = A->second->node->x.Distance(&C->second->node->x);
992 distance += tmp * tmp;
993 tmp = B->second->node->x.Distance(&C->second->node->x);
994 distance += tmp * tmp;
995 DistanceMMap.insert(DistanceMultiMapPair(distance, pair<
996 PointMap::iterator, PointMap::iterator> (B, C)));
997 }
998 }
999 }
1000 // // listing distances
1001 // *out << Verbose(1) << "Listing DistanceMMap:";
1002 // for(DistanceMultiMap::iterator runner = DistanceMMap.begin(); runner != DistanceMMap.end(); runner++) {
1003 // *out << " " << runner->first << "(" << *runner->second.first->second << ", " << *runner->second.second->second << ")";
1004 // }
1005 // *out << endl;
1006 // 4b2. pick three baselines forming a triangle
1007 // 1. we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
1008 DistanceMultiMap::iterator baseline = DistanceMMap.begin();
1009 for (; baseline != DistanceMMap.end(); baseline++)
1010 {
1011 // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
1012 // 2. next, we have to check whether all points reside on only one side of the triangle
1013 // 3. construct plane vector
1014 PlaneVector.MakeNormalVector(&A->second->node->x,
1015 &baseline->second.first->second->node->x,
1016 &baseline->second.second->second->node->x);
1017 *out << Verbose(2) << "Plane vector of candidate triangle is ";
1018 PlaneVector.Output(out);
1019 *out << endl;
1020 // 4. loop over all points
1021 double sign = 0.;
1022 PointMap::iterator checker = PointsOnBoundary.begin();
1023 for (; checker != PointsOnBoundary.end(); checker++)
1024 {
1025 // (neglecting A,B,C)
1026 if ((checker == A) || (checker == baseline->second.first) || (checker
1027 == baseline->second.second))
1028 continue;
1029 // 4a. project onto plane vector
1030 TrialVector.CopyVector(&checker->second->node->x);
1031 TrialVector.SubtractVector(&A->second->node->x);
1032 distance = TrialVector.Projection(&PlaneVector);
1033 if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
1034 continue;
1035 *out << Verbose(3) << "Projection of " << checker->second->node->Name
1036 << " yields distance of " << distance << "." << endl;
1037 tmp = distance / fabs(distance);
1038 // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
1039 if ((sign != 0) && (tmp != sign))
1040 {
1041 // 4c. If so, break 4. loop and continue with next candidate in 1. loop
1042 *out << Verbose(2) << "Current candidates: "
1043 << A->second->node->Name << ","
1044 << baseline->second.first->second->node->Name << ","
1045 << baseline->second.second->second->node->Name << " leave "
1046 << checker->second->node->Name << " outside the convex hull."
1047 << endl;
1048 break;
1049 }
1050 else
1051 { // note the sign for later
1052 *out << Verbose(2) << "Current candidates: "
1053 << A->second->node->Name << ","
1054 << baseline->second.first->second->node->Name << ","
1055 << baseline->second.second->second->node->Name << " leave "
1056 << checker->second->node->Name << " inside the convex hull."
1057 << endl;
1058 sign = tmp;
1059 }
1060 // 4d. Check whether the point is inside the triangle (check distance to each node
1061 tmp = checker->second->node->x.Distance(&A->second->node->x);
1062 int innerpoint = 0;
1063 if ((tmp < A->second->node->x.Distance(
1064 &baseline->second.first->second->node->x)) && (tmp
1065 < A->second->node->x.Distance(
1066 &baseline->second.second->second->node->x)))
1067 innerpoint++;
1068 tmp = checker->second->node->x.Distance(
1069 &baseline->second.first->second->node->x);
1070 if ((tmp < baseline->second.first->second->node->x.Distance(
1071 &A->second->node->x)) && (tmp
1072 < baseline->second.first->second->node->x.Distance(
1073 &baseline->second.second->second->node->x)))
1074 innerpoint++;
1075 tmp = checker->second->node->x.Distance(
1076 &baseline->second.second->second->node->x);
1077 if ((tmp < baseline->second.second->second->node->x.Distance(
1078 &baseline->second.first->second->node->x)) && (tmp
1079 < baseline->second.second->second->node->x.Distance(
1080 &A->second->node->x)))
1081 innerpoint++;
1082 // 4e. If so, break 4. loop and continue with next candidate in 1. loop
1083 if (innerpoint == 3)
1084 break;
1085 }
1086 // 5. come this far, all on same side? Then break 1. loop and construct triangle
1087 if (checker == PointsOnBoundary.end())
1088 {
1089 *out << "Looks like we have a candidate!" << endl;
1090 break;
1091 }
1092 }
1093 if (baseline != DistanceMMap.end())
1094 {
1095 BPS[0] = baseline->second.first->second;
1096 BPS[1] = baseline->second.second->second;
1097 BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1098 BPS[0] = A->second;
1099 BPS[1] = baseline->second.second->second;
1100 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1101 BPS[0] = baseline->second.first->second;
1102 BPS[1] = A->second;
1103 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1104
1105 // 4b3. insert created triangle
1106 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1107 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1108 TrianglesOnBoundaryCount++;
1109 for (int i = 0; i < NDIM; i++)
1110 {
1111 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
1112 LinesOnBoundaryCount++;
1113 }
1114
1115 *out << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
1116 }
1117 else
1118 {
1119 *out << Verbose(1) << "No starting triangle found." << endl;
1120 exit(255);
1121 }
1122}
1123;
1124
1125/** Tesselates the convex envelope of a cluster from a single starting triangle.
1126 * The starting triangle is made out of three baselines. Each line in the final tesselated cluster may belong to at most
1127 * 2 triangles. Hence, we go through all current lines:
1128 * -# if the lines contains to only one triangle
1129 * -# We search all points in the boundary
1130 * -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors
1131 * -# if the triangle is in forward direction of the baseline (at most 90 degrees angle between vector orthogonal to
1132 * baseline in triangle plane pointing out of the triangle and normal vector of new triangle)
1133 * -# then we have a new triangle, whose baselines we again add (or increase their TriangleCount)
1134 * \param *out output stream for debugging
1135 * \param *configuration for IsAngstroem
1136 * \param *mol the cluster as a molecule structure
1137 */
1138void
1139Tesselation::TesselateOnBoundary(ofstream *out, config *configuration,
1140 molecule *mol)
1141{
1142 bool flag;
1143 PointMap::iterator winner;
1144 class BoundaryPointSet *peak = NULL;
1145 double SmallestAngle, TempAngle;
1146 Vector NormalVector, VirtualNormalVector, CenterVector, TempVector,
1147 PropagationVector;
1148 LineMap::iterator LineChecker[2];
1149 do
1150 {
1151 flag = false;
1152 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline
1153 != LinesOnBoundary.end(); baseline++)
1154 if (baseline->second->TrianglesCount == 1)
1155 {
1156 *out << Verbose(2) << "Current baseline is between "
1157 << *(baseline->second) << "." << endl;
1158 // 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)
1159 SmallestAngle = M_PI;
1160 BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
1161 // get peak point with respect to this base line's only triangle
1162 for (int i = 0; i < 3; i++)
1163 if ((BTS->endpoints[i] != baseline->second->endpoints[0])
1164 && (BTS->endpoints[i] != baseline->second->endpoints[1]))
1165 peak = BTS->endpoints[i];
1166 *out << Verbose(3) << " and has peak " << *peak << "." << endl;
1167 // normal vector of triangle
1168 BTS->GetNormalVector(NormalVector);
1169 *out << Verbose(4) << "NormalVector of base triangle is ";
1170 NormalVector.Output(out);
1171 *out << endl;
1172 // offset to center of triangle
1173 CenterVector.Zero();
1174 for (int i = 0; i < 3; i++)
1175 CenterVector.AddVector(&BTS->endpoints[i]->node->x);
1176 CenterVector.Scale(1. / 3.);
1177 *out << Verbose(4) << "CenterVector of base triangle is ";
1178 CenterVector.Output(out);
1179 *out << endl;
1180 // vector in propagation direction (out of triangle)
1181 // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
1182 TempVector.CopyVector(&baseline->second->endpoints[0]->node->x);
1183 TempVector.SubtractVector(&baseline->second->endpoints[1]->node->x);
1184 PropagationVector.MakeNormalVector(&TempVector, &NormalVector);
1185 TempVector.CopyVector(&CenterVector);
1186 TempVector.SubtractVector(&baseline->second->endpoints[0]->node->x); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
1187 //*out << Verbose(2) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
1188 if (PropagationVector.Projection(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
1189 PropagationVector.Scale(-1.);
1190 *out << Verbose(4) << "PropagationVector of base triangle is ";
1191 PropagationVector.Output(out);
1192 *out << endl;
1193 winner = PointsOnBoundary.end();
1194 for (PointMap::iterator target = PointsOnBoundary.begin(); target
1195 != PointsOnBoundary.end(); target++)
1196 if ((target->second != baseline->second->endpoints[0])
1197 && (target->second != baseline->second->endpoints[1]))
1198 { // don't take the same endpoints
1199 *out << Verbose(3) << "Target point is " << *(target->second)
1200 << ":";
1201 bool continueflag = true;
1202
1203 VirtualNormalVector.CopyVector(
1204 &baseline->second->endpoints[0]->node->x);
1205 VirtualNormalVector.AddVector(
1206 &baseline->second->endpoints[0]->node->x);
1207 VirtualNormalVector.Scale(-1. / 2.); // points now to center of base line
1208 VirtualNormalVector.AddVector(&target->second->node->x); // points from center of base line to target
1209 TempAngle = VirtualNormalVector.Angle(&PropagationVector);
1210 continueflag = continueflag && (TempAngle < (M_PI/2.)); // no bends bigger than Pi/2 (90 degrees)
1211 if (!continueflag)
1212 {
1213 *out << Verbose(4)
1214 << "Angle between propagation direction and base line to "
1215 << *(target->second) << " is " << TempAngle
1216 << ", bad direction!" << endl;
1217 continue;
1218 }
1219 else
1220 *out << Verbose(4)
1221 << "Angle between propagation direction and base line to "
1222 << *(target->second) << " is " << TempAngle
1223 << ", good direction!" << endl;
1224 LineChecker[0] = baseline->second->endpoints[0]->lines.find(
1225 target->first);
1226 LineChecker[1] = baseline->second->endpoints[1]->lines.find(
1227 target->first);
1228 // if (LineChecker[0] != baseline->second->endpoints[0]->lines.end())
1229 // *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->TrianglesCount << " triangles." << endl;
1230 // else
1231 // *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has no line to " << *(target->second) << " as endpoint." << endl;
1232 // if (LineChecker[1] != baseline->second->endpoints[1]->lines.end())
1233 // *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->TrianglesCount << " triangles." << endl;
1234 // else
1235 // *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has no line to " << *(target->second) << " as endpoint." << endl;
1236 // check first endpoint (if any connecting line goes to target or at least not more than 1)
1237 continueflag = continueflag && (((LineChecker[0]
1238 == baseline->second->endpoints[0]->lines.end())
1239 || (LineChecker[0]->second->TrianglesCount == 1)));
1240 if (!continueflag)
1241 {
1242 *out << Verbose(4) << *(baseline->second->endpoints[0])
1243 << " has line " << *(LineChecker[0]->second)
1244 << " to " << *(target->second)
1245 << " as endpoint with "
1246 << LineChecker[0]->second->TrianglesCount
1247 << " triangles." << endl;
1248 continue;
1249 }
1250 // check second endpoint (if any connecting line goes to target or at least not more than 1)
1251 continueflag = continueflag && (((LineChecker[1]
1252 == baseline->second->endpoints[1]->lines.end())
1253 || (LineChecker[1]->second->TrianglesCount == 1)));
1254 if (!continueflag)
1255 {
1256 *out << Verbose(4) << *(baseline->second->endpoints[1])
1257 << " has line " << *(LineChecker[1]->second)
1258 << " to " << *(target->second)
1259 << " as endpoint with "
1260 << LineChecker[1]->second->TrianglesCount
1261 << " triangles." << endl;
1262 continue;
1263 }
1264 // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
1265 continueflag = continueflag && (!(((LineChecker[0]
1266 != baseline->second->endpoints[0]->lines.end())
1267 && (LineChecker[1]
1268 != baseline->second->endpoints[1]->lines.end())
1269 && (GetCommonEndpoint(LineChecker[0]->second,
1270 LineChecker[1]->second) == peak))));
1271 if (!continueflag)
1272 {
1273 *out << Verbose(4) << "Current target is peak!" << endl;
1274 continue;
1275 }
1276 // in case NOT both were found
1277 if (continueflag)
1278 { // create virtually this triangle, get its normal vector, calculate angle
1279 flag = true;
1280 VirtualNormalVector.MakeNormalVector(
1281 &baseline->second->endpoints[0]->node->x,
1282 &baseline->second->endpoints[1]->node->x,
1283 &target->second->node->x);
1284 // make it always point inward
1285 if (baseline->second->endpoints[0]->node->x.Projection(
1286 &VirtualNormalVector) > 0)
1287 VirtualNormalVector.Scale(-1.);
1288 // calculate angle
1289 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1290 *out << Verbose(4) << "NormalVector is ";
1291 VirtualNormalVector.Output(out);
1292 *out << " and the angle is " << TempAngle << "." << endl;
1293 if (SmallestAngle > TempAngle)
1294 { // set to new possible winner
1295 SmallestAngle = TempAngle;
1296 winner = target;
1297 }
1298 }
1299 }
1300 // 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
1301 if (winner != PointsOnBoundary.end())
1302 {
1303 *out << Verbose(2) << "Winning target point is "
1304 << *(winner->second) << " with angle " << SmallestAngle
1305 << "." << endl;
1306 // create the lins of not yet present
1307 BLS[0] = baseline->second;
1308 // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
1309 LineChecker[0] = baseline->second->endpoints[0]->lines.find(
1310 winner->first);
1311 LineChecker[1] = baseline->second->endpoints[1]->lines.find(
1312 winner->first);
1313 if (LineChecker[0]
1314 == baseline->second->endpoints[0]->lines.end())
1315 { // create
1316 BPS[0] = baseline->second->endpoints[0];
1317 BPS[1] = winner->second;
1318 BLS[1] = new class BoundaryLineSet(BPS,
1319 LinesOnBoundaryCount);
1320 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount,
1321 BLS[1]));
1322 LinesOnBoundaryCount++;
1323 }
1324 else
1325 BLS[1] = LineChecker[0]->second;
1326 if (LineChecker[1]
1327 == baseline->second->endpoints[1]->lines.end())
1328 { // create
1329 BPS[0] = baseline->second->endpoints[1];
1330 BPS[1] = winner->second;
1331 BLS[2] = new class BoundaryLineSet(BPS,
1332 LinesOnBoundaryCount);
1333 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount,
1334 BLS[2]));
1335 LinesOnBoundaryCount++;
1336 }
1337 else
1338 BLS[2] = LineChecker[1]->second;
1339 BTS = new class BoundaryTriangleSet(BLS,
1340 TrianglesOnBoundaryCount);
1341 TrianglesOnBoundary.insert(TrianglePair(
1342 TrianglesOnBoundaryCount, BTS));
1343 TrianglesOnBoundaryCount++;
1344 }
1345 else
1346 {
1347 *out << Verbose(1)
1348 << "I could not determine a winner for this baseline "
1349 << *(baseline->second) << "." << endl;
1350 }
1351
1352 // 5d. If the set of lines is not yet empty, go to 5. and continue
1353 }
1354 else
1355 *out << Verbose(2) << "Baseline candidate " << *(baseline->second)
1356 << " has a triangle count of "
1357 << baseline->second->TrianglesCount << "." << endl;
1358 }
1359 while (flag);
1360
1361}
1362;
1363
1364/** Adds an atom to the tesselation::PointsOnBoundary list.
1365 * \param *Walker atom to add
1366 */
1367void
1368Tesselation::AddPoint(atom *Walker)
1369{
1370 PointTestPair InsertUnique;
1371 BPS[0] = new class BoundaryPointSet(Walker);
1372 InsertUnique = PointsOnBoundary.insert(PointPair(Walker->nr, BPS[0]));
1373 if (InsertUnique.second) // if new point was not present before, increase counter
1374 PointsOnBoundaryCount++;
1375}
1376;
1377
1378/** Adds point to Tesselation::PointsOnBoundary if not yet present.
1379 * Tesselation::TPS is set to either this new BoundaryPointSet or to the existing one of not unique.
1380 * @param Candidate point to add
1381 * @param n index for this point in Tesselation::TPS array
1382 */
1383void
1384Tesselation::AddTrianglePoint(atom* Candidate, int n)
1385{
1386 PointTestPair InsertUnique;
1387 TPS[n] = new class BoundaryPointSet(Candidate);
1388 InsertUnique = PointsOnBoundary.insert(PointPair(Candidate->nr, TPS[n]));
1389 if (InsertUnique.second) // if new point was not present before, increase counter
1390 {
1391 PointsOnBoundaryCount++;
1392 }
1393 else
1394 {
1395 delete TPS[n];
1396 cout << Verbose(2) << "Atom " << *((InsertUnique.first)->second->node)
1397 << " gibt's schon in der PointMap." << endl;
1398 TPS[n] = (InsertUnique.first)->second;
1399 }
1400}
1401;
1402
1403/** Function tries to add line from current Points in BPS to BoundaryLineSet.
1404 * If succesful it raises the line count and inserts the new line into the BLS,
1405 * if unsuccesful, it writes the line which had been present into the BLS, deleting the new constructed one.
1406 * @param *a first endpoint
1407 * @param *b second endpoint
1408 * @param n index of Tesselation::BLS giving the line with both endpoints
1409 */
1410void
1411Tesselation::AddTriangleLine(class BoundaryPointSet *a,
1412 class BoundaryPointSet *b, int n)
1413{
1414 LineMap::iterator LineWalker;
1415 //cout << "Manually checking endpoints for line." << endl;
1416 if ((a->lines.find(b->node->nr)) != a->lines.end()) // ->first == b->node->nr)
1417 //If a line is there, how do I recognize that beyond a shadow of a doubt?
1418 {
1419 //cout << Verbose(2) << "Line exists already, retrieving it from LinesOnBoundarySet" << endl;
1420
1421 LineWalker = LinesOnBoundary.end();
1422 LineWalker--;
1423
1424 while (LineWalker->second->endpoints[0]->node->nr != min(a->node->nr,
1425 b->node->nr) or LineWalker->second->endpoints[1]->node->nr != max(
1426 a->node->nr, b->node->nr))
1427 {
1428 //cout << Verbose(1) << "Looking for line which already exists"<< endl;
1429 LineWalker--;
1430 }
1431 BPS[0] = LineWalker->second->endpoints[0];
1432 BPS[1] = LineWalker->second->endpoints[1];
1433 BLS[n] = LineWalker->second;
1434
1435 }
1436 else
1437 {
1438 cout << Verbose(2)
1439 << "Adding line which has not been used before between "
1440 << *(a->node) << " and " << *(b->node) << "." << endl;
1441 BPS[0] = a;
1442 BPS[1] = b;
1443 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1444
1445 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1446 LinesOnBoundaryCount++;
1447
1448 }
1449}
1450;
1451
1452/** Function tries to add Triangle just created to Triangle and remarks if already existent (Failure of algorithm).
1453 * Furthermore it adds the triangle to all of its lines, in order to recognize those which are saturated later.
1454 */
1455void
1456Tesselation::AddTriangleToLines()
1457{
1458
1459 cout << Verbose(1) << "Adding triangle to its lines" << endl;
1460 int i = 0;
1461 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1462 TrianglesOnBoundaryCount++;
1463
1464 /*
1465 * this is apparently done when constructing triangle
1466
1467 for (i=0; i<3; i++)
1468 {
1469 BLS[i]->AddTriangle(BTS);
1470 }
1471 */
1472}
1473;
1474
1475/**
1476 * Function returns center of sphere with RADIUS, which rests on points a, b, c
1477 * @param Center this vector will be used for return
1478 * @param a vector first point of triangle
1479 * @param b vector second point of triangle
1480 * @param c vector third point of triangle
1481 * @param *Umkreismittelpunkt new cneter point of circumference
1482 * @param Direction vector indicates up/down
1483 * @param AlternativeDirection vecotr, needed in case the triangles have 90 deg angle
1484 * @param Halfplaneindicator double indicates whether Direction is up or down
1485 * @param AlternativeIndicator doube indicates in case of orthogonal triangles which direction of AlternativeDirection is suitable
1486 * @param alpha double angle at a
1487 * @param beta double, angle at b
1488 * @param gamma, double, angle at c
1489 * @param Radius, double
1490 * @param Umkreisradius double radius of circumscribing circle
1491 */
1492
1493 void Get_center_of_sphere(Vector* Center, Vector a, Vector b, Vector c, Vector *NewUmkreismittelpunkt, Vector* Direction, Vector* AlternativeDirection,
1494 double HalfplaneIndicator, double AlternativeIndicator, double alpha, double beta, double gamma, double RADIUS, double Umkreisradius)
1495 {
1496 Vector TempNormal, helper;
1497 double Restradius;
1498 cout << Verbose(3) << "Begin of Get_center_of_sphere.\n";
1499 *Center = a * sin(2.*alpha) + b * sin(2.*beta) + c * sin(2.*gamma) ;
1500 Center->Scale(1./(sin(2.*alpha) + sin(2.*beta) + sin(2.*gamma)));
1501 NewUmkreismittelpunkt->CopyVector(Center);
1502 cout << Verbose(4) << "Center of new circumference is " << *NewUmkreismittelpunkt << ".\n";
1503 // Here we calculated center of circumscribing circle, using barycentric coordinates
1504 cout << Verbose(4) << "Center of circumference is " << *Center << " in direction " << *Direction << ".\n";
1505
1506 TempNormal.CopyVector(&a);
1507 TempNormal.SubtractVector(&b);
1508 helper.CopyVector(&a);
1509 helper.SubtractVector(&c);
1510 TempNormal.VectorProduct(&helper);
1511 if (fabs(HalfplaneIndicator) < MYEPSILON)
1512 {
1513 if ((TempNormal.ScalarProduct(AlternativeDirection) <0 and AlternativeIndicator >0) or (TempNormal.ScalarProduct(AlternativeDirection) >0 and AlternativeIndicator <0))
1514 {
1515 TempNormal.Scale(-1);
1516 }
1517 }
1518 else
1519 {
1520 if (TempNormal.ScalarProduct(Direction)<0 && HalfplaneIndicator >0 || TempNormal.ScalarProduct(Direction)>0 && HalfplaneIndicator<0)
1521 {
1522 TempNormal.Scale(-1);
1523 }
1524 }
1525
1526 TempNormal.Normalize();
1527 Restradius = sqrt(RADIUS*RADIUS - Umkreisradius*Umkreisradius);
1528 cout << Verbose(4) << "Height of center of circumference to center of sphere is " << Restradius << ".\n";
1529 TempNormal.Scale(Restradius);
1530 cout << Verbose(4) << "Shift vector to sphere of circumference is " << TempNormal << ".\n";
1531
1532 Center->AddVector(&TempNormal);
1533 cout << Verbose(4) << "Center of sphere of circumference is " << *Center << ".\n";
1534 cout << Verbose(3) << "End of Get_center_of_sphere.\n";
1535 }
1536 ;
1537
1538
1539/** This recursive function finds a third point, to form a triangle with two given ones.
1540 * Two atoms are fixed, a candidate is supplied, additionally two vectors for direction distinction, a Storage area to \
1541 * supply results to the calling function, the radius of the sphere which the triangle shall support and the molecule \
1542 * upon which we operate.
1543 * If the candidate is more fitting to support the sphere than the already stored atom is, then we write its general \
1544 * direction and angle into Storage.
1545 * We the determine the recursive level we have reached and if this is not on the threshold yet, call this function again, \
1546 * with all neighbours of the candidate.
1547 * @param a first point
1548 * @param b second point
1549 * *param c atom old third point of old triangle
1550 * @param Candidate base point along whose bonds to start looking from
1551 * @param Parent point to avoid during search as its wrong direction
1552 * @param RecursionLevel contains current recursion depth
1553 * @param Chord baseline vector of first and second point
1554 * @param direction1 second in plane vector (along with \a Chord) of the triangle the baseline belongs to
1555 * @param OldNormal normal of the triangle which the baseline belongs to
1556 * @param ReferencePoint Vector of center of circumscribing circle from which we look towards center of sphere
1557 * @param Opt_Candidate candidate reference to return
1558 * @param Storage array containing two angles of current Opt_Candidate
1559 * @param RADIUS radius of ball
1560 * @param mol molecule structure with atoms and bonds
1561 */
1562
1563void Find_next_suitable_point_via_Angle_of_Sphere(atom* a, atom* b, atom* c, atom* Candidate, atom* Parent,
1564 int RecursionLevel, Vector *Chord, Vector *direction1, Vector *OldNormal, Vector ReferencePoint,
1565 atom*& Opt_Candidate, double *Storage, const double RADIUS, molecule* mol)
1566{
1567 cout << Verbose(2) << "Begin of Find_next_suitable_point_via_Angle_of_Sphere, recursion level " << RecursionLevel << ".\n";
1568 cout << Verbose(3) << "Candidate is "<< *Candidate << endl;
1569 cout << Verbose(4) << "Baseline vector is " << *Chord << "." << endl;
1570 cout << Verbose(4) << "ReferencePoint is " << ReferencePoint << "." << endl;
1571 cout << Verbose(4) << "Normal of base triangle is " << *OldNormal << "." << endl;
1572 cout << Verbose(4) << "Search direction is " << *direction1 << "." << endl;
1573 /* OldNormal is normal vector on the old triangle
1574 * direction1 is normal on the triangle line, from which we come, as well as on OldNormal.
1575 * Chord points from b to a!!!
1576 */
1577 Vector dif_a; //Vector from a to candidate
1578 Vector dif_b; //Vector from b to candidate
1579 Vector AngleCheck;
1580 Vector TempNormal, Umkreismittelpunkt;
1581 Vector Mittelpunkt;
1582
1583 double CurrentEpsilon = 0.1;
1584 double alpha, beta, gamma, SideA, SideB, SideC, sign, Umkreisradius, Restradius, Distance;
1585 double BallAngle, AlternativeSign;
1586 atom *Walker; // variable atom point
1587
1588 Vector NewUmkreismittelpunkt;
1589
1590
1591 if (a != Candidate and b != Candidate and c != Candidate)
1592 {
1593 cout << Verbose(3) << "We have a unique candidate!" << endl;
1594 dif_a.CopyVector(&(a->x));
1595 dif_a.SubtractVector(&(Candidate->x));
1596 dif_b.CopyVector(&(b->x));
1597 dif_b.SubtractVector(&(Candidate->x));
1598 AngleCheck.CopyVector(&(Candidate->x));
1599 AngleCheck.SubtractVector(&(a->x));
1600 AngleCheck.ProjectOntoPlane(Chord);
1601
1602 SideA = dif_b.Norm();
1603 SideB = dif_a.Norm();
1604 SideC = Chord->Norm();
1605 //Chord->Scale(-1);
1606
1607 alpha = Chord->Angle(&dif_a);
1608 beta = M_PI - Chord->Angle(&dif_b);
1609 gamma = dif_a.Angle(&dif_b);
1610
1611 cout << Verbose(2) << "Base triangle has sides " << dif_a << ", " << dif_b << ", " << *Chord << " with angles " << alpha/M_PI*180. << ", " << beta/M_PI*180. << ", " << gamma/M_PI*180. << "." << endl;
1612
1613 if (fabs(M_PI - alpha - beta - gamma) > MYEPSILON)
1614 cerr << Verbose(0) << "WARNING: sum of angles for candidate triangle " << (alpha + beta + gamma)/M_PI*180. << " != 180.\n";
1615
1616 Umkreisradius = SideA / 2.0 / sin(alpha);
1617 //cout << Umkreisradius << endl;
1618 //cout << SideB / 2.0 / sin(beta) << endl;
1619 //cout << SideC / 2.0 / sin(gamma) << endl;
1620
1621 if (Umkreisradius < RADIUS) //Checking whether ball will at least rest on points.
1622 {
1623 cout << Verbose(3) << "Circle of circumference would fit: " << Umkreisradius << " < " << RADIUS << "." << endl;
1624 cout << Verbose(2) << "Candidate is "<< *Candidate << endl;
1625 sign = AngleCheck.ScalarProduct(direction1);
1626 if (fabs(sign)<MYEPSILON)
1627 {
1628 if (AngleCheck.ScalarProduct(OldNormal)<0)
1629 {
1630 sign =0;
1631 AlternativeSign=1;
1632 }
1633 else
1634 {
1635 sign =0;
1636 AlternativeSign=-1;
1637 }
1638 }
1639 else
1640 {
1641 sign /= fabs(sign);
1642 cout << Verbose(3) << "Candidate is in search direction: " << sign << "." << endl;
1643 }
1644
1645 Get_center_of_sphere(&Mittelpunkt, (a->x), (b->x), (Candidate->x), &NewUmkreismittelpunkt, OldNormal, direction1, sign, AlternativeSign, alpha, beta, gamma, RADIUS, Umkreisradius);
1646
1647 AngleCheck.CopyVector(&ReferencePoint);
1648 AngleCheck.Scale(-1);
1649 //cout << "AngleCheck is " << AngleCheck.x[0] << " "<< AngleCheck.x[1] << " "<< AngleCheck.x[2] << " "<< endl;
1650 AngleCheck.AddVector(&Mittelpunkt);
1651 //cout << "AngleCheck is " << AngleCheck.x[0] << " "<< AngleCheck.x[1] << " "<< AngleCheck.x[2] << " "<< endl;
1652 cout << Verbose(4) << "Reference vector to sphere's center is " << AngleCheck << "." << endl;
1653
1654 BallAngle = AngleCheck.Angle(OldNormal);
1655 cout << Verbose(3) << "Angle between normal of base triangle and center of ball sphere is :" << BallAngle << "." << endl;
1656
1657 //cout << "direction1 is " << direction1->x[0] <<" "<< direction1->x[1] <<" "<< direction1->x[2] <<" " << endl;
1658 //cout << "AngleCheck is " << AngleCheck.x[0] << " "<< AngleCheck.x[1] << " "<< AngleCheck.x[2] << " "<< endl;
1659
1660 cout << Verbose(3) << "BallAngle is " << BallAngle << " Sign is " << sign << endl;
1661
1662 NewUmkreismittelpunkt.SubtractVector(&ReferencePoint);
1663
1664 if ((AngleCheck.ScalarProduct(direction1) >=0) || (fabs(NewUmkreismittelpunkt.Norm()) < MYEPSILON))
1665 {
1666 if (Storage[0]< -1.5) // first Candidate at all
1667 {
1668
1669 cout << Verbose(2) << "First good candidate is " << *Candidate << " with ";
1670 Opt_Candidate = Candidate;
1671 Storage[0] = sign;
1672 Storage[1] = AlternativeSign;
1673 Storage[2] = BallAngle;
1674 cout << " angle " << Storage[2] << " and Up/Down "
1675 << Storage[0] << endl;
1676 }
1677 else
1678 {
1679 if ( Storage[2] > BallAngle)
1680 {
1681 cout << Verbose(2) << "Next better candidate is " << *Candidate << " with ";
1682 Opt_Candidate = Candidate;
1683 Storage[0] = sign;
1684 Storage[1] = AlternativeSign;
1685 Storage[2] = BallAngle;
1686 cout << " angle " << Storage[2] << " and Up/Down "
1687 << Storage[0] << endl;
1688 }
1689 else
1690 {
1691 if (DEBUG)
1692 {
1693 cout << Verbose(3) << *Candidate << " looses against better candidate " << *Opt_Candidate << "." << endl;
1694 }
1695 }
1696 }
1697 }
1698 else
1699 {
1700 if (DEBUG)
1701 {
1702 cout << Verbose(3) << *Candidate << " refused due to Up/Down sign which is " << sign << endl;
1703 }
1704 }
1705 }
1706 else
1707 {
1708 if (DEBUG)
1709 {
1710 cout << Verbose(3) << *Candidate << " would have circumference of " << Umkreisradius << " bigger than ball's radius " << RADIUS << "." << endl;
1711 }
1712 }
1713 }
1714 else
1715 {
1716 if (DEBUG)
1717 {
1718 cout << Verbose(3) << *Candidate << " is either " << *a << " or " << *b << "." << endl;
1719 }
1720 }
1721
1722
1723
1724 if (RecursionLevel < 9) // Seven is the recursion level threshold.
1725 {
1726 for (int i = 0; i < mol->NumberOfBondsPerAtom[Candidate->nr]; i++) // go through all bond
1727 {
1728 Walker = mol->ListOfBondsPerAtom[Candidate->nr][i]->GetOtherAtom(
1729 Candidate);
1730 if (Walker == Parent)
1731 { // don't go back the same bond
1732 continue;
1733 }
1734 else
1735 {
1736 Find_next_suitable_point_via_Angle_of_Sphere(a, b, c, Walker, Candidate, RecursionLevel
1737 + 1, Chord, direction1, OldNormal, ReferencePoint, Opt_Candidate, Storage, RADIUS,
1738 mol); //call function again
1739 }
1740 }
1741 }
1742 cout << Verbose(2) << "End of Find_next_suitable_point_via_Angle_of_Sphere, recursion level " << RecursionLevel << ".\n";
1743}
1744;
1745
1746
1747 /** This recursive function finds a third point, to form a triangle with two given ones.
1748 * Two atoms are fixed, a candidate is supplied, additionally two vectors for direction distinction, a Storage area to \
1749 * supply results to the calling function, the radius of the sphere which the triangle shall support and the molecule \
1750 * upon which we operate.
1751 * If the candidate is more fitting to support the sphere than the already stored atom is, then we write its general \
1752 * direction and angle into Storage.
1753 * We the determine the recursive level we have reached and if this is not on the threshold yet, call this function again, \
1754 * with all neighbours of the candidate.
1755 * @param a first point
1756 * @param b second point
1757 * @param Candidate base point along whose bonds to start looking from
1758 * @param Parent point to avoid during search as its wrong direction
1759 * @param RecursionLevel contains current recursion depth
1760 * @param Chord baseline vector of first and second point
1761 * @param d1 second in plane vector (along with \a Chord) of the triangle the baseline belongs to
1762 * @param OldNormal normal of the triangle which the baseline belongs to
1763 * @param Opt_Candidate candidate reference to return
1764 * @param Opt_Mittelpunkt Centerpoint of ball, when resting on Opt_Candidate
1765 * @param Storage array containing two angles of current Opt_Candidate
1766 * @param RADIUS radius of ball
1767 * @param mol molecule structure with atoms and bonds
1768 */
1769
1770void Find_next_suitable_point(atom* a, atom* b, atom* Candidate, atom* Parent,
1771 int RecursionLevel, Vector *Chord, Vector *d1, Vector *OldNormal,
1772 atom*& Opt_Candidate, Vector *Opt_Mittelpunkt, double *Storage, const double RADIUS, molecule* mol)
1773{
1774 /* OldNormal is normal vector on the old triangle
1775 * d1 is normal on the triangle line, from which we come, as well as on OldNormal.
1776 * Chord points from b to a!!!
1777 */
1778 Vector dif_a; //Vector from a to candidate
1779 Vector dif_b; //Vector from b to candidate
1780 Vector AngleCheck, AngleCheckReference, DirectionCheckPoint;
1781 Vector TempNormal, Umkreismittelpunkt, Mittelpunkt;
1782
1783 double CurrentEpsilon = 0.1;
1784 double alpha, beta, gamma, SideA, SideB, SideC, sign, Umkreisradius, Restradius, Distance;
1785 double BallAngle;
1786 atom *Walker; // variable atom point
1787
1788
1789 dif_a.CopyVector(&(a->x));
1790 dif_a.SubtractVector(&(Candidate->x));
1791 dif_b.CopyVector(&(b->x));
1792 dif_b.SubtractVector(&(Candidate->x));
1793 DirectionCheckPoint.CopyVector(&dif_a);
1794 DirectionCheckPoint.Scale(-1);
1795 DirectionCheckPoint.ProjectOntoPlane(Chord);
1796
1797 SideA = dif_b.Norm();
1798 SideB = dif_a.Norm();
1799 SideC = Chord->Norm();
1800 //Chord->Scale(-1);
1801
1802 alpha = Chord->Angle(&dif_a);
1803 beta = M_PI - Chord->Angle(&dif_b);
1804 gamma = dif_a.Angle(&dif_b);
1805
1806
1807 if (DEBUG)
1808 {
1809 cout << "Atom number" << Candidate->nr << endl;
1810 Candidate->x.Output((ofstream *) &cout);
1811 cout << "number of bonds " << mol->NumberOfBondsPerAtom[Candidate->nr]
1812 << endl;
1813 }
1814
1815 if (a != Candidate and b != Candidate)
1816 {
1817 // alpha = dif_a.Angle(&dif_b) / 2.;
1818 // SideA = Chord->Norm() / 2.;// (Chord->Norm()/2.) / sin(0.5*alpha);
1819 // SideB = dif_a.Norm();
1820 // centerline = SideA * SideA + SideB * SideB - 2. * SideA * SideB * cos(
1821 // alpha); // note this is squared of center line length
1822 // centerline = (Chord->Norm()/2.) / sin(0.5*alpha);
1823 // Those are remains from Freddie. Needed?
1824
1825
1826
1827 Umkreisradius = SideA / 2.0 / sin(alpha);
1828 //cout << Umkreisradius << endl;
1829 //cout << SideB / 2.0 / sin(beta) << endl;
1830 //cout << SideC / 2.0 / sin(gamma) << endl;
1831
1832 if (Umkreisradius < RADIUS && DirectionCheckPoint.ScalarProduct(&(Candidate->x))>0) //Checking whether ball will at least rest o points.
1833 {
1834
1835 // intermediate calculations to aquire centre of sphere, called Mittelpunkt:
1836
1837 Umkreismittelpunkt = (a->x) * sin(2.*alpha) + b->x * sin(2.*beta) + (Candidate->x) * sin(2.*gamma) ;
1838 Umkreismittelpunkt.Scale(1/(sin(2*alpha) + sin(2*beta) + sin(2*gamma)));
1839
1840 TempNormal.CopyVector(&dif_a);
1841 TempNormal.VectorProduct(&dif_b);
1842 if (TempNormal.ScalarProduct(OldNormal)<0 && sign>0 || TempNormal.ScalarProduct(OldNormal)>0 && sign<0)
1843 {
1844 TempNormal.Scale(-1);
1845 }
1846 TempNormal.Normalize();
1847 Restradius = sqrt(RADIUS*RADIUS - Umkreisradius*Umkreisradius);
1848 TempNormal.Scale(Restradius);
1849
1850 Mittelpunkt.CopyVector(&Umkreismittelpunkt);
1851 Mittelpunkt.AddVector(&TempNormal); //this is center of sphere supported by a, b and Candidate
1852
1853 AngleCheck.CopyVector(Chord);
1854 AngleCheck.Scale(-0.5);
1855 AngleCheck.SubtractVector(&(b->x));
1856 AngleCheckReference.CopyVector(&AngleCheck);
1857 AngleCheckReference.AddVector(Opt_Mittelpunkt);
1858 AngleCheck.AddVector(&Mittelpunkt);
1859
1860 BallAngle = AngleCheck.Angle(&AngleCheckReference);
1861
1862 d1->ProjectOntoPlane(&AngleCheckReference);
1863 sign = AngleCheck.ScalarProduct(d1);
1864 if (fabs(sign) < MYEPSILON)
1865 sign = 0;
1866 else
1867 sign /= fabs(sign); // +1 if in direction of triangle plane, -1 if in other direction...
1868
1869
1870 if (Storage[0]< -1.5) // first Candidate at all
1871 {
1872
1873 cout << "Next better candidate is " << *Candidate << " with ";
1874 Opt_Candidate = Candidate;
1875 Storage[0] = sign;
1876 Storage[1] = BallAngle;
1877 Opt_Mittelpunkt->CopyVector(&Mittelpunkt);
1878 cout << "Angle is " << Storage[1] << ", Halbraum ist "
1879 << Storage[0] << endl;
1880
1881
1882 }
1883 else
1884 {
1885 /*
1886 * removed due to change in criterium, now checking angle of ball to old normal.
1887 //We will now check for non interference, that is if the new candidate would have the Opt_Candidate
1888 //within the ball.
1889
1890 Distance = Opt_Candidate->x.Distance(&Mittelpunkt);
1891 //cout << "Opt_Candidate " << Opt_Candidate << " has distance " << Distance << " to Center of Candidate " << endl;
1892
1893
1894 if (Distance >RADIUS) // We have no interference and may now check whether the new point is better.
1895 */
1896 {
1897 //cout << "Atom " << Candidate << " has distance " << Candidate->x.Distance(Opt_Mittelpunkt) << " to Center of Candidate " << endl;
1898
1899 if (((Storage[0] < 0 && fabs(sign - Storage[0]) > CurrentEpsilon))) //This will give absolute preference to those in "right-hand" quadrants
1900 //(Candidate->x.Distance(Opt_Mittelpunkt) < RADIUS)) //and those where Candidate would be within old Sphere.
1901 {
1902 cout << "Next better candidate is " << *Candidate << " with ";
1903 Opt_Candidate = Candidate;
1904 Storage[0] = sign;
1905 Storage[1] = BallAngle;
1906 Opt_Mittelpunkt->CopyVector(&Mittelpunkt);
1907 cout << "Angle is " << Storage[1] << ", Halbraum ist "
1908 << Storage[0] << endl;
1909
1910
1911 }
1912 else
1913 {
1914 if ((fabs(sign - Storage[0]) < CurrentEpsilon && sign > 0
1915 && Storage[1] > BallAngle) ||
1916 (fabs(sign - Storage[0]) < CurrentEpsilon && sign < 0
1917 && Storage[1] < BallAngle))
1918 //Depending on quadrant we prefer higher or lower atom with respect to Triangle normal first.
1919 {
1920 cout << "Next better candidate is " << *Candidate << " with ";
1921 Opt_Candidate = Candidate;
1922 Storage[0] = sign;
1923 Storage[1] = BallAngle;
1924 Opt_Mittelpunkt->CopyVector(&Mittelpunkt);
1925 cout << "Angle is " << Storage[1] << ", Halbraum ist "
1926 << Storage[0] << endl;
1927 }
1928
1929 }
1930 }
1931 /*
1932 * This is for checking point-angle and presence of Candidates in Ball, currently we are checking the ball Angle.
1933 *
1934 else
1935 {
1936 if (sign>0 && BallAngle>0 && Storage[0]<0)
1937 {
1938 cout << "Next better candidate is " << *Candidate << " with ";
1939 Opt_Candidate = Candidate;
1940 Storage[0] = sign;
1941 Storage[1] = BallAngle;
1942 Opt_Mittelpunkt->CopyVector(&Mittelpunkt);
1943 cout << "Angle is " << Storage[1] << ", Halbraum ist "
1944 << Storage[0] << endl;
1945
1946//Debugging purposes only
1947 cout << "Umkreismittelpunkt has coordinates" << Umkreismittelpunkt.x[0] << " "<< Umkreismittelpunkt.x[1] <<" "<<Umkreismittelpunkt.x[2] << endl;
1948 cout << "Candidate has coordinates" << Candidate->x.x[0]<< " " << Candidate->x.x[1] << " " << Candidate->x.x[2] << endl;
1949 cout << "a has coordinates" << a->x.x[0]<< " " << a->x.x[1] << " " << a->x.x[2] << endl;
1950 cout << "b has coordinates" << b->x.x[0]<< " " << b->x.x[1] << " " << b->x.x[2] << endl;
1951 cout << "Mittelpunkt has coordinates" << Mittelpunkt.x[0] << " " << Mittelpunkt.x[1]<< " " <<Mittelpunkt.x[2] << endl;
1952 cout << "Umkreisradius ist " << Umkreisradius << endl;
1953 cout << "Restradius ist " << Restradius << endl;
1954 cout << "TempNormal has coordinates " << TempNormal.x[0] << " " << TempNormal.x[1] << " " << TempNormal.x[2] << " " << endl;
1955 cout << "OldNormal has coordinates " << OldNormal->x[0] << " " << OldNormal->x[1] << " " << OldNormal->x[2] << " " << endl;
1956 cout << "Dist a to UmkreisMittelpunkt " << a->x.Distance(&Umkreismittelpunkt) << endl;
1957 cout << "Dist b to UmkreisMittelpunkt " << b->x.Distance(&Umkreismittelpunkt) << endl;
1958 cout << "Dist Candidate to UmkreisMittelpunkt " << Candidate->x.Distance(&Umkreismittelpunkt) << endl;
1959 cout << "Dist a to Mittelpunkt " << a->x.Distance(&Mittelpunkt) << endl;
1960 cout << "Dist b to Mittelpunkt " << b->x.Distance(&Mittelpunkt) << endl;
1961 cout << "Dist Candidate to Mittelpunkt " << Candidate->x.Distance(&Mittelpunkt) << endl;
1962
1963
1964
1965 }
1966 else
1967 {
1968 if (DEBUG)
1969 cout << "Looses to better candidate" << endl;
1970 }
1971 }
1972 */
1973 }
1974 }
1975 else
1976 {
1977 if (DEBUG)
1978 {
1979 cout << "Doesn't satisfy requirements for circumscribing circle" << endl;
1980 }
1981 }
1982 }
1983
1984 else
1985 {
1986 if (DEBUG)
1987 cout << "identisch mit Ursprungslinie" << endl;
1988 }
1989
1990 if (RecursionLevel < 9) // Five is the recursion level threshold.
1991 {
1992 for (int i = 0; i < mol->NumberOfBondsPerAtom[Candidate->nr]; i++) // go through all bond
1993 {
1994 Walker = mol->ListOfBondsPerAtom[Candidate->nr][i]->GetOtherAtom(
1995 Candidate);
1996 if (Walker == Parent)
1997 { // don't go back the same bond
1998 continue;
1999 }
2000 else
2001 {
2002 Find_next_suitable_point(a, b, Walker, Candidate, RecursionLevel
2003 + 1, Chord, d1, OldNormal, Opt_Candidate, Opt_Mittelpunkt, Storage, RADIUS,
2004 mol); //call function again
2005
2006 }
2007 }
2008 }
2009}
2010;
2011
2012/** This function finds a triangle to a line, adjacent to an existing one.
2013 * @param out output stream for debugging
2014 * @param mol molecule structure with all atoms and bonds
2015 * @param Line current baseline to search from
2016 * @param T current triangle which \a Line is edge of
2017 * @param RADIUS radius of the rolling ball
2018 * @param N number of found triangles
2019 */
2020void Tesselation::Find_next_suitable_triangle(ofstream *out,
2021 molecule* mol, BoundaryLineSet &Line, BoundaryTriangleSet &T,
2022 const double& RADIUS, int N, const char *tempbasename)
2023{
2024 cout << Verbose(1) << "Begin of Find_next_suitable_triangle\n";
2025 Vector direction1;
2026 Vector helper;
2027 Vector Chord;
2028 ofstream *tempstream = NULL;
2029 char NumberName[255];
2030 double tmp;
2031 //atom* Walker;
2032 atom* OldThirdPoint;
2033
2034 double Storage[3];
2035 Storage[0] = -2.; // This direction is either +1 or -1 one, so any result will take precedence over initial values
2036 Storage[1] = -2.; // This is also lower then any value produced by an eligible atom, which are all positive
2037 Storage[2] = 9999999.;
2038 atom* Opt_Candidate = NULL;
2039 Vector Opt_Mittelpunkt;
2040
2041 cout << Verbose(1) << "Current baseline is " << Line << " of triangle " << T << "." << endl;
2042
2043 helper.CopyVector(&(Line.endpoints[0]->node->x));
2044 for (int i = 0; i < 3; i++)
2045 {
2046 if (T.endpoints[i]->node->nr != Line.endpoints[0]->node->nr
2047 && T.endpoints[i]->node->nr != Line.endpoints[1]->node->nr)
2048 {
2049 OldThirdPoint = T.endpoints[i]->node;
2050 helper.SubtractVector(&T.endpoints[i]->node->x);
2051 break;
2052 }
2053 }
2054
2055 direction1.CopyVector(&Line.endpoints[0]->node->x);
2056 direction1.SubtractVector(&Line.endpoints[1]->node->x);
2057 direction1.VectorProduct(&(T.NormalVector));
2058
2059 if (direction1.ScalarProduct(&helper) < 0)
2060 {
2061 direction1.Scale(-1);
2062 }
2063 cout << Verbose(2) << "Looking in direction " << direction1 << " for candidates.\n";
2064
2065 Chord.CopyVector(&(Line.endpoints[0]->node->x)); // bring into calling function
2066 Chord.SubtractVector(&(Line.endpoints[1]->node->x));
2067 cout << Verbose(2) << "Baseline vector is " << Chord << ".\n";
2068
2069
2070 Vector Umkreismittelpunkt, a, b, c;
2071 double alpha, beta, gamma;
2072 a.CopyVector(&(T.endpoints[0]->node->x));
2073 b.CopyVector(&(T.endpoints[1]->node->x));
2074 c.CopyVector(&(T.endpoints[2]->node->x));
2075 a.SubtractVector(&(T.endpoints[1]->node->x));
2076 b.SubtractVector(&(T.endpoints[2]->node->x));
2077 c.SubtractVector(&(T.endpoints[0]->node->x));
2078
2079// alpha = a.Angle(&c) - M_PI/2.;
2080// beta = b.Angle(&a);
2081// gamma = c.Angle(&b) - M_PI/2.;
2082 alpha = M_PI - a.Angle(&c);
2083 beta = M_PI - b.Angle(&a);
2084 gamma = M_PI - c.Angle(&b);
2085 if (fabs(M_PI - alpha - beta - gamma) > MYEPSILON)
2086 cerr << Verbose(0) << "WARNING: sum of angles for candidate triangle " << (alpha + beta + gamma)/M_PI*180. << " != 180.\n";
2087
2088 Umkreismittelpunkt = (T.endpoints[0]->node->x) * sin(2.*alpha) + T.endpoints[1]->node->x * sin(2.*beta) + (T.endpoints[2]->node->x) * sin(2.*gamma) ;
2089 //cout << "UmkreisMittelpunkt is " << Umkreismittelpunkt.x[0] << " "<< Umkreismittelpunkt.x[1] << " "<< Umkreismittelpunkt.x[2] << " "<< endl;
2090 Umkreismittelpunkt.Scale(1/(sin(2*alpha) + sin(2*beta) + sin(2*gamma)));
2091 cout << "UmkreisMittelpunkt is " << Umkreismittelpunkt.x[0] << " "<< Umkreismittelpunkt.x[1] << " "<< Umkreismittelpunkt.x[2] << " "<< endl;
2092 cout << " We look over line " << Line << " in direction " << direction1.x[0] << " " << direction1.x[1] << " " << direction1.x[2] << " " << endl;
2093 cout << " Old Normal is " << (T.NormalVector.x)[0] << " " << T.NormalVector.x[1] << " " << (T.NormalVector.x)[2] << " " << endl;
2094
2095 cout << Verbose(2) << "Base triangle has sides " << a << ", " << b << ", " << c << " with angles " << alpha/M_PI*180. << ", " << beta/M_PI*180. << ", " << gamma/M_PI*180. << "." << endl;
2096 Umkreismittelpunkt = (T.endpoints[0]->node->x) * sin(2.*alpha) + T.endpoints[1]->node->x * sin(2.*beta) + (T.endpoints[2]->node->x) * sin(2.*gamma) ;
2097 Umkreismittelpunkt.Scale(1/(sin(2*alpha) + sin(2*beta) + sin(2*gamma)));
2098 cout << Verbose(2) << "Center of circumference is " << Umkreismittelpunkt << "." << endl;
2099 if (DEBUG)
2100 cout << Verbose(3) << "Check of relative endpoints (same distance, equally spreaded): "<< endl;
2101 tmp = 0;
2102 for (int i=0;i<NDIM;i++) {
2103 helper.CopyVector(&T.endpoints[i]->node->x);
2104 helper.SubtractVector(&Umkreismittelpunkt);
2105 if (DEBUG)
2106 cout << Verbose(3) << "Endpoint[" << i << "]: " << helper << " with length " << helper.Norm() << "." << endl;
2107 if (tmp == 0) // set on first time for comparison against next ones
2108 tmp = helper.Norm();
2109 if (fabs(helper.Norm() - tmp) > MYEPSILON)
2110 cerr << Verbose(1) << "WARNING: center of circumference is wrong!" << endl;
2111 }
2112
2113 cout << Verbose(1) << "Looking for third point candidates for triangle ... " << endl;
2114
2115 Find_next_suitable_point_via_Angle_of_Sphere(Line.endpoints[0]->node, Line.endpoints[1]->node, OldThirdPoint,
2116 Line.endpoints[0]->node, Line.endpoints[1]->node, 0, &Chord, &direction1,
2117 &(T.NormalVector), Umkreismittelpunkt, Opt_Candidate, Storage, RADIUS, mol);
2118 Find_next_suitable_point_via_Angle_of_Sphere(Line.endpoints[0]->node, Line.endpoints[1]->node, OldThirdPoint,
2119 Line.endpoints[1]->node, Line.endpoints[0]->node, 0, &Chord, &direction1,
2120 &(T.NormalVector), Umkreismittelpunkt, Opt_Candidate, Storage, RADIUS, mol);
2121
2122
2123 cout << "Letzter Winkel bei " << TrianglesOnBoundaryCount << " Winkel ist " << Storage[2] << endl;
2124
2125 if ((TrianglesOnBoundaryCount % 10) == 0) {
2126 sprintf(NumberName, "-%d", TriangleFilesWritten);
2127 if (DoTecplotOutput) {
2128 string NameofTempFile(tempbasename);
2129 NameofTempFile.append(NumberName);
2130 NameofTempFile.append(TecplotSuffix);
2131 cout << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
2132 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
2133 write_tecplot_file(out, tempstream, this, mol, TriangleFilesWritten);
2134 tempstream->close();
2135 tempstream->flush();
2136 delete(tempstream);
2137 }
2138 if (DoRaster3DOutput) {
2139 string NameofTempFile(tempbasename);
2140 NameofTempFile.append(NumberName);
2141 NameofTempFile.append(Raster3DSuffix);
2142 cout << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
2143 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
2144 write_raster3d_file(out, tempstream, this, mol);
2145 tempstream->close();
2146 tempstream->flush();
2147 delete(tempstream);
2148 }
2149 if (DoTecplotOutput || DoRaster3DOutput)
2150 TriangleFilesWritten++;
2151 }
2152
2153 // Konstruiere nun neues Dreieck am Ende der Liste der Dreiecke
2154
2155 cout << Verbose(2) << " Optimal candidate is " << *Opt_Candidate << endl;
2156
2157 // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
2158
2159 AddTrianglePoint(Opt_Candidate, 0);
2160 LineMap::iterator TryAndError;
2161 TryAndError = TPS[0]->lines.find(Line.endpoints[0]->node->nr);
2162 bool flag = true;
2163 if ((TryAndError != TPS[0]->lines.end()) && (TryAndError->second->TrianglesCount > 1))
2164 flag = false;
2165 TryAndError = TPS[0]->lines.find(Line.endpoints[1]->node->nr);
2166 if ((TryAndError != TPS[0]->lines.end()) && (TryAndError->second->TrianglesCount > 1))
2167 flag = false;
2168
2169 if (flag) { // if so, add
2170 AddTrianglePoint(Line.endpoints[0]->node, 1);
2171 AddTrianglePoint(Line.endpoints[1]->node, 2);
2172
2173 AddTriangleLine(TPS[0], TPS[1], 0);
2174 AddTriangleLine(TPS[0], TPS[2], 1);
2175 AddTriangleLine(TPS[1], TPS[2], 2);
2176
2177 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2178 AddTriangleToLines();
2179
2180 BTS->GetNormalVector(BTS->NormalVector);
2181
2182 if ((BTS->NormalVector.ScalarProduct(&(T.NormalVector)) < 0 && Storage[0] > 0) ||
2183 (BTS->NormalVector.ScalarProduct(&(T.NormalVector)) > 0 && Storage[0] < 0) ||
2184 (fabs(Storage[0]) < MYEPSILON && Storage[1]*BTS->NormalVector.ScalarProduct(&direction1) < 0) )
2185
2186 {
2187 BTS->NormalVector.Scale(-1);
2188 };
2189 cout << Verbose(2) << "New triangle with " << *BTS << "and normal vector " << BTS->NormalVector << " for this triangle ... " << endl;
2190 cout << Verbose(2) << "We have "<< TrianglesOnBoundaryCount << " for line " << Line << "." << endl;
2191 } else { // else, yell and do nothing
2192 cout << Verbose(2) << "This triangle consisting of ";
2193 for (int i=0;i<NDIM;i++)
2194 cout << BLS[i] << "(" << BLS[i]->TrianglesCount << "), ";
2195 cout << " is invalid!" << endl;
2196 }
2197 cout << Verbose(1) << "End of Find_next_suitable_triangle\n";
2198}
2199;
2200
2201void Find_second_point_for_Tesselation(atom* a, atom* Candidate, atom* Parent,
2202 int RecursionLevel, Vector Oben, atom*& Opt_Candidate, double Storage[3],
2203 molecule* mol, double RADIUS)
2204{
2205 cout << Verbose(2)
2206 << "Begin of Find_second_point_for_Tesselation, recursive level "
2207 << RecursionLevel << endl;
2208 int i;
2209 Vector AngleCheck;
2210 atom* Walker;
2211 double norm = -1., angle;
2212
2213 // check if we only have one unique point yet ...
2214 if (a != Candidate)
2215 {
2216 cout << Verbose(3) << "Current candidate is " << *Candidate << ": ";
2217 AngleCheck.CopyVector(&(Candidate->x));
2218 AngleCheck.SubtractVector(&(a->x));
2219 norm = AngleCheck.Norm();
2220 // second point shall have smallest angle with respect to Oben vector
2221 if (norm < RADIUS)
2222 {
2223 angle = AngleCheck.Angle(&Oben);
2224 if (angle < Storage[0])
2225 {
2226 //cout << Verbose(1) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
2227 cout << "Is a better candidate with distance " << norm << " and " << angle << ".\n";
2228 Opt_Candidate = Candidate;
2229 Storage[0] = AngleCheck.Angle(&Oben);
2230 //cout << Verbose(1) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
2231 }
2232 else
2233 {
2234 cout << "Looses with angle " << angle << " to a better candidate "
2235 << *Opt_Candidate << endl;
2236 }
2237 }
2238 else
2239 {
2240 cout << "Refused due to Radius " << norm
2241 << endl;
2242 }
2243 }
2244
2245 // if not recursed to deeply, look at all its bonds
2246 if (RecursionLevel < 7)
2247 {
2248 for (i = 0; i < mol->NumberOfBondsPerAtom[Candidate->nr]; i++)
2249 {
2250 Walker = mol->ListOfBondsPerAtom[Candidate->nr][i]->GetOtherAtom(
2251 Candidate);
2252 if (Walker == Parent) // don't go back along the bond we came from
2253 continue;
2254 else
2255 Find_second_point_for_Tesselation(a, Walker, Candidate,
2256 RecursionLevel + 1, Oben, Opt_Candidate, Storage, mol, RADIUS);
2257 };
2258 };
2259 cout << Verbose(2) << "End of Find_second_point_for_Tesselation, recursive level "
2260 << RecursionLevel << endl;
2261}
2262;
2263
2264void Tesselation::Find_starting_triangle(molecule* mol, const double RADIUS)
2265{
2266 cout << Verbose(1) << "Begin of Find_starting_triangle\n";
2267 int i = 0;
2268 atom* Walker;
2269 atom* FirstPoint;
2270 atom* SecondPoint;
2271 atom* max_index[NDIM];
2272 double max_coordinate[NDIM];
2273 Vector Oben;
2274 Vector helper;
2275 Vector Chord;
2276 Vector CenterOfFirstLine;
2277
2278 Oben.Zero();
2279
2280 for (i = 0; i < 3; i++)
2281 {
2282 max_index[i] = NULL;
2283 max_coordinate[i] = -1;
2284 }
2285 cout << Verbose(2) << "Molecule mol is there and has " << mol->AtomCount
2286 << " Atoms \n";
2287
2288 // 1. searching topmost atom with respect to each axis
2289 Walker = mol->start;
2290 while (Walker->next != mol->end)
2291 {
2292 Walker = Walker->next;
2293 for (i = 0; i < 3; i++)
2294 {
2295 if (Walker->x.x[i] > max_coordinate[i])
2296 {
2297 max_coordinate[i] = Walker->x.x[i];
2298 max_index[i] = Walker;
2299 }
2300 }
2301 }
2302
2303 cout << Verbose(2) << "Found maximum coordinates: ";
2304 for (int i=0;i<NDIM;i++)
2305 cout << i << ": " << *max_index[i] << "\t";
2306 cout << endl;
2307 //Koennen dies fuer alle Richtungen, legen hier erstmal Richtung auf k=0
2308 const int k = 1;
2309 Oben.x[k] = 1.;
2310 FirstPoint = max_index[k];
2311
2312 cout << Verbose(1) << "Coordinates of start atom " << *FirstPoint << " at " << FirstPoint->x << " with " << mol->NumberOfBondsPerAtom[FirstPoint->nr] << " bonds." << endl;
2313 double Storage[3];
2314 atom* Opt_Candidate = NULL;
2315 Storage[0] = 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.
2316 Storage[1] = 999999.; // This will be an angle looking for the third point.
2317 Storage[2] = 999999.;
2318
2319 Find_second_point_for_Tesselation(FirstPoint, FirstPoint, FirstPoint, 0,
2320 Oben, Opt_Candidate, Storage, mol, RADIUS); // we give same point as next candidate as its bonds are looked into in find_second_...
2321 SecondPoint = Opt_Candidate;
2322 cout << Verbose(1) << "Found second point is " << *SecondPoint << " at " << SecondPoint->x << ".\n";
2323
2324 helper.CopyVector(&(FirstPoint->x));
2325 helper.SubtractVector(&(SecondPoint->x));
2326 helper.Normalize();
2327 Oben.ProjectOntoPlane(&helper);
2328 Oben.Normalize();
2329 helper.VectorProduct(&Oben);
2330 Storage[0] = -2.; // This will indicate the quadrant.
2331 Storage[1] = 9999999.; // This will be an angle looking for the third point.
2332 Storage[2] = 9999999.;
2333
2334 Chord.CopyVector(&(FirstPoint->x)); // bring into calling function
2335 Chord.SubtractVector(&(SecondPoint->x));
2336 // Now, oben and helper are two orthonormalized vectors in the plane defined by Chord (not normalized)
2337
2338 cout << Verbose(2) << "Looking for third point candidates \n";
2339 // look in one direction of baseline for initial candidate
2340 Opt_Candidate = NULL;
2341 CenterOfFirstLine.CopyVector(&Chord);
2342 CenterOfFirstLine.Scale(0.5);
2343 CenterOfFirstLine.AddVector(&(SecondPoint->x));
2344
2345 cout << Verbose(1) << "Looking for third point candidates from " << *FirstPoint << " onward ...\n";
2346 Find_next_suitable_point_via_Angle_of_Sphere(FirstPoint, SecondPoint, SecondPoint, SecondPoint, FirstPoint, 0,
2347 &Chord, &helper, &Oben, CenterOfFirstLine, Opt_Candidate, Storage, RADIUS, mol);
2348 // look in other direction of baseline for possible better candidate
2349 cout << Verbose(1) << "Looking for third point candidates from " << *SecondPoint << " onward ...\n";
2350 Find_next_suitable_point_via_Angle_of_Sphere(FirstPoint, SecondPoint, SecondPoint, FirstPoint, SecondPoint, 0,
2351 &Chord, &helper, &Oben, CenterOfFirstLine, Opt_Candidate, Storage, RADIUS, mol);
2352 cout << Verbose(1) << "Third Point is " << *Opt_Candidate << endl;
2353
2354 // FOUND Starting Triangle: FirstPoint, SecondPoint, Opt_Candidate
2355
2356 // Finally, we only have to add the found points
2357 AddTrianglePoint(FirstPoint, 0);
2358 AddTrianglePoint(SecondPoint, 1);
2359 AddTrianglePoint(Opt_Candidate, 2);
2360 // ... and respective lines
2361 AddTriangleLine(TPS[0], TPS[1], 0);
2362 AddTriangleLine(TPS[1], TPS[2], 1);
2363 AddTriangleLine(TPS[0], TPS[2], 2);
2364 // ... and triangles to the Maps of the Tesselation class
2365 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2366 AddTriangleToLines();
2367 // ... and calculate its normal vector (with correct orientation)
2368 Oben.Scale(-1.);
2369 BTS->GetNormalVector(Oben);
2370 cout << Verbose(0) << "==> The found starting triangle consists of "
2371 << *FirstPoint << ", " << *SecondPoint << " and " << *Opt_Candidate
2372 << " with normal vector " << BTS->NormalVector << ".\n";
2373 cout << Verbose(1) << "End of Find_starting_triangle\n";
2374}
2375;
2376
2377void Find_non_convex_border(ofstream *out, const char *filename, molecule* mol)
2378{
2379 int N = 0;
2380 struct Tesselation *Tess = new Tesselation;
2381 cout << Verbose(1) << "Entering search for non convex hull. " << endl;
2382 cout << flush;
2383 const double RADIUS = 6.;
2384 LineMap::iterator baseline;
2385 cout << Verbose(0) << "Begin of Find_non_convex_border\n";
2386 bool flag = false; // marks whether we went once through all baselines without finding any without two triangles
2387 Tess->Find_starting_triangle(mol, RADIUS);
2388
2389 baseline = Tess->LinesOnBoundary.begin();
2390 while ((baseline != Tess->LinesOnBoundary.end()) || (flag))
2391 {
2392 if (baseline->second->TrianglesCount == 1)
2393 {
2394 Tess->Find_next_suitable_triangle(out, mol,
2395 *(baseline->second),
2396 *(((baseline->second->triangles.begin()))->second), RADIUS, N, filename); //the line is there, so there is a triangle, but only one.
2397 flag = true;
2398 }
2399 else
2400 {
2401 cout << Verbose(1) << "Line " << baseline->second << " has "
2402 << baseline->second->TrianglesCount << " triangles adjacent"
2403 << endl;
2404 }
2405 N++;
2406 baseline++;
2407 if ((baseline == Tess->LinesOnBoundary.end()) && (flag)) {
2408 baseline = Tess->LinesOnBoundary.begin(); // restart if we reach end due to newly inserted lines
2409 flag = false;
2410 }
2411 }
2412 cout << Verbose(1) << "Writing final tecplot file\n";
2413 if (DoTecplotOutput) {
2414 string Name(filename);
2415 Name.append(TecplotSuffix);
2416 ofstream tecplot(Name.c_str(), ios::trunc);
2417 write_tecplot_file(out, &tecplot, Tess, mol, -1);
2418 tecplot.close();
2419 }
2420 if (DoRaster3DOutput) {
2421 string Name(filename);
2422 Name.append(Raster3DSuffix);
2423 ofstream raster(Name.c_str(), ios::trunc);
2424 write_raster3d_file(out, &raster, Tess, mol);
2425 raster.close();
2426 }
2427
2428 cout << Verbose(0) << "End of Find_non_convex_border\n";
2429}
2430;
2431
Note: See TracBrowser for help on using the repository browser.