source: src/molecule_dynamics.cpp@ 43dad6

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 43dad6 was a3fded, checked in by Frederik Heber <heber@…>, 15 years ago

New class ThermoStatContainer containing all parameters and changes to ConfigFileBuffer.

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