source: src/boundary.cpp@ c5805a

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

FIX: allowing empty config files, and filling can deal with no molecules being present.

FillBoxWithMolecule():

  • Additional checks whether AtomCount>0
  • FIX: CopyAtoms was not initialised to NULL, hence wrong atoms might get "bonded".
  • if TesselStruct or LCList are NULL, these refer to empty molecules not to an error
  • breaking when atom would be placed was wrong, just continue to next atom of filler molecule.

config::LoadMolecule()

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