source: src/molecule_geometry.cpp@ ff58f1

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 ff58f1 was bf3817, checked in by Frederik Heber <heber@…>, 15 years ago

Added ifdef HAVE_CONFIG and config.h include to each and every cpp file.

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