source: src/molecule_geometry.cpp@ 4a187d

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 4a187d was f01769, checked in by Frederik Heber <heber@…>, 9 years ago

Replaced World::getAtom() wherever possible by const version.

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