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