source: src/boundary.cpp@ 72d108

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 72d108 was a5028f, checked in by Frederik Heber <heber@…>, 14 years ago

RandomNumberGeneratorFactory is now used instead of rand() throughout the code.

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