source: src/Tesselation/boundary.cpp@ 5f7b95

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

Convex-envelope has debug parameter DoOutputEveryStep.

  • Property mode set to 100644
File size: 40.4 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
5 * Copyright (C) 2013 Frederik Heber. All rights reserved.
6 *
7 *
8 * This file is part of MoleCuilder.
9 *
10 * MoleCuilder is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * MoleCuilder is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24/** \file boundary.cpp
25 *
26 * Implementations and super-function for envelopes
27 */
28
29// include config.h
30#ifdef HAVE_CONFIG_H
31#include <config.h>
32#endif
33
34#include "CodePatterns/MemDebug.hpp"
35
36#include "Atom/atom.hpp"
37#include "Bond/bond.hpp"
38#include "boundary.hpp"
39#include "BoundaryLineSet.hpp"
40#include "BoundaryPointSet.hpp"
41#include "BoundaryTriangleSet.hpp"
42#include "Box.hpp"
43#include "CandidateForTesselation.hpp"
44#include "CodePatterns/Info.hpp"
45#include "CodePatterns/Log.hpp"
46#include "CodePatterns/Verbose.hpp"
47#include "config.hpp"
48#include "Element/element.hpp"
49#include "LinearAlgebra/Plane.hpp"
50#include "LinearAlgebra/RealSpaceMatrix.hpp"
51#include "LinkedCell/linkedcell.hpp"
52#include "LinkedCell/PointCloudAdaptor.hpp"
53#include "molecule.hpp"
54#include "MoleculeListClass.hpp"
55#include "RandomNumbers/RandomNumberGeneratorFactory.hpp"
56#include "RandomNumbers/RandomNumberGenerator.hpp"
57#include "tesselation.hpp"
58#include "tesselationhelpers.hpp"
59#include "World.hpp"
60
61#include <iostream>
62#include <iomanip>
63
64#include<gsl/gsl_poly.h>
65#include<time.h>
66
67// ========================================== F U N C T I O N S =================================
68
69
70/** Determines greatest diameters of a cluster defined by its convex envelope.
71 * Looks at lines parallel to one axis and where they intersect on the projected planes
72 * \param *out output stream for debugging
73 * \param *BoundaryPoints NDIM set of boundary points defining the convex envelope on each projected plane
74 * \param *mol molecule structure representing the cluster
75 * \param *&TesselStruct Tesselation structure with triangles
76 * \param IsAngstroem whether we have angstroem or atomic units
77 * \return NDIM array of the diameters
78 */
79double *GetDiametersOfCluster(const Boundaries *BoundaryPtr, const molecule *mol, Tesselation *&TesselStruct, const bool IsAngstroem)
80{
81 //Info FunctionInfo(__func__);
82 // get points on boundary of NULL was given as parameter
83 bool BoundaryFreeFlag = false;
84 double OldComponent = 0.;
85 double tmp = 0.;
86 double w1 = 0.;
87 double w2 = 0.;
88 Vector DistanceVector;
89 Vector OtherVector;
90 int component = 0;
91 int Othercomponent = 0;
92 Boundaries::const_iterator Neighbour;
93 Boundaries::const_iterator OtherNeighbour;
94 double *GreatestDiameter = new double[NDIM];
95
96 const Boundaries *BoundaryPoints;
97 if (BoundaryPtr == NULL) {
98 BoundaryFreeFlag = true;
99 BoundaryPoints = GetBoundaryPoints(mol, TesselStruct);
100 } else {
101 BoundaryPoints = BoundaryPtr;
102 LOG(0, "Using given boundary points set.");
103 }
104 // determine biggest "diameter" of cluster for each axis
105 for (int i = 0; i < NDIM; i++)
106 GreatestDiameter[i] = 0.;
107 for (int axis = 0; axis < NDIM; axis++)
108 { // regard each projected plane
109 //LOG(1, "Current axis is " << axis << ".");
110 for (int j = 0; j < 2; j++)
111 { // and for both axis on the current plane
112 component = (axis + j + 1) % NDIM;
113 Othercomponent = (axis + 1 + ((j + 1) & 1)) % NDIM;
114 //LOG(1, "Current component is " << component << ", Othercomponent is " << Othercomponent << ".");
115 for (Boundaries::const_iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
116 //LOG(1, "Current runner is " << *(runner->second.second) << ".");
117 // seek for the neighbours pair where the Othercomponent sign flips
118 Neighbour = runner;
119 Neighbour++;
120 if (Neighbour == BoundaryPoints[axis].end()) // make it wrap around
121 Neighbour = BoundaryPoints[axis].begin();
122 DistanceVector = (runner->second.second->getPosition()) - (Neighbour->second.second->getPosition());
123 do { // seek for neighbour pair where it flips
124 OldComponent = DistanceVector[Othercomponent];
125 Neighbour++;
126 if (Neighbour == BoundaryPoints[axis].end()) // make it wrap around
127 Neighbour = BoundaryPoints[axis].begin();
128 DistanceVector = (runner->second.second->getPosition()) - (Neighbour->second.second->getPosition());
129 //LOG(2, "OldComponent is " << OldComponent << ", new one is " << DistanceVector.x[Othercomponent] << ".");
130 } while ((runner != Neighbour) && (fabs(OldComponent / fabs(
131 OldComponent) - DistanceVector[Othercomponent] / fabs(
132 DistanceVector[Othercomponent])) < MYEPSILON)); // as long as sign does not flip
133 if (runner != Neighbour) {
134 OtherNeighbour = Neighbour;
135 if (OtherNeighbour == BoundaryPoints[axis].begin()) // make it wrap around
136 OtherNeighbour = BoundaryPoints[axis].end();
137 OtherNeighbour--;
138 //LOG(1, "The pair, where the sign of OtherComponent flips, is: " << *(Neighbour->second.second) << " and " << *(OtherNeighbour->second.second) << ".");
139 // now we have found the pair: Neighbour and OtherNeighbour
140 OtherVector = (runner->second.second->getPosition()) - (OtherNeighbour->second.second->getPosition());
141 //LOG(1, "Distances to Neighbour and OtherNeighbour are " << DistanceVector.x[component] << " and " << OtherVector.x[component] << ".");
142 //LOG(1, "OtherComponents to Neighbour and OtherNeighbour are " << DistanceVector.x[Othercomponent] << " and " << OtherVector.x[Othercomponent] << ".");
143 // do linear interpolation between points (is exact) to extract exact intersection between Neighbour and OtherNeighbour
144 w1 = fabs(OtherVector[Othercomponent]);
145 w2 = fabs(DistanceVector[Othercomponent]);
146 tmp = fabs((w1 * DistanceVector[component] + w2
147 * OtherVector[component]) / (w1 + w2));
148 // mark if it has greater diameter
149 //LOG(1, "Comparing current greatest " << GreatestDiameter[component] << " to new " << tmp << ".");
150 GreatestDiameter[component] = (GreatestDiameter[component]
151 > tmp) ? GreatestDiameter[component] : tmp;
152 } //else
153 //LOG(1, "Saw no sign flip, probably top or bottom node.");
154 }
155 }
156 }
157 LOG(0, "RESULT: The biggest diameters are "
158 << GreatestDiameter[0] << " and " << GreatestDiameter[1] << " and "
159 << GreatestDiameter[2] << " " << (IsAngstroem ? "angstrom"
160 : "atomiclength") << ".");
161
162 // free reference lists
163 if (BoundaryFreeFlag)
164 delete[] (BoundaryPoints);
165
166 return GreatestDiameter;
167}
168;
169
170
171/** Determines the boundary points of a cluster.
172 * Does a projection per axis onto the orthogonal plane, transforms into spherical coordinates, sorts them by the angle
173 * and looks at triples: if the middle has less a distance than the allowed maximum height of the triangle formed by the plane's
174 * center and first and last point in the triple, it is thrown out.
175 * \param *out output stream for debugging
176 * \param *mol molecule structure representing the cluster
177 * \param *&TesselStruct pointer to Tesselation structure
178 */
179Boundaries *GetBoundaryPoints(const molecule *mol, Tesselation *&TesselStruct)
180{
181 //Info FunctionInfo(__func__);
182 PointMap PointsOnBoundary;
183 LineMap LinesOnBoundary;
184 TriangleMap TrianglesOnBoundary;
185 Vector MolCenter = mol->DetermineCenterOfAll();
186 Vector helper;
187 BoundariesTestPair BoundaryTestPair;
188 Vector AxisVector;
189 Vector AngleReferenceVector;
190 Vector AngleReferenceNormalVector;
191 Vector ProjectedVector;
192 Boundaries *BoundaryPoints = new Boundaries[NDIM]; // first is alpha, second is (r, Nr)
193 double angle = 0.;
194
195 // 3a. Go through every axis
196 for (int axis = 0; axis < NDIM; axis++) {
197 AxisVector.Zero();
198 AngleReferenceVector.Zero();
199 AngleReferenceNormalVector.Zero();
200 AxisVector[axis] = 1.;
201 AngleReferenceVector[(axis + 1) % NDIM] = 1.;
202 AngleReferenceNormalVector[(axis + 2) % NDIM] = 1.;
203
204 LOG(1, "Axisvector is " << AxisVector << " and AngleReferenceVector is " << AngleReferenceVector << ", and AngleReferenceNormalVector is " << AngleReferenceNormalVector << ".");
205
206 // 3b. construct set of all points, transformed into cylindrical system and with left and right neighbours
207 // Boundaries stores non-const TesselPoint ref, hence we need iterator here
208 for (molecule::iterator iter = mol->begin(); iter != mol->end(); ++iter) {
209 ProjectedVector = (*iter)->getPosition() - (MolCenter);
210 ProjectedVector.ProjectOntoPlane(AxisVector);
211
212 // correct for negative side
213 const double radius = ProjectedVector.NormSquared();
214 if (fabs(radius) > MYEPSILON)
215 angle = ProjectedVector.Angle(AngleReferenceVector);
216 else
217 angle = 0.; // otherwise it's a vector in Axis Direction and unimportant for boundary issues
218
219 //LOG(1, "Checking sign in quadrant : " << ProjectedVector.Projection(&AngleReferenceNormalVector) << ".");
220 if (ProjectedVector.ScalarProduct(AngleReferenceNormalVector) > 0) {
221 angle = 2. * M_PI - angle;
222 }
223 LOG(1, "Inserting " << **iter << ": (r, alpha) = (" << radius << "," << angle << "): " << ProjectedVector);
224 BoundaryTestPair = BoundaryPoints[axis].insert(BoundariesPair(angle, TesselPointDistancePair (radius, (*iter))));
225 if (!BoundaryTestPair.second) { // same point exists, check first r, then distance of original vectors to center of gravity
226 LOG(2, "Encountered two vectors whose projection onto axis " << axis << " is equal: ");
227 LOG(2, "Present vector: " << *BoundaryTestPair.first->second.second);
228 LOG(2, "New vector: " << **iter);
229 const double ProjectedVectorNorm = ProjectedVector.NormSquared();
230 if ((ProjectedVectorNorm - BoundaryTestPair.first->second.first) > MYEPSILON) {
231 BoundaryTestPair.first->second.first = ProjectedVectorNorm;
232 BoundaryTestPair.first->second.second = (*iter);
233 LOG(2, "Keeping new vector due to larger projected distance " << ProjectedVectorNorm << ".");
234 } else if (fabs(ProjectedVectorNorm - BoundaryTestPair.first->second.first) < MYEPSILON) {
235 helper = (*iter)->getPosition() - (MolCenter);
236 const double oldhelperNorm = helper.NormSquared();
237 helper = BoundaryTestPair.first->second.second->getPosition() - (MolCenter);
238 if (helper.NormSquared() < oldhelperNorm) {
239 BoundaryTestPair.first->second.second = (*iter);
240 LOG(2, "Keeping new vector due to larger distance to molecule center " << helper.NormSquared() << ".");
241 } else {
242 LOG(2, "Keeping present vector due to larger distance to molecule center " << oldhelperNorm << ".");
243 }
244 } else {
245 LOG(2, "Keeping present vector due to larger projected distance " << ProjectedVectorNorm << ".");
246 }
247 }
248 }
249 // printing all inserted for debugging
250 // {
251 // std::stringstream output;
252 // output << "Printing list of candidates for axis " << axis << " which we have inserted so far: ";
253 // int i=0;
254 // for(Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
255 // if (runner != BoundaryPoints[axis].begin())
256 // output << ", " << i << ": " << *runner->second.second;
257 // else
258 // output << i << ": " << *runner->second.second;
259 // i++;
260 // }
261 // LOG(1, output.str());
262 // }
263 // 3c. throw out points whose distance is less than the mean of left and right neighbours
264 bool flag = false;
265 LOG(1, "Looking for candidates to kick out by convex condition ... ");
266 do { // do as long as we still throw one out per round
267 flag = false;
268 Boundaries::iterator left = BoundaryPoints[axis].begin();
269 Boundaries::iterator right = BoundaryPoints[axis].begin();
270 Boundaries::iterator runner = BoundaryPoints[axis].begin();
271 bool LoopOnceDone = false;
272 while (!LoopOnceDone) {
273 runner = right;
274 right++;
275 // set neighbours correctly
276 if (runner == BoundaryPoints[axis].begin()) {
277 left = BoundaryPoints[axis].end();
278 } else {
279 left = runner;
280 }
281 left--;
282 if (right == BoundaryPoints[axis].end()) {
283 right = BoundaryPoints[axis].begin();
284 LoopOnceDone = true;
285 }
286 // check distance
287
288 // construct the vector of each side of the triangle on the projected plane (defined by normal vector AxisVector)
289 {
290 Vector SideA, SideB, SideC, SideH;
291 SideA = left->second.second->getPosition() - (MolCenter);
292 SideA.ProjectOntoPlane(AxisVector);
293 // LOG(1, "SideA: " << SideA);
294
295 SideB = right->second.second->getPosition() -(MolCenter);
296 SideB.ProjectOntoPlane(AxisVector);
297 // LOG(1, "SideB: " << SideB);
298
299 SideC = left->second.second->getPosition() - right->second.second->getPosition();
300 SideC.ProjectOntoPlane(AxisVector);
301 // LOG(1, "SideC: " << SideC);
302
303 SideH = runner->second.second->getPosition() -(MolCenter);
304 SideH.ProjectOntoPlane(AxisVector);
305 // LOG(1, "SideH: " << SideH);
306
307 // calculate each length
308 const double a = SideA.Norm();
309 //const double b = SideB.Norm();
310 //const double c = SideC.Norm();
311 const double h = SideH.Norm();
312 // calculate the angles
313 const double alpha = SideA.Angle(SideH);
314 const double beta = SideA.Angle(SideC);
315 const double gamma = SideB.Angle(SideH);
316 const double delta = SideC.Angle(SideH);
317 const double MinDistance = a * sin(beta) / (sin(delta)) * (((alpha < M_PI / 2.) || (gamma < M_PI / 2.)) ? 1. : -1.);
318 //LOG(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 << ".");
319 LOG(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 << ".");
320 if ((fabs(h / fabs(h) - MinDistance / fabs(MinDistance)) < MYEPSILON) && ((h - MinDistance)) < -MYEPSILON) {
321 // throw out point
322 LOG(1, "Throwing out " << *runner->second.second << ".");
323 BoundaryPoints[axis].erase(runner);
324 runner = right;
325 flag = true;
326 }
327 }
328 }
329 } while (flag);
330 }
331 return BoundaryPoints;
332};
333
334/** Tesselates the convex boundary by finding all boundary points.
335 * \param *out output stream for debugging
336 * \param *mol molecule structure with Atom's and Bond's.
337 * \param *BoundaryPts set of boundary points to use or NULL
338 * \param *TesselStruct Tesselation filled with points, lines and triangles on boundary on return
339 * \param *LCList atoms in LinkedCell_deprecated list
340 * \param *filename filename prefix for output of vertex data
341 * \return *TesselStruct is filled with convex boundary and tesselation is stored under \a *filename.
342 */
343void FindConvexBorder(const molecule* mol, Boundaries *BoundaryPts, Tesselation *&TesselStruct, const LinkedCell_deprecated *LCList, const char *filename)
344{
345 //Info FunctionInfo(__func__);
346 bool BoundaryFreeFlag = false;
347 Boundaries *BoundaryPoints = NULL;
348
349 if (TesselStruct != NULL) // free if allocated
350 delete(TesselStruct);
351 TesselStruct = new class Tesselation;
352
353 // 1. Find all points on the boundary
354 if (BoundaryPts == NULL) {
355 BoundaryFreeFlag = true;
356 BoundaryPoints = GetBoundaryPoints(mol, TesselStruct);
357 } else {
358 BoundaryPoints = BoundaryPts;
359 LOG(0, "Using given boundary points set.");
360 }
361
362// printing all inserted for debugging
363 if (DoLog(1)) {
364 for (int axis=0; axis < NDIM; axis++) {
365 std::stringstream output;
366 output << "Printing list of candidates for axis " << axis << " which we have inserted so far: ";
367 int i=0;
368 for(Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
369 if (runner != BoundaryPoints[axis].begin())
370 output << ", " << i << ": " << *runner->second.second;
371 else
372 output << i << ": " << *runner->second.second;
373 i++;
374 }
375 LOG(1, output.str());
376 }
377 }
378
379 // 2. fill the boundary point list
380 for (int axis = 0; axis < NDIM; axis++)
381 for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++)
382 if (!TesselStruct->AddBoundaryPoint(runner->second.second, 0))
383 LOG(2, "Point " << *(runner->second.second) << " is already present.");
384
385 LOG(0, "I found " << TesselStruct->PointsOnBoundaryCount << " points on the convex boundary.");
386 // now we have the whole set of edge points in the BoundaryList
387
388 // listing for debugging
389 //if (DoLog(1)) {
390 // std::stringstream output;
391 // output << "Listing PointsOnBoundary:";
392 // for(PointMap::iterator runner = PointsOnBoundary.begin(); runner != PointsOnBoundary.end(); runner++) {
393 // output << " " << *runner->second;
394 // }
395 // LOG(1, output.str());
396 //}
397
398 // 3a. guess starting triangle
399 TesselStruct->GuessStartingTriangle();
400
401 // 3b. go through all lines, that are not yet part of two triangles (only of one so far)
402 PointCloudAdaptor< molecule > cloud(const_cast<molecule *>(mol), mol->name);
403 TesselStruct->TesselateOnBoundary(cloud);
404
405 // 3c. check whether all atoms lay inside the boundary, if not, add to boundary points, segment triangle into three with the new point
406 if (!TesselStruct->InsertStraddlingPoints(cloud, LCList))
407 ELOG(1, "Insertion of straddling points failed!");
408
409 LOG(0, "I created " << TesselStruct->TrianglesOnBoundary.size() << " intermediate triangles with " << TesselStruct->LinesOnBoundary.size() << " lines and " << TesselStruct->PointsOnBoundary.size() << " points.");
410
411 // 4. Store triangles in tecplot file
412 StoreTrianglesinFile(mol, TesselStruct, filename, "_intermed");
413
414 // 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
415 bool AllConvex = true;
416 class BoundaryLineSet *line = NULL;
417 do {
418 AllConvex = true;
419 for (LineMap::iterator LineRunner = TesselStruct->LinesOnBoundary.begin(); LineRunner != TesselStruct->LinesOnBoundary.end(); LineRunner++) {
420 line = LineRunner->second;
421 LOG(1, "INFO: Current line is " << *line << ".");
422 if (!line->CheckConvexityCriterion()) {
423 LOG(1, "... line " << *line << " is concave, flipping it.");
424
425 // flip the line
426 if (TesselStruct->PickFarthestofTwoBaselines(line) == 0.)
427 ELOG(1, "Correction of concave baselines failed!");
428 else {
429 TesselStruct->FlipBaseline(line);
430 LOG(1, "INFO: Correction of concave baselines worked.");
431 LineRunner = TesselStruct->LinesOnBoundary.begin(); // LineRunner may have been erase if line was deleted from LinesOnBoundary
432 }
433 }
434 }
435 } while (!AllConvex);
436
437 // 3e. we need another correction here, for TesselPoints that are below the surface (i.e. have an odd number of concave triangles surrounding it)
438// if (!TesselStruct->CorrectConcaveTesselPoints(out))
439// ELOG(1, "Correction of concave tesselpoints failed!");
440
441 LOG(0, "I created " << TesselStruct->TrianglesOnBoundary.size() << " triangles with " << TesselStruct->LinesOnBoundary.size() << " lines and " << TesselStruct->PointsOnBoundary.size() << " points.");
442
443 // 4. Store triangles in tecplot file
444 StoreTrianglesinFile(mol, TesselStruct, filename, "");
445
446 // free reference lists
447 if (BoundaryFreeFlag)
448 delete[] (BoundaryPoints);
449};
450
451/** For testing removes one boundary point after another to check for leaks.
452 * \param *out output stream for debugging
453 * \param *TesselStruct Tesselation containing envelope with boundary points
454 * \param *mol molecule
455 * \param *filename name of file
456 * \return true - all removed, false - something went wrong
457 */
458bool RemoveAllBoundaryPoints(class Tesselation *&TesselStruct, const molecule * const mol, const char * const filename)
459{
460 //Info FunctionInfo(__func__);
461 int i=0;
462 char number[MAXSTRINGSIZE];
463
464 if ((TesselStruct == NULL) || (TesselStruct->PointsOnBoundary.empty())) {
465 ELOG(1, "TesselStruct is empty.");
466 return false;
467 }
468
469 PointMap::iterator PointRunner;
470 while (!TesselStruct->PointsOnBoundary.empty()) {
471 if (DoLog(1)) {
472 std::stringstream output;
473 output << "Remaining points are: ";
474 for (PointMap::iterator PointSprinter = TesselStruct->PointsOnBoundary.begin(); PointSprinter != TesselStruct->PointsOnBoundary.end(); PointSprinter++)
475 output << *(PointSprinter->second) << "\t";
476 LOG(1, output.str());
477 }
478
479 PointRunner = TesselStruct->PointsOnBoundary.begin();
480 // remove point
481 TesselStruct->RemovePointFromTesselatedSurface(PointRunner->second);
482
483 // store envelope
484 sprintf(number, "-%04d", i++);
485 StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, number);
486 }
487
488 return true;
489};
490
491/** Creates a convex envelope from a given non-convex one.
492 * -# First step, remove concave spots, i.e. singular "dents"
493 * -# We go through all PointsOnBoundary.
494 * -# We CheckConvexityCriterion() for all its lines.
495 * -# If all its lines are concave, it cannot be on the convex envelope.
496 * -# Hence, we remove it and re-create all its triangles from its getCircleOfConnectedPoints()
497 * -# We calculate the additional volume.
498 * -# We go over all lines until none yields a concavity anymore.
499 * -# Second step, remove concave lines, i.e. line-shape "dents"
500 * -# We go through all LinesOnBoundary
501 * -# We CheckConvexityCriterion()
502 * -# If it returns concave, we flip the line in this quadrupel of points (abusing the degeneracy of the tesselation)
503 * -# We CheckConvexityCriterion(),
504 * -# if it's concave, we continue
505 * -# if not, we mark an error and stop
506 * Note: This routine - for free - calculates the difference in volume between convex and
507 * non-convex envelope, as the former is easy to calculate - Tesselation::getVolumeOfConvexEnvelope() - it
508 * can be used to compute volumes of arbitrary shapes.
509 * \param *out output stream for debugging
510 * \param *TesselStruct non-convex envelope, is changed in return!
511 * \param *mol molecule
512 * \param *filename name of file
513 * \return volume difference between the non- and the created convex envelope
514 */
515double ConvexizeNonconvexEnvelope(
516 Tesselation *&TesselStruct,
517 const molecule * const mol,
518 const char * const filename,
519 bool DebugOutputEveryStep)
520{
521 //Info FunctionInfo(__func__);
522 double volume = 0;
523 class BoundaryPointSet *point = NULL;
524 class BoundaryLineSet *line = NULL;
525 bool Concavity = false;
526 char dummy[MAXSTRINGSIZE];
527 PointMap::iterator PointRunner;
528 PointMap::iterator PointAdvance;
529 LineMap::iterator LineRunner;
530 LineMap::iterator LineAdvance;
531 TriangleMap::iterator TriangleRunner;
532 TriangleMap::iterator TriangleAdvance;
533 int run = 0;
534
535 // check whether there is something to work on
536 if (TesselStruct == NULL) {
537 ELOG(1, "TesselStruct is empty!");
538 return volume;
539 }
540
541 LOG(1, "INFO: Making tesselated surface with " << TesselStruct->TrianglesOnBoundaryCount
542 << " convex ...");
543
544 // first purge all degenerate triangles
545 TesselStruct->RemoveDegeneratedTriangles();
546
547 do {
548 Concavity = false;
549
550 if (DebugOutputEveryStep) {
551 sprintf(dummy, "-%d", run++);
552 //CalculateConcavityPerBoundaryPoint(TesselStruct);
553 LOG(1, "INFO: Writing " << run << "th tesselation file.");
554 StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, dummy);
555 }
556
557 // first step: remove all full-concave point
558 PointRunner = TesselStruct->PointsOnBoundary.begin();
559 PointAdvance = PointRunner; // we need an advanced point, as the PointRunner might get removed
560 while (PointRunner != TesselStruct->PointsOnBoundary.end()) {
561 PointAdvance++;
562 point = PointRunner->second;
563 LOG(2, "INFO: Current point is " << *point << ".");
564 // check that at least a single line is concave
565 LineMap::iterator LineRunner = point->lines.begin();
566 for (; LineRunner != point->lines.end(); LineRunner++) {
567 const BoundaryLineSet * line = LineRunner->second;
568 LOG(3, "INFO: Current line of point " << *point << " is " << *line << ".");
569 if (!line->CheckConvexityCriterion())
570 break;
571 }
572 // remove the point if needed
573 if (LineRunner != point->lines.end()) {
574 const double tmp = TesselStruct->RemoveFullConcavePointFromTesselatedSurface(point);
575 if (tmp > 0.) {
576 volume += tmp;
577 Concavity = true;
578 }
579 }
580 PointRunner = PointAdvance;
581 }
582
583 if (DebugOutputEveryStep) {
584 sprintf(dummy, "-%d", run++);
585 //CalculateConcavityPerBoundaryPoint(TesselStruct);
586 LOG(1, "INFO: Writing " << run << "th tesselation file.");
587 StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, dummy);
588 }
589
590 // second step: flip baselines, i.e. add general tetraeder at concave lines
591 // when the tetraeder does not intersect with other already present triangles
592 LineRunner = TesselStruct->LinesOnBoundary.begin();
593 LineAdvance = LineRunner; // we need an advanced line, as the LineRunner might get removed
594 std::map<double, std::pair<BoundaryLineSet *, double> > GainMap;
595 while (LineRunner != TesselStruct->LinesOnBoundary.end()) {
596 LineAdvance++;
597 line = LineRunner->second;
598 if (!line->CheckConvexityCriterion()) {
599 LOG(2, "INFO: concave line is " << *line << ".");
600 // gather the other points
601 BoundaryPointSet *BPS[4];
602 int m = 0;
603 {
604 for (TriangleMap::iterator runner = line->triangles.begin(); runner != line->triangles.end(); runner++)
605 for (int j = 0; j < 3; j++) // all of their endpoints and baselines
606 if (!line->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
607 BPS[m++] = runner->second->endpoints[j];
608 }
609 BPS[2] = line->endpoints[0];
610 BPS[3] = line->endpoints[1];
611 LOG(3, "DEBUG: other line would consist of " << *BPS[0] << " and "
612 << *BPS[1] << ".");
613
614 // check for already present (third) side of the tetraeder as we then
615 // would create a degenerate triangle
616 bool TetraederSidePresent = false;
617 {
618 class TesselPoint *TriangleCandidates[3];
619 TriangleCandidates[0] = BPS[0]->node;
620 TriangleCandidates[1] = BPS[1]->node;
621 TriangleCandidates[2] = BPS[2]->node;
622 if ((TesselStruct->GetPresentTriangle(TriangleCandidates) != NULL)) {
623 LOG(2, "REJECT: Triangle side " << *TriangleCandidates[0] << ","
624 << *TriangleCandidates[1] << "," << *TriangleCandidates[2] << " present.");
625 TetraederSidePresent = true;
626 }
627 TriangleCandidates[2] = BPS[3]->node;
628 if ((TesselStruct->GetPresentTriangle(TriangleCandidates) != NULL)) {
629 LOG(2, "REJECT: Triangle side " << *TriangleCandidates[0] << ","
630 << *TriangleCandidates[1] << "," << *TriangleCandidates[2] << " present.");
631 TetraederSidePresent = true;
632 }
633 }
634
635 if ((BPS[0] != BPS[1]) && (m == 2) && (!TetraederSidePresent)) {
636 // check whether all adjacent triangles do not intersect with new line
637 bool no_line_intersects = true;
638 Vector Intersection;
639 TriangleSet triangles;
640 TriangleSet *firsttriangles = TesselStruct->GetAllTriangles(line->endpoints[0]);
641 TriangleSet *secondtriangles = TesselStruct->GetAllTriangles(line->endpoints[1]);
642 triangles.insert( firsttriangles->begin(), firsttriangles->end() );
643 triangles.insert( secondtriangles->begin(), secondtriangles->end() );
644 delete firsttriangles;
645 delete secondtriangles;
646 for (TriangleSet::const_iterator triangleiter = triangles.begin();
647 triangleiter != triangles.end(); ++triangleiter) {
648 const BoundaryTriangleSet * triangle = *triangleiter;
649 bool line_intersects = triangle->GetIntersectionInsideTriangle(
650 BPS[0]->node->getPosition(),
651 BPS[1]->node->getPosition(),
652 Intersection);
653 // switch result when coinciding with endpoint
654 bool concave_adjacent_line = false;
655 bool intersection_is_endnode = false;
656 for (int j=0;j<2;++j) {
657 if (Intersection.DistanceSquared(BPS[j]->node->getPosition()) < MYEPSILON) {
658 intersection_is_endnode = true;
659 // check whether its an adjacent triangle and if it's concavely connected
660 // only then are we in danger of cutting through it and need to check
661 // sign of normal vector and intersecting line
662 for (int i=0;i<2;++i)
663 for (int lineindex=0;lineindex < 3;++lineindex)
664 if ((triangle->lines[lineindex]->ContainsBoundaryPoint(line->endpoints[i]))
665 && (triangle->lines[lineindex]->ContainsBoundaryPoint(BPS[j]))) {
666 concave_adjacent_line = !triangle->lines[lineindex]->CheckConvexityCriterion();
667 }
668 if (concave_adjacent_line) {
669 const Vector intersector =
670 BPS[(j+1)%2]->node->getPosition() - Intersection;
671 if (triangle->NormalVector.ScalarProduct(intersector) >= -MYEPSILON) {
672 LOG(4, "ACCEPT: Intersection coincides with first endpoint "
673 << *BPS[j] << ".");
674 line_intersects = false;
675 } else {
676 LOG(4, "REJECT: Intersection ends on wrong side of triangle.");
677 }
678 } else {
679 LOG(4, "ACCEPT: Intersection coincides with first endpoint "
680 << *BPS[j] << ".");
681 line_intersects = false;
682 }
683 }
684 }
685 // if we have an intersection, check that it is within either
686 // endpoint, i.e. check that scalar product between vectors going
687 // from intersction to either endpoint has negative sign (both
688 // vectors point in opposite directions)
689 if (!intersection_is_endnode && line_intersects) {
690 const Vector firstvector = BPS[0]->node->getPosition() - Intersection;
691 const Vector secondvector = BPS[1]->node->getPosition() - Intersection;
692 if (firstvector.ScalarProduct(secondvector) >= 0)
693 line_intersects = false;
694 }
695 no_line_intersects &= !line_intersects;
696 }
697
698 if (no_line_intersects) {
699 // calculate the volume
700 const double tmp = line->CalculateConvexity();
701 const double gain =
702 CalculateVolumeofGeneralTetraeder(
703 BPS[0]->node->getPosition(),
704 BPS[1]->node->getPosition(),
705 BPS[2]->node->getPosition(),
706 BPS[3]->node->getPosition());
707
708 GainMap.insert(std::make_pair(tmp, std::make_pair(line,gain) ));
709 LOG(2, "DEBUG: Adding concave line " << *line << " with gain of "
710 << gain << ".");
711 } else {
712 // if 2 or 3 don't
713 LOG(2, "DEBUG: We don't added concave line " << *line
714 << " as other line intersects with adjacent triangles.");
715 }
716 }
717 }
718 LineRunner = LineAdvance;
719 }
720 // flip line with most gain
721 if (!GainMap.empty()) {
722 line = GainMap.begin()->second.first;
723 const double tmp = GainMap.begin()->second.second;
724 volume += tmp;
725
726// GainMap.clear();
727
728 // and flip the line
729 LOG(1, "INFO: Flipping current most concave line " << *line << " with gain of "
730 << tmp << ".");
731 TesselStruct->FlipBaseline(line);
732 Concavity = true;
733 }
734 } while ((Concavity)); // && (run < 100)
735
736 CalculateConcavityPerBoundaryPoint(TesselStruct);
737 StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, "");
738
739 // end
740 LOG(0, "RESULT: Added volume in convexization is " << volume << ".");
741 return volume;
742};
743
744
745/** Stores triangles to file.
746 * \param *out output stream for debugging
747 * \param *mol molecule with atoms and bonds
748 * \param *TesselStruct Tesselation with boundary triangles
749 * \param *filename prefix of filename
750 * \param *extraSuffix intermediate suffix
751 */
752void StoreTrianglesinFile(const molecule * const mol, const Tesselation * const TesselStruct, const char *filename, const char *extraSuffix)
753{
754 //Info FunctionInfo(__func__);
755 PointCloudAdaptor< molecule > cloud(const_cast<molecule *>(mol), mol->name);
756 // 4. Store triangles in tecplot file
757 if (filename != NULL) {
758 if (DoTecplotOutput) {
759 string OutputName(filename);
760 OutputName.append(extraSuffix);
761 OutputName.append(TecplotSuffix);
762 ofstream *tecplot = new ofstream(OutputName.c_str());
763 WriteTecplotFile(tecplot, TesselStruct, cloud, -1);
764 tecplot->close();
765 delete(tecplot);
766 }
767 if (DoRaster3DOutput) {
768 string OutputName(filename);
769 OutputName.append(extraSuffix);
770 OutputName.append(Raster3DSuffix);
771 ofstream *rasterplot = new ofstream(OutputName.c_str());
772 WriteRaster3dFile(rasterplot, TesselStruct, cloud);
773 rasterplot->close();
774 delete(rasterplot);
775 }
776 }
777};
778
779/** Tesselates the non convex boundary by rolling a virtual sphere along the surface of the molecule.
780 * \param *out output stream for debugging
781 * \param *mol molecule structure with Atom's and Bond's
782 * \param *&TesselStruct Tesselation filled with points, lines and triangles on boundary on return
783 * \param *&LCList atoms in LinkedCell_deprecated list
784 * \param RADIUS radius of the virtual sphere
785 * \param *filename filename prefix for output of vertex data
786 * \return true - tesselation successful, false - tesselation failed
787 */
788bool FindNonConvexBorder(molecule* const mol, Tesselation *&TesselStruct, const LinkedCell_deprecated *&LCList, const double RADIUS, const char *filename = NULL)
789{
790 //Info FunctionInfo(__func__);
791 bool freeLC = false;
792 bool status = false;
793 CandidateForTesselation *baseline = NULL;
794 bool OneLoopWithoutSuccessFlag = true; // marks whether we went once through all baselines without finding any without two triangles
795// bool TesselationFailFlag = false;
796
797 mol->getAtomCount();
798
799 if (TesselStruct == NULL) {
800 LOG(1, "Allocating Tesselation struct ...");
801 TesselStruct= new Tesselation;
802 } else {
803 delete(TesselStruct);
804 LOG(1, "Re-Allocating Tesselation struct ...");
805 TesselStruct = new Tesselation;
806 }
807
808 // initialise Linked Cell
809 PointCloudAdaptor< molecule > cloud(mol, mol->name);
810 if (LCList == NULL) {
811 LCList = new LinkedCell_deprecated(cloud, 2.*RADIUS);
812 freeLC = true;
813 }
814
815 // 1. get starting triangle
816 if (!TesselStruct->FindStartingTriangle(RADIUS, LCList)) {
817 ELOG(0, "No valid starting triangle found.");
818 //performCriticalExit();
819 }
820 if (filename != NULL) {
821 if ((DoSingleStepOutput && ((TesselStruct->TrianglesOnBoundary.size() % SingleStepWidth == 0)))) { // if we have a new triangle and want to output each new triangle configuration
822 TesselStruct->Output(filename, cloud);
823 }
824 }
825
826 // 2. expand from there
827 while ((!TesselStruct->OpenLines.empty()) && (OneLoopWithoutSuccessFlag)) {
828 (cerr << "There are " << TesselStruct->TrianglesOnBoundary.size() << " triangles and " << TesselStruct->OpenLines.size() << " open lines to scan for candidates." << endl);
829 // 2a. print OpenLines without candidates
830 LOG(1, "There are the following open lines to scan for a candidates:");
831 for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++)
832 if (Runner->second->pointlist.empty())
833 LOG(1, " " << *(Runner->second));
834
835 // 2b. find best candidate for each OpenLine
836 const bool TesselationFailFlag = TesselStruct->FindCandidatesforOpenLines(RADIUS, LCList);
837 ASSERT( TesselationFailFlag,
838 "FindNonConvexBorder() - at least one open line without candidate exists.");
839
840 // 2c. print OpenLines with candidates again
841 LOG(1, "There are " << TesselStruct->OpenLines.size() << " open lines to scan for the best candidates:");
842 for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++)
843 LOG(1, " " << *(Runner->second));
844
845 // 2d. search for smallest ShortestAngle among all candidates
846 double ShortestAngle = 4.*M_PI;
847 for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++) {
848 if (Runner->second->ShortestAngle < ShortestAngle) {
849 baseline = Runner->second;
850 ShortestAngle = baseline->ShortestAngle;
851 LOG(1, "New best candidate is " << *baseline->BaseLine << " with point " << *(*baseline->pointlist.begin()) << " and angle " << baseline->ShortestAngle);
852 }
853 }
854 // 2e. if we found one, add candidate
855 if ((ShortestAngle == 4.*M_PI) || (baseline->pointlist.empty()))
856 OneLoopWithoutSuccessFlag = false;
857 else {
858 TesselStruct->AddCandidatePolygon(*baseline, RADIUS, LCList);
859 }
860
861 // 2f. write temporary envelope
862 if (filename != NULL) {
863 if ((DoSingleStepOutput && ((TesselStruct->TrianglesOnBoundary.size() % SingleStepWidth == 0)))) { // if we have a new triangle and want to output each new triangle configuration
864 TesselStruct->Output(filename, cloud);
865 }
866 }
867 }
868// // check envelope for consistency
869// status = CheckListOfBaselines(TesselStruct);
870//
871// // look whether all points are inside of the convex envelope, otherwise add them via degenerated triangles
872// //->InsertStraddlingPoints(mol, LCList);
873// for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
874// class TesselPoint *Runner = NULL;
875// Runner = *iter;
876// LOG(1, "Checking on " << Runner->Name << " ... ");
877// if (!->IsInnerPoint(Runner, LCList)) {
878// LOG(2, Runner->Name << " is outside of envelope, adding via degenerated triangles.");
879// ->AddBoundaryPointByDegeneratedTriangle(Runner, LCList);
880// } else {
881// LOG(2, Runner->Name << " is inside of or on envelope.");
882// }
883// }
884
885// // Purges surplus triangles.
886// TesselStruct->RemoveDegeneratedTriangles();
887//
888// // check envelope for consistency
889// status = CheckListOfBaselines(TesselStruct);
890
891// cout << "before correction" << endl;
892
893 // store before correction
894 StoreTrianglesinFile(mol, TesselStruct, filename, "");
895
896// // correct degenerated polygons
897// TesselStruct->CorrectAllDegeneratedPolygons();
898//
899 // check envelope for consistency
900 status = CheckListOfBaselines(TesselStruct);
901
902 // write final envelope
903 CalculateConcavityPerBoundaryPoint(TesselStruct);
904// cout << "after correction" << endl;
905 StoreTrianglesinFile(mol, TesselStruct, filename, "");
906
907 if (freeLC)
908 delete(LCList);
909
910 return status;
911};
912
913
914/** Finds a hole of sufficient size in \a *mols to embed \a *srcmol into it.
915 * \param *out output stream for debugging
916 * \param *mols molecules in the domain to embed in between
917 * \param *srcmol embedding molecule
918 * \return *Vector new center of \a *srcmol for embedding relative to \a this
919 */
920Vector* FindEmbeddingHole(MoleculeListClass *mols, molecule *srcmol)
921{
922 //Info FunctionInfo(__func__);
923 Vector *Center = new Vector;
924 Center->Zero();
925 // calculate volume/shape of \a *srcmol
926
927 // find embedding holes
928
929 // if more than one, let user choose
930
931 // return embedding center
932 return Center;
933};
934
Note: See TracBrowser for help on using the repository browser.