source: src/molecule_geometry.cpp@ 1883f9

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

Removed molecule::Center.

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