source: src/molecule_geometry.cpp@ 33d774

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 33d774 was c94eeb, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Replaced several double* that were used as Matrixes with actuall matrix objects

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