source: src/molecule_geometry.cpp@ 41a467

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 41a467 was 47d041, checked in by Frederik Heber <heber@…>, 13 years ago

HUGE: Removed all calls to Log(), eLog(), replaced by LOG() and ELOG().

  • Replaced DoLog(.) && (Log() << Verbose(.) << ... << std::endl) by Log(., ...).
  • Replaced Log() << Verbose(.) << .. << by Log(., ...)
  • on multiline used stringstream to generate and message which was finally used in LOG(., output.str())
  • there should be no more occurence of Log(). LOG() and ELOG() must be used instead.
  • Eventually, this will allow for storing all errors and re-printing them on program exit which would be very helpful to ascertain error-free runs for the user.
  • Property mode set to 100644
File size: 17.5 KB
RevLine 
[bcf653]1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
[cee0b57]8/*
9 * molecule_geometry.cpp
10 *
11 * Created on: Oct 5, 2009
12 * Author: heber
13 */
14
[bf3817]15// include config.h
[aafd77]16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
[bf3817]19
[ad011c]20#include "CodePatterns/MemDebug.hpp"
[aafd77]21
[129204]22#include "atom.hpp"
23#include "Bond/bond.hpp"
24#include "Box.hpp"
[ad011c]25#include "CodePatterns/Log.hpp"
26#include "CodePatterns/Verbose.hpp"
[cee0b57]27#include "config.hpp"
[3bdb6d]28#include "Element/element.hpp"
[129204]29#include "Graph/BondGraph.hpp"
[13d150]30#include "LinearAlgebra/leastsquaremin.hpp"
[129204]31#include "LinearAlgebra/Line.hpp"
32#include "LinearAlgebra/RealSpaceMatrix.hpp"
33#include "LinearAlgebra/Plane.hpp"
[cee0b57]34#include "molecule.hpp"
[b34306]35#include "World.hpp"
[6e5084]36
[76c0d6]37#include <boost/foreach.hpp>
38
[aafd77]39#include <gsl/gsl_eigen.h>
40#include <gsl/gsl_multimin.h>
41
[cee0b57]42
43/************************************* Functions for class molecule *********************************/
44
45
46/** Centers the molecule in the box whose lengths are defined by vector \a *BoxLengths.
47 * \param *out output stream for debugging
48 */
[e138de]49bool molecule::CenterInBox()
[cee0b57]50{
51 bool status = true;
[e138de]52 const Vector *Center = DetermineCenterOfAll();
[eddea2]53 const Vector *CenterBox = DetermineCenterOfBox();
[f429d7]54 Box &domain = World::getInstance().getDomain();
[cee0b57]55
56 // go through all atoms
[d0f111]57 BOOST_FOREACH(atom* iter, atoms){
[6625c3]58 std::cout << "atom before is at " << *iter << std::endl;
[d74077]59 *iter -= *Center;
[6625c3]60 *iter += *CenterBox;
61 std::cout << "atom after is at " << *iter << std::endl;
[d0f111]62 }
[0632c5]63 atoms.transformNodes(boost::bind(&Box::WrapPeriodically,domain,_1));
[cee0b57]64
65 delete(Center);
[52d777]66 delete(CenterBox);
[cee0b57]67 return status;
68};
69
70
71/** Bounds the molecule in the box whose lengths are defined by vector \a *BoxLengths.
72 * \param *out output stream for debugging
73 */
[e138de]74bool molecule::BoundInBox()
[cee0b57]75{
76 bool status = true;
[f429d7]77 Box &domain = World::getInstance().getDomain();
[cee0b57]78
79 // go through all atoms
[0632c5]80 atoms.transformNodes(boost::bind(&Box::WrapPeriodically,domain,_1));
[cee0b57]81
82 return status;
83};
84
85/** Centers the edge of the atoms at (0,0,0).
86 * \param *out output stream for debugging
87 * \param *max coordinates of other edge, specifying box dimensions.
88 */
[e138de]89void molecule::CenterEdge(Vector *max)
[cee0b57]90{
[47d041]91// Info info(__func__);
[cee0b57]92 Vector *min = new Vector;
93
[9879f6]94 molecule::const_iterator iter = begin(); // start at first in list
95 if (iter != end()) { //list not empty?
[cee0b57]96 for (int i=NDIM;i--;) {
[d74077]97 max->at(i) = (*iter)->at(i);
98 min->at(i) = (*iter)->at(i);
[cee0b57]99 }
[9879f6]100 for (; iter != end(); ++iter) {// continue with second if present
101 //(*iter)->Output(1,1,out);
[cee0b57]102 for (int i=NDIM;i--;) {
[d74077]103 max->at(i) = (max->at(i) < (*iter)->at(i)) ? (*iter)->at(i) : max->at(i);
104 min->at(i) = (min->at(i) > (*iter)->at(i)) ? (*iter)->at(i) : min->at(i);
[cee0b57]105 }
106 }
[47d041]107 LOG(1, "INFO: Maximum is " << *max << ", Minimum is " << *min << ".");
[cee0b57]108 min->Scale(-1.);
[273382]109 (*max) += (*min);
[cee0b57]110 Translate(min);
111 }
112 delete(min);
113};
114
115/** Centers the center of the atoms at (0,0,0).
116 * \param *out output stream for debugging
117 * \param *center return vector for translation vector
118 */
[e138de]119void molecule::CenterOrigin()
[cee0b57]120{
121 int Num = 0;
[9879f6]122 molecule::const_iterator iter = begin(); // start at first in list
[1883f9]123 Vector Center;
[cee0b57]124
125 Center.Zero();
[9879f6]126 if (iter != end()) { //list not empty?
127 for (; iter != end(); ++iter) { // continue with second if present
[cee0b57]128 Num++;
[d74077]129 Center += (*iter)->getPosition();
[cee0b57]130 }
[bdc91e]131 Center.Scale(-1./(double)Num); // divide through total number (and sign for direction)
[cee0b57]132 Translate(&Center);
133 }
134};
135
136/** Returns vector pointing to center of all atoms.
137 * \return pointer to center of all vector
138 */
[e138de]139Vector * molecule::DetermineCenterOfAll() const
[cee0b57]140{
[9879f6]141 molecule::const_iterator iter = begin(); // start at first in list
[cee0b57]142 Vector *a = new Vector();
143 double Num = 0;
144
145 a->Zero();
146
[9879f6]147 if (iter != end()) { //list not empty?
148 for (; iter != end(); ++iter) { // continue with second if present
[15b670]149 Num++;
[d74077]150 (*a) += (*iter)->getPosition();
[cee0b57]151 }
[bdc91e]152 a->Scale(1./(double)Num); // divide through total mass (and sign for direction)
[cee0b57]153 }
154 return a;
155};
156
[eddea2]157/** Returns vector pointing to center of the domain.
158 * \return pointer to center of the domain
159 */
160Vector * molecule::DetermineCenterOfBox() const
161{
162 Vector *a = new Vector(0.5,0.5,0.5);
[cca9ef]163 const RealSpaceMatrix &M = World::getInstance().getDomain().getM();
[5108e1]164 (*a) *= M;
[eddea2]165 return a;
166};
167
[cee0b57]168/** Returns vector pointing to center of gravity.
169 * \param *out output stream for debugging
170 * \return pointer to center of gravity vector
171 */
[4bb63c]172Vector * molecule::DetermineCenterOfGravity() const
[cee0b57]173{
[9879f6]174 molecule::const_iterator iter = begin(); // start at first in list
[cee0b57]175 Vector *a = new Vector();
176 Vector tmp;
177 double Num = 0;
178
179 a->Zero();
180
[9879f6]181 if (iter != end()) { //list not empty?
182 for (; iter != end(); ++iter) { // continue with second if present
[83f176]183 Num += (*iter)->getType()->getMass();
184 tmp = (*iter)->getType()->getMass() * (*iter)->getPosition();
[273382]185 (*a) += tmp;
[cee0b57]186 }
[bdc91e]187 a->Scale(1./Num); // divide through total mass
[cee0b57]188 }
[47d041]189 LOG(1, "INFO: Resulting center of gravity: " << *a << ".");
[cee0b57]190 return a;
191};
192
193/** Centers the center of gravity of the atoms at (0,0,0).
194 * \param *out output stream for debugging
195 * \param *center return vector for translation vector
196 */
[e138de]197void molecule::CenterPeriodic()
[cee0b57]198{
[1883f9]199 Vector NewCenter;
200 DeterminePeriodicCenter(NewCenter);
201 // go through all atoms
202 BOOST_FOREACH(atom* iter, atoms){
203 *iter -= NewCenter;
204 }
[cee0b57]205};
206
207
208/** Centers the center of gravity of the atoms at (0,0,0).
209 * \param *out output stream for debugging
210 * \param *center return vector for translation vector
211 */
[e138de]212void molecule::CenterAtVector(Vector *newcenter)
[cee0b57]213{
[1883f9]214 // go through all atoms
215 BOOST_FOREACH(atom* iter, atoms){
216 *iter -= *newcenter;
217 }
[cee0b57]218};
219
[1f91f4]220/** Calculate the inertia tensor of a the molecule.
221 *
222 * @return inertia tensor
223 */
224RealSpaceMatrix molecule::getInertiaTensor() const
225{
226 RealSpaceMatrix InertiaTensor;
227 Vector *CenterOfGravity = DetermineCenterOfGravity();
228
229 // reset inertia tensor
230 InertiaTensor.setZero();
231
232 // sum up inertia tensor
233 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
234 Vector x = (*iter)->getPosition();
235 x -= *CenterOfGravity;
236 const double mass = (*iter)->getType()->getMass();
237 InertiaTensor.at(0,0) += mass*(x[1]*x[1] + x[2]*x[2]);
238 InertiaTensor.at(0,1) += mass*(-x[0]*x[1]);
239 InertiaTensor.at(0,2) += mass*(-x[0]*x[2]);
240 InertiaTensor.at(1,0) += mass*(-x[1]*x[0]);
241 InertiaTensor.at(1,1) += mass*(x[0]*x[0] + x[2]*x[2]);
242 InertiaTensor.at(1,2) += mass*(-x[1]*x[2]);
243 InertiaTensor.at(2,0) += mass*(-x[2]*x[0]);
244 InertiaTensor.at(2,1) += mass*(-x[2]*x[1]);
245 InertiaTensor.at(2,2) += mass*(x[0]*x[0] + x[1]*x[1]);
246 }
247 // print InertiaTensor
[47d041]248 LOG(1, "INFO: The inertia tensor of molecule " << getName() << " is:" << InertiaTensor);
[1f91f4]249
250 delete CenterOfGravity;
251 return InertiaTensor;
252}
253
254/** Rotates the molecule in such a way that biggest principal axis corresponds
255 * to given \a Axis.
256 *
257 * @param Axis Axis to align with biggest principal axis
258 */
259void molecule::RotateToPrincipalAxisSystem(Vector &Axis)
260{
261 Vector *CenterOfGravity = DetermineCenterOfGravity();
262 RealSpaceMatrix InertiaTensor = getInertiaTensor();
263
264 // diagonalize to determine principal axis system
265 Vector Eigenvalues = InertiaTensor.transformToEigenbasis();
266
267 for(int i=0;i<NDIM;i++)
[47d041]268 LOG(0, "eigenvalue = " << Eigenvalues[i] << ", eigenvector = " << InertiaTensor.column(i));
[1f91f4]269
[47d041]270 LOG(0, "STATUS: Transforming to PAS ... ");
[1f91f4]271
272 // obtain first column, eigenvector to biggest eigenvalue
273 Vector BiggestEigenvector(InertiaTensor.column(Eigenvalues.SmallestComponent()));
274 Vector DesiredAxis(Axis);
275
276 // Creation Line that is the rotation axis
277 DesiredAxis.VectorProduct(BiggestEigenvector);
278 Line RotationAxis(Vector(0.,0.,0.), DesiredAxis);
279
280 // determine angle
281 const double alpha = BiggestEigenvector.Angle(Axis);
282
[47d041]283 LOG(1, "INFO: Rotation angle is " << alpha);
[1f91f4]284
285 // and rotate
286 for (molecule::iterator iter = begin(); iter != end(); ++iter) {
287 *(*iter) -= *CenterOfGravity;
288 (*iter)->setPosition(RotationAxis.rotateVector((*iter)->getPosition(), alpha));
289 *(*iter) += *CenterOfGravity;
290 }
[47d041]291 LOG(0, "STATUS: done.");
[1f91f4]292
293 delete CenterOfGravity;
294}
[cee0b57]295
296/** Scales all atoms by \a *factor.
297 * \param *factor pointer to scaling factor
[1bd79e]298 *
299 * TODO: Is this realy what is meant, i.e.
300 * x=(x[0]*factor[0],x[1]*factor[1],x[2]*factor[2]) (current impl)
301 * or rather
302 * x=(**factor) * x (as suggested by comment)
[cee0b57]303 */
[776b64]304void molecule::Scale(const double ** const factor)
[cee0b57]305{
[9879f6]306 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
[6625c3]307 for (size_t j=0;j<(*iter)->getTrajectorySize();j++) {
[056e70]308 Vector temp = (*iter)->getPositionAtStep(j);
[6625c3]309 temp.ScaleAll(*factor);
[056e70]310 (*iter)->setPositionAtStep(j,temp);
[6625c3]311 }
[cee0b57]312 }
313};
314
315/** Translate all atoms by given vector.
316 * \param trans[] translation vector.
317 */
318void molecule::Translate(const Vector *trans)
319{
[9879f6]320 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
[6625c3]321 for (size_t j=0;j<(*iter)->getTrajectorySize();j++) {
[056e70]322 (*iter)->setPositionAtStep(j, (*iter)->getPositionAtStep(j) + (*trans));
[6625c3]323 }
[cee0b57]324 }
325};
326
327/** Translate the molecule periodically in the box.
328 * \param trans[] translation vector.
[6625c3]329 * TODO treatment of trajectories missing
[cee0b57]330 */
331void molecule::TranslatePeriodically(const Vector *trans)
332{
[f429d7]333 Box &domain = World::getInstance().getDomain();
[cee0b57]334
335 // go through all atoms
[d0f111]336 BOOST_FOREACH(atom* iter, atoms){
[d74077]337 *iter += *trans;
[d0f111]338 }
[0632c5]339 atoms.transformNodes(boost::bind(&Box::WrapPeriodically,domain,_1));
[cee0b57]340
341};
342
343
344/** Mirrors all atoms against a given plane.
345 * \param n[] normal vector of mirror plane.
346 */
347void molecule::Mirror(const Vector *n)
348{
[76c0d6]349 OBSERVE;
[ccf826]350 Plane p(*n,0);
[0632c5]351 atoms.transformNodes(boost::bind(&Plane::mirrorVector,p,_1));
[cee0b57]352};
353
354/** Determines center of molecule (yet not considering atom masses).
355 * \param center reference to return vector
[07a47e]356 * \param saturation whether to treat hydrogen special or not
[cee0b57]357 */
[07a47e]358void molecule::DeterminePeriodicCenter(Vector &center, const enum HydrogenSaturation saturation)
[cee0b57]359{
[cca9ef]360 const RealSpaceMatrix &matrix = World::getInstance().getDomain().getM();
361 const RealSpaceMatrix &inversematrix = World::getInstance().getDomain().getM();
[cee0b57]362 double tmp;
363 bool flag;
364 Vector Testvector, Translationvector;
[1883f9]365 Vector Center;
[7adf0f]366 BondGraph *BG = World::getInstance().getBondGraph();
[cee0b57]367
368 do {
369 Center.Zero();
370 flag = true;
[9879f6]371 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
[07a47e]372 if ((saturation == DontSaturate) || ((*iter)->getType()->getAtomicNumber() != 1)) {
[d74077]373 Testvector = inversematrix * (*iter)->getPosition();
[cee0b57]374 Translationvector.Zero();
[9d83b6]375 const BondList& ListOfBonds = (*iter)->getListOfBonds();
376 for (BondList::const_iterator Runner = ListOfBonds.begin();
377 Runner != ListOfBonds.end();
378 ++Runner) {
[735b1c]379 if ((*iter)->getNr() < (*Runner)->GetOtherAtom((*iter))->getNr()) // otherwise we shift one to, the other fro and gain nothing
[cee0b57]380 for (int j=0;j<NDIM;j++) {
[d74077]381 tmp = (*iter)->at(j) - (*Runner)->GetOtherAtom(*iter)->at(j);
[607eab]382 const range<double> MinMaxBondDistance(
383 BG->getMinMaxDistance((*iter), (*Runner)->GetOtherAtom(*iter)));
[300220]384 if (fabs(tmp) > MinMaxBondDistance.last) { // check against Min is not useful for components
[cee0b57]385 flag = false;
[47d041]386 LOG(0, "Hit: atom " << (*iter)->getName() << " in bond " << *(*Runner) << " has to be shifted due to " << tmp << ".");
[cee0b57]387 if (tmp > 0)
[0a4f7f]388 Translationvector[j] -= 1.;
[cee0b57]389 else
[0a4f7f]390 Translationvector[j] += 1.;
[cee0b57]391 }
392 }
393 }
[273382]394 Testvector += Translationvector;
[5108e1]395 Testvector *= matrix;
[273382]396 Center += Testvector;
[47d041]397 LOG(1, "vector is: " << Testvector);
[07a47e]398 if (saturation == DoSaturate) {
399 // now also change all hydrogens
400 for (BondList::const_iterator Runner = ListOfBonds.begin();
401 Runner != ListOfBonds.end();
402 ++Runner) {
403 if ((*Runner)->GetOtherAtom((*iter))->getType()->getAtomicNumber() == 1) {
404 Testvector = inversematrix * (*Runner)->GetOtherAtom((*iter))->getPosition();
405 Testvector += Translationvector;
406 Testvector *= matrix;
407 Center += Testvector;
[47d041]408 LOG(1, "Hydrogen vector is: " << Testvector);
[07a47e]409 }
[cee0b57]410 }
411 }
412 }
413 }
414 } while (!flag);
[1614174]415
[ea7176]416 Center.Scale(1./static_cast<double>(getAtomCount()));
[1883f9]417 CenterAtVector(&Center);
[cee0b57]418};
419
420/** Align all atoms in such a manner that given vector \a *n is along z axis.
421 * \param n[] alignment vector.
422 */
423void molecule::Align(Vector *n)
424{
425 double alpha, tmp;
426 Vector z_axis;
[0a4f7f]427 z_axis[0] = 0.;
428 z_axis[1] = 0.;
429 z_axis[2] = 1.;
[cee0b57]430
431 // rotate on z-x plane
[47d041]432 LOG(0, "Begin of Aligning all atoms.");
[0a4f7f]433 alpha = atan(-n->at(0)/n->at(2));
[47d041]434 LOG(1, "INFO: Z-X-angle: " << alpha << " ... ");
[9879f6]435 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
[d74077]436 tmp = (*iter)->at(0);
437 (*iter)->set(0, cos(alpha) * tmp + sin(alpha) * (*iter)->at(2));
438 (*iter)->set(2, -sin(alpha) * tmp + cos(alpha) * (*iter)->at(2));
[cee0b57]439 for (int j=0;j<MDSteps;j++) {
[6625c3]440 Vector temp;
[056e70]441 temp[0] = cos(alpha) * (*iter)->getPositionAtStep(j)[0] + sin(alpha) * (*iter)->getPositionAtStep(j)[2];
442 temp[2] = -sin(alpha) * (*iter)->getPositionAtStep(j)[0] + cos(alpha) * (*iter)->getPositionAtStep(j)[2];
443 (*iter)->setPositionAtStep(j,temp);
[cee0b57]444 }
445 }
446 // rotate n vector
[0a4f7f]447 tmp = n->at(0);
448 n->at(0) = cos(alpha) * tmp + sin(alpha) * n->at(2);
449 n->at(2) = -sin(alpha) * tmp + cos(alpha) * n->at(2);
[47d041]450 LOG(1, "alignment vector after first rotation: " << n);
[cee0b57]451
452 // rotate on z-y plane
[0a4f7f]453 alpha = atan(-n->at(1)/n->at(2));
[47d041]454 LOG(1, "INFO: Z-Y-angle: " << alpha << " ... ");
[9879f6]455 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
[d74077]456 tmp = (*iter)->at(1);
457 (*iter)->set(1, cos(alpha) * tmp + sin(alpha) * (*iter)->at(2));
458 (*iter)->set(2, -sin(alpha) * tmp + cos(alpha) * (*iter)->at(2));
[cee0b57]459 for (int j=0;j<MDSteps;j++) {
[6625c3]460 Vector temp;
[056e70]461 temp[1] = cos(alpha) * (*iter)->getPositionAtStep(j)[1] + sin(alpha) * (*iter)->getPositionAtStep(j)[2];
462 temp[2] = -sin(alpha) * (*iter)->getPositionAtStep(j)[1] + cos(alpha) * (*iter)->getPositionAtStep(j)[2];
463 (*iter)->setPositionAtStep(j,temp);
[cee0b57]464 }
465 }
466 // rotate n vector (for consistency check)
[0a4f7f]467 tmp = n->at(1);
468 n->at(1) = cos(alpha) * tmp + sin(alpha) * n->at(2);
469 n->at(2) = -sin(alpha) * tmp + cos(alpha) * n->at(2);
[cee0b57]470
471
[47d041]472 LOG(1, "alignment vector after second rotation: " << n);
473 LOG(0, "End of Aligning all atoms.");
[cee0b57]474};
475
476
477/** Calculates sum over least square distance to line hidden in \a *x.
478 * \param *x offset and direction vector
479 * \param *params pointer to lsq_params structure
480 * \return \f$ sum_i^N | y_i - (a + t_i b)|^2\f$
481 */
482double LeastSquareDistance (const gsl_vector * x, void * params)
483{
484 double res = 0, t;
485 Vector a,b,c,d;
486 struct lsq_params *par = (struct lsq_params *)params;
487
488 // initialize vectors
[0a4f7f]489 a[0] = gsl_vector_get(x,0);
490 a[1] = gsl_vector_get(x,1);
491 a[2] = gsl_vector_get(x,2);
492 b[0] = gsl_vector_get(x,3);
493 b[1] = gsl_vector_get(x,4);
494 b[2] = gsl_vector_get(x,5);
[cee0b57]495 // go through all atoms
[9879f6]496 for (molecule::const_iterator iter = par->mol->begin(); iter != par->mol->end(); ++iter) {
[d74077]497 if ((*iter)->getType() == ((struct lsq_params *)params)->type) { // for specific type
498 c = (*iter)->getPosition() - a;
[273382]499 t = c.ScalarProduct(b); // get direction parameter
500 d = t*b; // and create vector
501 c -= d; // ... yielding distance vector
502 res += d.ScalarProduct(d); // add squared distance
[cee0b57]503 }
504 }
505 return res;
506};
507
508/** By minimizing the least square distance gains alignment vector.
509 * \bug this is not yet working properly it seems
510 */
511void molecule::GetAlignvector(struct lsq_params * par) const
512{
513 int np = 6;
514
515 const gsl_multimin_fminimizer_type *T =
516 gsl_multimin_fminimizer_nmsimplex;
517 gsl_multimin_fminimizer *s = NULL;
518 gsl_vector *ss;
519 gsl_multimin_function minex_func;
520
521 size_t iter = 0, i;
522 int status;
523 double size;
524
525 /* Initial vertex size vector */
526 ss = gsl_vector_alloc (np);
527
528 /* Set all step sizes to 1 */
529 gsl_vector_set_all (ss, 1.0);
530
531 /* Starting point */
532 par->x = gsl_vector_alloc (np);
533 par->mol = this;
534
535 gsl_vector_set (par->x, 0, 0.0); // offset
536 gsl_vector_set (par->x, 1, 0.0);
537 gsl_vector_set (par->x, 2, 0.0);
538 gsl_vector_set (par->x, 3, 0.0); // direction
539 gsl_vector_set (par->x, 4, 0.0);
540 gsl_vector_set (par->x, 5, 1.0);
541
542 /* Initialize method and iterate */
543 minex_func.f = &LeastSquareDistance;
544 minex_func.n = np;
545 minex_func.params = (void *)par;
546
547 s = gsl_multimin_fminimizer_alloc (T, np);
548 gsl_multimin_fminimizer_set (s, &minex_func, par->x, ss);
549
550 do
551 {
552 iter++;
553 status = gsl_multimin_fminimizer_iterate(s);
554
555 if (status)
556 break;
557
558 size = gsl_multimin_fminimizer_size (s);
559 status = gsl_multimin_test_size (size, 1e-2);
560
561 if (status == GSL_SUCCESS)
562 {
563 printf ("converged to minimum at\n");
564 }
565
566 printf ("%5d ", (int)iter);
567 for (i = 0; i < (size_t)np; i++)
568 {
569 printf ("%10.3e ", gsl_vector_get (s->x, i));
570 }
571 printf ("f() = %7.3f size = %.3f\n", s->fval, size);
572 }
573 while (status == GSL_CONTINUE && iter < 100);
574
575 for (i=0;i<(size_t)np;i++)
576 gsl_vector_set(par->x, i, gsl_vector_get(s->x, i));
577 //gsl_vector_free(par->x);
578 gsl_vector_free(ss);
579 gsl_multimin_fminimizer_free (s);
580};
Note: See TracBrowser for help on using the repository browser.