source: src/ellipsoid.cpp@ 89c8b2

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

Huge refactoring of Tesselation routines, but not finished yet.

  • new file tesselation.cpp with all of classes tesselation, Boundary..Set and CandidatesForTesselationOB
  • new file tesselationhelper.cpp with all auxiliary functions.
  • boundary.cpp just contains super functions, combininb molecule and Tesselation pointers
  • new pointer molecule::TesselStruct
  • PointMap, LineMap, TriangleMap DistanceMap have been moved from molecules.hpp to tesselation.hpp
  • new abstract class PointCloud and TesselPoint
  • atom inherits TesselPoint
  • molecule inherits PointCloud (i.e. a set of TesselPoints) and implements all virtual functions for the chained list
  • TriangleFilesWritten is thrown out, intermediate steps are written in find_nonconvex_border and not in find_next_triangle()
  • LinkedCell class uses TesselPoint as its nodes, i.e. as long as any class inherits TesselPoint, it may make use of LinkedCell as well and a PointCloud is used to initialize
  • class atom and bond definitions have been moved to own header files

NOTE: This is not bugfree yet. Tesselation of heptan produces way too many triangles, but runs without faults or leaks.

  • Property mode set to 100644
File size: 16.4 KB
Line 
1/*
2 * ellipsoid.cpp
3 *
4 * Created on: Jan 20, 2009
5 * Author: heber
6 */
7
8#include <gsl/gsl_multimin.h>
9#include <gsl/gsl_vector.h>
10
11#include "boundary.hpp"
12#include "ellipsoid.hpp"
13
14/** Determines squared distance for a given point \a x to surface of ellipsoid.
15 * \param x given point
16 * \param EllipsoidCenter center of ellipsoid
17 * \param EllipsoidLength[3] three lengths of half axis of ellipsoid
18 * \param EllipsoidAngle[3] three rotation angles of ellipsoid
19 * \return squared distance from point to surface
20 */
21double SquaredDistanceToEllipsoid(Vector &x, Vector &EllipsoidCenter, double *EllipsoidLength, double *EllipsoidAngle)
22{
23 Vector helper, RefPoint;
24 double distance = -1.;
25 double Matrix[NDIM*NDIM];
26 double InverseLength[3];
27 double psi,theta,phi; // euler angles in ZX'Z'' convention
28
29 //cout << Verbose(3) << "Begin of SquaredDistanceToEllipsoid" << endl;
30
31 for(int i=0;i<3;i++)
32 InverseLength[i] = 1./EllipsoidLength[i];
33
34 // 1. translate coordinate system so that ellipsoid center is in origin
35 helper.CopyVector(&x);
36 helper.SubtractVector(&EllipsoidCenter);
37 RefPoint.CopyVector(&helper);
38 //cout << Verbose(4) << "Translated given point is at " << RefPoint << "." << endl;
39
40 // 2. transform coordinate system by inverse of rotation matrix and of diagonal matrix
41 psi = EllipsoidAngle[0];
42 theta = EllipsoidAngle[1];
43 phi = EllipsoidAngle[2];
44 Matrix[0] = cos(psi)*cos(phi) - sin(psi)*cos(theta)*sin(phi);
45 Matrix[1] = -cos(psi)*sin(phi) - sin(psi)*cos(theta)*cos(phi);
46 Matrix[2] = sin(psi)*sin(theta);
47 Matrix[3] = sin(psi)*cos(phi) + cos(psi)*cos(theta)*sin(phi);
48 Matrix[4] = cos(psi)*cos(theta)*cos(phi) - sin(psi)*sin(phi);
49 Matrix[5] = -cos(psi)*sin(theta);
50 Matrix[6] = sin(theta)*sin(phi);
51 Matrix[7] = sin(theta)*cos(phi);
52 Matrix[8] = cos(theta);
53 helper.MatrixMultiplication(Matrix);
54 helper.Scale(InverseLength);
55 //cout << Verbose(4) << "Transformed RefPoint is at " << helper << "." << endl;
56
57 // 3. construct intersection point with unit sphere and ray between origin and x
58 helper.Normalize(); // is simply normalizes vector in distance direction
59 //cout << Verbose(4) << "Transformed intersection is at " << helper << "." << endl;
60
61 // 4. transform back the constructed intersection point
62 psi = -EllipsoidAngle[0];
63 theta = -EllipsoidAngle[1];
64 phi = -EllipsoidAngle[2];
65 helper.Scale(EllipsoidLength);
66 Matrix[0] = cos(psi)*cos(phi) - sin(psi)*cos(theta)*sin(phi);
67 Matrix[1] = -cos(psi)*sin(phi) - sin(psi)*cos(theta)*cos(phi);
68 Matrix[2] = sin(psi)*sin(theta);
69 Matrix[3] = sin(psi)*cos(phi) + cos(psi)*cos(theta)*sin(phi);
70 Matrix[4] = cos(psi)*cos(theta)*cos(phi) - sin(psi)*sin(phi);
71 Matrix[5] = -cos(psi)*sin(theta);
72 Matrix[6] = sin(theta)*sin(phi);
73 Matrix[7] = sin(theta)*cos(phi);
74 Matrix[8] = cos(theta);
75 helper.MatrixMultiplication(Matrix);
76 //cout << Verbose(4) << "Intersection is at " << helper << "." << endl;
77
78 // 5. determine distance between backtransformed point and x
79 distance = RefPoint.DistanceSquared(&helper);
80 //cout << Verbose(4) << "Squared distance between intersection and RefPoint is " << distance << "." << endl;
81
82 return distance;
83 //cout << Verbose(3) << "End of SquaredDistanceToEllipsoid" << endl;
84};
85
86/** structure for ellipsoid minimisation containing points to fit to.
87 */
88struct EllipsoidMinimisation {
89 int N; //!< dimension of vector set
90 Vector *x; //!< array of vectors
91};
92
93/** Sum of squared distance to ellipsoid to be minimised.
94 * \param *x parameters for the ellipsoid
95 * \param *params EllipsoidMinimisation with set of data points to minimise distance to and dimension
96 * \return sum of squared distance, \sa SquaredDistanceToEllipsoid()
97 */
98double SumSquaredDistance (const gsl_vector * x, void * params)
99{
100 Vector *set= ((struct EllipsoidMinimisation *)params)->x;
101 int N = ((struct EllipsoidMinimisation *)params)->N;
102 double SumDistance = 0.;
103 double distance;
104 Vector Center;
105 double EllipsoidLength[3], EllipsoidAngle[3];
106
107 // put parameters into suitable ellipsoid form
108 for (int i=0;i<3;i++) {
109 Center.x[i] = gsl_vector_get(x, i+0);
110 EllipsoidLength[i] = gsl_vector_get(x, i+3);
111 EllipsoidAngle[i] = gsl_vector_get(x, i+6);
112 }
113
114 // go through all points and sum distance
115 for (int i=0;i<N;i++) {
116 distance = SquaredDistanceToEllipsoid(set[i], Center, EllipsoidLength, EllipsoidAngle);
117 if (!isnan(distance)) {
118 SumDistance += distance;
119 } else {
120 SumDistance = GSL_NAN;
121 break;
122 }
123 }
124
125 //cout << "Current summed distance is " << SumDistance << "." << endl;
126 return SumDistance;
127};
128
129/** Finds best fitting ellipsoid parameter set in Least square sense for a given point set.
130 * \param *out output stream for debugging
131 * \param *set given point set
132 * \param N number of points in set
133 * \param EllipsoidParamter[3] three parameters in ellipsoid equation
134 * \return true - fit successful, false - fit impossible
135 */
136bool FitPointSetToEllipsoid(ofstream *out, Vector *set, int N, Vector *EllipsoidCenter, double *EllipsoidLength, double *EllipsoidAngle)
137{
138 int status = GSL_SUCCESS;
139 *out << Verbose(2) << "Begin of FitPointSetToEllipsoid " << endl;
140 if (N >= 3) { // check that enough points are given (9 d.o.f.)
141 struct EllipsoidMinimisation par;
142 const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
143 gsl_multimin_fminimizer *s = NULL;
144 gsl_vector *ss, *x;
145 gsl_multimin_function minex_func;
146
147 size_t iter = 0;
148 double size;
149
150 /* Starting point */
151 x = gsl_vector_alloc (9);
152 for (int i=0;i<3;i++) {
153 gsl_vector_set (x, i+0, EllipsoidCenter->x[i]);
154 gsl_vector_set (x, i+3, EllipsoidLength[i]);
155 gsl_vector_set (x, i+6, EllipsoidAngle[i]);
156 }
157 par.x = set;
158 par.N = N;
159
160 /* Set initial step sizes */
161 ss = gsl_vector_alloc (9);
162 for (int i=0;i<3;i++) {
163 gsl_vector_set (ss, i+0, 0.1);
164 gsl_vector_set (ss, i+3, 1.0);
165 gsl_vector_set (ss, i+6, M_PI/20.);
166 }
167
168 /* Initialize method and iterate */
169 minex_func.n = 9;
170 minex_func.f = &SumSquaredDistance;
171 minex_func.params = (void *)&par;
172
173 s = gsl_multimin_fminimizer_alloc (T, 9);
174 gsl_multimin_fminimizer_set (s, &minex_func, x, ss);
175
176 do {
177 iter++;
178 status = gsl_multimin_fminimizer_iterate(s);
179
180 if (status)
181 break;
182
183 size = gsl_multimin_fminimizer_size (s);
184 status = gsl_multimin_test_size (size, 1e-2);
185
186 if (status == GSL_SUCCESS) {
187 for (int i=0;i<3;i++) {
188 EllipsoidCenter->x[i] = gsl_vector_get (s->x,i+0);
189 EllipsoidLength[i] = gsl_vector_get (s->x, i+3);
190 EllipsoidAngle[i] = gsl_vector_get (s->x, i+6);
191 }
192 *out << setprecision(3) << Verbose(4) << "Converged fit at: " << *EllipsoidCenter << ", lengths " << EllipsoidLength[0] << ", " << EllipsoidLength[1] << ", " << EllipsoidLength[2] << ", angles " << EllipsoidAngle[0] << ", " << EllipsoidAngle[1] << ", " << EllipsoidAngle[2] << " with summed distance " << s->fval << "." << endl;
193 }
194
195 } while (status == GSL_CONTINUE && iter < 1000);
196
197 gsl_vector_free(x);
198 gsl_vector_free(ss);
199 gsl_multimin_fminimizer_free (s);
200
201 } else {
202 *out << Verbose(3) << "Not enough points provided for fit to ellipsoid." << endl;
203 return false;
204 }
205 *out << Verbose(2) << "End of FitPointSetToEllipsoid" << endl;
206 if (status == GSL_SUCCESS)
207 return true;
208 else
209 return false;
210};
211
212/** Picks a number of random points from a LC neighbourhood as a fitting set.
213 * \param *out output stream for debugging
214 * \param *T Tesselation containing boundary points
215 * \param *LC linked cell list of all atoms
216 * \param *&x random point set on return (not allocated!)
217 * \param PointsToPick number of points in set to pick
218 */
219void PickRandomNeighbouredPointSet(ofstream *out, class Tesselation *T, class LinkedCell *LC, Vector *&x, size_t PointsToPick)
220{
221 size_t PointsLeft = 0;
222 size_t PointsPicked = 0;
223 int Nlower[NDIM], Nupper[NDIM];
224 set<int> PickedAtomNrs; // ordered list of picked atoms
225 set<int>::iterator current;
226 int index;
227 TesselPoint *Candidate = NULL;
228 LinkedNodes *List = NULL;
229 *out << Verbose(2) << "Begin of PickRandomPointSet" << endl;
230
231 // allocate array
232 if (x == NULL) {
233 x = new Vector[PointsToPick];
234 } else {
235 *out << "WARNING: Given pointer to vector array seems already allocated." << endl;
236 }
237
238 do {
239 for(int i=0;i<NDIM;i++) // pick three random indices
240 LC->n[i] = (rand() % LC->N[i]);
241 *out << Verbose(2) << "INFO: Center cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " ... ";
242 // get random cell
243 List = LC->GetCurrentCell();
244 if (List == NULL) { // set index to it
245 continue;
246 }
247 *out << "with No. " << LC->index << "." << endl;
248
249 *out << Verbose(2) << "LC Intervals:";
250 for (int i=0;i<NDIM;i++) {
251 Nlower[i] = ((LC->n[i]-1) >= 0) ? LC->n[i]-1 : 0;
252 Nupper[i] = ((LC->n[i]+1) < LC->N[i]) ? LC->n[i]+1 : LC->N[i]-1;
253 *out << " [" << Nlower[i] << "," << Nupper[i] << "] ";
254 }
255 *out << endl;
256
257 // count whether there are sufficient atoms in this cell+neighbors
258 PointsLeft=0;
259 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
260 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
261 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
262 List = LC->GetCurrentCell();
263 PointsLeft += List->size();
264 }
265 *out << Verbose(2) << "There are " << PointsLeft << " atoms in this neighbourhood." << endl;
266 if (PointsLeft < PointsToPick) { // ensure that we can pick enough points in its neighbourhood at all.
267 continue;
268 }
269
270 // pre-pick a fixed number of atoms
271 PickedAtomNrs.clear();
272 do {
273 index = (rand() % PointsLeft);
274 current = PickedAtomNrs.find(index); // not present?
275 if (current == PickedAtomNrs.end()) {
276 //*out << Verbose(2) << "Picking atom nr. " << index << "." << endl;
277 PickedAtomNrs.insert(index);
278 }
279 } while (PickedAtomNrs.size() < PointsToPick);
280
281 index = 0; // now go through all and pick those whose from PickedAtomsNr
282 PointsPicked=0;
283 current = PickedAtomNrs.begin();
284 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
285 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
286 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
287 List = LC->GetCurrentCell();
288// *out << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << " containing " << List->size() << " points." << endl;
289 if (List != NULL) {
290// if (List->begin() != List->end())
291// *out << Verbose(2) << "Going through candidates ... " << endl;
292// else
293// *out << Verbose(2) << "Cell is empty ... " << endl;
294 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
295 if ((current != PickedAtomNrs.end()) && (*current == index)) {
296 Candidate = (*Runner);
297 *out << Verbose(2) << "Current picked node is " << **Runner << " with index " << index << "." << endl;
298 x[PointsPicked++].CopyVector(Candidate->node); // we have one more atom picked
299 current++; // next pre-picked atom
300 }
301 index++; // next atom nr.
302 }
303// } else {
304// *out << Verbose(2) << "List for this index not allocated!" << endl;
305 }
306 }
307 *out << Verbose(2) << "The following points were picked: " << endl;
308 for (size_t i=0;i<PointsPicked;i++)
309 *out << Verbose(2) << x[i] << endl;
310 if (PointsPicked == PointsToPick) // break out of loop if we have all
311 break;
312 } while(1);
313
314 *out << Verbose(2) << "End of PickRandomPointSet" << endl;
315};
316
317/** Picks a number of random points from a set of boundary points as a fitting set.
318 * \param *out output stream for debugging
319 * \param *T Tesselation containing boundary points
320 * \param *&x random point set on return (not allocated!)
321 * \param PointsToPick number of points in set to pick
322 */
323void PickRandomPointSet(ofstream *out, class Tesselation *T, Vector *&x, size_t PointsToPick)
324{
325 size_t PointsLeft = (size_t) T->PointsOnBoundaryCount;
326 size_t PointsPicked = 0;
327 double value, threshold;
328 PointMap *List = &T->PointsOnBoundary;
329 *out << Verbose(2) << "Begin of PickRandomPointSet" << endl;
330
331 // allocate array
332 if (x == NULL) {
333 x = new Vector[PointsToPick];
334 } else {
335 *out << "WARNING: Given pointer to vector array seems already allocated." << endl;
336 }
337
338 if (List != NULL)
339 for (PointMap::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
340 threshold = 1. - (double)(PointsToPick - PointsPicked)/(double)PointsLeft;
341 value = (double)rand()/(double)RAND_MAX;
342 //*out << Verbose(3) << "Current node is " << *Runner->second->node << " with " << value << " ... " << threshold << ": ";
343 if (value > threshold) {
344 x[PointsPicked].CopyVector(Runner->second->node->node);
345 PointsPicked++;
346 //*out << "IN." << endl;
347 } else {
348 //*out << "OUT." << endl;
349 }
350 PointsLeft--;
351 }
352 *out << Verbose(2) << "The following points were picked: " << endl;
353 for (size_t i=0;i<PointsPicked;i++)
354 *out << Verbose(3) << x[i] << endl;
355
356 *out << Verbose(2) << "End of PickRandomPointSet" << endl;
357};
358
359/** Finds best fitting ellipsoid parameter set in least square sense for a given point set.
360 * \param *out output stream for debugging
361 * \param *T Tesselation containing boundary points
362 * \param *LCList linked cell list of all atoms
363 * \param N number of unique points in ellipsoid fit, must be greater equal 6
364 * \param number of fits (i.e. parameter sets in output file)
365 * \param *filename name for output file
366 */
367void FindDistributionOfEllipsoids(ofstream *out, class Tesselation *T, class LinkedCell *LCList, int N, int number, const char *filename)
368{
369 ofstream output;
370 Vector *x = NULL;
371 Vector Center;
372 Vector EllipsoidCenter;
373 double EllipsoidLength[3];
374 double EllipsoidAngle[3];
375 double distance, MaxDistance, MinDistance;
376 *out << Verbose(0) << "Begin of FindDistributionOfEllipsoids" << endl;
377
378 // construct center of gravity of boundary point set for initial ellipsoid center
379 Center.Zero();
380 for (PointMap::iterator Runner = T->PointsOnBoundary.begin(); Runner != T->PointsOnBoundary.end(); Runner++)
381 Center.AddVector(Runner->second->node->node);
382 Center.Scale(1./T->PointsOnBoundaryCount);
383 *out << Verbose(1) << "Center is at " << Center << "." << endl;
384
385 // Output header
386 output.open(filename, ios::trunc);
387 output << "# Nr.\tCenterX\tCenterY\tCenterZ\ta\tb\tc\tpsi\ttheta\tphi" << endl;
388
389 // loop over desired number of parameter sets
390 for (;number >0;number--) {
391 *out << Verbose(1) << "Determining data set " << number << " ... " << endl;
392 // pick the point set
393 x = NULL;
394 //PickRandomPointSet(out, T, LCList, x, N);
395 PickRandomNeighbouredPointSet(out, T, LCList, x, N);
396
397 // calculate some sensible starting values for parameter fit
398 MaxDistance = 0.;
399 MinDistance = x[0].ScalarProduct(&x[0]);
400 for (int i=0;i<N;i++) {
401 distance = x[i].ScalarProduct(&x[i]);
402 if (distance > MaxDistance)
403 MaxDistance = distance;
404 if (distance < MinDistance)
405 MinDistance = distance;
406 }
407 //*out << Verbose(2) << "MinDistance " << MinDistance << ", MaxDistance " << MaxDistance << "." << endl;
408 EllipsoidCenter.CopyVector(&Center); // use Center of Gravity as initial center of ellipsoid
409 for (int i=0;i<3;i++)
410 EllipsoidAngle[i] = 0.;
411 EllipsoidLength[0] = sqrt(MaxDistance);
412 EllipsoidLength[1] = sqrt((MaxDistance+MinDistance)/2.);
413 EllipsoidLength[2] = sqrt(MinDistance);
414
415 // fit the parameters
416 if (FitPointSetToEllipsoid(out, x, N, &EllipsoidCenter, &EllipsoidLength[0], &EllipsoidAngle[0])) {
417 *out << Verbose(1) << "Picking succeeded!" << endl;
418 // output obtained parameter set
419 output << number << "\t";
420 for (int i=0;i<3;i++)
421 output << setprecision(9) << EllipsoidCenter.x[i] << "\t";
422 for (int i=0;i<3;i++)
423 output << setprecision(9) << EllipsoidLength[i] << "\t";
424 for (int i=0;i<3;i++)
425 output << setprecision(9) << EllipsoidAngle[i] << "\t";
426 output << endl;
427 } else { // increase N to pick one more
428 *out << Verbose(1) << "Picking failed!" << endl;
429 number++;
430 }
431 delete[](x); // free allocated memory for point set
432 }
433 // close output and finish
434 output.close();
435
436 *out << Verbose(0) << "End of FindDistributionOfEllipsoids" << endl;
437};
Note: See TracBrowser for help on using the repository browser.