source: molecuilder/src/molecule_geometry.cpp@ 1f591b

Last change on this file since 1f591b was 1f591b, checked in by Tillmann Crueger <crueger@…>, 16 years ago

Prepared interface of Vector Class for transition to VectorComposites

  • Property mode set to 100644
File size: 17.0 KB
Line 
1/*
2 * molecule_geometry.cpp
3 *
4 * Created on: Oct 5, 2009
5 * Author: heber
6 */
7
8#include "atom.hpp"
9#include "bond.hpp"
10#include "config.hpp"
11#include "element.hpp"
12#include "helpers.hpp"
13#include "leastsquaremin.hpp"
14#include "log.hpp"
15#include "memoryallocator.hpp"
16#include "molecule.hpp"
17
18/************************************* Functions for class molecule *********************************/
19
20
21/** Centers the molecule in the box whose lengths are defined by vector \a *BoxLengths.
22 * \param *out output stream for debugging
23 */
24bool molecule::CenterInBox()
25{
26 bool status = true;
27 const Vector *Center = DetermineCenterOfAll();
28 double *M = ReturnFullMatrixforSymmetric(cell_size);
29 double *Minv = InverseMatrix(M);
30
31 // go through all atoms
32 ActOnAllVectors( &Vector::SubtractVector, *Center);
33 ActOnAllVectors( &Vector::WrapPeriodically, (const double *)M, (const double *)Minv);
34
35 Free(&M);
36 Free(&Minv);
37 delete(Center);
38 return status;
39};
40
41
42/** Bounds the molecule in the box whose lengths are defined by vector \a *BoxLengths.
43 * \param *out output stream for debugging
44 */
45bool molecule::BoundInBox()
46{
47 bool status = true;
48 double *M = ReturnFullMatrixforSymmetric(cell_size);
49 double *Minv = InverseMatrix(M);
50
51 // go through all atoms
52 ActOnAllVectors( &Vector::WrapPeriodically, (const double *)M, (const double *)Minv);
53
54 Free(&M);
55 Free(&Minv);
56 return status;
57};
58
59/** Centers the edge of the atoms at (0,0,0).
60 * \param *out output stream for debugging
61 * \param *max coordinates of other edge, specifying box dimensions.
62 */
63void molecule::CenterEdge(Vector *max)
64{
65 Vector *min = new Vector;
66
67// Log() << Verbose(3) << "Begin of CenterEdge." << endl;
68 atom *ptr = start->next; // start at first in list
69 if (ptr != end) { //list not empty?
70 for (int i=NDIM;i--;) {
71 max->at(i) = ptr->x[i];
72 min->at(i) = ptr->x[i];
73 }
74 while (ptr->next != end) { // continue with second if present
75 ptr = ptr->next;
76 //ptr->Output(1,1,out);
77 for (int i=NDIM;i--;) {
78 max->at(i) = (max->at(i) < ptr->x[i]) ? ptr->x[i] : max->at(i);
79 min->at(i) = (min->at(i) > ptr->x[i]) ? ptr->x[i] : min->at(i);
80 }
81 }
82// Log() << Verbose(4) << "Maximum is ";
83// max->Output(out);
84// Log() << Verbose(0) << ", Minimum is ";
85// min->Output(out);
86// Log() << Verbose(0) << endl;
87 min->Scale(-1.);
88 (*max) += (*min);
89 Translate(min);
90 Center.Zero();
91 }
92 delete(min);
93// Log() << Verbose(3) << "End of CenterEdge." << endl;
94};
95
96/** Centers the center of the atoms at (0,0,0).
97 * \param *out output stream for debugging
98 * \param *center return vector for translation vector
99 */
100void molecule::CenterOrigin()
101{
102 int Num = 0;
103 atom *ptr = start; // start at first in list
104
105 Center.Zero();
106
107 if (ptr->next != end) { //list not empty?
108 while (ptr->next != end) { // continue with second if present
109 ptr = ptr->next;
110 Num++;
111 Center += ptr->x;
112 }
113 Center.Scale(-1./Num); // divide through total number (and sign for direction)
114 Translate(&Center);
115 Center.Zero();
116 }
117};
118
119/** Returns vector pointing to center of all atoms.
120 * \return pointer to center of all vector
121 */
122Vector * molecule::DetermineCenterOfAll() const
123{
124 atom *ptr = start->next; // start at first in list
125 Vector *a = new Vector();
126 Vector tmp;
127 double Num = 0;
128
129 a->Zero();
130
131 if (ptr != end) { //list not empty?
132 while (ptr->next != end) { // continue with second if present
133 ptr = ptr->next;
134 Num += 1.;
135 tmp = ptr->x;
136 (*a) += tmp;
137 }
138 a->Scale(1./Num); // divide through total mass (and sign for direction)
139 }
140 return a;
141};
142
143/** Returns vector pointing to center of gravity.
144 * \param *out output stream for debugging
145 * \return pointer to center of gravity vector
146 */
147Vector * molecule::DetermineCenterOfGravity()
148{
149 atom *ptr = start->next; // start at first in list
150 Vector *a = new Vector();
151 Vector tmp;
152 double Num = 0;
153
154 a->Zero();
155
156 if (ptr != end) { //list not empty?
157 while (ptr->next != end) { // continue with second if present
158 ptr = ptr->next;
159 Num += ptr->type->mass;
160 tmp = ptr->type->mass * ptr->x;
161 (*a) += tmp;
162 }
163 a->Scale(-1./Num); // divide through total mass (and sign for direction)
164 }
165// Log() << Verbose(1) << "Resulting center of gravity: ";
166// a->Output(out);
167// Log() << Verbose(0) << endl;
168 return a;
169};
170
171/** Centers the center of gravity of the atoms at (0,0,0).
172 * \param *out output stream for debugging
173 * \param *center return vector for translation vector
174 */
175void molecule::CenterPeriodic()
176{
177 DeterminePeriodicCenter(Center);
178};
179
180
181/** Centers the center of gravity of the atoms at (0,0,0).
182 * \param *out output stream for debugging
183 * \param *center return vector for translation vector
184 */
185void molecule::CenterAtVector(Vector *newcenter)
186{
187 Center = *newcenter;
188};
189
190
191/** Scales all atoms by \a *factor.
192 * \param *factor pointer to scaling factor
193 */
194void molecule::Scale(const double ** const factor)
195{
196 atom *ptr = start;
197
198 while (ptr->next != end) {
199 ptr = ptr->next;
200 for (int j=0;j<MDSteps;j++)
201 ptr->Trajectory.R.at(j).Scale(factor);
202 ptr->x.Scale(factor);
203 }
204};
205
206/** Translate all atoms by given vector.
207 * \param trans[] translation vector.
208 */
209void molecule::Translate(const Vector *trans)
210{
211 atom *ptr = start;
212
213 while (ptr->next != end) {
214 ptr = ptr->next;
215 for (int j=0;j<MDSteps;j++)
216 ptr->Trajectory.R.at(j).Translate(*trans);
217 ptr->x.Translate(*trans);
218 }
219};
220
221/** Translate the molecule periodically in the box.
222 * \param trans[] translation vector.
223 * TODO treatment of trajetories missing
224 */
225void molecule::TranslatePeriodically(const Vector *trans)
226{
227 double *M = ReturnFullMatrixforSymmetric(cell_size);
228 double *Minv = InverseMatrix(M);
229
230 // go through all atoms
231 ActOnAllVectors( &Vector::SubtractVector, *trans);
232 ActOnAllVectors( &Vector::WrapPeriodically, (const double *)M, (const double *)Minv);
233
234 Free(&M);
235 Free(&Minv);
236};
237
238
239/** Mirrors all atoms against a given plane.
240 * \param n[] normal vector of mirror plane.
241 */
242void molecule::Mirror(const Vector *n)
243{
244 ActOnAllVectors( &Vector::Mirror, *n );
245};
246
247/** Determines center of molecule (yet not considering atom masses).
248 * \param center reference to return vector
249 */
250void molecule::DeterminePeriodicCenter(Vector &center)
251{
252 atom *Walker = start;
253 double *matrix = ReturnFullMatrixforSymmetric(cell_size);
254 double *inversematrix = InverseMatrix(cell_size);
255 double tmp;
256 bool flag;
257 Vector Testvector, Translationvector;
258
259 do {
260 Center.Zero();
261 flag = true;
262 while (Walker->next != end) {
263 Walker = Walker->next;
264#ifdef ADDHYDROGEN
265 if (Walker->type->Z != 1) {
266#endif
267 Testvector = Walker->x;
268 Testvector.MatrixMultiplication(inversematrix);
269 Translationvector.Zero();
270 for (BondList::const_iterator Runner = Walker->ListOfBonds.begin(); Runner != Walker->ListOfBonds.end(); (++Runner)) {
271 if (Walker->nr < (*Runner)->GetOtherAtom(Walker)->nr) // otherwise we shift one to, the other fro and gain nothing
272 for (int j=0;j<NDIM;j++) {
273 tmp = Walker->x[j] - (*Runner)->GetOtherAtom(Walker)->x[j];
274 if ((fabs(tmp)) > BondDistance) {
275 flag = false;
276 Log() << Verbose(0) << "Hit: atom " << Walker->Name << " in bond " << *(*Runner) << " has to be shifted due to " << tmp << "." << endl;
277 if (tmp > 0)
278 Translationvector[j] -= 1.;
279 else
280 Translationvector[j] += 1.;
281 }
282 }
283 }
284 Testvector += Translationvector;
285 Testvector.MatrixMultiplication(matrix);
286 Center += Testvector;
287 Log() << Verbose(1) << "vector is: " << Testvector << endl;
288#ifdef ADDHYDROGEN
289 // now also change all hydrogens
290 for (BondList::const_iterator Runner = Walker->ListOfBonds.begin(); Runner != Walker->ListOfBonds.end(); (++Runner)) {
291 if ((*Runner)->GetOtherAtom(Walker)->type->Z == 1) {
292 Testvector = (*Runner)->GetOtherAtom(Walker)->x;
293 Testvector.MatrixMultiplication(inversematrix);
294 Testvector += Translationvector;
295 Testvector.MatrixMultiplication(matrix);
296 Center += Testvector;
297 Log() << Verbose(1) << "Hydrogen vector is: " << Testvector << endl;
298 }
299 }
300 }
301#endif
302 }
303 } while (!flag);
304 Free(&matrix);
305 Free(&inversematrix);
306
307 Center.Scale(1./(double)AtomCount);
308};
309
310/** Transforms/Rotates the given molecule into its principal axis system.
311 * \param *out output stream for debugging
312 * \param DoRotate whether to rotate (true) or only to determine the PAS.
313 * TODO treatment of trajetories missing
314 */
315void molecule::PrincipalAxisSystem(bool DoRotate)
316{
317 atom *ptr = start; // start at first in list
318 double InertiaTensor[NDIM*NDIM];
319 Vector *CenterOfGravity = DetermineCenterOfGravity();
320
321 CenterPeriodic();
322
323 // reset inertia tensor
324 for(int i=0;i<NDIM*NDIM;i++)
325 InertiaTensor[i] = 0.;
326
327 // sum up inertia tensor
328 while (ptr->next != end) {
329 ptr = ptr->next;
330 Vector x = ptr->x;
331 //x.SubtractVector(CenterOfGravity);
332 InertiaTensor[0] += ptr->type->mass*(x[1]*x[1] + x[2]*x[2]);
333 InertiaTensor[1] += ptr->type->mass*(-x[0]*x[1]);
334 InertiaTensor[2] += ptr->type->mass*(-x[0]*x[2]);
335 InertiaTensor[3] += ptr->type->mass*(-x[1]*x[0]);
336 InertiaTensor[4] += ptr->type->mass*(x[0]*x[0] + x[2]*x[2]);
337 InertiaTensor[5] += ptr->type->mass*(-x[1]*x[2]);
338 InertiaTensor[6] += ptr->type->mass*(-x[2]*x[0]);
339 InertiaTensor[7] += ptr->type->mass*(-x[2]*x[1]);
340 InertiaTensor[8] += ptr->type->mass*(x[0]*x[0] + x[1]*x[1]);
341 }
342 // print InertiaTensor for debugging
343 Log() << Verbose(0) << "The inertia tensor is:" << endl;
344 for(int i=0;i<NDIM;i++) {
345 for(int j=0;j<NDIM;j++)
346 Log() << Verbose(0) << InertiaTensor[i*NDIM+j] << " ";
347 Log() << Verbose(0) << endl;
348 }
349 Log() << Verbose(0) << endl;
350
351 // diagonalize to determine principal axis system
352 gsl_eigen_symmv_workspace *T = gsl_eigen_symmv_alloc(NDIM);
353 gsl_matrix_view m = gsl_matrix_view_array(InertiaTensor, NDIM, NDIM);
354 gsl_vector *eval = gsl_vector_alloc(NDIM);
355 gsl_matrix *evec = gsl_matrix_alloc(NDIM, NDIM);
356 gsl_eigen_symmv(&m.matrix, eval, evec, T);
357 gsl_eigen_symmv_free(T);
358 gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_ABS_DESC);
359
360 for(int i=0;i<NDIM;i++) {
361 Log() << Verbose(1) << "eigenvalue = " << gsl_vector_get(eval, i);
362 Log() << Verbose(0) << ", eigenvector = (" << evec->data[i * evec->tda + 0] << "," << evec->data[i * evec->tda + 1] << "," << evec->data[i * evec->tda + 2] << ")" << endl;
363 }
364
365 // check whether we rotate or not
366 if (DoRotate) {
367 Log() << Verbose(1) << "Transforming molecule into PAS ... ";
368 // the eigenvectors specify the transformation matrix
369 ActOnAllVectors( &Vector::MatrixMultiplication, (const double *) evec->data );
370 Log() << Verbose(0) << "done." << endl;
371
372 // summing anew for debugging (resulting matrix has to be diagonal!)
373 // reset inertia tensor
374 for(int i=0;i<NDIM*NDIM;i++)
375 InertiaTensor[i] = 0.;
376
377 // sum up inertia tensor
378 ptr = start;
379 while (ptr->next != end) {
380 ptr = ptr->next;
381 Vector x = ptr->x;
382 //x.SubtractVector(CenterOfGravity);
383 InertiaTensor[0] += ptr->type->mass*(x[1]*x[1] + x[2]*x[2]);
384 InertiaTensor[1] += ptr->type->mass*(-x[0]*x[1]);
385 InertiaTensor[2] += ptr->type->mass*(-x[0]*x[2]);
386 InertiaTensor[3] += ptr->type->mass*(-x[1]*x[0]);
387 InertiaTensor[4] += ptr->type->mass*(x[0]*x[0] + x[2]*x[2]);
388 InertiaTensor[5] += ptr->type->mass*(-x[1]*x[2]);
389 InertiaTensor[6] += ptr->type->mass*(-x[2]*x[0]);
390 InertiaTensor[7] += ptr->type->mass*(-x[2]*x[1]);
391 InertiaTensor[8] += ptr->type->mass*(x[0]*x[0] + x[1]*x[1]);
392 }
393 // print InertiaTensor for debugging
394 Log() << Verbose(0) << "The inertia tensor is:" << endl;
395 for(int i=0;i<NDIM;i++) {
396 for(int j=0;j<NDIM;j++)
397 Log() << Verbose(0) << InertiaTensor[i*NDIM+j] << " ";
398 Log() << Verbose(0) << endl;
399 }
400 Log() << Verbose(0) << endl;
401 }
402
403 // free everything
404 delete(CenterOfGravity);
405 gsl_vector_free(eval);
406 gsl_matrix_free(evec);
407};
408
409
410/** Align all atoms in such a manner that given vector \a *n is along z axis.
411 * \param n[] alignment vector.
412 */
413void molecule::Align(Vector *n)
414{
415 atom *ptr = start;
416 double alpha, tmp;
417 Vector z_axis;
418 z_axis[0] = 0.;
419 z_axis[1] = 0.;
420 z_axis[2] = 1.;
421
422 // rotate on z-x plane
423 Log() << Verbose(0) << "Begin of Aligning all atoms." << endl;
424 alpha = atan(-n->at(0)/n->at(2));
425 Log() << Verbose(1) << "Z-X-angle: " << alpha << " ... ";
426 while (ptr->next != end) {
427 ptr = ptr->next;
428 tmp = ptr->x[0];
429 ptr->x[0] = cos(alpha) * tmp + sin(alpha) * ptr->x[2];
430 ptr->x[2] = -sin(alpha) * tmp + cos(alpha) * ptr->x[2];
431 for (int j=0;j<MDSteps;j++) {
432 tmp = ptr->Trajectory.R.at(j)[0];
433 ptr->Trajectory.R.at(j)[0] = cos(alpha) * tmp + sin(alpha) * ptr->Trajectory.R.at(j)[2];
434 ptr->Trajectory.R.at(j)[2] = -sin(alpha) * tmp + cos(alpha) * ptr->Trajectory.R.at(j)[2];
435 }
436 }
437 // rotate n vector
438 tmp = n->at(0);
439 n->at(0) = cos(alpha) * tmp + sin(alpha) * n->at(2);
440 n->at(2) = -sin(alpha) * tmp + cos(alpha) * n->at(2);
441 Log() << Verbose(1) << "alignment vector after first rotation: " << n << endl;
442
443 // rotate on z-y plane
444 ptr = start;
445 alpha = atan(-n->at(1)/n->at(2));
446 Log() << Verbose(1) << "Z-Y-angle: " << alpha << " ... ";
447 while (ptr->next != end) {
448 ptr = ptr->next;
449 tmp = ptr->x[1];
450 ptr->x[1] = cos(alpha) * tmp + sin(alpha) * ptr->x[2];
451 ptr->x[2] = -sin(alpha) * tmp + cos(alpha) * ptr->x[2];
452 for (int j=0;j<MDSteps;j++) {
453 tmp = ptr->Trajectory.R.at(j)[1];
454 ptr->Trajectory.R.at(j)[1] = cos(alpha) * tmp + sin(alpha) * ptr->Trajectory.R.at(j)[2];
455 ptr->Trajectory.R.at(j)[2] = -sin(alpha) * tmp + cos(alpha) * ptr->Trajectory.R.at(j)[2];
456 }
457 }
458 // rotate n vector (for consistency check)
459 tmp = n->at(1);
460 n->at(1) = cos(alpha) * tmp + sin(alpha) * n->at(2);
461 n->at(2) = -sin(alpha) * tmp + cos(alpha) * n->at(2);
462
463 Log() << Verbose(1) << "alignment vector after second rotation: " << n << endl;
464 Log() << Verbose(0) << "End of Aligning all atoms." << endl;
465};
466
467
468/** Calculates sum over least square distance to line hidden in \a *x.
469 * \param *x offset and direction vector
470 * \param *params pointer to lsq_params structure
471 * \return \f$ sum_i^N | y_i - (a + t_i b)|^2\f$
472 */
473double LeastSquareDistance (const gsl_vector * x, void * params)
474{
475 double res = 0, t;
476 Vector a,b,c,d;
477 struct lsq_params *par = (struct lsq_params *)params;
478 atom *ptr = par->mol->start;
479
480 // initialize vectors
481 a[0] = gsl_vector_get(x,0);
482 a[1] = gsl_vector_get(x,1);
483 a[2] = gsl_vector_get(x,2);
484 b[0] = gsl_vector_get(x,3);
485 b[1] = gsl_vector_get(x,4);
486 b[2] = gsl_vector_get(x,5);
487 // go through all atoms
488 while (ptr != par->mol->end) {
489 ptr = ptr->next;
490 if (ptr->type == ((struct lsq_params *)params)->type) { // for specific type
491 c = ptr->x - a;
492 t = c.ScalarProduct(b); // get direction parameter
493 d = t*b; // and create vector
494 c -= d; // ... yielding distance vector
495 res += d.ScalarProduct(d); // add squared distance
496 }
497 }
498 return res;
499};
500
501/** By minimizing the least square distance gains alignment vector.
502 * \bug this is not yet working properly it seems
503 */
504void molecule::GetAlignvector(struct lsq_params * par) const
505{
506 int np = 6;
507
508 const gsl_multimin_fminimizer_type *T =
509 gsl_multimin_fminimizer_nmsimplex;
510 gsl_multimin_fminimizer *s = NULL;
511 gsl_vector *ss;
512 gsl_multimin_function minex_func;
513
514 size_t iter = 0, i;
515 int status;
516 double size;
517
518 /* Initial vertex size vector */
519 ss = gsl_vector_alloc (np);
520
521 /* Set all step sizes to 1 */
522 gsl_vector_set_all (ss, 1.0);
523
524 /* Starting point */
525 par->x = gsl_vector_alloc (np);
526 par->mol = this;
527
528 gsl_vector_set (par->x, 0, 0.0); // offset
529 gsl_vector_set (par->x, 1, 0.0);
530 gsl_vector_set (par->x, 2, 0.0);
531 gsl_vector_set (par->x, 3, 0.0); // direction
532 gsl_vector_set (par->x, 4, 0.0);
533 gsl_vector_set (par->x, 5, 1.0);
534
535 /* Initialize method and iterate */
536 minex_func.f = &LeastSquareDistance;
537 minex_func.n = np;
538 minex_func.params = (void *)par;
539
540 s = gsl_multimin_fminimizer_alloc (T, np);
541 gsl_multimin_fminimizer_set (s, &minex_func, par->x, ss);
542
543 do
544 {
545 iter++;
546 status = gsl_multimin_fminimizer_iterate(s);
547
548 if (status)
549 break;
550
551 size = gsl_multimin_fminimizer_size (s);
552 status = gsl_multimin_test_size (size, 1e-2);
553
554 if (status == GSL_SUCCESS)
555 {
556 printf ("converged to minimum at\n");
557 }
558
559 printf ("%5d ", (int)iter);
560 for (i = 0; i < (size_t)np; i++)
561 {
562 printf ("%10.3e ", gsl_vector_get (s->x, i));
563 }
564 printf ("f() = %7.3f size = %.3f\n", s->fval, size);
565 }
566 while (status == GSL_CONTINUE && iter < 100);
567
568 for (i=0;i<(size_t)np;i++)
569 gsl_vector_set(par->x, i, gsl_vector_get(s->x, i));
570 //gsl_vector_free(par->x);
571 gsl_vector_free(ss);
572 gsl_multimin_fminimizer_free (s);
573};
Note: See TracBrowser for help on using the repository browser.