source: molecuilder/src/molecule_dynamics.cpp@ f70c2a

Last change on this file since f70c2a was 0d111b, checked in by Tillmann Crueger <crueger@…>, 16 years ago

Merge branch 'VectorRefactoring' into StructureRefactoring

Conflicts:

molecuilder/src/Legacy/oldmenu.cpp
molecuilder/src/Makefile.am
molecuilder/src/analysis_correlation.cpp
molecuilder/src/boundary.cpp
molecuilder/src/builder.cpp
molecuilder/src/config.cpp
molecuilder/src/ellipsoid.cpp
molecuilder/src/linkedcell.cpp
molecuilder/src/molecule.cpp
molecuilder/src/molecule_fragmentation.cpp
molecuilder/src/molecule_geometry.cpp
molecuilder/src/molecule_graph.cpp
molecuilder/src/moleculelist.cpp
molecuilder/src/tesselation.cpp
molecuilder/src/tesselationhelpers.cpp
molecuilder/src/unittests/AnalysisCorrelationToSurfaceUnitTest.cpp
molecuilder/src/unittests/bondgraphunittest.cpp
molecuilder/src/vector.cpp
molecuilder/src/vector.hpp

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