source: src/boundary.cpp@ cd5047

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

Fix of PrepareClustersInWater (at least it does not stumble over memory issues).

  • note: this was just done to make check test Filling/2 work again (which only runs and does not check the output)
  • GetBoundaryPoints() - using now left and right to have a good runner even if it is discarded/deleted, flag check when loop is through
  • PrepareClustersinWater() - LCList is now a pointer and removed after FindConvexBorder()
  • DOCUFIX: Tesselation::RemoveTesselationTriangle() - triangles attached to lines are printed starting on next line, not current
  • BUGFIX: Tesselation::FlipBaseline() - as we remove the two connected triangles, the baseline who they are attached to will be deleted and removed, hence the loop over the line's triangles does not work. Now, we first put all into a list, then delete the triangles.

This was the last test to fail. All unit tests (33), all testsuite cases (45) and all tesselation tests (15) work.

Signed-off-by: Frederik Heber <heber@…>

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