1 | /*
|
---|
2 | * ForceAnnealing.hpp
|
---|
3 | *
|
---|
4 | * Created on: Aug 02, 2014
|
---|
5 | * Author: heber
|
---|
6 | */
|
---|
7 |
|
---|
8 | #ifndef FORCEANNEALING_HPP_
|
---|
9 | #define FORCEANNEALING_HPP_
|
---|
10 |
|
---|
11 | // include config.h
|
---|
12 | #ifdef HAVE_CONFIG_H
|
---|
13 | #include <config.h>
|
---|
14 | #endif
|
---|
15 |
|
---|
16 | #include <algorithm>
|
---|
17 | #include <functional>
|
---|
18 | #include <iterator>
|
---|
19 |
|
---|
20 | #include <boost/bind.hpp>
|
---|
21 |
|
---|
22 | #include "Atom/atom.hpp"
|
---|
23 | #include "Atom/AtomSet.hpp"
|
---|
24 | #include "CodePatterns/Assert.hpp"
|
---|
25 | #include "CodePatterns/Info.hpp"
|
---|
26 | #include "CodePatterns/Log.hpp"
|
---|
27 | #include "CodePatterns/Verbose.hpp"
|
---|
28 | #include "Descriptors/AtomIdDescriptor.hpp"
|
---|
29 | #include "Dynamics/AtomicForceManipulator.hpp"
|
---|
30 | #include "Dynamics/BondVectors.hpp"
|
---|
31 | #include "Fragmentation/ForceMatrix.hpp"
|
---|
32 | #include "Graph/BoostGraphCreator.hpp"
|
---|
33 | #include "Graph/BoostGraphHelpers.hpp"
|
---|
34 | #include "Graph/BreadthFirstSearchGatherer.hpp"
|
---|
35 | #include "Helpers/helpers.hpp"
|
---|
36 | #include "Helpers/defs.hpp"
|
---|
37 | #include "LinearAlgebra/LinearSystemOfEquations.hpp"
|
---|
38 | #include "LinearAlgebra/MatrixContent.hpp"
|
---|
39 | #include "LinearAlgebra/Vector.hpp"
|
---|
40 | #include "LinearAlgebra/VectorContent.hpp"
|
---|
41 | #include "Thermostats/ThermoStatContainer.hpp"
|
---|
42 | #include "Thermostats/Thermostat.hpp"
|
---|
43 | #include "World.hpp"
|
---|
44 |
|
---|
45 | /** This class is the essential build block for performing structural optimization.
|
---|
46 | *
|
---|
47 | * Sadly, we have to use some static instances as so far values cannot be passed
|
---|
48 | * between actions. Hence, we need to store the current step and the adaptive-
|
---|
49 | * step width (we cannot perform a line search, as we have no control over the
|
---|
50 | * calculation of the forces).
|
---|
51 | *
|
---|
52 | * However, we do use the bond graph, i.e. if a single atom needs to be shifted
|
---|
53 | * to the left, then the whole molecule left of it is shifted, too. This is
|
---|
54 | * controlled by the \a max_distance parameter.
|
---|
55 | */
|
---|
56 | template <class T>
|
---|
57 | class ForceAnnealing : public AtomicForceManipulator<T>
|
---|
58 | {
|
---|
59 | public:
|
---|
60 | /** Constructor of class ForceAnnealing.
|
---|
61 | *
|
---|
62 | * \note We use a fixed delta t of 1.
|
---|
63 | *
|
---|
64 | * \param _atoms set of atoms to integrate
|
---|
65 | * \param _Deltat time step width in atomic units
|
---|
66 | * \param _IsAngstroem whether length units are in angstroem or bohr radii
|
---|
67 | * \param _maxSteps number of optimization steps to perform
|
---|
68 | * \param _max_distance up to this bond order is bond graph taken into account.
|
---|
69 | */
|
---|
70 | ForceAnnealing(
|
---|
71 | AtomSetMixin<T> &_atoms,
|
---|
72 | const double _Deltat,
|
---|
73 | bool _IsAngstroem,
|
---|
74 | const size_t _maxSteps,
|
---|
75 | const int _max_distance,
|
---|
76 | const double _damping_factor) :
|
---|
77 | AtomicForceManipulator<T>(_atoms, _Deltat, _IsAngstroem),
|
---|
78 | maxSteps(_maxSteps),
|
---|
79 | max_distance(_max_distance),
|
---|
80 | damping_factor(_damping_factor)
|
---|
81 | {}
|
---|
82 |
|
---|
83 | /** Destructor of class ForceAnnealing.
|
---|
84 | *
|
---|
85 | */
|
---|
86 | ~ForceAnnealing()
|
---|
87 | {}
|
---|
88 |
|
---|
89 | /** Performs Gradient optimization.
|
---|
90 | *
|
---|
91 | * We assume that forces have just been calculated.
|
---|
92 | *
|
---|
93 | *
|
---|
94 | * \param _TimeStep current time step (i.e. \f$ t + \Delta t \f$ in the sense of the velocity verlet)
|
---|
95 | * \param offset offset in matrix file to the first force component
|
---|
96 | * \todo This is not yet checked if it is correctly working with DoConstrainedMD set >0.
|
---|
97 | */
|
---|
98 | void operator()(
|
---|
99 | const int _TimeStep,
|
---|
100 | const size_t _offset,
|
---|
101 | const bool _UseBondgraph)
|
---|
102 | {
|
---|
103 | const int CurrentTimeStep = _TimeStep-1;
|
---|
104 | ASSERT( CurrentTimeStep >= 0,
|
---|
105 | "ForceAnnealing::operator() - a new time step (upon which we work) must already have been copied.");
|
---|
106 |
|
---|
107 | // make sum of forces equal zero
|
---|
108 | AtomicForceManipulator<T>::correctForceMatrixForFixedCenterOfMass(
|
---|
109 | _offset,
|
---|
110 | CurrentTimeStep);
|
---|
111 |
|
---|
112 | // are we in initial step? Then set static entities
|
---|
113 | Vector maxComponents(zeroVec);
|
---|
114 | if (currentStep == 0) {
|
---|
115 | currentDeltat = AtomicForceManipulator<T>::Deltat;
|
---|
116 | currentStep = 1;
|
---|
117 | LOG(2, "DEBUG: Initial step, setting values, current step is #" << currentStep);
|
---|
118 |
|
---|
119 | // always use atomic annealing on first step
|
---|
120 | maxComponents = anneal(_TimeStep);
|
---|
121 | } else {
|
---|
122 | ++currentStep;
|
---|
123 | LOG(2, "DEBUG: current step is #" << currentStep);
|
---|
124 |
|
---|
125 | // bond graph annealing is always followed by a normal annealing
|
---|
126 | if (_UseBondgraph)
|
---|
127 | maxComponents = annealWithBondGraph_BarzilaiBorwein(_TimeStep);
|
---|
128 | // cannot store RemnantGradient in Atom's Force as it ruins BB stepwidth calculation
|
---|
129 | else
|
---|
130 | maxComponents = anneal_BarzilaiBorwein(_TimeStep);
|
---|
131 | }
|
---|
132 |
|
---|
133 | LOG(1, "STATUS: Largest remaining force components at step #"
|
---|
134 | << currentStep << " are " << maxComponents);
|
---|
135 |
|
---|
136 | // are we in final step? Remember to reset static entities
|
---|
137 | if (currentStep == maxSteps) {
|
---|
138 | LOG(2, "DEBUG: Final step, resetting values");
|
---|
139 | reset();
|
---|
140 | }
|
---|
141 | }
|
---|
142 |
|
---|
143 | /** Performs Gradient optimization on the atoms.
|
---|
144 | *
|
---|
145 | * We assume that forces have just been calculated.
|
---|
146 | *
|
---|
147 | * \param _TimeStep current time step (i.e. \f$ t + \Delta t \f$ in the sense of the velocity verlet)
|
---|
148 | * \return to be filled with maximum force component over all atoms
|
---|
149 | */
|
---|
150 | Vector anneal(
|
---|
151 | const int _TimeStep)
|
---|
152 | {
|
---|
153 | const int CurrentTimeStep = _TimeStep-1;
|
---|
154 | ASSERT( CurrentTimeStep >= 0,
|
---|
155 | "ForceAnnealing::anneal() - a new time step (upon which we work) must already have been copied.");
|
---|
156 |
|
---|
157 | LOG(1, "STATUS: performing simple anneal with default stepwidth " << currentDeltat << " at step #" << currentStep);
|
---|
158 |
|
---|
159 | Vector maxComponents;
|
---|
160 | bool deltat_decreased = false;
|
---|
161 | for(typename AtomSetMixin<T>::iterator iter = AtomicForceManipulator<T>::atoms.begin();
|
---|
162 | iter != AtomicForceManipulator<T>::atoms.end(); ++iter) {
|
---|
163 | // atom's force vector gives steepest descent direction
|
---|
164 | const Vector currentPosition = (*iter)->getPositionAtStep(CurrentTimeStep);
|
---|
165 | const Vector currentGradient = (*iter)->getAtomicForceAtStep(CurrentTimeStep);
|
---|
166 | LOG(4, "DEBUG: currentPosition for atom #" << (*iter)->getId() << " is " << currentPosition);
|
---|
167 | LOG(4, "DEBUG: currentGradient for atom #" << (*iter)->getId() << " is " << currentGradient);
|
---|
168 | // LOG(4, "DEBUG: Force for atom " << **iter << " is " << currentGradient);
|
---|
169 |
|
---|
170 | // we use Barzilai-Borwein update with position reversed to get descent
|
---|
171 | double stepwidth = currentDeltat;
|
---|
172 | Vector PositionUpdate = stepwidth * currentGradient;
|
---|
173 | LOG(3, "DEBUG: Update would be " << stepwidth << "*" << currentGradient << " = " << PositionUpdate);
|
---|
174 |
|
---|
175 | // extract largest components for showing progress of annealing
|
---|
176 | for(size_t i=0;i<NDIM;++i)
|
---|
177 | maxComponents[i] = std::max(maxComponents[i], fabs(currentGradient[i]));
|
---|
178 |
|
---|
179 | // steps may go back and forth again (updates are of same magnitude but
|
---|
180 | // have different sign: Check whether this is the case and one step with
|
---|
181 | // deltat to interrupt this sequence
|
---|
182 | if (currentStep > 1) {
|
---|
183 | const int OldTimeStep = _TimeStep-2;
|
---|
184 | ASSERT( OldTimeStep >= 0,
|
---|
185 | "ForceAnnealing::anneal() - if currentStep is "+toString(currentStep)
|
---|
186 | +", then there should be at least three time steps.");
|
---|
187 | const Vector oldPosition = (*iter)->getPositionAtStep(OldTimeStep);
|
---|
188 | const Vector PositionDifference = currentPosition - oldPosition;
|
---|
189 | LOG(4, "DEBUG: oldPosition for atom #" << (*iter)->getId() << " is " << oldPosition);
|
---|
190 | LOG(4, "DEBUG: PositionDifference for atom #" << (*iter)->getId() << " is " << PositionDifference);
|
---|
191 | if ((PositionUpdate.ScalarProduct(PositionDifference) < 0)
|
---|
192 | && (fabs(PositionUpdate.NormSquared()-PositionDifference.NormSquared()) < 1e-3)) {
|
---|
193 | // for convergence we want a null sequence here, too
|
---|
194 | if (!deltat_decreased) {
|
---|
195 | deltat_decreased = true;
|
---|
196 | currentDeltat = .5*currentDeltat;
|
---|
197 | }
|
---|
198 | LOG(2, "DEBUG: Upgrade in other direction: " << PositionUpdate
|
---|
199 | << " > " << PositionDifference
|
---|
200 | << ", using deltat: " << currentDeltat);
|
---|
201 | PositionUpdate = currentDeltat * currentGradient;
|
---|
202 | }
|
---|
203 | }
|
---|
204 |
|
---|
205 | // finally set new values
|
---|
206 | (*iter)->setPositionAtStep(_TimeStep, currentPosition + PositionUpdate);
|
---|
207 | }
|
---|
208 |
|
---|
209 | return maxComponents;
|
---|
210 | }
|
---|
211 |
|
---|
212 | /** Performs Gradient optimization on the atoms using BarzilaiBorwein step width.
|
---|
213 | *
|
---|
214 | * \note this can only be called when there are at least two optimization
|
---|
215 | * time steps present, i.e. this must be preceeded by a simple anneal().
|
---|
216 | *
|
---|
217 | * We assume that forces have just been calculated.
|
---|
218 | *
|
---|
219 | * \param _TimeStep current time step (i.e. \f$ t + \Delta t \f$ in the sense of the velocity verlet)
|
---|
220 | * \return to be filled with maximum force component over all atoms
|
---|
221 | */
|
---|
222 | Vector anneal_BarzilaiBorwein(
|
---|
223 | const int _TimeStep)
|
---|
224 | {
|
---|
225 | const int OldTimeStep = _TimeStep-2;
|
---|
226 | const int CurrentTimeStep = _TimeStep-1;
|
---|
227 | ASSERT( OldTimeStep >= 0,
|
---|
228 | "ForceAnnealing::anneal_BarzilaiBorwein() - we need two present optimization steps to compute stepwidth.");
|
---|
229 | ASSERT(currentStep > 1,
|
---|
230 | "ForceAnnealing::anneal_BarzilaiBorwein() - we need two present optimization steps to compute stepwidth.");
|
---|
231 |
|
---|
232 | LOG(1, "STATUS: performing BarzilaiBorwein anneal at step #" << currentStep);
|
---|
233 |
|
---|
234 | Vector maxComponents;
|
---|
235 | bool deltat_decreased = false;
|
---|
236 | for(typename AtomSetMixin<T>::iterator iter = AtomicForceManipulator<T>::atoms.begin();
|
---|
237 | iter != AtomicForceManipulator<T>::atoms.end(); ++iter) {
|
---|
238 | // atom's force vector gives steepest descent direction
|
---|
239 | const Vector oldPosition = (*iter)->getPositionAtStep(OldTimeStep);
|
---|
240 | const Vector currentPosition = (*iter)->getPositionAtStep(CurrentTimeStep);
|
---|
241 | const Vector oldGradient = (*iter)->getAtomicForceAtStep(OldTimeStep);
|
---|
242 | const Vector currentGradient = (*iter)->getAtomicForceAtStep(CurrentTimeStep);
|
---|
243 | LOG(4, "DEBUG: oldPosition for atom #" << (*iter)->getId() << " is " << oldPosition);
|
---|
244 | LOG(4, "DEBUG: currentPosition for atom #" << (*iter)->getId() << " is " << currentPosition);
|
---|
245 | LOG(4, "DEBUG: oldGradient for atom #" << (*iter)->getId() << " is " << oldGradient);
|
---|
246 | LOG(4, "DEBUG: currentGradient for atom #" << (*iter)->getId() << " is " << currentGradient);
|
---|
247 | // LOG(4, "DEBUG: Force for atom #" << (*iter)->getId() << " is " << currentGradient);
|
---|
248 |
|
---|
249 | // we use Barzilai-Borwein update with position reversed to get descent
|
---|
250 | const Vector PositionDifference = currentPosition - oldPosition;
|
---|
251 | const Vector GradientDifference = (currentGradient - oldGradient);
|
---|
252 | double stepwidth = 0.;
|
---|
253 | if (GradientDifference.Norm() > MYEPSILON)
|
---|
254 | stepwidth = fabs(PositionDifference.ScalarProduct(GradientDifference))/
|
---|
255 | GradientDifference.NormSquared();
|
---|
256 | if (fabs(stepwidth) < 1e-10) {
|
---|
257 | // dont' warn in first step, deltat usage normal
|
---|
258 | if (currentStep != 1)
|
---|
259 | ELOG(1, "INFO: Barzilai-Borwein stepwidth is zero, using deltat " << currentDeltat << " instead.");
|
---|
260 | stepwidth = currentDeltat;
|
---|
261 | }
|
---|
262 | Vector PositionUpdate = stepwidth * currentGradient;
|
---|
263 | LOG(3, "DEBUG: Update would be " << stepwidth << "*" << currentGradient << " = " << PositionUpdate);
|
---|
264 |
|
---|
265 | // extract largest components for showing progress of annealing
|
---|
266 | for(size_t i=0;i<NDIM;++i)
|
---|
267 | maxComponents[i] = std::max(maxComponents[i], fabs(currentGradient[i]));
|
---|
268 |
|
---|
269 | // steps may go back and forth again (updates are of same magnitude but
|
---|
270 | // have different sign: Check whether this is the case and one step with
|
---|
271 | // deltat to interrupt this sequence
|
---|
272 | if (!PositionDifference.IsZero())
|
---|
273 | if ((PositionUpdate.ScalarProduct(PositionDifference) < 0)
|
---|
274 | && (fabs(PositionUpdate.NormSquared()-PositionDifference.NormSquared()) < 1e-3)) {
|
---|
275 | // for convergence we want a null sequence here, too
|
---|
276 | if (!deltat_decreased) {
|
---|
277 | deltat_decreased = true;
|
---|
278 | currentDeltat = .5*currentDeltat;
|
---|
279 | }
|
---|
280 | LOG(2, "DEBUG: Upgrade in other direction: " << PositionUpdate
|
---|
281 | << " > " << PositionDifference
|
---|
282 | << ", using deltat: " << currentDeltat);
|
---|
283 | PositionUpdate = currentDeltat * currentGradient;
|
---|
284 | }
|
---|
285 |
|
---|
286 | // finally set new values
|
---|
287 | (*iter)->setPositionAtStep(_TimeStep, currentPosition + PositionUpdate);
|
---|
288 | }
|
---|
289 |
|
---|
290 | return maxComponents;
|
---|
291 | }
|
---|
292 |
|
---|
293 | // knowing the number of bonds in total, we can setup the storage for the
|
---|
294 | // projected forces
|
---|
295 | enum whichatom_t {
|
---|
296 | leftside=0,
|
---|
297 | rightside=1,
|
---|
298 | MAX_sides
|
---|
299 | };
|
---|
300 |
|
---|
301 | /** Helper function to put bond force into a container.
|
---|
302 | *
|
---|
303 | * \param _walker atom
|
---|
304 | * \param _current_bond current bond of \a _walker
|
---|
305 | * \param _timestep time step
|
---|
306 | * \param _force calculated bond force
|
---|
307 | * \param _bv bondvectors for obtaining the correct index
|
---|
308 | * \param _projected_forces container
|
---|
309 | */
|
---|
310 | static void ForceStore(
|
---|
311 | const atom &_walker,
|
---|
312 | const bond::ptr &_current_bond,
|
---|
313 | const size_t &_timestep,
|
---|
314 | const double _force,
|
---|
315 | const BondVectors &_bv,
|
---|
316 | std::vector< // time step
|
---|
317 | std::vector< // which bond side
|
---|
318 | std::vector<double> > // over all bonds
|
---|
319 | > &_projected_forces)
|
---|
320 | {
|
---|
321 | std::vector<double> &forcelist = (&_walker == _current_bond->leftatom) ?
|
---|
322 | _projected_forces[_timestep][leftside] : _projected_forces[_timestep][rightside];
|
---|
323 | const size_t index = _bv.getIndexForBond(_current_bond);
|
---|
324 | ASSERT( index != (size_t)-1,
|
---|
325 | "ForceAnnealing() - could not find bond "+toString(*_current_bond)
|
---|
326 | +" in bondvectors");
|
---|
327 | forcelist[index] = _force;
|
---|
328 | }
|
---|
329 |
|
---|
330 | /** Performs Gradient optimization on the bonds with BarzilaiBorwein stepwdith.
|
---|
331 | *
|
---|
332 | * \note this can only be called when there are at least two optimization
|
---|
333 | * time steps present, i.e. this must be preceeded by a simple anneal().
|
---|
334 | *
|
---|
335 | * We assume that forces have just been calculated. These forces are projected
|
---|
336 | * onto the bonds and these are annealed subsequently by moving atoms in the
|
---|
337 | * bond neighborhood on either side conjunctively.
|
---|
338 | *
|
---|
339 | *
|
---|
340 | * \param _TimeStep current time step (i.e. \f$ t + \Delta t \f$ in the sense of the velocity verlet)
|
---|
341 | * \param maxComponents to be filled with maximum force component over all atoms
|
---|
342 | */
|
---|
343 | Vector annealWithBondGraph_BarzilaiBorwein(
|
---|
344 | const int _TimeStep)
|
---|
345 | {
|
---|
346 | const int OldTimeStep = _TimeStep-2;
|
---|
347 | const int CurrentTimeStep = _TimeStep-1;
|
---|
348 | ASSERT(currentStep > 1,
|
---|
349 | "annealWithBondGraph_BarzilaiBorwein() - we need two present optimization steps to compute stepwidth.");
|
---|
350 | ASSERT(OldTimeStep >= 0,
|
---|
351 | "annealWithBondGraph_BarzilaiBorwein() - we need two present optimization steps to compute stepwidth, and the new one to update on already present.");
|
---|
352 |
|
---|
353 | LOG(1, "STATUS: performing BarzilaiBorwein anneal on bonds at step #" << currentStep);
|
---|
354 |
|
---|
355 | Vector maxComponents;
|
---|
356 |
|
---|
357 | // get nodes on either side of selected bond via BFS discovery
|
---|
358 | BoostGraphCreator BGcreator;
|
---|
359 | BGcreator.createFromRange(
|
---|
360 | AtomicForceManipulator<T>::atoms.begin(),
|
---|
361 | AtomicForceManipulator<T>::atoms.end(),
|
---|
362 | AtomicForceManipulator<T>::atoms.size(),
|
---|
363 | BreadthFirstSearchGatherer::AlwaysTruePredicate);
|
---|
364 | BreadthFirstSearchGatherer NodeGatherer(BGcreator);
|
---|
365 |
|
---|
366 | /// We assume that a force is local, i.e. a bond is too short yet and hence
|
---|
367 | /// the atom needs to be moved. However, all the adjacent (bound) atoms might
|
---|
368 | /// already be at the perfect distance. If we just move the atom alone, we ruin
|
---|
369 | /// all the other bonds. Hence, it would be sensible to move every atom found
|
---|
370 | /// through the bond graph in the direction of the force as well by the same
|
---|
371 | /// PositionUpdate. This is almost what we are going to do.
|
---|
372 |
|
---|
373 | /// One issue is: If we need to shorten bond, then we use the PositionUpdate
|
---|
374 | /// also on the the other bond partner already. This is because it is in the
|
---|
375 | /// direction of the bond. Therefore, the update is actually performed twice on
|
---|
376 | /// each bond partner, i.e. the step size is twice as large as it should be.
|
---|
377 | /// This problem only occurs when bonds need to be shortened, not when they
|
---|
378 | /// need to be made longer (then the force vector is facing the other
|
---|
379 | /// direction than the bond vector).
|
---|
380 | /// As a remedy we need to average the force on either end of the bond and
|
---|
381 | /// check whether each gradient points inwards out or outwards with respect
|
---|
382 | /// to the bond and then shift accordingly.
|
---|
383 |
|
---|
384 | /// One more issue is that the projection onto the bond directions does not
|
---|
385 | /// recover the gradient but may be larger as the bond directions are a
|
---|
386 | /// generating system and not a basis (e.g. 3 bonds on a plane where 2 would
|
---|
387 | /// suffice to span the plane). To this end, we need to account for the
|
---|
388 | /// overestimation and obtain a weighting for each bond.
|
---|
389 |
|
---|
390 | // initialize helper class for bond vectors using bonds from range of atoms
|
---|
391 | BondVectors bv;
|
---|
392 | bv.setFromAtomRange< T >(
|
---|
393 | AtomicForceManipulator<T>::atoms.begin(),
|
---|
394 | AtomicForceManipulator<T>::atoms.end(),
|
---|
395 | _TimeStep);
|
---|
396 | const BondVectors::container_t &sorted_bonds = bv.getSorted();
|
---|
397 |
|
---|
398 | std::vector< // time step
|
---|
399 | std::vector< // which bond side
|
---|
400 | std::vector<double> > // over all bonds
|
---|
401 | > projected_forces(2); // one for leftatoms, one for rightatoms (and for both time steps)
|
---|
402 | for (size_t i=0;i<2;++i) {
|
---|
403 | projected_forces[i].resize(MAX_sides);
|
---|
404 | for (size_t j=0;j<MAX_sides;++j)
|
---|
405 | projected_forces[i][j].resize(sorted_bonds.size(), 0.);
|
---|
406 | }
|
---|
407 |
|
---|
408 | // for each atom we need to gather weights and then project the gradient
|
---|
409 | typedef std::map<atomId_t, BondVectors::weights_t > weights_per_atom_t;
|
---|
410 | std::vector<weights_per_atom_t> weights_per_atom(2);
|
---|
411 | typedef std::map<atomId_t, Vector> RemnantGradient_per_atom_t;
|
---|
412 | RemnantGradient_per_atom_t RemnantGradient_per_atom;
|
---|
413 | for (size_t timestep = 0; timestep <= 1; ++timestep) {
|
---|
414 | const size_t ReferenceTimeStep = _TimeStep-timestep-1;
|
---|
415 | LOG(2, "DEBUG: given time step is " << _TimeStep
|
---|
416 | << ", timestep is " << timestep
|
---|
417 | << ", and ReferenceTimeStep is " << ReferenceTimeStep);
|
---|
418 |
|
---|
419 | for(typename AtomSetMixin<T>::const_iterator iter = AtomicForceManipulator<T>::atoms.begin();
|
---|
420 | iter != AtomicForceManipulator<T>::atoms.end(); ++iter) {
|
---|
421 | const atom &walker = *(*iter);
|
---|
422 | const Vector &walkerGradient = walker.getAtomicForceAtStep(ReferenceTimeStep);
|
---|
423 | LOG(3, "DEBUG: Gradient of atom #" << walker.getId() << ", namely "
|
---|
424 | << walker << " is " << walkerGradient << " with magnitude of "
|
---|
425 | << walkerGradient.Norm());
|
---|
426 |
|
---|
427 | const BondList& ListOfBonds = walker.getListOfBonds();
|
---|
428 | if (walkerGradient.Norm() > MYEPSILON) {
|
---|
429 |
|
---|
430 | // gather subset of BondVectors for the current atom
|
---|
431 | const std::vector<Vector> BondVectors =
|
---|
432 | bv.getAtomsBondVectorsAtStep(walker, ReferenceTimeStep);
|
---|
433 |
|
---|
434 | // go through all its bonds and calculate what magnitude is represented
|
---|
435 | // by the others i.e. sum of scalar products against other bonds
|
---|
436 | const std::pair<weights_per_atom_t::iterator, bool> inserter =
|
---|
437 | weights_per_atom[timestep].insert(
|
---|
438 | std::make_pair(walker.getId(),
|
---|
439 | bv.getWeightsForAtomAtStep(walker, BondVectors, ReferenceTimeStep)) );
|
---|
440 | ASSERT( inserter.second,
|
---|
441 | "ForceAnnealing::operator() - weight map for atom "+toString(walker)
|
---|
442 | +" and time step "+toString(timestep)+" already filled?");
|
---|
443 | BondVectors::weights_t &weights = inserter.first->second;
|
---|
444 | ASSERT( weights.size() == ListOfBonds.size(),
|
---|
445 | "ForceAnnealing::operator() - number of weights "
|
---|
446 | +toString(weights.size())+" does not match number of bonds "
|
---|
447 | +toString(ListOfBonds.size())+", error in calculation?");
|
---|
448 |
|
---|
449 | // projected gradient over all bonds and place in one of projected_forces
|
---|
450 | // using the obtained weights
|
---|
451 | BondVectors::forcestore_t forcestoring =
|
---|
452 | boost::bind(&ForceAnnealing::ForceStore, _1, _2, _3, _4,
|
---|
453 | boost::cref(bv), boost::ref(projected_forces));
|
---|
454 | const Vector RemnantGradient = bv.getRemnantGradientForAtomAtStep(
|
---|
455 | walker, walkerGradient, BondVectors, weights, timestep, forcestoring
|
---|
456 | );
|
---|
457 | RemnantGradient_per_atom.insert( std::make_pair(walker.getId(), RemnantGradient) );
|
---|
458 | } else {
|
---|
459 | LOG(2, "DEBUG: Gradient is " << walkerGradient << " less than "
|
---|
460 | << MYEPSILON << " for atom " << walker);
|
---|
461 | // note that projected_forces is initialized to full length and filled
|
---|
462 | // with zeros. Hence, nothing to do here
|
---|
463 | }
|
---|
464 | }
|
---|
465 | }
|
---|
466 |
|
---|
467 | // step through each bond and shift the atoms
|
---|
468 | std::map<atomId_t, Vector> GatheredUpdates; //!< gathers all updates which are applied at the end
|
---|
469 |
|
---|
470 | LOG(3, "DEBUG: current step is " << currentStep << ", given time step is " << CurrentTimeStep);
|
---|
471 | const BondVectors::mapped_t bondvectors = bv.getBondVectorsAtStep(CurrentTimeStep);
|
---|
472 |
|
---|
473 | for (BondVectors::container_t::const_iterator bondsiter = sorted_bonds.begin();
|
---|
474 | bondsiter != sorted_bonds.end(); ++bondsiter) {
|
---|
475 | const bond::ptr ¤t_bond = *bondsiter;
|
---|
476 | const size_t index = bv.getIndexForBond(current_bond);
|
---|
477 | const atom* bondatom[MAX_sides] = {
|
---|
478 | current_bond->leftatom,
|
---|
479 | current_bond->rightatom
|
---|
480 | };
|
---|
481 |
|
---|
482 | // remove the edge
|
---|
483 | #ifndef NDEBUG
|
---|
484 | const bool status =
|
---|
485 | #endif
|
---|
486 | BGcreator.removeEdge(bondatom[leftside]->getId(), bondatom[rightside]->getId());
|
---|
487 | ASSERT( status, "ForceAnnealing() - edge to found bond is not present?");
|
---|
488 |
|
---|
489 | // gather nodes for either atom
|
---|
490 | BoostGraphHelpers::Nodeset_t bondside_set[MAX_sides];
|
---|
491 | BreadthFirstSearchGatherer::distance_map_t distance_map[MAX_sides];
|
---|
492 | for (size_t side=leftside;side<MAX_sides;++side) {
|
---|
493 | bondside_set[side] = NodeGatherer(bondatom[side]->getId(), max_distance);
|
---|
494 | distance_map[side] = NodeGatherer.getDistances();
|
---|
495 | std::sort(bondside_set[side].begin(), bondside_set[side].end());
|
---|
496 | }
|
---|
497 |
|
---|
498 | // re-add edge
|
---|
499 | BGcreator.addEdge(bondatom[leftside]->getId(), bondatom[rightside]->getId());
|
---|
500 |
|
---|
501 | // do for both leftatom and rightatom of bond
|
---|
502 | for (size_t side = leftside; side < MAX_sides; ++side) {
|
---|
503 | const double &bondforce = projected_forces[0][side][index];
|
---|
504 | const double &oldbondforce = projected_forces[1][side][index];
|
---|
505 | const double bondforcedifference = fabs(bondforce - oldbondforce);
|
---|
506 | LOG(4, "DEBUG: bondforce for " << (side == leftside ? "left" : "right")
|
---|
507 | << " side of bond is " << bondforce);
|
---|
508 | LOG(4, "DEBUG: oldbondforce for " << (side == leftside ? "left" : "right")
|
---|
509 | << " side of bond is " << oldbondforce);
|
---|
510 | // if difference or bondforce itself is zero, do nothing
|
---|
511 | if ((fabs(bondforce) < MYEPSILON) || (fabs(bondforcedifference) < MYEPSILON))
|
---|
512 | continue;
|
---|
513 |
|
---|
514 | // get BondVector to bond
|
---|
515 | const BondVectors::mapped_t::const_iterator bviter =
|
---|
516 | bondvectors.find(current_bond);
|
---|
517 | ASSERT( bviter != bondvectors.end(),
|
---|
518 | "ForceAnnealing() - cannot find current_bond ?");
|
---|
519 | ASSERT( fabs(bviter->second.Norm() -1.) < MYEPSILON,
|
---|
520 | "ForceAnnealing() - norm of BondVector is not one");
|
---|
521 | const Vector &BondVector = bviter->second;
|
---|
522 |
|
---|
523 | // calculate gradient and position differences for stepwidth
|
---|
524 | const Vector currentGradient = bondforce * BondVector;
|
---|
525 | LOG(4, "DEBUG: current projected gradient for "
|
---|
526 | << (side == leftside ? "left" : "right") << " side of bond is " << currentGradient);
|
---|
527 | const Vector &oldPosition = bondatom[side]->getPositionAtStep(OldTimeStep);
|
---|
528 | const Vector ¤tPosition = bondatom[side]->getPositionAtStep(CurrentTimeStep);
|
---|
529 | const Vector PositionDifference = currentPosition - oldPosition;
|
---|
530 | LOG(4, "DEBUG: old position is " << oldPosition);
|
---|
531 | LOG(4, "DEBUG: current position is " << currentPosition);
|
---|
532 | LOG(4, "DEBUG: difference in position is " << PositionDifference);
|
---|
533 | LOG(4, "DEBUG: bondvector is " << BondVector);
|
---|
534 | const double projected_PositionDifference = PositionDifference.ScalarProduct(BondVector);
|
---|
535 | LOG(4, "DEBUG: difference in position projected onto bondvector is "
|
---|
536 | << projected_PositionDifference);
|
---|
537 | LOG(4, "DEBUG: abs. difference in forces is " << bondforcedifference);
|
---|
538 |
|
---|
539 | // calculate step width
|
---|
540 | double stepwidth =
|
---|
541 | fabs(projected_PositionDifference)/bondforcedifference;
|
---|
542 | if (fabs(stepwidth) < 1e-10) {
|
---|
543 | // dont' warn in first step, deltat usage normal
|
---|
544 | if (currentStep != 1)
|
---|
545 | ELOG(1, "INFO: Barzilai-Borwein stepwidth is zero, using deltat " << currentDeltat << " instead.");
|
---|
546 | stepwidth = currentDeltat;
|
---|
547 | }
|
---|
548 | Vector PositionUpdate = stepwidth * currentGradient;
|
---|
549 | LOG(3, "DEBUG: Update would be " << stepwidth << "*" << currentGradient << " = " << PositionUpdate);
|
---|
550 |
|
---|
551 | // add PositionUpdate for all nodes in the bondside_set
|
---|
552 | for (BoostGraphHelpers::Nodeset_t::const_iterator setiter = bondside_set[side].begin();
|
---|
553 | setiter != bondside_set[side].end(); ++setiter) {
|
---|
554 | const BreadthFirstSearchGatherer::distance_map_t::const_iterator diter
|
---|
555 | = distance_map[side].find(*setiter);
|
---|
556 | ASSERT( diter != distance_map[side].end(),
|
---|
557 | "ForceAnnealing() - could not find distance to an atom.");
|
---|
558 | const double factor = pow(damping_factor, diter->second+1);
|
---|
559 | LOG(3, "DEBUG: Update for atom #" << *setiter << " will be "
|
---|
560 | << factor << "*" << PositionUpdate);
|
---|
561 | if (GatheredUpdates.count((*setiter))) {
|
---|
562 | GatheredUpdates[(*setiter)] += factor*PositionUpdate;
|
---|
563 | } else {
|
---|
564 | GatheredUpdates.insert(
|
---|
565 | std::make_pair(
|
---|
566 | (*setiter),
|
---|
567 | factor*PositionUpdate) );
|
---|
568 | }
|
---|
569 | }
|
---|
570 | }
|
---|
571 | }
|
---|
572 |
|
---|
573 | for(typename AtomSetMixin<T>::iterator iter = AtomicForceManipulator<T>::atoms.begin();
|
---|
574 | iter != AtomicForceManipulator<T>::atoms.end(); ++iter) {
|
---|
575 | atom &walker = *(*iter);
|
---|
576 | // extract largest components for showing progress of annealing
|
---|
577 | const Vector currentGradient = walker.getAtomicForceAtStep(CurrentTimeStep);
|
---|
578 | for(size_t i=0;i<NDIM;++i)
|
---|
579 | maxComponents[i] = std::max(maxComponents[i], fabs(currentGradient[i]));
|
---|
580 | }
|
---|
581 |
|
---|
582 | // remove center of weight translation from gathered updates
|
---|
583 | Vector CommonTranslation;
|
---|
584 | for (std::map<atomId_t, Vector>::const_iterator iter = GatheredUpdates.begin();
|
---|
585 | iter != GatheredUpdates.end(); ++iter) {
|
---|
586 | const Vector &update = iter->second;
|
---|
587 | CommonTranslation += update;
|
---|
588 | }
|
---|
589 | CommonTranslation *= 1./(double)GatheredUpdates.size();
|
---|
590 | LOG(3, "DEBUG: Subtracting common translation " << CommonTranslation
|
---|
591 | << " from all updates.");
|
---|
592 |
|
---|
593 | // apply the gathered updates and set remnant gradients for atomic annealing
|
---|
594 | for (std::map<atomId_t, Vector>::const_iterator iter = GatheredUpdates.begin();
|
---|
595 | iter != GatheredUpdates.end(); ++iter) {
|
---|
596 | const atomId_t &atomid = iter->first;
|
---|
597 | const Vector &update = iter->second;
|
---|
598 | atom* const walker = World::getInstance().getAtom(AtomById(atomid));
|
---|
599 | ASSERT( walker != NULL,
|
---|
600 | "ForceAnnealing() - walker with id "+toString(atomid)+" has suddenly disappeared.");
|
---|
601 | LOG(3, "DEBUG: Applying update " << update << " to atom #" << atomid
|
---|
602 | << ", namely " << *walker);
|
---|
603 | walker->setPositionAtStep(_TimeStep,
|
---|
604 | walker->getPositionAtStep(CurrentTimeStep) + update - CommonTranslation);
|
---|
605 | // walker->setAtomicForce( RemnantGradient_per_atom[walker->getId()] );
|
---|
606 | }
|
---|
607 |
|
---|
608 | return maxComponents;
|
---|
609 | }
|
---|
610 |
|
---|
611 | /** Reset function to unset static entities and artificial velocities.
|
---|
612 | *
|
---|
613 | */
|
---|
614 | void reset()
|
---|
615 | {
|
---|
616 | currentDeltat = 0.;
|
---|
617 | currentStep = 0;
|
---|
618 | }
|
---|
619 |
|
---|
620 | private:
|
---|
621 | //!> contains the current step in relation to maxsteps
|
---|
622 | static size_t currentStep;
|
---|
623 | //!> contains the maximum number of steps, determines initial and final step with currentStep
|
---|
624 | size_t maxSteps;
|
---|
625 | static double currentDeltat;
|
---|
626 | //!> minimum deltat for internal while loop (adaptive step width)
|
---|
627 | static double MinimumDeltat;
|
---|
628 | //!> contains the maximum bond graph distance up to which shifts of a single atom are spread
|
---|
629 | const int max_distance;
|
---|
630 | //!> the shifted is dampened by this factor with the power of the bond graph distance to the shift causing atom
|
---|
631 | const double damping_factor;
|
---|
632 | };
|
---|
633 |
|
---|
634 | template <class T>
|
---|
635 | double ForceAnnealing<T>::currentDeltat = 0.;
|
---|
636 | template <class T>
|
---|
637 | size_t ForceAnnealing<T>::currentStep = 0;
|
---|
638 | template <class T>
|
---|
639 | double ForceAnnealing<T>::MinimumDeltat = 1e-8;
|
---|
640 |
|
---|
641 | #endif /* FORCEANNEALING_HPP_ */
|
---|