source: src/molecule_dynamics.cpp@ 42af9e

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 42af9e was 920c70, checked in by Frederik Heber <heber@…>, 15 years ago

Removed all Malloc/Calloc/ReAlloc (&Free) and replaced by new and delete/delete[].

Due to the new MemDebug framework there is no need (or even unnecessary/unwanted competition between it and) for the MemoryAllocator and ..UsageObserver anymore.
They can however still be used with c codes such as pcp and alikes.

In Molecuilder lots of glibc corruptions arose and the C-like syntax make it generally harder to get allocation and deallocation straight.

Signed-off-by: Frederik Heber <heber@…>

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