source: src/boundary.cpp@ f429d7

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

Made the world store the cell_size within a Box object.

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