source: src/molecule_dynamics.cpp@ 72e7fa

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 72e7fa was 0a4f7f, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made data internal data-structure of vector class private

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