source: src/boundary.cpp@ a567c3

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

ConvexTesselation working again.

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