source: src/boundary.cpp@ 36ec71

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

Merge branch 'master' into ConcaveHull

Conflicts:

molecuilder/src/analyzer.cpp
molecuilder/src/bond.cpp
molecuilder/src/boundary.cpp
molecuilder/src/boundary.hpp
molecuilder/src/builder.cpp
molecuilder/src/config.cpp
molecuilder/src/datacreator.cpp
molecuilder/src/datacreator.hpp
molecuilder/src/defs.hpp
molecuilder/src/ellipsoid.cpp
molecuilder/src/joiner.cpp
molecuilder/src/molecules.cpp
molecuilder/src/molecules.hpp
molecuilder/src/parser.cpp
molecuilder/src/parser.hpp

merges:

compilation fixes:

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