source: src/boundary.cpp@ 542ab3

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

Removed unnecessary code

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