source: src/molecule_geometry.cpp@ 458447

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

Merge branch 'AtomicPositionEncapsulation' into stable

Conflicts:

src/Actions/AtomAction/ChangeElementAction.cpp
src/Actions/WorldAction/RemoveSphereOfAtomsAction.cpp
src/Makefile.am
src/UIElements/TextUI/TextDialog.cpp
src/analysis_correlation.hpp
src/atom.cpp
src/atom_atominfo.hpp
src/bond.cpp
src/boundary.cpp
src/molecule_geometry.cpp
src/tesselation.cpp
src/tesselationhelpers.cpp
src/triangleintersectionlist.cpp
src/unittests/Makefile.am

  • fixed #includes due to moves to Helpers and LinearAlgebra
  • moved VectorInterface.* and vector_ops.* to LinearAlgebra
  • no more direct access of atom::node, remapped to set/getPosition()
  • no more direct access to atom::type, remapped to set/getType() (also in atom due to derivation and atominfo::AtomicElement is private not protected).
  • Property mode set to 100644
File size: 14.2 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 Center.Zero();
107 }
108 delete(min);
109// Log() << Verbose(3) << "End of CenterEdge." << endl;
110};
111
112/** Centers the center of the atoms at (0,0,0).
113 * \param *out output stream for debugging
114 * \param *center return vector for translation vector
115 */
116void molecule::CenterOrigin()
117{
118 int Num = 0;
119 molecule::const_iterator iter = begin(); // start at first in list
120
121 Center.Zero();
122
123 if (iter != end()) { //list not empty?
124 for (; iter != end(); ++iter) { // continue with second if present
125 Num++;
126 Center += (*iter)->getPosition();
127 }
128 Center.Scale(-1./(double)Num); // divide through total number (and sign for direction)
129 Translate(&Center);
130 Center.Zero();
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 DeterminePeriodicCenter(Center);
200};
201
202
203/** Centers the center of gravity of the atoms at (0,0,0).
204 * \param *out output stream for debugging
205 * \param *center return vector for translation vector
206 */
207void molecule::CenterAtVector(Vector *newcenter)
208{
209 Center = *newcenter;
210};
211
212
213/** Scales all atoms by \a *factor.
214 * \param *factor pointer to scaling factor
215 *
216 * TODO: Is this realy what is meant, i.e.
217 * x=(x[0]*factor[0],x[1]*factor[1],x[2]*factor[2]) (current impl)
218 * or rather
219 * x=(**factor) * x (as suggested by comment)
220 */
221void molecule::Scale(const double ** const factor)
222{
223 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
224 for (int j=0;j<MDSteps;j++)
225 (*iter)->Trajectory.R.at(j).ScaleAll(*factor);
226 (*iter)->ScaleAll(*factor);
227 }
228};
229
230/** Translate all atoms by given vector.
231 * \param trans[] translation vector.
232 */
233void molecule::Translate(const Vector *trans)
234{
235 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
236 for (int j=0;j<MDSteps;j++)
237 (*iter)->Trajectory.R.at(j) += (*trans);
238 *(*iter) += (*trans);
239 }
240};
241
242/** Translate the molecule periodically in the box.
243 * \param trans[] translation vector.
244 * TODO treatment of trajetories missing
245 */
246void molecule::TranslatePeriodically(const Vector *trans)
247{
248 Box &domain = World::getInstance().getDomain();
249
250 // go through all atoms
251 BOOST_FOREACH(atom* iter, atoms){
252 *iter += *trans;
253 }
254 atoms.transformNodes(boost::bind(&Box::WrapPeriodically,domain,_1));
255
256};
257
258
259/** Mirrors all atoms against a given plane.
260 * \param n[] normal vector of mirror plane.
261 */
262void molecule::Mirror(const Vector *n)
263{
264 OBSERVE;
265 Plane p(*n,0);
266 atoms.transformNodes(boost::bind(&Plane::mirrorVector,p,_1));
267};
268
269/** Determines center of molecule (yet not considering atom masses).
270 * \param center reference to return vector
271 */
272void molecule::DeterminePeriodicCenter(Vector &center)
273{
274 const Matrix &matrix = World::getInstance().getDomain().getM();
275 const Matrix &inversematrix = World::getInstance().getDomain().getM();
276 double tmp;
277 bool flag;
278 Vector Testvector, Translationvector;
279
280 do {
281 Center.Zero();
282 flag = true;
283 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
284#ifdef ADDHYDROGEN
285 if ((*iter)->getType()->Z != 1) {
286#endif
287 Testvector = inversematrix * (*iter)->getPosition();
288 Translationvector.Zero();
289 for (BondList::const_iterator Runner = (*iter)->ListOfBonds.begin(); Runner != (*iter)->ListOfBonds.end(); (++Runner)) {
290 if ((*iter)->nr < (*Runner)->GetOtherAtom((*iter))->nr) // otherwise we shift one to, the other fro and gain nothing
291 for (int j=0;j<NDIM;j++) {
292 tmp = (*iter)->at(j) - (*Runner)->GetOtherAtom(*iter)->at(j);
293 if ((fabs(tmp)) > BondDistance) {
294 flag = false;
295 DoLog(0) && (Log() << Verbose(0) << "Hit: atom " << (*iter)->getName() << " in bond " << *(*Runner) << " has to be shifted due to " << tmp << "." << endl);
296 if (tmp > 0)
297 Translationvector[j] -= 1.;
298 else
299 Translationvector[j] += 1.;
300 }
301 }
302 }
303 Testvector += Translationvector;
304 Testvector *= matrix;
305 Center += Testvector;
306 Log() << Verbose(1) << "vector is: " << Testvector << endl;
307#ifdef ADDHYDROGEN
308 // now also change all hydrogens
309 for (BondList::const_iterator Runner = (*iter)->ListOfBonds.begin(); Runner != (*iter)->ListOfBonds.end(); (++Runner)) {
310 if ((*Runner)->GetOtherAtom((*iter))->getType()->Z == 1) {
311 Testvector = inversematrix * (*Runner)->GetOtherAtom((*iter))->getPosition();
312 Testvector += Translationvector;
313 Testvector *= matrix;
314 Center += Testvector;
315 Log() << Verbose(1) << "Hydrogen vector is: " << Testvector << endl;
316 }
317 }
318 }
319#endif
320 }
321 } while (!flag);
322
323 Center.Scale(1./static_cast<double>(getAtomCount()));
324};
325
326/** Align all atoms in such a manner that given vector \a *n is along z axis.
327 * \param n[] alignment vector.
328 */
329void molecule::Align(Vector *n)
330{
331 double alpha, tmp;
332 Vector z_axis;
333 z_axis[0] = 0.;
334 z_axis[1] = 0.;
335 z_axis[2] = 1.;
336
337 // rotate on z-x plane
338 DoLog(0) && (Log() << Verbose(0) << "Begin of Aligning all atoms." << endl);
339 alpha = atan(-n->at(0)/n->at(2));
340 DoLog(1) && (Log() << Verbose(1) << "Z-X-angle: " << alpha << " ... ");
341 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
342 tmp = (*iter)->at(0);
343 (*iter)->set(0, cos(alpha) * tmp + sin(alpha) * (*iter)->at(2));
344 (*iter)->set(2, -sin(alpha) * tmp + cos(alpha) * (*iter)->at(2));
345 for (int j=0;j<MDSteps;j++) {
346 tmp = (*iter)->Trajectory.R.at(j)[0];
347 (*iter)->Trajectory.R.at(j)[0] = cos(alpha) * tmp + sin(alpha) * (*iter)->Trajectory.R.at(j)[2];
348 (*iter)->Trajectory.R.at(j)[2] = -sin(alpha) * tmp + cos(alpha) * (*iter)->Trajectory.R.at(j)[2];
349 }
350 }
351 // rotate n vector
352 tmp = n->at(0);
353 n->at(0) = cos(alpha) * tmp + sin(alpha) * n->at(2);
354 n->at(2) = -sin(alpha) * tmp + cos(alpha) * n->at(2);
355 DoLog(1) && (Log() << Verbose(1) << "alignment vector after first rotation: " << n << endl);
356
357 // rotate on z-y plane
358 alpha = atan(-n->at(1)/n->at(2));
359 DoLog(1) && (Log() << Verbose(1) << "Z-Y-angle: " << alpha << " ... ");
360 for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
361 tmp = (*iter)->at(1);
362 (*iter)->set(1, cos(alpha) * tmp + sin(alpha) * (*iter)->at(2));
363 (*iter)->set(2, -sin(alpha) * tmp + cos(alpha) * (*iter)->at(2));
364 for (int j=0;j<MDSteps;j++) {
365 tmp = (*iter)->Trajectory.R.at(j)[1];
366 (*iter)->Trajectory.R.at(j)[1] = cos(alpha) * tmp + sin(alpha) * (*iter)->Trajectory.R.at(j)[2];
367 (*iter)->Trajectory.R.at(j)[2] = -sin(alpha) * tmp + cos(alpha) * (*iter)->Trajectory.R.at(j)[2];
368 }
369 }
370 // rotate n vector (for consistency check)
371 tmp = n->at(1);
372 n->at(1) = cos(alpha) * tmp + sin(alpha) * n->at(2);
373 n->at(2) = -sin(alpha) * tmp + cos(alpha) * n->at(2);
374
375
376 DoLog(1) && (Log() << Verbose(1) << "alignment vector after second rotation: " << n << endl);
377 DoLog(0) && (Log() << Verbose(0) << "End of Aligning all atoms." << endl);
378};
379
380
381/** Calculates sum over least square distance to line hidden in \a *x.
382 * \param *x offset and direction vector
383 * \param *params pointer to lsq_params structure
384 * \return \f$ sum_i^N | y_i - (a + t_i b)|^2\f$
385 */
386double LeastSquareDistance (const gsl_vector * x, void * params)
387{
388 double res = 0, t;
389 Vector a,b,c,d;
390 struct lsq_params *par = (struct lsq_params *)params;
391
392 // initialize vectors
393 a[0] = gsl_vector_get(x,0);
394 a[1] = gsl_vector_get(x,1);
395 a[2] = gsl_vector_get(x,2);
396 b[0] = gsl_vector_get(x,3);
397 b[1] = gsl_vector_get(x,4);
398 b[2] = gsl_vector_get(x,5);
399 // go through all atoms
400 for (molecule::const_iterator iter = par->mol->begin(); iter != par->mol->end(); ++iter) {
401 if ((*iter)->getType() == ((struct lsq_params *)params)->type) { // for specific type
402 c = (*iter)->getPosition() - a;
403 t = c.ScalarProduct(b); // get direction parameter
404 d = t*b; // and create vector
405 c -= d; // ... yielding distance vector
406 res += d.ScalarProduct(d); // add squared distance
407 }
408 }
409 return res;
410};
411
412/** By minimizing the least square distance gains alignment vector.
413 * \bug this is not yet working properly it seems
414 */
415void molecule::GetAlignvector(struct lsq_params * par) const
416{
417 int np = 6;
418
419 const gsl_multimin_fminimizer_type *T =
420 gsl_multimin_fminimizer_nmsimplex;
421 gsl_multimin_fminimizer *s = NULL;
422 gsl_vector *ss;
423 gsl_multimin_function minex_func;
424
425 size_t iter = 0, i;
426 int status;
427 double size;
428
429 /* Initial vertex size vector */
430 ss = gsl_vector_alloc (np);
431
432 /* Set all step sizes to 1 */
433 gsl_vector_set_all (ss, 1.0);
434
435 /* Starting point */
436 par->x = gsl_vector_alloc (np);
437 par->mol = this;
438
439 gsl_vector_set (par->x, 0, 0.0); // offset
440 gsl_vector_set (par->x, 1, 0.0);
441 gsl_vector_set (par->x, 2, 0.0);
442 gsl_vector_set (par->x, 3, 0.0); // direction
443 gsl_vector_set (par->x, 4, 0.0);
444 gsl_vector_set (par->x, 5, 1.0);
445
446 /* Initialize method and iterate */
447 minex_func.f = &LeastSquareDistance;
448 minex_func.n = np;
449 minex_func.params = (void *)par;
450
451 s = gsl_multimin_fminimizer_alloc (T, np);
452 gsl_multimin_fminimizer_set (s, &minex_func, par->x, ss);
453
454 do
455 {
456 iter++;
457 status = gsl_multimin_fminimizer_iterate(s);
458
459 if (status)
460 break;
461
462 size = gsl_multimin_fminimizer_size (s);
463 status = gsl_multimin_test_size (size, 1e-2);
464
465 if (status == GSL_SUCCESS)
466 {
467 printf ("converged to minimum at\n");
468 }
469
470 printf ("%5d ", (int)iter);
471 for (i = 0; i < (size_t)np; i++)
472 {
473 printf ("%10.3e ", gsl_vector_get (s->x, i));
474 }
475 printf ("f() = %7.3f size = %.3f\n", s->fval, size);
476 }
477 while (status == GSL_CONTINUE && iter < 100);
478
479 for (i=0;i<(size_t)np;i++)
480 gsl_vector_set(par->x, i, gsl_vector_get(s->x, i));
481 //gsl_vector_free(par->x);
482 gsl_vector_free(ss);
483 gsl_multimin_fminimizer_free (s);
484};
Note: See TracBrowser for help on using the repository browser.