source: src/molecule_dynamics.cpp@ 14c57a

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 Candidate_v1.7.0 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 14c57a was 14c57a, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made all parts of the programm use the new thermostat structure

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