source: src/ellipsoid.cpp@ 7326b2

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

Huge refactoring to make const what is const (ticket #38), continued.

  • too many changes because of too many cross-references to be able to list them up here.
  • NOTE that "make check" runs fine and did catch several error.
  • note that we had to use const_iterator several times when the map, ... was declared const.
  • at times we changed an allocated LinkedCell LCList(...) into

const LinkedCell *LCList;
LCList = new LinkedCell(...);

  • also mutable (see ticket #5) was used, e.g. for molecule::InternalPointer (PointCloud changes are allowed, because they are just accounting).

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

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