1 | /*
|
---|
2 | * Project: MoleCuilder
|
---|
3 | * Description: creates and alters molecular systems
|
---|
4 | * Copyright (C) 2010 University of Bonn. All rights reserved.
|
---|
5 | * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
|
---|
6 | */
|
---|
7 |
|
---|
8 | /*
|
---|
9 | * molecule_dynamics.cpp
|
---|
10 | *
|
---|
11 | * Created on: Oct 5, 2009
|
---|
12 | * Author: heber
|
---|
13 | */
|
---|
14 |
|
---|
15 | // include config.h
|
---|
16 | #ifdef HAVE_CONFIG_H
|
---|
17 | #include <config.h>
|
---|
18 | #endif
|
---|
19 |
|
---|
20 | #include "CodePatterns/MemDebug.hpp"
|
---|
21 |
|
---|
22 | #include "World.hpp"
|
---|
23 | #include "atom.hpp"
|
---|
24 | #include "config.hpp"
|
---|
25 | #include "element.hpp"
|
---|
26 | #include "CodePatterns/Info.hpp"
|
---|
27 | #include "CodePatterns/Verbose.hpp"
|
---|
28 | #include "CodePatterns/Log.hpp"
|
---|
29 | #include "molecule.hpp"
|
---|
30 | #include "parser.hpp"
|
---|
31 | #include "LinearAlgebra/Plane.hpp"
|
---|
32 | #include "ThermoStatContainer.hpp"
|
---|
33 | #include "Thermostats/Berendsen.hpp"
|
---|
34 |
|
---|
35 | #include "CodePatterns/enumeration.hpp"
|
---|
36 |
|
---|
37 | #include <gsl/gsl_matrix.h>
|
---|
38 | #include <gsl/gsl_vector.h>
|
---|
39 | #include <gsl/gsl_linalg.h>
|
---|
40 |
|
---|
41 | /************************************* Functions for class molecule *********************************/
|
---|
42 |
|
---|
43 | /** Penalizes long trajectories.
|
---|
44 | * \param *Walker atom to check against others
|
---|
45 | * \param *mol molecule with other atoms
|
---|
46 | * \param &Params constraint potential parameters
|
---|
47 | * \return penalty times each distance
|
---|
48 | */
|
---|
49 | double SumDistanceOfTrajectories(atom *Walker, molecule *mol, struct EvaluatePotential &Params)
|
---|
50 | {
|
---|
51 | gsl_matrix *A = gsl_matrix_alloc(NDIM,NDIM);
|
---|
52 | gsl_vector *x = gsl_vector_alloc(NDIM);
|
---|
53 | atom *Sprinter = NULL;
|
---|
54 | Vector trajectory1, trajectory2, normal, TestVector;
|
---|
55 | double Norm1, Norm2, tmp, result = 0.;
|
---|
56 |
|
---|
57 | for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
|
---|
58 | if ((*iter) == Walker) // hence, we only go up to the Walker, not beyond (similar to i=0; i<j; i++)
|
---|
59 | break;
|
---|
60 | // determine normalized trajectories direction vector (n1, n2)
|
---|
61 | Sprinter = Params.PermutationMap[Walker->nr]; // find first target point
|
---|
62 | trajectory1 = Sprinter->Trajectory.R.at(Params.endstep) - Walker->Trajectory.R.at(Params.startstep);
|
---|
63 | trajectory1.Normalize();
|
---|
64 | Norm1 = trajectory1.Norm();
|
---|
65 | Sprinter = Params.PermutationMap[(*iter)->nr]; // find second target point
|
---|
66 | trajectory2 = Sprinter->Trajectory.R.at(Params.endstep) - (*iter)->Trajectory.R.at(Params.startstep);
|
---|
67 | trajectory2.Normalize();
|
---|
68 | Norm2 = trajectory1.Norm();
|
---|
69 | // check whether either is zero()
|
---|
70 | if ((Norm1 < MYEPSILON) && (Norm2 < MYEPSILON)) {
|
---|
71 | tmp = Walker->Trajectory.R.at(Params.startstep).distance((*iter)->Trajectory.R.at(Params.startstep));
|
---|
72 | } else if (Norm1 < MYEPSILON) {
|
---|
73 | Sprinter = Params.PermutationMap[Walker->nr]; // find first target point
|
---|
74 | trajectory1 = Sprinter->Trajectory.R.at(Params.endstep) - (*iter)->Trajectory.R.at(Params.startstep);
|
---|
75 | trajectory2 *= trajectory1.ScalarProduct(trajectory2); // trajectory2 is scaled to unity, hence we don't need to divide by anything
|
---|
76 | trajectory1 -= trajectory2; // project the part in norm direction away
|
---|
77 | tmp = trajectory1.Norm(); // remaining norm is distance
|
---|
78 | } else if (Norm2 < MYEPSILON) {
|
---|
79 | Sprinter = Params.PermutationMap[(*iter)->nr]; // find second target point
|
---|
80 | trajectory2 = Sprinter->Trajectory.R.at(Params.endstep) - Walker->Trajectory.R.at(Params.startstep); // copy second offset
|
---|
81 | trajectory1 *= trajectory2.ScalarProduct(trajectory1); // trajectory1 is scaled to unity, hence we don't need to divide by anything
|
---|
82 | trajectory2 -= trajectory1; // project the part in norm direction away
|
---|
83 | tmp = trajectory2.Norm(); // remaining norm is distance
|
---|
84 | } else if ((fabs(trajectory1.ScalarProduct(trajectory2)/Norm1/Norm2) - 1.) < MYEPSILON) { // check whether they're linear dependent
|
---|
85 | // Log() << Verbose(3) << "Both trajectories of " << *Walker << " and " << *Runner << " are linear dependent: ";
|
---|
86 | // Log() << Verbose(0) << trajectory1;
|
---|
87 | // Log() << Verbose(0) << " and ";
|
---|
88 | // Log() << Verbose(0) << trajectory2;
|
---|
89 | tmp = Walker->Trajectory.R.at(Params.startstep).distance((*iter)->Trajectory.R.at(Params.startstep));
|
---|
90 | // Log() << Verbose(0) << " with distance " << tmp << "." << endl;
|
---|
91 | } else { // determine distance by finding minimum distance
|
---|
92 | // Log() << Verbose(3) << "Both trajectories of " << *Walker << " and " << *(*iter) << " are linear independent ";
|
---|
93 | // Log() << Verbose(0) << endl;
|
---|
94 | // Log() << Verbose(0) << "First Trajectory: ";
|
---|
95 | // Log() << Verbose(0) << trajectory1 << endl;
|
---|
96 | // Log() << Verbose(0) << "Second Trajectory: ";
|
---|
97 | // Log() << Verbose(0) << trajectory2 << endl;
|
---|
98 | // determine normal vector for both
|
---|
99 | normal = Plane(trajectory1, trajectory2,0).getNormal();
|
---|
100 | // print all vectors for debugging
|
---|
101 | // Log() << Verbose(0) << "Normal vector in between: ";
|
---|
102 | // Log() << Verbose(0) << normal << endl;
|
---|
103 | // setup matrix
|
---|
104 | for (int i=NDIM;i--;) {
|
---|
105 | gsl_matrix_set(A, 0, i, trajectory1[i]);
|
---|
106 | gsl_matrix_set(A, 1, i, trajectory2[i]);
|
---|
107 | gsl_matrix_set(A, 2, i, normal[i]);
|
---|
108 | gsl_vector_set(x,i, (Walker->Trajectory.R.at(Params.startstep)[i] - (*iter)->Trajectory.R.at(Params.startstep)[i]));
|
---|
109 | }
|
---|
110 | // solve the linear system by Householder transformations
|
---|
111 | gsl_linalg_HH_svx(A, x);
|
---|
112 | // distance from last component
|
---|
113 | tmp = gsl_vector_get(x,2);
|
---|
114 | // Log() << Verbose(0) << " with distance " << tmp << "." << endl;
|
---|
115 | // test whether we really have the intersection (by checking on c_1 and c_2)
|
---|
116 | trajectory1.Scale(gsl_vector_get(x,0));
|
---|
117 | trajectory2.Scale(gsl_vector_get(x,1));
|
---|
118 | normal.Scale(gsl_vector_get(x,2));
|
---|
119 | TestVector = (*iter)->Trajectory.R.at(Params.startstep) + trajectory2 + normal
|
---|
120 | - (Walker->Trajectory.R.at(Params.startstep) + trajectory1);
|
---|
121 | if (TestVector.Norm() < MYEPSILON) {
|
---|
122 | // Log() << Verbose(2) << "Test: ok.\tDistance of " << tmp << " is correct." << endl;
|
---|
123 | } else {
|
---|
124 | // Log() << Verbose(2) << "Test: failed.\tIntersection is off by ";
|
---|
125 | // Log() << Verbose(0) << TestVector;
|
---|
126 | // Log() << Verbose(0) << "." << endl;
|
---|
127 | }
|
---|
128 | }
|
---|
129 | // add up
|
---|
130 | tmp *= Params.IsAngstroem ? 1. : 1./AtomicLengthToAngstroem;
|
---|
131 | if (fabs(tmp) > MYEPSILON) {
|
---|
132 | result += Params.PenaltyConstants[1] * 1./tmp;
|
---|
133 | //Log() << Verbose(4) << "Adding " << 1./tmp*constants[1] << "." << endl;
|
---|
134 | }
|
---|
135 | }
|
---|
136 | return result;
|
---|
137 | };
|
---|
138 |
|
---|
139 | /** Penalizes atoms heading to same target.
|
---|
140 | * \param *Walker atom to check against others
|
---|
141 | * \param *mol molecule with other atoms
|
---|
142 | * \param &Params constrained potential parameters
|
---|
143 | * \return \a penalty times the number of equal targets
|
---|
144 | */
|
---|
145 | double PenalizeEqualTargets(atom *Walker, molecule *mol, struct EvaluatePotential &Params)
|
---|
146 | {
|
---|
147 | double result = 0.;
|
---|
148 | for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
|
---|
149 | if ((Params.PermutationMap[Walker->nr] == Params.PermutationMap[(*iter)->nr]) && (Walker->nr < (*iter)->nr)) {
|
---|
150 | // atom *Sprinter = PermutationMap[Walker->nr];
|
---|
151 | // Log() << Verbose(0) << *Walker << " and " << *(*iter) << " are heading to the same target at ";
|
---|
152 | // Log() << Verbose(0) << Sprinter->Trajectory.R.at(endstep);
|
---|
153 | // Log() << Verbose(0) << ", penalting." << endl;
|
---|
154 | result += Params.PenaltyConstants[2];
|
---|
155 | //Log() << Verbose(4) << "Adding " << constants[2] << "." << endl;
|
---|
156 | }
|
---|
157 | }
|
---|
158 | return result;
|
---|
159 | };
|
---|
160 |
|
---|
161 | /** Evaluates the potential energy used for constrained molecular dynamics.
|
---|
162 | * \f$V_i^{con} = c^{bond} \cdot | r_{P(i)} - R_i | + sum_{i \neq j} C^{min} \cdot \frac{1}{C_{ij}} + C^{inj} \Bigl (1 - \theta \bigl (\prod_{i \neq j} (P(i) - P(j)) \bigr ) \Bigr )\f$
|
---|
163 | * where the first term points to the target in minimum distance, the second is a penalty for trajectories lying too close to each other (\f$C_{ij}\f$ is minimum distance between
|
---|
164 | * trajectories i and j) and the third term is a penalty for two atoms trying to each the same target point.
|
---|
165 | * Note that for the second term we have to solve the following linear system:
|
---|
166 | * \f$-c_1 \cdot n_1 + c_2 \cdot n_2 + C \cdot n_3 = - p_2 + p_1\f$, where \f$c_1\f$, \f$c_2\f$ and \f$C\f$ are constants,
|
---|
167 | * offset vector \f$p_1\f$ in direction \f$n_1\f$, offset vector \f$p_2\f$ in direction \f$n_2\f$,
|
---|
168 | * \f$n_3\f$ is the normal vector to both directions. \f$C\f$ would be the minimum distance between the two lines.
|
---|
169 | * \sa molecule::MinimiseConstrainedPotential(), molecule::VerletForceIntegration()
|
---|
170 | * \param *out output stream for debugging
|
---|
171 | * \param &Params constrained potential parameters
|
---|
172 | * \return potential energy
|
---|
173 | * \note This routine is scaling quadratically which is not optimal.
|
---|
174 | * \todo There's a bit double counting going on for the first time, bu nothing to worry really about.
|
---|
175 | */
|
---|
176 | double molecule::ConstrainedPotential(struct EvaluatePotential &Params)
|
---|
177 | {
|
---|
178 | double tmp = 0.;
|
---|
179 | double result = 0.;
|
---|
180 | // go through every atom
|
---|
181 | atom *Runner = NULL;
|
---|
182 | for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
|
---|
183 | // first term: distance to target
|
---|
184 | Runner = Params.PermutationMap[(*iter)->nr]; // find target point
|
---|
185 | tmp = ((*iter)->Trajectory.R.at(Params.startstep).distance(Runner->Trajectory.R.at(Params.endstep)));
|
---|
186 | tmp *= Params.IsAngstroem ? 1. : 1./AtomicLengthToAngstroem;
|
---|
187 | result += Params.PenaltyConstants[0] * tmp;
|
---|
188 | //Log() << Verbose(4) << "Adding " << tmp*constants[0] << "." << endl;
|
---|
189 |
|
---|
190 | // second term: sum of distances to other trajectories
|
---|
191 | result += SumDistanceOfTrajectories((*iter), this, Params);
|
---|
192 |
|
---|
193 | // third term: penalty for equal targets
|
---|
194 | result += PenalizeEqualTargets((*iter), this, Params);
|
---|
195 | }
|
---|
196 |
|
---|
197 | return result;
|
---|
198 | };
|
---|
199 |
|
---|
200 | /** print the current permutation map.
|
---|
201 | * \param *out output stream for debugging
|
---|
202 | * \param &Params constrained potential parameters
|
---|
203 | * \param AtomCount number of atoms
|
---|
204 | */
|
---|
205 | void PrintPermutationMap(int AtomCount, struct EvaluatePotential &Params)
|
---|
206 | {
|
---|
207 | stringstream zeile1, zeile2;
|
---|
208 | int *DoubleList = new int[AtomCount];
|
---|
209 | for(int i=0;i<AtomCount;i++)
|
---|
210 | DoubleList[i] = 0;
|
---|
211 | int doubles = 0;
|
---|
212 | zeile1 << "PermutationMap: ";
|
---|
213 | zeile2 << " ";
|
---|
214 | for (int i=0;i<AtomCount;i++) {
|
---|
215 | Params.DoubleList[Params.PermutationMap[i]->nr]++;
|
---|
216 | zeile1 << i << " ";
|
---|
217 | zeile2 << Params.PermutationMap[i]->nr << " ";
|
---|
218 | }
|
---|
219 | for (int i=0;i<AtomCount;i++)
|
---|
220 | if (Params.DoubleList[i] > 1)
|
---|
221 | doubles++;
|
---|
222 | if (doubles >0)
|
---|
223 | DoLog(2) && (Log() << Verbose(2) << "Found " << doubles << " Doubles." << endl);
|
---|
224 | delete[](DoubleList);
|
---|
225 | // Log() << Verbose(2) << zeile1.str() << endl << zeile2.str() << endl;
|
---|
226 | };
|
---|
227 |
|
---|
228 | /** \f$O(N^2)\f$ operation of calculation distance between each atom pair and putting into DistanceList.
|
---|
229 | * \param *mol molecule to scan distances in
|
---|
230 | * \param &Params constrained potential parameters
|
---|
231 | */
|
---|
232 | void FillDistanceList(molecule *mol, struct EvaluatePotential &Params)
|
---|
233 | {
|
---|
234 | for (int i=mol->getAtomCount(); i--;) {
|
---|
235 | Params.DistanceList[i] = new DistanceMap; // is the distance sorted target list per atom
|
---|
236 | Params.DistanceList[i]->clear();
|
---|
237 | }
|
---|
238 |
|
---|
239 | for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
|
---|
240 | for (molecule::const_iterator runner = mol->begin(); runner != mol->end(); ++runner) {
|
---|
241 | Params.DistanceList[(*iter)->nr]->insert( DistancePair((*iter)->Trajectory.R.at(Params.startstep).distance((*runner)->Trajectory.R.at(Params.endstep)), (*runner)) );
|
---|
242 | }
|
---|
243 | }
|
---|
244 | };
|
---|
245 |
|
---|
246 | /** initialize lists.
|
---|
247 | * \param *out output stream for debugging
|
---|
248 | * \param *mol molecule to scan distances in
|
---|
249 | * \param &Params constrained potential parameters
|
---|
250 | */
|
---|
251 | void CreateInitialLists(molecule *mol, struct EvaluatePotential &Params)
|
---|
252 | {
|
---|
253 | for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
|
---|
254 | Params.StepList[(*iter)->nr] = Params.DistanceList[(*iter)->nr]->begin(); // stores the step to the next iterator that could be a possible next target
|
---|
255 | Params.PermutationMap[(*iter)->nr] = Params.DistanceList[(*iter)->nr]->begin()->second; // always pick target with the smallest distance
|
---|
256 | Params.DoubleList[Params.DistanceList[(*iter)->nr]->begin()->second->nr]++; // increase this target's source count (>1? not injective)
|
---|
257 | Params.DistanceIterators[(*iter)->nr] = Params.DistanceList[(*iter)->nr]->begin(); // and remember which one we picked
|
---|
258 | DoLog(2) && (Log() << Verbose(2) << **iter << " starts with distance " << Params.DistanceList[(*iter)->nr]->begin()->first << "." << endl);
|
---|
259 | }
|
---|
260 | };
|
---|
261 |
|
---|
262 | /** Try the next nearest neighbour in order to make the permutation map injective.
|
---|
263 | * \param *out output stream for debugging
|
---|
264 | * \param *mol molecule
|
---|
265 | * \param *Walker atom to change its target
|
---|
266 | * \param &OldPotential old value of constraint potential to see if we do better with new target
|
---|
267 | * \param &Params constrained potential parameters
|
---|
268 | */
|
---|
269 | double TryNextNearestNeighbourForInjectivePermutation(molecule *mol, atom *Walker, double &OldPotential, struct EvaluatePotential &Params)
|
---|
270 | {
|
---|
271 | double Potential = 0;
|
---|
272 | DistanceMap::iterator NewBase = Params.DistanceIterators[Walker->nr]; // store old base
|
---|
273 | do {
|
---|
274 | NewBase++; // take next further distance in distance to targets list that's a target of no one
|
---|
275 | } while ((Params.DoubleList[NewBase->second->nr] != 0) && (NewBase != Params.DistanceList[Walker->nr]->end()));
|
---|
276 | if (NewBase != Params.DistanceList[Walker->nr]->end()) {
|
---|
277 | Params.PermutationMap[Walker->nr] = NewBase->second;
|
---|
278 | Potential = fabs(mol->ConstrainedPotential(Params));
|
---|
279 | if (Potential > OldPotential) { // undo
|
---|
280 | Params.PermutationMap[Walker->nr] = Params.DistanceIterators[Walker->nr]->second;
|
---|
281 | } else { // do
|
---|
282 | Params.DoubleList[Params.DistanceIterators[Walker->nr]->second->nr]--; // decrease the old entry in the doubles list
|
---|
283 | Params.DoubleList[NewBase->second->nr]++; // increase the old entry in the doubles list
|
---|
284 | Params.DistanceIterators[Walker->nr] = NewBase;
|
---|
285 | OldPotential = Potential;
|
---|
286 | DoLog(3) && (Log() << Verbose(3) << "Found a new permutation, new potential is " << OldPotential << "." << endl);
|
---|
287 | }
|
---|
288 | }
|
---|
289 | return Potential;
|
---|
290 | };
|
---|
291 |
|
---|
292 | /** Permutes \a **&PermutationMap until the penalty is below constants[2].
|
---|
293 | * \param *out output stream for debugging
|
---|
294 | * \param *mol molecule to scan distances in
|
---|
295 | * \param &Params constrained potential parameters
|
---|
296 | */
|
---|
297 | void MakeInjectivePermutation(molecule *mol, struct EvaluatePotential &Params)
|
---|
298 | {
|
---|
299 | molecule::const_iterator iter = mol->begin();
|
---|
300 | DistanceMap::iterator NewBase;
|
---|
301 | double Potential = fabs(mol->ConstrainedPotential(Params));
|
---|
302 |
|
---|
303 | if (mol->empty()) {
|
---|
304 | eLog() << Verbose(1) << "Molecule is empty." << endl;
|
---|
305 | return;
|
---|
306 | }
|
---|
307 | while ((Potential) > Params.PenaltyConstants[2]) {
|
---|
308 | PrintPermutationMap(mol->getAtomCount(), Params);
|
---|
309 | iter++;
|
---|
310 | if (iter == mol->end()) // round-robin at the end
|
---|
311 | iter = mol->begin();
|
---|
312 | if (Params.DoubleList[Params.DistanceIterators[(*iter)->nr]->second->nr] <= 1) // no need to make those injective that aren't
|
---|
313 | continue;
|
---|
314 | // now, try finding a new one
|
---|
315 | Potential = TryNextNearestNeighbourForInjectivePermutation(mol, (*iter), Potential, Params);
|
---|
316 | }
|
---|
317 | for (int i=mol->getAtomCount(); i--;) // now each single entry in the DoubleList should be <=1
|
---|
318 | if (Params.DoubleList[i] > 1) {
|
---|
319 | DoeLog(0) && (eLog()<< Verbose(0) << "Failed to create an injective PermutationMap!" << endl);
|
---|
320 | performCriticalExit();
|
---|
321 | }
|
---|
322 | DoLog(1) && (Log() << Verbose(1) << "done." << endl);
|
---|
323 | };
|
---|
324 |
|
---|
325 | /** Minimises the extra potential for constrained molecular dynamics and gives forces and the constrained potential energy.
|
---|
326 | * We do the following:
|
---|
327 | * -# Generate a distance list from all source to all target points
|
---|
328 | * -# Sort this per source point
|
---|
329 | * -# Take for each source point the target point with minimum distance, use this as initial permutation
|
---|
330 | * -# check whether molecule::ConstrainedPotential() is greater than injective penalty
|
---|
331 | * -# If so, we go through each source point, stepping down in the sorted target point distance list and re-checking potential.
|
---|
332 | * -# Next, we only apply transformations that keep the injectivity of the permutations list.
|
---|
333 | * -# Hence, for one source point we step down the ladder and seek the corresponding owner of this new target
|
---|
334 | * point and try to change it for one with lesser distance, or for the next one with greater distance, but only
|
---|
335 | * if this decreases the conditional potential.
|
---|
336 | * -# finished.
|
---|
337 | * -# Then, we calculate the forces by taking the spatial derivative, where we scale the potential to such a degree,
|
---|
338 | * that the total force is always pointing in direction of the constraint force (ensuring that we move in the
|
---|
339 | * right direction).
|
---|
340 | * -# Finally, we calculate the potential energy and return.
|
---|
341 | * \param *out output stream for debugging
|
---|
342 | * \param **PermutationMap on return: mapping between the atom label of the initial and the final configuration
|
---|
343 | * \param startstep current MD step giving initial position between which and \a endstep we perform the constrained MD (as further steps are always concatenated)
|
---|
344 | * \param endstep step giving final position in constrained MD
|
---|
345 | * \param IsAngstroem whether coordinates are in angstroem (true) or bohrradius (false)
|
---|
346 | * \sa molecule::VerletForceIntegration()
|
---|
347 | * \return potential energy (and allocated **PermutationMap (array of molecule::AtomCount ^2)
|
---|
348 | * \todo The constrained potential's constants are set to fixed values right now, but they should scale based on checks of the system in order
|
---|
349 | * to ensure they're properties (e.g. constants[2] always greater than the energy of the system).
|
---|
350 | * \bug this all is not O(N log N) but O(N^2)
|
---|
351 | */
|
---|
352 | double molecule::MinimiseConstrainedPotential(atom **&PermutationMap, int startstep, int endstep, bool IsAngstroem)
|
---|
353 | {
|
---|
354 | double Potential, OldPotential, OlderPotential;
|
---|
355 | struct EvaluatePotential Params;
|
---|
356 | Params.PermutationMap = new atom *[getAtomCount()];
|
---|
357 | Params.DistanceList = new DistanceMap *[getAtomCount()];
|
---|
358 | Params.DistanceIterators = new DistanceMap::iterator[getAtomCount()];
|
---|
359 | Params.DoubleList = new int[getAtomCount()];
|
---|
360 | Params.StepList = new DistanceMap::iterator[getAtomCount()];
|
---|
361 | int round;
|
---|
362 | atom *Sprinter = NULL;
|
---|
363 | DistanceMap::iterator Rider, Strider;
|
---|
364 |
|
---|
365 | // set to zero
|
---|
366 | for (int i=0;i<getAtomCount();i++) {
|
---|
367 | Params.PermutationMap[i] = NULL;
|
---|
368 | Params.DoubleList[i] = 0;
|
---|
369 | }
|
---|
370 |
|
---|
371 | /// Minimise the potential
|
---|
372 | // set Lagrange multiplier constants
|
---|
373 | Params.PenaltyConstants[0] = 10.;
|
---|
374 | Params.PenaltyConstants[1] = 1.;
|
---|
375 | Params.PenaltyConstants[2] = 1e+7; // just a huge penalty
|
---|
376 | // generate the distance list
|
---|
377 | DoLog(1) && (Log() << Verbose(1) << "Allocating, initializting and filling the distance list ... " << endl);
|
---|
378 | FillDistanceList(this, Params);
|
---|
379 |
|
---|
380 | // create the initial PermutationMap (source -> target)
|
---|
381 | CreateInitialLists(this, Params);
|
---|
382 |
|
---|
383 | // make the PermutationMap injective by checking whether we have a non-zero constants[2] term in it
|
---|
384 | DoLog(1) && (Log() << Verbose(1) << "Making the PermutationMap injective ... " << endl);
|
---|
385 | MakeInjectivePermutation(this, Params);
|
---|
386 | delete[](Params.DoubleList);
|
---|
387 |
|
---|
388 | // argument minimise the constrained potential in this injective PermutationMap
|
---|
389 | DoLog(1) && (Log() << Verbose(1) << "Argument minimising the PermutationMap." << endl);
|
---|
390 | OldPotential = 1e+10;
|
---|
391 | round = 0;
|
---|
392 | do {
|
---|
393 | DoLog(2) && (Log() << Verbose(2) << "Starting round " << ++round << ", at current potential " << OldPotential << " ... " << endl);
|
---|
394 | OlderPotential = OldPotential;
|
---|
395 | molecule::const_iterator iter;
|
---|
396 | do {
|
---|
397 | iter = begin();
|
---|
398 | for (; iter != end(); ++iter) {
|
---|
399 | PrintPermutationMap(getAtomCount(), Params);
|
---|
400 | Sprinter = Params.DistanceIterators[(*iter)->nr]->second; // store initial partner
|
---|
401 | Strider = Params.DistanceIterators[(*iter)->nr]; //remember old iterator
|
---|
402 | Params.DistanceIterators[(*iter)->nr] = Params.StepList[(*iter)->nr];
|
---|
403 | if (Params.DistanceIterators[(*iter)->nr] == Params.DistanceList[(*iter)->nr]->end()) {// stop, before we run through the list and still on
|
---|
404 | Params.DistanceIterators[(*iter)->nr] == Params.DistanceList[(*iter)->nr]->begin();
|
---|
405 | break;
|
---|
406 | }
|
---|
407 | //Log() << Verbose(2) << "Current Walker: " << *(*iter) << " with old/next candidate " << *Sprinter << "/" << *DistanceIterators[(*iter)->nr]->second << "." << endl;
|
---|
408 | // find source of the new target
|
---|
409 | molecule::const_iterator runner = begin();
|
---|
410 | for (; runner != end(); ++runner) { // find the source whose toes we might be stepping on (Walker's new target should be in use by another already)
|
---|
411 | if (Params.PermutationMap[(*runner)->nr] == Params.DistanceIterators[(*iter)->nr]->second) {
|
---|
412 | //Log() << Verbose(2) << "Found the corresponding owner " << *(*runner) << " to " << *PermutationMap[(*runner)->nr] << "." << endl;
|
---|
413 | break;
|
---|
414 | }
|
---|
415 | }
|
---|
416 | if (runner != end()) { // we found the other source
|
---|
417 | // then look in its distance list for Sprinter
|
---|
418 | Rider = Params.DistanceList[(*runner)->nr]->begin();
|
---|
419 | for (; Rider != Params.DistanceList[(*runner)->nr]->end(); Rider++)
|
---|
420 | if (Rider->second == Sprinter)
|
---|
421 | break;
|
---|
422 | if (Rider != Params.DistanceList[(*runner)->nr]->end()) { // if we have found one
|
---|
423 | //Log() << Verbose(2) << "Current Other: " << *(*runner) << " with old/next candidate " << *PermutationMap[(*runner)->nr] << "/" << *Rider->second << "." << endl;
|
---|
424 | // exchange both
|
---|
425 | Params.PermutationMap[(*iter)->nr] = Params.DistanceIterators[(*iter)->nr]->second; // put next farther distance into PermutationMap
|
---|
426 | Params.PermutationMap[(*runner)->nr] = Sprinter; // and hand the old target to its respective owner
|
---|
427 | PrintPermutationMap(getAtomCount(), Params);
|
---|
428 | // calculate the new potential
|
---|
429 | //Log() << Verbose(2) << "Checking new potential ..." << endl;
|
---|
430 | Potential = ConstrainedPotential(Params);
|
---|
431 | if (Potential > OldPotential) { // we made everything worse! Undo ...
|
---|
432 | //Log() << Verbose(3) << "Nay, made the potential worse: " << Potential << " vs. " << OldPotential << "!" << endl;
|
---|
433 | //Log() << Verbose(3) << "Setting " << *(*runner) << "'s source to " << *Params.DistanceIterators[(*runner)->nr]->second << "." << endl;
|
---|
434 | // Undo for Runner (note, we haven't moved the iteration yet, we may use this)
|
---|
435 | Params.PermutationMap[(*runner)->nr] = Params.DistanceIterators[(*runner)->nr]->second;
|
---|
436 | // Undo for Walker
|
---|
437 | Params.DistanceIterators[(*iter)->nr] = Strider; // take next farther distance target
|
---|
438 | //Log() << Verbose(3) << "Setting " << *(*iter) << "'s source to " << *Params.DistanceIterators[(*iter)->nr]->second << "." << endl;
|
---|
439 | Params.PermutationMap[(*iter)->nr] = Params.DistanceIterators[(*iter)->nr]->second;
|
---|
440 | } else {
|
---|
441 | Params.DistanceIterators[(*runner)->nr] = Rider; // if successful also move the pointer in the iterator list
|
---|
442 | DoLog(3) && (Log() << Verbose(3) << "Found a better permutation, new potential is " << Potential << " vs." << OldPotential << "." << endl);
|
---|
443 | OldPotential = Potential;
|
---|
444 | }
|
---|
445 | if (Potential > Params.PenaltyConstants[2]) {
|
---|
446 | DoeLog(1) && (eLog()<< Verbose(1) << "The two-step permutation procedure did not maintain injectivity!" << endl);
|
---|
447 | exit(255);
|
---|
448 | }
|
---|
449 | //Log() << Verbose(0) << endl;
|
---|
450 | } else {
|
---|
451 | DoeLog(1) && (eLog()<< Verbose(1) << **runner << " was not the owner of " << *Sprinter << "!" << endl);
|
---|
452 | exit(255);
|
---|
453 | }
|
---|
454 | } else {
|
---|
455 | Params.PermutationMap[(*iter)->nr] = Params.DistanceIterators[(*iter)->nr]->second; // new target has no source!
|
---|
456 | }
|
---|
457 | Params.StepList[(*iter)->nr]++; // take next farther distance target
|
---|
458 | }
|
---|
459 | } while (++iter != end());
|
---|
460 | } while ((OlderPotential - OldPotential) > 1e-3);
|
---|
461 | DoLog(1) && (Log() << Verbose(1) << "done." << endl);
|
---|
462 |
|
---|
463 |
|
---|
464 | /// free memory and return with evaluated potential
|
---|
465 | for (int i=getAtomCount(); i--;)
|
---|
466 | Params.DistanceList[i]->clear();
|
---|
467 | delete[](Params.DistanceList);
|
---|
468 | delete[](Params.DistanceIterators);
|
---|
469 | return ConstrainedPotential(Params);
|
---|
470 | };
|
---|
471 |
|
---|
472 |
|
---|
473 | /** Evaluates the (distance-related part) of the constrained potential for the constrained forces.
|
---|
474 | * \param *out output stream for debugging
|
---|
475 | * \param startstep current MD step giving initial position between which and \a endstep we perform the constrained MD (as further steps are always concatenated)
|
---|
476 | * \param endstep step giving final position in constrained MD
|
---|
477 | * \param **PermutationMap mapping between the atom label of the initial and the final configuration
|
---|
478 | * \param *Force ForceMatrix containing force vectors from the external energy functional minimisation.
|
---|
479 | * \todo the constant for the constrained potential distance part is hard-coded independently of the hard-coded value in MinimiseConstrainedPotential()
|
---|
480 | */
|
---|
481 | void molecule::EvaluateConstrainedForces(int startstep, int endstep, atom **PermutationMap, ForceMatrix *Force)
|
---|
482 | {
|
---|
483 | /// evaluate forces (only the distance to target dependent part) with the final PermutationMap
|
---|
484 | DoLog(1) && (Log() << Verbose(1) << "Calculating forces and adding onto ForceMatrix ... " << endl);
|
---|
485 | for_each(atoms.begin(),
|
---|
486 | atoms.end(),
|
---|
487 | boost::bind(&atom::EvaluateConstrainedForce,_1,startstep,endstep,PermutationMap,Force));
|
---|
488 | DoLog(1) && (Log() << Verbose(1) << "done." << endl);
|
---|
489 | };
|
---|
490 |
|
---|
491 | /** Performs a linear interpolation between two desired atomic configurations with a given number of steps.
|
---|
492 | * Note, step number is config::MaxOuterStep
|
---|
493 | * \param *out output stream for debugging
|
---|
494 | * \param startstep stating initial configuration in molecule::Trajectories
|
---|
495 | * \param endstep stating final configuration in molecule::Trajectories
|
---|
496 | * \param &prefix path and prefix
|
---|
497 | * \param &config configuration structure
|
---|
498 | * \param MapByIdentity if true we just use the identity to map atoms in start config to end config, if not we find mapping by \sa MinimiseConstrainedPotential()
|
---|
499 | * \return true - success in writing step files, false - error writing files or only one step in molecule::Trajectories
|
---|
500 | */
|
---|
501 | bool molecule::LinearInterpolationBetweenConfiguration(int startstep, int endstep, std::string prefix, config &configuration, bool MapByIdentity)
|
---|
502 | {
|
---|
503 | // TODO: rewrite permutationMaps using enumeration objects
|
---|
504 | molecule *mol = NULL;
|
---|
505 | bool status = true;
|
---|
506 | int MaxSteps = configuration.MaxOuterStep;
|
---|
507 | MoleculeListClass *MoleculePerStep = new MoleculeListClass(World::getPointer());
|
---|
508 | // Get the Permutation Map by MinimiseConstrainedPotential
|
---|
509 | atom **PermutationMap = NULL;
|
---|
510 | atom *Sprinter = NULL;
|
---|
511 | if (!MapByIdentity)
|
---|
512 | MinimiseConstrainedPotential(PermutationMap, startstep, endstep, configuration.GetIsAngstroem());
|
---|
513 | else {
|
---|
514 | // TODO: construction of enumeration goes here
|
---|
515 | PermutationMap = new atom *[getAtomCount()];
|
---|
516 | for(internal_iterator iter = atoms.begin(); iter != atoms.end();++iter){
|
---|
517 | PermutationMap[(*iter)->nr] = (*iter);
|
---|
518 | }
|
---|
519 | }
|
---|
520 |
|
---|
521 | // check whether we have sufficient space in Trajectories for each atom
|
---|
522 | for_each(atoms.begin(),atoms.end(),bind2nd(mem_fun(&atom::ResizeTrajectory),MaxSteps));
|
---|
523 | // push endstep to last one
|
---|
524 | for_each(atoms.begin(),atoms.end(),boost::bind(&atom::CopyStepOnStep,_1,MaxSteps,endstep));
|
---|
525 | endstep = MaxSteps;
|
---|
526 |
|
---|
527 | // go through all steps and add the molecular configuration to the list and to the Trajectories of \a this molecule
|
---|
528 | DoLog(1) && (Log() << Verbose(1) << "Filling intermediate " << MaxSteps << " steps with MDSteps of " << MDSteps << "." << endl);
|
---|
529 | for (int step = 0; step <= MaxSteps; step++) {
|
---|
530 | mol = World::getInstance().createMolecule();
|
---|
531 | MoleculePerStep->insert(mol);
|
---|
532 | for (molecule::const_iterator iter = begin(); iter != end(); ++iter) {
|
---|
533 | // add to molecule list
|
---|
534 | Sprinter = mol->AddCopyAtom((*iter));
|
---|
535 | for (int n=NDIM;n--;) {
|
---|
536 | Sprinter->set(n, (*iter)->Trajectory.R.at(startstep)[n] + (PermutationMap[(*iter)->nr]->Trajectory.R.at(endstep)[n] - (*iter)->Trajectory.R.at(startstep)[n])*((double)step/(double)MaxSteps));
|
---|
537 | // add to Trajectories
|
---|
538 | //Log() << Verbose(3) << step << ">=" << MDSteps-1 << endl;
|
---|
539 | if (step < MaxSteps) {
|
---|
540 | (*iter)->Trajectory.R.at(step)[n] = (*iter)->Trajectory.R.at(startstep)[n] + (PermutationMap[(*iter)->nr]->Trajectory.R.at(endstep)[n] - (*iter)->Trajectory.R.at(startstep)[n])*((double)step/(double)MaxSteps);
|
---|
541 | (*iter)->Trajectory.U.at(step)[n] = 0.;
|
---|
542 | (*iter)->Trajectory.F.at(step)[n] = 0.;
|
---|
543 | }
|
---|
544 | }
|
---|
545 | }
|
---|
546 | }
|
---|
547 | MDSteps = MaxSteps+1; // otherwise new Trajectories' points aren't stored on save&exit
|
---|
548 |
|
---|
549 | // store the list to single step files
|
---|
550 | int *SortIndex = new int[getAtomCount()];
|
---|
551 | for (int i=getAtomCount(); i--; )
|
---|
552 | SortIndex[i] = i;
|
---|
553 |
|
---|
554 | status = MoleculePerStep->OutputConfigForListOfFragments(prefix, SortIndex);
|
---|
555 | delete[](SortIndex);
|
---|
556 |
|
---|
557 | // free and return
|
---|
558 | delete[](PermutationMap);
|
---|
559 | delete(MoleculePerStep);
|
---|
560 | return status;
|
---|
561 | };
|
---|
562 |
|
---|
563 | /** Parses nuclear forces from file and performs Verlet integration.
|
---|
564 | * Note that we assume the parsed forces to be in atomic units (hence, if coordinates are in angstroem, we
|
---|
565 | * have to transform them).
|
---|
566 | * This adds a new MD step to the config file.
|
---|
567 | * \param *file filename
|
---|
568 | * \param config structure with config::Deltat, config::IsAngstroem, config::DoConstrained
|
---|
569 | * \param offset offset in matrix file to the first force component
|
---|
570 | * \return true - file found and parsed, false - file not found or imparsable
|
---|
571 | * \todo This is not yet checked if it is correctly working with DoConstrained set to true.
|
---|
572 | */
|
---|
573 | bool molecule::VerletForceIntegration(char *file, config &configuration, const size_t offset)
|
---|
574 | {
|
---|
575 | Info FunctionInfo(__func__);
|
---|
576 | string token;
|
---|
577 | stringstream item;
|
---|
578 | double IonMass, ConstrainedPotentialEnergy, ActualTemp;
|
---|
579 | Vector Velocity;
|
---|
580 | ForceMatrix Force;
|
---|
581 |
|
---|
582 | const int AtomCount = getAtomCount();
|
---|
583 | // parse file into ForceMatrix
|
---|
584 | std::ifstream input(file);
|
---|
585 | if ((input.good()) && (!Force.ParseMatrix(input, 0,0,0))) {
|
---|
586 | DoeLog(0) && (eLog()<< Verbose(0) << "Could not parse Force Matrix file " << file << "." << endl);
|
---|
587 | performCriticalExit();
|
---|
588 | return false;
|
---|
589 | }
|
---|
590 | input.close();
|
---|
591 | if (Force.RowCounter[0] != AtomCount) {
|
---|
592 | DoeLog(0) && (eLog()<< Verbose(0) << "Mismatch between number of atoms in file " << Force.RowCounter[0] << " and in molecule " << getAtomCount() << "." << endl);
|
---|
593 | performCriticalExit();
|
---|
594 | return false;
|
---|
595 | }
|
---|
596 | // correct Forces
|
---|
597 | Velocity.Zero();
|
---|
598 | for(int i=0;i<AtomCount;i++)
|
---|
599 | for(int d=0;d<NDIM;d++) {
|
---|
600 | Velocity[d] += Force.Matrix[0][i][d+offset];
|
---|
601 | }
|
---|
602 | for(int i=0;i<AtomCount;i++)
|
---|
603 | for(int d=0;d<NDIM;d++) {
|
---|
604 | Force.Matrix[0][i][d+offset] -= Velocity[d]/static_cast<double>(AtomCount);
|
---|
605 | }
|
---|
606 | // solve a constrained potential if we are meant to
|
---|
607 | if (configuration.DoConstrainedMD) {
|
---|
608 | // calculate forces and potential
|
---|
609 | atom **PermutationMap = NULL;
|
---|
610 | ConstrainedPotentialEnergy = MinimiseConstrainedPotential(PermutationMap,configuration.DoConstrainedMD, 0, configuration.GetIsAngstroem());
|
---|
611 | EvaluateConstrainedForces(configuration.DoConstrainedMD, 0, PermutationMap, &Force);
|
---|
612 | delete[](PermutationMap);
|
---|
613 | }
|
---|
614 |
|
---|
615 | // and perform Verlet integration for each atom with position, velocity and force vector
|
---|
616 | // check size of vectors
|
---|
617 | for_each(atoms.begin(),
|
---|
618 | atoms.end(),
|
---|
619 | boost::bind(&atom::VelocityVerletUpdate,_1,MDSteps+1, &configuration, &Force, (const size_t) 0));
|
---|
620 |
|
---|
621 | // correct velocities (rather momenta) so that center of mass remains motionless
|
---|
622 | Velocity = atoms.totalMomentumAtStep(MDSteps+1);
|
---|
623 | IonMass = atoms.totalMass();
|
---|
624 |
|
---|
625 | // correct velocities (rather momenta) so that center of mass remains motionless
|
---|
626 | Velocity *= 1./IonMass;
|
---|
627 |
|
---|
628 | atoms.addVelocityAtStep(-1*Velocity,MDSteps+1);
|
---|
629 | ActualTemp = atoms.totalTemperatureAtStep(MDSteps+1);
|
---|
630 | Berendsen berendsen = Berendsen();
|
---|
631 | berendsen.addToContainer(configuration.Thermostats);
|
---|
632 | double ekin = berendsen.scaleAtoms(MDSteps,ActualTemp,atoms);
|
---|
633 | DoLog(1) && (Log() << Verbose(1) << "Kinetic energy is " << ekin << "." << endl);
|
---|
634 | MDSteps++;
|
---|
635 |
|
---|
636 | // exit
|
---|
637 | return true;
|
---|
638 | };
|
---|