source: src/boundary.cpp@ 46d958

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 46d958 was 46d958, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made the world solely responsible for creating and destroying atoms.

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