source: src/molecule_dynamics.cpp@ 735b1c

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

ParticleInfo::ParticleInfo_nr is protected and accessed via getter/setter.

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