source: src/boundary.cpp@ d51975

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

Small changes to FindConvexBorder().

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

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