source: src/boundary.cpp@ 8725ed

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 8725ed was 1e168b, checked in by Frederik Heber <heber@…>, 15 years ago

Now the best (in terms of ShortestAngle) baseline is picked among all open ones instead of the next.

  • Element initialization was done for all constructors in tesselation.cpp
  • Property mode set to 100755
File size: 49.3 KB
Line 
1/** \file boundary.cpp
2 *
3 * Implementations and super-function for envelopes
4 */
5
6#include "atom.hpp"
7#include "bond.hpp"
8#include "boundary.hpp"
9#include "config.hpp"
10#include "element.hpp"
11#include "helpers.hpp"
12#include "linkedcell.hpp"
13#include "log.hpp"
14#include "memoryallocator.hpp"
15#include "molecule.hpp"
16#include "tesselation.hpp"
17#include "tesselationhelpers.hpp"
18
19#include<gsl/gsl_poly.h>
20
21// ========================================== F U N C T I O N S =================================
22
23
24/** Determines greatest diameters of a cluster defined by its convex envelope.
25 * Looks at lines parallel to one axis and where they intersect on the projected planes
26 * \param *out output stream for debugging
27 * \param *BoundaryPoints NDIM set of boundary points defining the convex envelope on each projected plane
28 * \param *mol molecule structure representing the cluster
29 * \param *&TesselStruct Tesselation structure with triangles
30 * \param IsAngstroem whether we have angstroem or atomic units
31 * \return NDIM array of the diameters
32 */
33double *GetDiametersOfCluster(const Boundaries *BoundaryPtr, const molecule *mol, Tesselation *&TesselStruct, const bool IsAngstroem)
34{
35 // get points on boundary of NULL was given as parameter
36 bool BoundaryFreeFlag = false;
37 double OldComponent = 0.;
38 double tmp = 0.;
39 double w1 = 0.;
40 double w2 = 0.;
41 Vector DistanceVector;
42 Vector OtherVector;
43 int component = 0;
44 int Othercomponent = 0;
45 Boundaries::const_iterator Neighbour;
46 Boundaries::const_iterator OtherNeighbour;
47 double *GreatestDiameter = new double[NDIM];
48
49 const Boundaries *BoundaryPoints;
50 if (BoundaryPtr == NULL) {
51 BoundaryFreeFlag = true;
52 BoundaryPoints = GetBoundaryPoints(mol, TesselStruct);
53 } else {
54 BoundaryPoints = BoundaryPtr;
55 Log() << Verbose(1) << "Using given boundary points set." << endl;
56 }
57 // determine biggest "diameter" of cluster for each axis
58 for (int i = 0; i < NDIM; i++)
59 GreatestDiameter[i] = 0.;
60 for (int axis = 0; axis < NDIM; axis++)
61 { // regard each projected plane
62 //Log() << Verbose(1) << "Current axis is " << axis << "." << endl;
63 for (int j = 0; j < 2; j++)
64 { // and for both axis on the current plane
65 component = (axis + j + 1) % NDIM;
66 Othercomponent = (axis + 1 + ((j + 1) & 1)) % NDIM;
67 //Log() << Verbose(1) << "Current component is " << component << ", Othercomponent is " << Othercomponent << "." << endl;
68 for (Boundaries::const_iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
69 //Log() << Verbose(2) << "Current runner is " << *(runner->second.second) << "." << endl;
70 // seek for the neighbours pair where the Othercomponent sign flips
71 Neighbour = runner;
72 Neighbour++;
73 if (Neighbour == BoundaryPoints[axis].end()) // make it wrap around
74 Neighbour = BoundaryPoints[axis].begin();
75 DistanceVector.CopyVector(&runner->second.second->x);
76 DistanceVector.SubtractVector(&Neighbour->second.second->x);
77 do { // seek for neighbour pair where it flips
78 OldComponent = DistanceVector.x[Othercomponent];
79 Neighbour++;
80 if (Neighbour == BoundaryPoints[axis].end()) // make it wrap around
81 Neighbour = BoundaryPoints[axis].begin();
82 DistanceVector.CopyVector(&runner->second.second->x);
83 DistanceVector.SubtractVector(&Neighbour->second.second->x);
84 //Log() << Verbose(3) << "OldComponent is " << OldComponent << ", new one is " << DistanceVector.x[Othercomponent] << "." << endl;
85 } while ((runner != Neighbour) && (fabs(OldComponent / fabs(
86 OldComponent) - DistanceVector.x[Othercomponent] / fabs(
87 DistanceVector.x[Othercomponent])) < MYEPSILON)); // as long as sign does not flip
88 if (runner != Neighbour) {
89 OtherNeighbour = Neighbour;
90 if (OtherNeighbour == BoundaryPoints[axis].begin()) // make it wrap around
91 OtherNeighbour = BoundaryPoints[axis].end();
92 OtherNeighbour--;
93 //Log() << Verbose(2) << "The pair, where the sign of OtherComponent flips, is: " << *(Neighbour->second.second) << " and " << *(OtherNeighbour->second.second) << "." << endl;
94 // now we have found the pair: Neighbour and OtherNeighbour
95 OtherVector.CopyVector(&runner->second.second->x);
96 OtherVector.SubtractVector(&OtherNeighbour->second.second->x);
97 //Log() << Verbose(2) << "Distances to Neighbour and OtherNeighbour are " << DistanceVector.x[component] << " and " << OtherVector.x[component] << "." << endl;
98 //Log() << Verbose(2) << "OtherComponents to Neighbour and OtherNeighbour are " << DistanceVector.x[Othercomponent] << " and " << OtherVector.x[Othercomponent] << "." << endl;
99 // do linear interpolation between points (is exact) to extract exact intersection between Neighbour and OtherNeighbour
100 w1 = fabs(OtherVector.x[Othercomponent]);
101 w2 = fabs(DistanceVector.x[Othercomponent]);
102 tmp = fabs((w1 * DistanceVector.x[component] + w2
103 * OtherVector.x[component]) / (w1 + w2));
104 // mark if it has greater diameter
105 //Log() << Verbose(2) << "Comparing current greatest " << GreatestDiameter[component] << " to new " << tmp << "." << endl;
106 GreatestDiameter[component] = (GreatestDiameter[component]
107 > tmp) ? GreatestDiameter[component] : tmp;
108 } //else
109 //Log() << Verbose(2) << "Saw no sign flip, probably top or bottom node." << endl;
110 }
111 }
112 }
113 Log() << Verbose(0) << "RESULT: The biggest diameters are "
114 << GreatestDiameter[0] << " and " << GreatestDiameter[1] << " and "
115 << GreatestDiameter[2] << " " << (IsAngstroem ? "angstrom"
116 : "atomiclength") << "." << endl;
117
118 // free reference lists
119 if (BoundaryFreeFlag)
120 delete[] (BoundaryPoints);
121
122 return GreatestDiameter;
123}
124;
125
126
127/** Determines the boundary points of a cluster.
128 * Does a projection per axis onto the orthogonal plane, transforms into spherical coordinates, sorts them by the angle
129 * and looks at triples: if the middle has less a distance than the allowed maximum height of the triangle formed by the plane's
130 * center and first and last point in the triple, it is thrown out.
131 * \param *out output stream for debugging
132 * \param *mol molecule structure representing the cluster
133 * \param *&TesselStruct pointer to Tesselation structure
134 */
135Boundaries *GetBoundaryPoints(const molecule *mol, Tesselation *&TesselStruct)
136{
137 atom *Walker = NULL;
138 PointMap PointsOnBoundary;
139 LineMap LinesOnBoundary;
140 TriangleMap TrianglesOnBoundary;
141 Vector *MolCenter = mol->DetermineCenterOfAll();
142 Vector helper;
143 BoundariesTestPair BoundaryTestPair;
144 Vector AxisVector;
145 Vector AngleReferenceVector;
146 Vector AngleReferenceNormalVector;
147 Vector ProjectedVector;
148 Boundaries *BoundaryPoints = new Boundaries[NDIM]; // first is alpha, second is (r, nr)
149 double angle = 0.;
150
151 Log() << Verbose(1) << "Finding all boundary points." << endl;
152 // 3a. Go through every axis
153 for (int axis = 0; axis < NDIM; axis++) {
154 AxisVector.Zero();
155 AngleReferenceVector.Zero();
156 AngleReferenceNormalVector.Zero();
157 AxisVector.x[axis] = 1.;
158 AngleReferenceVector.x[(axis + 1) % NDIM] = 1.;
159 AngleReferenceNormalVector.x[(axis + 2) % NDIM] = 1.;
160
161 Log() << Verbose(1) << "Axisvector is " << AxisVector << " and AngleReferenceVector is " << AngleReferenceVector << ", and AngleReferenceNormalVector is " << AngleReferenceNormalVector << "." << endl;
162
163 // 3b. construct set of all points, transformed into cylindrical system and with left and right neighbours
164 Walker = mol->start;
165 while (Walker->next != mol->end) {
166 Walker = Walker->next;
167 ProjectedVector.CopyVector(&Walker->x);
168 ProjectedVector.SubtractVector(MolCenter);
169 ProjectedVector.ProjectOntoPlane(&AxisVector);
170
171 // correct for negative side
172 const double radius = ProjectedVector.NormSquared();
173 if (fabs(radius) > MYEPSILON)
174 angle = ProjectedVector.Angle(&AngleReferenceVector);
175 else
176 angle = 0.; // otherwise it's a vector in Axis Direction and unimportant for boundary issues
177
178 //Log() << Verbose(2) << "Checking sign in quadrant : " << ProjectedVector.Projection(&AngleReferenceNormalVector) << "." << endl;
179 if (ProjectedVector.ScalarProduct(&AngleReferenceNormalVector) > 0) {
180 angle = 2. * M_PI - angle;
181 }
182 Log() << Verbose(2) << "Inserting " << *Walker << ": (r, alpha) = (" << radius << "," << angle << "): " << ProjectedVector << endl;
183 BoundaryTestPair = BoundaryPoints[axis].insert(BoundariesPair(angle, DistancePair (radius, Walker)));
184 if (!BoundaryTestPair.second) { // same point exists, check first r, then distance of original vectors to center of gravity
185 Log() << Verbose(2) << "Encountered two vectors whose projection onto axis " << axis << " is equal: " << endl;
186 Log() << Verbose(2) << "Present vector: " << *BoundaryTestPair.first->second.second << endl;
187 Log() << Verbose(2) << "New vector: " << *Walker << endl;
188 const double ProjectedVectorNorm = ProjectedVector.NormSquared();
189 if ((ProjectedVectorNorm - BoundaryTestPair.first->second.first) > MYEPSILON) {
190 BoundaryTestPair.first->second.first = ProjectedVectorNorm;
191 BoundaryTestPair.first->second.second = Walker;
192 Log() << Verbose(2) << "Keeping new vector due to larger projected distance " << ProjectedVectorNorm << "." << endl;
193 } else if (fabs(ProjectedVectorNorm - BoundaryTestPair.first->second.first) < MYEPSILON) {
194 helper.CopyVector(&Walker->x);
195 helper.SubtractVector(MolCenter);
196 const double oldhelperNorm = helper.NormSquared();
197 helper.CopyVector(&BoundaryTestPair.first->second.second->x);
198 helper.SubtractVector(MolCenter);
199 if (helper.NormSquared() < oldhelperNorm) {
200 BoundaryTestPair.first->second.second = Walker;
201 Log() << Verbose(2) << "Keeping new vector due to larger distance to molecule center " << helper.NormSquared() << "." << endl;
202 } else {
203 Log() << Verbose(2) << "Keeping present vector due to larger distance to molecule center " << oldhelperNorm << "." << endl;
204 }
205 } else {
206 Log() << Verbose(2) << "Keeping present vector due to larger projected distance " << ProjectedVectorNorm << "." << endl;
207 }
208 }
209 }
210 // printing all inserted for debugging
211 // {
212 // Log() << Verbose(2) << "Printing list of candidates for axis " << axis << " which we have inserted so far." << endl;
213 // int i=0;
214 // for(Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
215 // if (runner != BoundaryPoints[axis].begin())
216 // Log() << Verbose(2) << ", " << i << ": " << *runner->second.second;
217 // else
218 // Log() << Verbose(2) << i << ": " << *runner->second.second;
219 // i++;
220 // }
221 // Log() << Verbose(2) << endl;
222 // }
223 // 3c. throw out points whose distance is less than the mean of left and right neighbours
224 bool flag = false;
225 Log() << Verbose(1) << "Looking for candidates to kick out by convex condition ... " << endl;
226 do { // do as long as we still throw one out per round
227 flag = false;
228 Boundaries::iterator left = BoundaryPoints[axis].end();
229 Boundaries::iterator right = BoundaryPoints[axis].end();
230 for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
231 // set neighbours correctly
232 if (runner == BoundaryPoints[axis].begin()) {
233 left = BoundaryPoints[axis].end();
234 } else {
235 left = runner;
236 }
237 left--;
238 right = runner;
239 right++;
240 if (right == BoundaryPoints[axis].end()) {
241 right = BoundaryPoints[axis].begin();
242 }
243 // check distance
244
245 // construct the vector of each side of the triangle on the projected plane (defined by normal vector AxisVector)
246 {
247 Vector SideA, SideB, SideC, SideH;
248 SideA.CopyVector(&left->second.second->x);
249 SideA.SubtractVector(MolCenter);
250 SideA.ProjectOntoPlane(&AxisVector);
251 // Log() << Verbose(0) << "SideA: " << SideA << endl;
252
253 SideB.CopyVector(&right->second.second->x);
254 SideB.SubtractVector(MolCenter);
255 SideB.ProjectOntoPlane(&AxisVector);
256 // Log() << Verbose(0) << "SideB: " << SideB << endl;
257
258 SideC.CopyVector(&left->second.second->x);
259 SideC.SubtractVector(&right->second.second->x);
260 SideC.ProjectOntoPlane(&AxisVector);
261 // Log() << Verbose(0) << "SideC: " << SideC << endl;
262
263 SideH.CopyVector(&runner->second.second->x);
264 SideH.SubtractVector(MolCenter);
265 SideH.ProjectOntoPlane(&AxisVector);
266 // Log() << Verbose(0) << "SideH: " << SideH << endl;
267
268 // calculate each length
269 const double a = SideA.Norm();
270 //const double b = SideB.Norm();
271 //const double c = SideC.Norm();
272 const double h = SideH.Norm();
273 // calculate the angles
274 const double alpha = SideA.Angle(&SideH);
275 const double beta = SideA.Angle(&SideC);
276 const double gamma = SideB.Angle(&SideH);
277 const double delta = SideC.Angle(&SideH);
278 const double MinDistance = a * sin(beta) / (sin(delta)) * (((alpha < M_PI / 2.) || (gamma < M_PI / 2.)) ? 1. : -1.);
279 //Log() << 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;
280 Log() << 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;
281 if ((fabs(h / fabs(h) - MinDistance / fabs(MinDistance)) < MYEPSILON) && ((h - MinDistance)) < -MYEPSILON) {
282 // throw out point
283 Log() << Verbose(1) << "Throwing out " << *runner->second.second << "." << endl;
284 BoundaryPoints[axis].erase(runner);
285 flag = true;
286 }
287 }
288 }
289 } while (flag);
290 }
291 delete(MolCenter);
292 return BoundaryPoints;
293};
294
295/** Tesselates the convex boundary by finding all boundary points.
296 * \param *out output stream for debugging
297 * \param *mol molecule structure with Atom's and Bond's.
298 * \param *TesselStruct Tesselation filled with points, lines and triangles on boundary on return
299 * \param *LCList atoms in LinkedCell list
300 * \param *filename filename prefix for output of vertex data
301 * \return *TesselStruct is filled with convex boundary and tesselation is stored under \a *filename.
302 */
303void FindConvexBorder(const molecule* mol, Tesselation *&TesselStruct, const LinkedCell *LCList, const char *filename)
304{
305 bool BoundaryFreeFlag = false;
306 Boundaries *BoundaryPoints = NULL;
307
308 Log() << Verbose(1) << "Begin of FindConvexBorder" << endl;
309
310 if (TesselStruct != NULL) // free if allocated
311 delete(TesselStruct);
312 TesselStruct = new class Tesselation;
313
314 // 1. Find all points on the boundary
315 if (BoundaryPoints == NULL) {
316 BoundaryFreeFlag = true;
317 BoundaryPoints = GetBoundaryPoints(mol, TesselStruct);
318 } else {
319 Log() << Verbose(1) << "Using given boundary points set." << endl;
320 }
321
322// printing all inserted for debugging
323 for (int axis=0; axis < NDIM; axis++)
324 {
325 Log() << Verbose(2) << "Printing list of candidates for axis " << axis << " which we have inserted so far." << endl;
326 int i=0;
327 for(Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
328 if (runner != BoundaryPoints[axis].begin())
329 Log() << Verbose(2) << ", " << i << ": " << *runner->second.second;
330 else
331 Log() << Verbose(2) << i << ": " << *runner->second.second;
332 i++;
333 }
334 Log() << Verbose(2) << endl;
335 }
336
337 // 2. fill the boundary point list
338 for (int axis = 0; axis < NDIM; axis++)
339 for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++)
340 if (!TesselStruct->AddBoundaryPoint(runner->second.second, 0))
341 eLog() << Verbose(2) << "Point " << *(runner->second.second) << " is already present!" << endl;
342
343 Log() << Verbose(2) << "I found " << TesselStruct->PointsOnBoundaryCount << " points on the convex boundary." << endl;
344 // now we have the whole set of edge points in the BoundaryList
345
346 // listing for debugging
347 // Log() << Verbose(1) << "Listing PointsOnBoundary:";
348 // for(PointMap::iterator runner = PointsOnBoundary.begin(); runner != PointsOnBoundary.end(); runner++) {
349 // Log() << Verbose(1) << " " << *runner->second;
350 // }
351 // Log() << Verbose(1) << endl;
352
353 // 3a. guess starting triangle
354 TesselStruct->GuessStartingTriangle();
355
356 // 3b. go through all lines, that are not yet part of two triangles (only of one so far)
357 TesselStruct->TesselateOnBoundary(mol);
358
359 // 3c. check whether all atoms lay inside the boundary, if not, add to boundary points, segment triangle into three with the new point
360 if (!TesselStruct->InsertStraddlingPoints(mol, LCList))
361 Log() << Verbose(1) << "Insertion of straddling points failed!" << endl;
362
363 Log() << Verbose(2) << "I created " << TesselStruct->TrianglesOnBoundary.size() << " intermediate triangles with " << TesselStruct->LinesOnBoundary.size() << " lines and " << TesselStruct->PointsOnBoundary.size() << " points." << endl;
364
365 // 4. Store triangles in tecplot file
366 if (filename != NULL) {
367 if (DoTecplotOutput) {
368 string OutputName(filename);
369 OutputName.append("_intermed");
370 OutputName.append(TecplotSuffix);
371 ofstream *tecplot = new ofstream(OutputName.c_str());
372 WriteTecplotFile(tecplot, TesselStruct, mol, 0);
373 tecplot->close();
374 delete(tecplot);
375 }
376 if (DoRaster3DOutput) {
377 string OutputName(filename);
378 OutputName.append("_intermed");
379 OutputName.append(Raster3DSuffix);
380 ofstream *rasterplot = new ofstream(OutputName.c_str());
381 WriteRaster3dFile(rasterplot, TesselStruct, mol);
382 rasterplot->close();
383 delete(rasterplot);
384 }
385 }
386
387 // 3d. check all baselines whether the peaks of the two adjacent triangles with respect to center of baseline are convex, if not, make the baseline between the two peaks and baseline endpoints become the new peaks
388 bool AllConvex = true;
389 class BoundaryLineSet *line = NULL;
390 do {
391 AllConvex = true;
392 for (LineMap::iterator LineRunner = TesselStruct->LinesOnBoundary.begin(); LineRunner != TesselStruct->LinesOnBoundary.end(); LineRunner++) {
393 line = LineRunner->second;
394 Log() << Verbose(1) << "INFO: Current line is " << *line << "." << endl;
395 if (!line->CheckConvexityCriterion()) {
396 Log() << Verbose(1) << "... line " << *line << " is concave, flipping it." << endl;
397
398 // flip the line
399 if (TesselStruct->PickFarthestofTwoBaselines(line) == 0.)
400 eLog() << Verbose(1) << "Correction of concave baselines failed!" << endl;
401 else {
402 TesselStruct->FlipBaseline(line);
403 Log() << Verbose(1) << "INFO: Correction of concave baselines worked." << endl;
404 }
405 }
406 }
407 } while (!AllConvex);
408
409 // 3e. we need another correction here, for TesselPoints that are below the surface (i.e. have an odd number of concave triangles surrounding it)
410// if (!TesselStruct->CorrectConcaveTesselPoints(out))
411// Log() << Verbose(1) << "Correction of concave tesselpoints failed!" << endl;
412
413 Log() << Verbose(2) << "I created " << TesselStruct->TrianglesOnBoundary.size() << " triangles with " << TesselStruct->LinesOnBoundary.size() << " lines and " << TesselStruct->PointsOnBoundary.size() << " points." << endl;
414
415 // 4. Store triangles in tecplot file
416 if (filename != NULL) {
417 if (DoTecplotOutput) {
418 string OutputName(filename);
419 OutputName.append(TecplotSuffix);
420 ofstream *tecplot = new ofstream(OutputName.c_str());
421 WriteTecplotFile(tecplot, TesselStruct, mol, 0);
422 tecplot->close();
423 delete(tecplot);
424 }
425 if (DoRaster3DOutput) {
426 string OutputName(filename);
427 OutputName.append(Raster3DSuffix);
428 ofstream *rasterplot = new ofstream(OutputName.c_str());
429 WriteRaster3dFile(rasterplot, TesselStruct, mol);
430 rasterplot->close();
431 delete(rasterplot);
432 }
433 }
434
435
436 // free reference lists
437 if (BoundaryFreeFlag)
438 delete[] (BoundaryPoints);
439
440 Log() << Verbose(1) << "End of FindConvexBorder" << endl;
441};
442
443/** For testing removes one boundary point after another to check for leaks.
444 * \param *out output stream for debugging
445 * \param *TesselStruct Tesselation containing envelope with boundary points
446 * \param *mol molecule
447 * \param *filename name of file
448 * \return true - all removed, false - something went wrong
449 */
450bool RemoveAllBoundaryPoints(class Tesselation *&TesselStruct, const molecule * const mol, const char * const filename)
451{
452 int i=0;
453 char number[MAXSTRINGSIZE];
454
455 if ((TesselStruct == NULL) || (TesselStruct->PointsOnBoundary.empty())) {
456 eLog() << Verbose(1) << "TesselStruct is empty." << endl;
457 return false;
458 }
459
460 PointMap::iterator PointRunner;
461 while (!TesselStruct->PointsOnBoundary.empty()) {
462 Log() << Verbose(2) << "Remaining points are: ";
463 for (PointMap::iterator PointSprinter = TesselStruct->PointsOnBoundary.begin(); PointSprinter != TesselStruct->PointsOnBoundary.end(); PointSprinter++)
464 Log() << Verbose(2) << *(PointSprinter->second) << "\t";
465 Log() << Verbose(2) << endl;
466
467 PointRunner = TesselStruct->PointsOnBoundary.begin();
468 // remove point
469 TesselStruct->RemovePointFromTesselatedSurface(PointRunner->second);
470
471 // store envelope
472 sprintf(number, "-%04d", i++);
473 StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, number);
474 }
475
476 return true;
477};
478
479/** Creates a convex envelope from a given non-convex one.
480 * -# First step, remove concave spots, i.e. singular "dents"
481 * -# We go through all PointsOnBoundary.
482 * -# We CheckConvexityCriterion() for all its lines.
483 * -# If all its lines are concave, it cannot be on the convex envelope.
484 * -# Hence, we remove it and re-create all its triangles from its getCircleOfConnectedPoints()
485 * -# We calculate the additional volume.
486 * -# We go over all lines until none yields a concavity anymore.
487 * -# Second step, remove concave lines, i.e. line-shape "dents"
488 * -# We go through all LinesOnBoundary
489 * -# We CheckConvexityCriterion()
490 * -# If it returns concave, we flip the line in this quadrupel of points (abusing the degeneracy of the tesselation)
491 * -# We CheckConvexityCriterion(),
492 * -# if it's concave, we continue
493 * -# if not, we mark an error and stop
494 * Note: This routine - for free - calculates the difference in volume between convex and
495 * non-convex envelope, as the former is easy to calculate - VolumeOfConvexEnvelope() - it
496 * can be used to compute volumes of arbitrary shapes.
497 * \param *out output stream for debugging
498 * \param *TesselStruct non-convex envelope, is changed in return!
499 * \param *mol molecule
500 * \param *filename name of file
501 * \return volume difference between the non- and the created convex envelope
502 */
503double ConvexizeNonconvexEnvelope(class Tesselation *&TesselStruct, const molecule * const mol, const char * const filename)
504{
505 double volume = 0;
506 class BoundaryPointSet *point = NULL;
507 class BoundaryLineSet *line = NULL;
508 bool Concavity = false;
509 char dummy[MAXSTRINGSIZE];
510 PointMap::iterator PointRunner;
511 PointMap::iterator PointAdvance;
512 LineMap::iterator LineRunner;
513 LineMap::iterator LineAdvance;
514 TriangleMap::iterator TriangleRunner;
515 TriangleMap::iterator TriangleAdvance;
516 int run = 0;
517
518 Log() << Verbose(0) << "Begin of ConvexizeNonconvexEnvelope" << endl;
519
520 // check whether there is something to work on
521 if (TesselStruct == NULL) {
522 eLog() << Verbose(1) << "TesselStruct is empty!" << endl;
523 return volume;
524 }
525
526 // First step: RemovePointFromTesselatedSurface
527 do {
528 Concavity = false;
529 sprintf(dummy, "-first-%d", run);
530 //CalculateConcavityPerBoundaryPoint(TesselStruct);
531 StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, dummy);
532
533 PointRunner = TesselStruct->PointsOnBoundary.begin();
534 PointAdvance = PointRunner; // we need an advanced point, as the PointRunner might get removed
535 while (PointRunner != TesselStruct->PointsOnBoundary.end()) {
536 PointAdvance++;
537 point = PointRunner->second;
538 Log() << Verbose(1) << "INFO: Current point is " << *point << "." << endl;
539 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
540 line = LineRunner->second;
541 Log() << Verbose(2) << "INFO: Current line of point " << *point << " is " << *line << "." << endl;
542 if (!line->CheckConvexityCriterion()) {
543 // remove the point if needed
544 Log() << Verbose(1) << "... point " << *point << " cannot be on convex envelope." << endl;
545 volume += TesselStruct->RemovePointFromTesselatedSurface(point);
546 sprintf(dummy, "-first-%d", ++run);
547 StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, dummy);
548 Concavity = true;
549 break;
550 }
551 }
552 PointRunner = PointAdvance;
553 }
554
555 sprintf(dummy, "-second-%d", run);
556 //CalculateConcavityPerBoundaryPoint(TesselStruct);
557 StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, dummy);
558
559 // second step: PickFarthestofTwoBaselines
560 LineRunner = TesselStruct->LinesOnBoundary.begin();
561 LineAdvance = LineRunner; // we need an advanced line, as the LineRunner might get removed
562 while (LineRunner != TesselStruct->LinesOnBoundary.end()) {
563 LineAdvance++;
564 line = LineRunner->second;
565 Log() << Verbose(1) << "INFO: Picking farthest baseline for line is " << *line << "." << endl;
566 // take highest of both lines
567 if (TesselStruct->IsConvexRectangle(line) == NULL) {
568 const double tmp = TesselStruct->PickFarthestofTwoBaselines(line);
569 volume += tmp;
570 if (tmp != 0.) {
571 TesselStruct->FlipBaseline(line);
572 Concavity = true;
573 }
574 }
575 LineRunner = LineAdvance;
576 }
577 run++;
578 } while (Concavity);
579 //CalculateConcavityPerBoundaryPoint(TesselStruct);
580 //StoreTrianglesinFile(mol, filename, "-third");
581
582 // third step: IsConvexRectangle
583// LineRunner = TesselStruct->LinesOnBoundary.begin();
584// LineAdvance = LineRunner; // we need an advanced line, as the LineRunner might get removed
585// while (LineRunner != TesselStruct->LinesOnBoundary.end()) {
586// LineAdvance++;
587// line = LineRunner->second;
588// Log() << Verbose(1) << "INFO: Current line is " << *line << "." << endl;
589// //if (LineAdvance != TesselStruct->LinesOnBoundary.end())
590// //Log() << Verbose(1) << "INFO: Next line will be " << *(LineAdvance->second) << "." << endl;
591// if (!line->CheckConvexityCriterion(out)) {
592// Log() << Verbose(1) << "... line " << *line << " is concave, flipping it." << endl;
593//
594// // take highest of both lines
595// point = TesselStruct->IsConvexRectangle(line);
596// if (point != NULL)
597// volume += TesselStruct->RemovePointFromTesselatedSurface(point);
598// }
599// LineRunner = LineAdvance;
600// }
601
602 CalculateConcavityPerBoundaryPoint(TesselStruct);
603 StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, "");
604
605 // end
606 Log() << Verbose(1) << "Volume is " << volume << "." << endl;
607 Log() << Verbose(0) << "End of ConvexizeNonconvexEnvelope" << endl;
608 return volume;
609};
610
611
612/** Determines the volume of a cluster.
613 * Determines first the convex envelope, then tesselates it and calculates its volume.
614 * \param *out output stream for debugging
615 * \param *TesselStruct Tesselation filled with points, lines and triangles on boundary on return
616 * \param *configuration needed for path to store convex envelope file
617 * \return determined volume of the cluster in cubed config:GetIsAngstroem()
618 */
619double VolumeOfConvexEnvelope(class Tesselation *TesselStruct, class config *configuration)
620{
621 bool IsAngstroem = configuration->GetIsAngstroem();
622 double volume = 0.;
623 Vector x;
624 Vector y;
625
626 // 6a. Every triangle forms a pyramid with the center of gravity as its peak, sum up the volumes
627 Log() << Verbose(1)
628 << "Calculating the volume of the pyramids formed out of triangles and center of gravity."
629 << endl;
630 for (TriangleMap::iterator runner = TesselStruct->TrianglesOnBoundary.begin(); runner != TesselStruct->TrianglesOnBoundary.end(); runner++)
631 { // go through every triangle, calculate volume of its pyramid with CoG as peak
632 x.CopyVector(runner->second->endpoints[0]->node->node);
633 x.SubtractVector(runner->second->endpoints[1]->node->node);
634 y.CopyVector(runner->second->endpoints[0]->node->node);
635 y.SubtractVector(runner->second->endpoints[2]->node->node);
636 const double a = sqrt(runner->second->endpoints[0]->node->node->DistanceSquared(runner->second->endpoints[1]->node->node));
637 const double b = sqrt(runner->second->endpoints[0]->node->node->DistanceSquared(runner->second->endpoints[2]->node->node));
638 const double c = sqrt(runner->second->endpoints[2]->node->node->DistanceSquared(runner->second->endpoints[1]->node->node));
639 const double G = sqrt(((a + b + c) * (a + b + c) - 2 * (a * a + b * b + c * c)) / 16.); // area of tesselated triangle
640 x.MakeNormalVector(runner->second->endpoints[0]->node->node, runner->second->endpoints[1]->node->node, runner->second->endpoints[2]->node->node);
641 x.Scale(runner->second->endpoints[1]->node->node->ScalarProduct(&x));
642 const double h = x.Norm(); // distance of CoG to triangle
643 const double PyramidVolume = (1. / 3.) * G * h; // this formula holds for _all_ pyramids (independent of n-edge base or (not) centered peak)
644 Log() << Verbose(2) << "Area of triangle is " << setprecision(10) << G << " "
645 << (IsAngstroem ? "angstrom" : "atomiclength") << "^2, height is "
646 << h << " and the volume is " << PyramidVolume << " "
647 << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
648 volume += PyramidVolume;
649 }
650 Log() << Verbose(0) << "RESULT: The summed volume is " << setprecision(6)
651 << volume << " " << (IsAngstroem ? "angstrom" : "atomiclength") << "^3."
652 << endl;
653
654 return volume;
655};
656
657/** Stores triangles to file.
658 * \param *out output stream for debugging
659 * \param *mol molecule with atoms and bonds
660 * \param *&TesselStruct Tesselation with boundary triangles
661 * \param *filename prefix of filename
662 * \param *extraSuffix intermediate suffix
663 */
664void StoreTrianglesinFile(const molecule * const mol, const Tesselation *&TesselStruct, const char *filename, const char *extraSuffix)
665{
666 // 4. Store triangles in tecplot file
667 if (filename != NULL) {
668 if (DoTecplotOutput) {
669 string OutputName(filename);
670 OutputName.append(extraSuffix);
671 OutputName.append(TecplotSuffix);
672 ofstream *tecplot = new ofstream(OutputName.c_str());
673 WriteTecplotFile(tecplot, TesselStruct, mol, -1);
674 tecplot->close();
675 delete(tecplot);
676 }
677 if (DoRaster3DOutput) {
678 string OutputName(filename);
679 OutputName.append(extraSuffix);
680 OutputName.append(Raster3DSuffix);
681 ofstream *rasterplot = new ofstream(OutputName.c_str());
682 WriteRaster3dFile(rasterplot, TesselStruct, mol);
683 rasterplot->close();
684 delete(rasterplot);
685 }
686 }
687};
688
689/** Creates multiples of the by \a *mol given cluster and suspends them in water with a given final density.
690 * We get cluster volume by VolumeOfConvexEnvelope() and its diameters by GetDiametersOfCluster()
691 * \param *out output stream for debugging
692 * \param *configuration needed for path to store convex envelope file
693 * \param *mol molecule structure representing the cluster
694 * \param *&TesselStruct Tesselation structure with triangles on return
695 * \param ClusterVolume guesstimated cluster volume, if equal 0 we used VolumeOfConvexEnvelope() instead.
696 * \param celldensity desired average density in final cell
697 */
698void PrepareClustersinWater(config *configuration, molecule *mol, double ClusterVolume, double celldensity)
699{
700 bool IsAngstroem = true;
701 double *GreatestDiameter = NULL;
702 Boundaries *BoundaryPoints = NULL;
703 class Tesselation *TesselStruct = NULL;
704 Vector BoxLengths;
705 int repetition[NDIM] = { 1, 1, 1 };
706 int TotalNoClusters = 1;
707 atom *Walker = NULL;
708 double totalmass = 0.;
709 double clustervolume = 0.;
710 double cellvolume = 0.;
711
712 // transform to PAS
713 mol->PrincipalAxisSystem(true);
714
715 IsAngstroem = configuration->GetIsAngstroem();
716 GreatestDiameter = GetDiametersOfCluster(BoundaryPoints, mol, TesselStruct, IsAngstroem);
717 BoundaryPoints = GetBoundaryPoints(mol, TesselStruct);
718 LinkedCell LCList(mol, 10.);
719 FindConvexBorder(mol, TesselStruct, &LCList, NULL);
720
721 // some preparations beforehand
722 if (ClusterVolume == 0)
723 clustervolume = VolumeOfConvexEnvelope(TesselStruct, configuration);
724 else
725 clustervolume = ClusterVolume;
726
727 for (int i = 0; i < NDIM; i++)
728 TotalNoClusters *= repetition[i];
729
730 // sum up the atomic masses
731 Walker = mol->start;
732 while (Walker->next != mol->end) {
733 Walker = Walker->next;
734 totalmass += Walker->type->mass;
735 }
736 Log() << Verbose(0) << "RESULT: The summed mass is " << setprecision(10) << totalmass << " atomicmassunit." << endl;
737 Log() << Verbose(0) << "RESULT: The average density is " << setprecision(10) << totalmass / clustervolume << " atomicmassunit/" << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
738
739 // solve cubic polynomial
740 Log() << Verbose(1) << "Solving equidistant suspension in water problem ..." << endl;
741 if (IsAngstroem)
742 cellvolume = (TotalNoClusters * totalmass / SOLVENTDENSITY_A - (totalmass / clustervolume)) / (celldensity - 1);
743 else
744 cellvolume = (TotalNoClusters * totalmass / SOLVENTDENSITY_a0 - (totalmass / clustervolume)) / (celldensity - 1);
745 Log() << Verbose(1) << "Cellvolume needed for a density of " << celldensity << " g/cm^3 is " << cellvolume << " " << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
746
747 double minimumvolume = TotalNoClusters * (GreatestDiameter[0] * GreatestDiameter[1] * GreatestDiameter[2]);
748 Log() << Verbose(1) << "Minimum volume of the convex envelope contained in a rectangular box is " << minimumvolume << " atomicmassunit/" << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
749 if (minimumvolume > cellvolume) {
750 eLog() << Verbose(1) << "the containing box already has a greater volume than the envisaged cell volume!" << endl;
751 Log() << Verbose(0) << "Setting Box dimensions to minimum possible, the greatest diameters." << endl;
752 for (int i = 0; i < NDIM; i++)
753 BoxLengths.x[i] = GreatestDiameter[i];
754 mol->CenterEdge(&BoxLengths);
755 } else {
756 BoxLengths.x[0] = (repetition[0] * GreatestDiameter[0] + repetition[1] * GreatestDiameter[1] + repetition[2] * GreatestDiameter[2]);
757 BoxLengths.x[1] = (repetition[0] * repetition[1] * GreatestDiameter[0] * GreatestDiameter[1] + repetition[0] * repetition[2] * GreatestDiameter[0] * GreatestDiameter[2] + repetition[1] * repetition[2] * GreatestDiameter[1] * GreatestDiameter[2]);
758 BoxLengths.x[2] = minimumvolume - cellvolume;
759 double x0 = 0.;
760 double x1 = 0.;
761 double x2 = 0.;
762 if (gsl_poly_solve_cubic(BoxLengths.x[0], BoxLengths.x[1], BoxLengths.x[2], &x0, &x1, &x2) == 1) // either 1 or 3 on return
763 Log() << Verbose(0) << "RESULT: The resulting spacing is: " << x0 << " ." << endl;
764 else {
765 Log() << Verbose(0) << "RESULT: The resulting spacings are: " << x0 << " and " << x1 << " and " << x2 << " ." << endl;
766 x0 = x2; // sorted in ascending order
767 }
768
769 cellvolume = 1.;
770 for (int i = 0; i < NDIM; i++) {
771 BoxLengths.x[i] = repetition[i] * (x0 + GreatestDiameter[i]);
772 cellvolume *= BoxLengths.x[i];
773 }
774
775 // set new box dimensions
776 Log() << Verbose(0) << "Translating to box with these boundaries." << endl;
777 mol->SetBoxDimension(&BoxLengths);
778 mol->CenterInBox();
779 }
780 // update Box of atoms by boundary
781 mol->SetBoxDimension(&BoxLengths);
782 Log() << Verbose(0) << "RESULT: The resulting cell dimensions are: " << BoxLengths.x[0] << " and " << BoxLengths.x[1] << " and " << BoxLengths.x[2] << " with total volume of " << cellvolume << " " << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
783};
784
785
786/** Fills the empty space of the simulation box with water/
787 * \param *out output stream for debugging
788 * \param *List list of molecules already present in box
789 * \param *TesselStruct contains tesselated surface
790 * \param *filler molecule which the box is to be filled with
791 * \param configuration contains box dimensions
792 * \param distance[NDIM] distance between filling molecules in each direction
793 * \param RandAtomDisplacement maximum distance for random displacement per atom
794 * \param RandMolDisplacement maximum distance for random displacement per filler molecule
795 * \param DoRandomRotation true - do random rotiations, false - don't
796 * \return *mol pointer to new molecule with filled atoms
797 */
798molecule * FillBoxWithMolecule(MoleculeListClass *List, molecule *filler, config &configuration, double distance[NDIM], double RandomAtomDisplacement, double RandomMolDisplacement, bool DoRandomRotation)
799{
800 molecule *Filling = new molecule(filler->elemente);
801 Vector CurrentPosition;
802 int N[NDIM];
803 int n[NDIM];
804 double *M = ReturnFullMatrixforSymmetric(filler->cell_size);
805 double Rotations[NDIM*NDIM];
806 Vector AtomTranslations;
807 Vector FillerTranslations;
808 Vector FillerDistance;
809 double FillIt = false;
810 atom *Walker = NULL;
811 bond *Binder = NULL;
812 int i = 0;
813 LinkedCell *LCList[List->ListOfMolecules.size()];
814 double phi[NDIM];
815 class Tesselation *TesselStruct[List->ListOfMolecules.size()];
816
817 Log() << Verbose(0) << "Begin of FillBoxWithMolecule" << endl;
818
819 i=0;
820 for (MoleculeList::iterator ListRunner = List->ListOfMolecules.begin(); ListRunner != List->ListOfMolecules.end(); ListRunner++) {
821 Log() << Verbose(1) << "Pre-creating linked cell lists for molecule " << *ListRunner << "." << endl;
822 LCList[i] = new LinkedCell((*ListRunner), 5.); // get linked cell list
823 if (TesselStruct[i] == NULL) {
824 Log() << Verbose(1) << "Pre-creating tesselation for molecule " << *ListRunner << "." << endl;
825 FindNonConvexBorder((*ListRunner), TesselStruct[i], (const LinkedCell *&)LCList[i], 5., NULL);
826 }
827 i++;
828 }
829
830 // Center filler at origin
831 filler->CenterOrigin();
832 filler->Center.Zero();
833
834 filler->CountAtoms();
835 atom * CopyAtoms[filler->AtomCount];
836
837 // calculate filler grid in [0,1]^3
838 FillerDistance.Init(distance[0], distance[1], distance[2]);
839 FillerDistance.InverseMatrixMultiplication(M);
840 Log() << Verbose(1) << "INFO: Grid steps are ";
841 for(int i=0;i<NDIM;i++) {
842 N[i] = (int) ceil(1./FillerDistance.x[i]);
843 Log() << Verbose(1) << N[i];
844 if (i != NDIM-1)
845 Log() << Verbose(1)<< ", ";
846 else
847 Log() << Verbose(1) << "." << endl;
848 }
849
850 // go over [0,1]^3 filler grid
851 for (n[0] = 0; n[0] < N[0]; n[0]++)
852 for (n[1] = 0; n[1] < N[1]; n[1]++)
853 for (n[2] = 0; n[2] < N[2]; n[2]++) {
854 // calculate position of current grid vector in untransformed box
855 CurrentPosition.Init((double)n[0]/(double)N[0], (double)n[1]/(double)N[1], (double)n[2]/(double)N[2]);
856 CurrentPosition.MatrixMultiplication(M);
857 Log() << Verbose(2) << "INFO: Current Position is " << CurrentPosition << "." << endl;
858 // Check whether point is in- or outside
859 FillIt = true;
860 i=0;
861 for (MoleculeList::iterator ListRunner = List->ListOfMolecules.begin(); ListRunner != List->ListOfMolecules.end(); ListRunner++) {
862 // get linked cell list
863 if (TesselStruct[i] == NULL) {
864 eLog() << Verbose(1) << "TesselStruct of " << (*ListRunner) << " is NULL. Didn't we pre-create it?" << endl;
865 FillIt = false;
866 } else {
867 FillIt = FillIt && (!TesselStruct[i]->IsInnerPoint(CurrentPosition, LCList[i]));
868 i++;
869 }
870 }
871
872 if (FillIt) {
873 // fill in Filler
874 Log() << Verbose(2) << "Space at " << CurrentPosition << " is unoccupied by any molecule, filling in." << endl;
875
876 // create molecule random translation vector ...
877 for (int i=0;i<NDIM;i++)
878 FillerTranslations.x[i] = RandomMolDisplacement*(rand()/(RAND_MAX/2.) - 1.);
879 Log() << Verbose(3) << "INFO: Translating this filler by " << FillerTranslations << "." << endl;
880
881 // go through all atoms
882 Walker = filler->start;
883 while (Walker->next != filler->end) {
884 Walker = Walker->next;
885 // copy atom ...
886 CopyAtoms[Walker->nr] = new atom(Walker);
887
888 // create atomic random translation vector ...
889 for (int i=0;i<NDIM;i++)
890 AtomTranslations.x[i] = RandomAtomDisplacement*(rand()/(RAND_MAX/2.) - 1.);
891
892 // ... and rotation matrix
893 if (DoRandomRotation) {
894 for (int i=0;i<NDIM;i++) {
895 phi[i] = rand()/(RAND_MAX/(2.*M_PI));
896 }
897
898 Rotations[0] = cos(phi[0]) *cos(phi[2]) + (sin(phi[0])*sin(phi[1])*sin(phi[2]));
899 Rotations[3] = sin(phi[0]) *cos(phi[2]) - (cos(phi[0])*sin(phi[1])*sin(phi[2]));
900 Rotations[6] = cos(phi[1])*sin(phi[2]) ;
901 Rotations[1] = - sin(phi[0])*cos(phi[1]) ;
902 Rotations[4] = cos(phi[0])*cos(phi[1]) ;
903 Rotations[7] = sin(phi[1]) ;
904 Rotations[3] = - cos(phi[0]) *sin(phi[2]) + (sin(phi[0])*sin(phi[1])*cos(phi[2]));
905 Rotations[5] = - sin(phi[0]) *sin(phi[2]) - (cos(phi[0])*sin(phi[1])*cos(phi[2]));
906 Rotations[8] = cos(phi[1])*cos(phi[2]) ;
907 }
908
909 // ... and put at new position
910 if (DoRandomRotation)
911 CopyAtoms[Walker->nr]->x.MatrixMultiplication(Rotations);
912 CopyAtoms[Walker->nr]->x.AddVector(&AtomTranslations);
913 CopyAtoms[Walker->nr]->x.AddVector(&FillerTranslations);
914 CopyAtoms[Walker->nr]->x.AddVector(&CurrentPosition);
915
916 // insert into Filling
917
918 // FIXME: gives completely different results if CopyAtoms[..] used instead of Walker, why???
919 Log() << Verbose(4) << "Filling atom " << *Walker << ", translated to " << AtomTranslations << ", at final position is " << (CopyAtoms[Walker->nr]->x) << "." << endl;
920 Filling->AddAtom(CopyAtoms[Walker->nr]);
921 }
922
923 // go through all bonds and add as well
924 Binder = filler->first;
925 while(Binder->next != filler->last) {
926 Binder = Binder->next;
927 Log() << Verbose(3) << "Adding Bond between " << *CopyAtoms[Binder->leftatom->nr] << " and " << *CopyAtoms[Binder->rightatom->nr]<< "." << endl;
928 Filling->AddBond(CopyAtoms[Binder->leftatom->nr], CopyAtoms[Binder->rightatom->nr], Binder->BondDegree);
929 }
930 } else {
931 // leave empty
932 Log() << Verbose(2) << "Space at " << CurrentPosition << " is occupied." << endl;
933 }
934 }
935 Free(&M);
936 for (size_t i=0;i<List->ListOfMolecules.size();i++) {
937 delete(LCList[i]);
938 delete(TesselStruct[i]);
939 }
940 Log() << Verbose(0) << "End of FillBoxWithMolecule" << endl;
941
942 return Filling;
943};
944
945
946/** Tesselates the non convex boundary by rolling a virtual sphere along the surface of the molecule.
947 * \param *out output stream for debugging
948 * \param *mol molecule structure with Atom's and Bond's
949 * \param *&TesselStruct Tesselation filled with points, lines and triangles on boundary on return
950 * \param *&LCList atoms in LinkedCell list
951 * \param RADIUS radius of the virtual sphere
952 * \param *filename filename prefix for output of vertex data
953 */
954void FindNonConvexBorder(const molecule* const mol, Tesselation *&TesselStruct, const LinkedCell *&LCList, const double RADIUS, const char *filename = NULL)
955{
956 bool freeLC = false;
957 CandidateForTesselation *baseline;
958 LineMap::iterator testline;
959 bool OneLoopWithoutSuccessFlag = true; // marks whether we went once through all baselines without finding any without two triangles
960 bool TesselationFailFlag = false;
961
962 Log() << Verbose(1) << "Entering search for non convex hull. " << endl;
963 if (TesselStruct == NULL) {
964 Log() << Verbose(1) << "Allocating Tesselation struct ..." << endl;
965 TesselStruct= new Tesselation;
966 } else {
967 delete(TesselStruct);
968 Log() << Verbose(1) << "Re-Allocating Tesselation struct ..." << endl;
969 TesselStruct = new Tesselation;
970 }
971
972 Log() << Verbose(0) << "Begin of FindNonConvexBorder\n";
973
974 // initialise Linked Cell
975 if (LCList == NULL) {
976 LCList = new LinkedCell(mol, 2.*RADIUS);
977 freeLC = true;
978 }
979
980 // 1. get starting triangle
981 TesselStruct->FindStartingTriangle(RADIUS, LCList);
982
983 // 2. expand from there
984 while ((!TesselStruct->OpenLines.empty()) && (OneLoopWithoutSuccessFlag)) {
985 // 2a. fill all new OpenLines
986 Log() << Verbose(0) << "There are " << TesselStruct->OpenLines.size() << " open lines to scan for candidates:" << endl;
987 for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++)
988 Log() << Verbose(1) << *(Runner->second) << endl;
989
990 for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++) {
991 baseline = Runner->second;
992 if (baseline->point == NULL) {
993 Log() << Verbose(0) << "Finding best candidate for open line " << *baseline->BaseLine << endl;
994 TesselationFailFlag = TesselStruct->FindNextSuitableTriangle(*baseline, *(((baseline->BaseLine->triangles.begin()))->second), RADIUS, LCList); //the line is there, so there is a triangle, but only one.
995 }
996 }
997
998 // 2b. search for smallest ShortestAngle among all candidates
999 double ShortestAngle = 4.*M_PI;
1000 Log() << Verbose(0) << "There are " << TesselStruct->OpenLines.size() << " open lines to scan for the best candidates:" << endl;
1001 for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++)
1002 Log() << Verbose(1) << *(Runner->second) << endl;
1003
1004 for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++) {
1005 if (Runner->second->ShortestAngle < ShortestAngle) {
1006 baseline = Runner->second;
1007 ShortestAngle = baseline->ShortestAngle;
1008 //Log() << Verbose(0) << "New best candidate is " << *baseline->BaseLine << " with point " << *baseline->point << " and angle " << baseline->ShortestAngle << endl;
1009 }
1010 }
1011 if ((ShortestAngle == 4.*M_PI) || (baseline->point == NULL))
1012 OneLoopWithoutSuccessFlag = false;
1013 else {
1014 TesselStruct->AddCandidateTriangle(*baseline);
1015 }
1016
1017 // write temporary envelope
1018 if (filename != NULL) {
1019 if ((DoSingleStepOutput && ((TesselStruct->TrianglesOnBoundary.size() % SingleStepWidth == 0)))) { // if we have a new triangle and want to output each new triangle configuration
1020 TesselStruct->Output(filename, mol);
1021 }
1022 }
1023 }
1024 // check envelope for consistency
1025 CheckListOfBaselines(TesselStruct);
1026
1027 // look whether all points are inside of the convex envelope, otherwise add them via degenerated triangles
1028 //->InsertStraddlingPoints(mol, LCList);
1029// mol->GoToFirst();
1030// class TesselPoint *Runner = NULL;
1031// while (!mol->IsEnd()) {
1032// Runner = mol->GetPoint();
1033// Log() << Verbose(1) << "Checking on " << Runner->Name << " ... " << endl;
1034// if (!->IsInnerPoint(Runner, LCList)) {
1035// Log() << Verbose(2) << Runner->Name << " is outside of envelope, adding via degenerated triangles." << endl;
1036// ->AddBoundaryPointByDegeneratedTriangle(Runner, LCList);
1037// } else {
1038// Log() << Verbose(2) << Runner->Name << " is inside of or on envelope." << endl;
1039// }
1040// mol->GoToNext();
1041// }
1042
1043 // Purges surplus triangles.
1044 TesselStruct->RemoveDegeneratedTriangles();
1045
1046 // check envelope for consistency
1047 CheckListOfBaselines(TesselStruct);
1048
1049 // write final envelope
1050 CalculateConcavityPerBoundaryPoint(TesselStruct);
1051 StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, "");
1052
1053 if (freeLC)
1054 delete(LCList);
1055 Log() << Verbose(0) << "End of FindNonConvexBorder\n";
1056};
1057
1058
1059/** Finds a hole of sufficient size in \a *mols to embed \a *srcmol into it.
1060 * \param *out output stream for debugging
1061 * \param *mols molecules in the domain to embed in between
1062 * \param *srcmol embedding molecule
1063 * \return *Vector new center of \a *srcmol for embedding relative to \a this
1064 */
1065Vector* FindEmbeddingHole(MoleculeListClass *mols, molecule *srcmol)
1066{
1067 Vector *Center = new Vector;
1068 Center->Zero();
1069 // calculate volume/shape of \a *srcmol
1070
1071 // find embedding holes
1072
1073 // if more than one, let user choose
1074
1075 // return embedding center
1076 return Center;
1077};
1078
Note: See TracBrowser for help on using the repository browser.