source: src/molecule_geometry.cpp@ 8d6d31

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 8d6d31 was 4bb63c, checked in by Frederik Heber <heber@…>, 15 years ago

made molecule::DetermineCenterOfGravity() a const member function.

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