source: src/molecule_dynamics.cpp@ 9cd807

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 9cd807 was bf3817, checked in by Frederik Heber <heber@…>, 15 years ago

Added ifdef HAVE_CONFIG and config.h include to each and every cpp file.

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