source: src/boundary.cpp@ 57f243

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

Created libMolecuilderLinearAlgebra.

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