source: src/Dynamics/ForceAnnealing.hpp@ ccbdf4

ForceAnnealing_with_BondGraph_continued
Last change on this file since ccbdf4 was ccbdf4, checked in by Frederik Heber <frederik.heber@…>, 8 years ago

tempcommit: BondVectors::getRemnant...() now requires atom's gradient.

  • Property mode set to 100644
File size: 22.4 KB
Line 
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 */
56template <class T>
57class ForceAnnealing : public AtomicForceManipulator<T>
58{
59public:
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 CurrentTimeStep 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 _CurrentTimeStep,
100 const size_t _offset,
101 const bool _UseBondgraph)
102 {
103 // make sum of forces equal zero
104 AtomicForceManipulator<T>::correctForceMatrixForFixedCenterOfMass(_offset, _CurrentTimeStep);
105
106 // are we in initial step? Then set static entities
107 Vector maxComponents(zeroVec);
108 if (currentStep == 0) {
109 currentDeltat = AtomicForceManipulator<T>::Deltat;
110 currentStep = 1;
111 LOG(2, "DEBUG: Initial step, setting values, current step is #" << currentStep);
112
113 // always use atomic annealing on first step
114 anneal(_CurrentTimeStep, _offset, maxComponents);
115 } else {
116 ++currentStep;
117 LOG(2, "DEBUG: current step is #" << currentStep);
118
119 // bond graph annealing is always followed by a normal annealing
120 if (_UseBondgraph)
121 annealWithBondGraph(_CurrentTimeStep, _offset, maxComponents);
122 anneal(_CurrentTimeStep, _offset, maxComponents);
123 }
124
125 LOG(1, "STATUS: Largest remaining force components at step #"
126 << currentStep << " are " << maxComponents);
127
128 // are we in final step? Remember to reset static entities
129 if (currentStep == maxSteps) {
130 LOG(2, "DEBUG: Final step, resetting values");
131 reset();
132 }
133 }
134
135 /** Performs Gradient optimization on the atoms.
136 *
137 * We assume that forces have just been calculated.
138 *
139 * \param CurrentTimeStep current time step (i.e. \f$ t + \Delta t \f$ in the sense of the velocity verlet)
140 * \param offset offset in matrix file to the first force component
141 * \param maxComponents to be filled with maximum force component over all atoms
142 */
143 void anneal(
144 const int CurrentTimeStep,
145 const size_t offset,
146 Vector &maxComponents)
147 {
148 bool deltat_decreased = false;
149 for(typename AtomSetMixin<T>::iterator iter = AtomicForceManipulator<T>::atoms.begin();
150 iter != AtomicForceManipulator<T>::atoms.end(); ++iter) {
151 // atom's force vector gives steepest descent direction
152 const Vector oldPosition = (*iter)->getPositionAtStep(CurrentTimeStep-2 >= 0 ? CurrentTimeStep - 2 : 0);
153 const Vector currentPosition = (*iter)->getPosition();
154 const Vector oldGradient = (*iter)->getAtomicForceAtStep(CurrentTimeStep-2 >= 0 ? CurrentTimeStep - 2 : 0);
155 const Vector currentGradient = (*iter)->getAtomicForce();
156 LOG(4, "DEBUG: oldPosition for atom " << **iter << " is " << oldPosition);
157 LOG(4, "DEBUG: currentPosition for atom " << **iter << " is " << currentPosition);
158 LOG(4, "DEBUG: oldGradient for atom " << **iter << " is " << oldGradient);
159 LOG(4, "DEBUG: currentGradient for atom " << **iter << " is " << currentGradient);
160// LOG(4, "DEBUG: Force for atom " << **iter << " is " << currentGradient);
161
162 // we use Barzilai-Borwein update with position reversed to get descent
163 const Vector PositionDifference = currentPosition - oldPosition;
164 const Vector GradientDifference = (currentGradient - oldGradient);
165 double stepwidth = 0.;
166 if (GradientDifference.Norm() > MYEPSILON)
167 stepwidth = fabs(PositionDifference.ScalarProduct(GradientDifference))/
168 GradientDifference.NormSquared();
169 if (fabs(stepwidth) < 1e-10) {
170 // dont' warn in first step, deltat usage normal
171 if (currentStep != 1)
172 ELOG(1, "INFO: Barzilai-Borwein stepwidth is zero, using deltat " << currentDeltat << " instead.");
173 stepwidth = currentDeltat;
174 }
175 Vector PositionUpdate = stepwidth * currentGradient;
176 LOG(3, "DEBUG: Update would be " << stepwidth << "*" << currentGradient << " = " << PositionUpdate);
177
178 // extract largest components for showing progress of annealing
179 for(size_t i=0;i<NDIM;++i)
180 if (currentGradient[i] > maxComponents[i])
181 maxComponents[i] = currentGradient[i];
182
183 // steps may go back and forth again (updates are of same magnitude but
184 // have different sign: Check whether this is the case and one step with
185 // deltat to interrupt this sequence
186 if ((currentStep > 1) && (!PositionDifference.IsZero()))
187 if ((PositionUpdate.ScalarProduct(PositionDifference) < 0)
188 && (fabs(PositionUpdate.NormSquared()-PositionDifference.NormSquared()) < 1e-3)) {
189 // for convergence we want a null sequence here, too
190 if (!deltat_decreased) {
191 deltat_decreased = true;
192 currentDeltat = .5*currentDeltat;
193 }
194 LOG(2, "DEBUG: Upgrade in other direction: " << PositionUpdate
195 << " > " << PositionDifference
196 << ", using deltat: " << currentDeltat);
197 PositionUpdate = currentDeltat * currentGradient;
198 }
199
200 // finally set new values
201 (*iter)->setPosition(currentPosition + PositionUpdate);
202 }
203 }
204
205 // knowing the number of bonds in total, we can setup the storage for the
206 // projected forces
207 enum whichatom_t {
208 leftside=0,
209 rightside=1,
210 MAX_sides
211 };
212
213 /** Helper function to put bond force into a container.
214 *
215 * \param _walker atom
216 * \param _current_bond current bond of \a _walker
217 * \param _timestep time step
218 * \param _force calculated bond force
219 * \param _bv bondvectors for obtaining the correct index
220 * \param _projected_forces container
221 */
222 static void ForceStore(
223 const atom &_walker,
224 const bond::ptr &_current_bond,
225 const size_t &_timestep,
226 const double _force,
227 const BondVectors &_bv,
228 std::vector< // time step
229 std::vector< // which bond side
230 std::vector<double> > // over all bonds
231 > &_projected_forces)
232 {
233 std::vector<double> &forcelist = (&_walker == _current_bond->leftatom) ?
234 _projected_forces[_timestep][leftside] : _projected_forces[_timestep][rightside];
235 const size_t index = _bv.getIndexForBond(_current_bond);
236 ASSERT( index != (size_t)-1,
237 "ForceAnnealing() - could not find bond "+toString(*_current_bond)
238 +" in bondvectors");
239 forcelist[index] = _force;
240 }
241
242 /** Performs Gradient optimization on the bonds.
243 *
244 * We assume that forces have just been calculated. These forces are projected
245 * onto the bonds and these are annealed subsequently by moving atoms in the
246 * bond neighborhood on either side conjunctively.
247 *
248 *
249 * \param CurrentTimeStep current time step (i.e. \f$ t + \Delta t \f$ in the sense of the velocity verlet)
250 * \param offset offset in matrix file to the first force component
251 * \param maxComponents to be filled with maximum force component over all atoms
252 */
253 void annealWithBondGraph(
254 const int CurrentTimeStep,
255 const size_t offset,
256 Vector &maxComponents)
257 {
258 // get nodes on either side of selected bond via BFS discovery
259 BoostGraphCreator BGcreator;
260 BGcreator.createFromRange(
261 AtomicForceManipulator<T>::atoms.begin(),
262 AtomicForceManipulator<T>::atoms.end(),
263 AtomicForceManipulator<T>::atoms.size(),
264 BreadthFirstSearchGatherer::AlwaysTruePredicate);
265 BreadthFirstSearchGatherer NodeGatherer(BGcreator);
266
267 /// We assume that a force is local, i.e. a bond is too short yet and hence
268 /// the atom needs to be moved. However, all the adjacent (bound) atoms might
269 /// already be at the perfect distance. If we just move the atom alone, we ruin
270 /// all the other bonds. Hence, it would be sensible to move every atom found
271 /// through the bond graph in the direction of the force as well by the same
272 /// PositionUpdate. This is almost what we are going to do.
273
274 /// One issue is: If we need to shorten bond, then we use the PositionUpdate
275 /// also on the the other bond partner already. This is because it is in the
276 /// direction of the bond. Therefore, the update is actually performed twice on
277 /// each bond partner, i.e. the step size is twice as large as it should be.
278 /// This problem only occurs when bonds need to be shortened, not when they
279 /// need to be made longer (then the force vector is facing the other
280 /// direction than the bond vector).
281 /// As a remedy we need to average the force on either end of the bond and
282 /// check whether each gradient points inwards out or outwards with respect
283 /// to the bond and then shift accordingly.
284
285 /// One more issue is that the projection onto the bond directions does not
286 /// recover the gradient but may be larger as the bond directions are a
287 /// generating system and not a basis (e.g. 3 bonds on a plane where 2 would
288 /// suffice to span the plane). To this end, we need to account for the
289 /// overestimation and obtain a weighting for each bond.
290
291 // initialize helper class for bond vectors using bonds from range of atoms
292 BondVectors bv;
293 bv.setFromAtomRange< T >(
294 AtomicForceManipulator<T>::atoms.begin(),
295 AtomicForceManipulator<T>::atoms.end(),
296 currentStep);
297 const BondVectors::container_t &sorted_bonds = bv.getSorted();
298
299 std::vector< // time step
300 std::vector< // which bond side
301 std::vector<double> > // over all bonds
302 > projected_forces(2); // one for leftatoms, one for rightatoms (and for both time steps)
303 for (size_t i=0;i<2;++i) {
304 projected_forces[i].resize(MAX_sides);
305 for (size_t j=0;j<MAX_sides;++j)
306 projected_forces[i][j].resize(sorted_bonds.size(), 0.);
307 }
308
309 // for each atom we need to gather weights and then project the gradient
310 typedef std::map<atomId_t, BondVectors::weights_t > weights_per_atom_t;
311 std::vector<weights_per_atom_t> weights_per_atom(2);
312 typedef std::map<atomId_t, Vector> RemnantGradient_per_atom_t;
313 RemnantGradient_per_atom_t RemnantGradient_per_atom;
314 for (size_t timestep = 0; timestep <= 1; ++timestep) {
315 // TODO: We have this extra step in between because of DoOutput copying
316 // change this making the code easier to understand
317 const size_t CurrentStep = CurrentTimeStep-2*timestep >= 0 ? CurrentTimeStep - 2*timestep : 0;
318
319 for(typename AtomSetMixin<T>::const_iterator iter = AtomicForceManipulator<T>::atoms.begin();
320 iter != AtomicForceManipulator<T>::atoms.end(); ++iter) {
321 const atom &walker = *(*iter);
322 const Vector &walkerGradient = walker.getAtomicForceAtStep(CurrentStep);
323 LOG(3, "DEBUG: Gradient of atom #" << walker.getId() << ", namely "
324 << walker << " is " << walkerGradient);
325
326 const BondList& ListOfBonds = walker.getListOfBonds();
327 if (walkerGradient.Norm() > MYEPSILON) {
328
329 // gather subset of BondVectors for the current atom
330 const std::vector<Vector> BondVectors =
331 bv.getAtomsBondVectorsAtStep(walker, CurrentStep);
332
333 // go through all its bonds and calculate what magnitude is represented
334 // by the others i.e. sum of scalar products against other bonds
335 const std::pair<weights_per_atom_t::iterator, bool> inserter =
336 weights_per_atom[timestep].insert(
337 std::make_pair(walker.getId(),
338 bv.getWeightsForAtomAtStep(walker, BondVectors, CurrentStep)) );
339 ASSERT( inserter.second,
340 "ForceAnnealing::operator() - weight map for atom "+toString(walker)
341 +" and time step "+toString(timestep)+" already filled?");
342 BondVectors::weights_t &weights = inserter.first->second;
343 ASSERT( weights.size() == ListOfBonds.size(),
344 "ForceAnnealing::operator() - number of weights "
345 +toString(weights.size())+" does not match number of bonds "
346 +toString(ListOfBonds.size())+", error in calculation?");
347
348 // projected gradient over all bonds and place in one of projected_forces
349 // using the obtained weights
350 BondVectors::forcestore_t forcestoring =
351 boost::bind(&ForceAnnealing::ForceStore, _1, _2, _3, _4,
352 boost::cref(bv), boost::ref(projected_forces));
353 const Vector RemnantGradient = bv.getRemnantGradientForAtomAtStep(
354 walker, walkerGradient, BondVectors, weights, timestep, forcestoring
355 );
356 RemnantGradient_per_atom.insert( std::make_pair(walker.getId(), RemnantGradient) );
357 } else {
358 LOG(2, "DEBUG: Gradient is " << walkerGradient << " less than "
359 << MYEPSILON << " for atom " << walker);
360 // note that projected_forces is initialized to full length and filled
361 // with zeros. Hence, nothing to do here
362 }
363 }
364 }
365
366 // step through each bond and shift the atoms
367 std::map<atomId_t, Vector> GatheredUpdates; //!< gathers all updates which are applied at the end
368
369 LOG(3, "DEBUG: current step is " << currentStep << ", given time step is " << CurrentTimeStep);
370 const BondVectors::mapped_t bondvectors = bv.getBondVectorsAtStep(currentStep);
371
372 for (BondVectors::container_t::const_iterator bondsiter = sorted_bonds.begin();
373 bondsiter != sorted_bonds.end(); ++bondsiter) {
374 const bond::ptr &current_bond = *bondsiter;
375 const size_t index = bv.getIndexForBond(current_bond);
376 const atom* bondatom[MAX_sides] = {
377 current_bond->leftatom,
378 current_bond->rightatom
379 };
380
381 // remove the edge
382#ifndef NDEBUG
383 const bool status =
384#endif
385 BGcreator.removeEdge(bondatom[leftside]->getId(), bondatom[rightside]->getId());
386 ASSERT( status, "ForceAnnealing() - edge to found bond is not present?");
387
388 // gather nodes for either atom
389 BoostGraphHelpers::Nodeset_t bondside_set[MAX_sides];
390 BreadthFirstSearchGatherer::distance_map_t distance_map[MAX_sides];
391 for (size_t side=leftside;side<MAX_sides;++side) {
392 bondside_set[side] = NodeGatherer(bondatom[side]->getId(), max_distance);
393 distance_map[side] = NodeGatherer.getDistances();
394 std::sort(bondside_set[side].begin(), bondside_set[side].end());
395 }
396
397 // re-add edge
398 BGcreator.addEdge(bondatom[leftside]->getId(), bondatom[rightside]->getId());
399
400 // do for both leftatom and rightatom of bond
401 for (size_t side = leftside; side < MAX_sides; ++side) {
402 const double &bondforce = projected_forces[0][side][index];
403 const double &oldbondforce = projected_forces[1][side][index];
404 const double bondforcedifference = fabs(bondforce - oldbondforce);
405 LOG(4, "DEBUG: bondforce for " << (side == leftside ? "left" : "right")
406 << " side of bond is " << bondforce);
407 LOG(4, "DEBUG: oldbondforce for " << (side == leftside ? "left" : "right")
408 << " side of bond is " << oldbondforce);
409 // if difference or bondforce itself is zero, do nothing
410 if ((fabs(bondforce) < MYEPSILON) || (fabs(bondforcedifference) < MYEPSILON))
411 continue;
412
413 // get BondVector to bond
414 const BondVectors::mapped_t::const_iterator bviter =
415 bondvectors.find(current_bond);
416 ASSERT( bviter != bondvectors.end(),
417 "ForceAnnealing() - cannot find current_bond ?");
418 ASSERT( fabs(bviter->second.Norm() -1.) < MYEPSILON,
419 "ForceAnnealing() - norm of BondVector is not one");
420 const Vector &BondVector = bviter->second;
421
422 // calculate gradient and position differences for stepwidth
423 const Vector currentGradient = bondforce * BondVector;
424 LOG(4, "DEBUG: current projected gradient for "
425 << (side == leftside ? "left" : "right") << " side of bond is " << currentGradient);
426 const Vector &oldPosition = bondatom[side]->getPositionAtStep(CurrentTimeStep-2 >= 0 ? CurrentTimeStep - 2 : 0);
427 const Vector &currentPosition = bondatom[side]->getPositionAtStep(currentStep);
428 const Vector PositionDifference = currentPosition - oldPosition;
429 LOG(4, "DEBUG: old position is " << oldPosition);
430 LOG(4, "DEBUG: current position is " << currentPosition);
431 LOG(4, "DEBUG: difference in position is " << PositionDifference);
432 LOG(4, "DEBUG: abs. difference in forces is " << bondforcedifference);
433 LOG(4, "DEBUG: bondvector is " << BondVector);
434
435 // calculate step width
436 double stepwidth =
437 fabs(PositionDifference.ScalarProduct(BondVector))/bondforcedifference;
438 if (fabs(stepwidth) < 1e-10) {
439 // dont' warn in first step, deltat usage normal
440 if (currentStep != 1)
441 ELOG(1, "INFO: Barzilai-Borwein stepwidth is zero, using deltat " << currentDeltat << " instead.");
442 stepwidth = currentDeltat;
443 }
444 Vector PositionUpdate = stepwidth * currentGradient;
445 LOG(3, "DEBUG: Update would be " << stepwidth << "*" << currentGradient << " = " << PositionUpdate);
446
447 // add PositionUpdate for all nodes in the bondside_set
448 for (BoostGraphHelpers::Nodeset_t::const_iterator setiter = bondside_set[side].begin();
449 setiter != bondside_set[side].end(); ++setiter) {
450 const BreadthFirstSearchGatherer::distance_map_t::const_iterator diter
451 = distance_map[side].find(*setiter);
452 ASSERT( diter != distance_map[side].end(),
453 "ForceAnnealing() - could not find distance to an atom.");
454 const double factor = pow(damping_factor, diter->second+1);
455 LOG(3, "DEBUG: Update for atom #" << *setiter << " will be "
456 << factor << "*" << PositionUpdate);
457 if (GatheredUpdates.count((*setiter))) {
458 GatheredUpdates[(*setiter)] += factor*PositionUpdate;
459 } else {
460 GatheredUpdates.insert(
461 std::make_pair(
462 (*setiter),
463 factor*PositionUpdate) );
464 }
465 }
466 }
467 }
468
469 for(typename AtomSetMixin<T>::iterator iter = AtomicForceManipulator<T>::atoms.begin();
470 iter != AtomicForceManipulator<T>::atoms.end(); ++iter) {
471 atom &walker = *(*iter);
472 // extract largest components for showing progress of annealing
473 const Vector currentGradient = walker.getAtomicForce();
474 for(size_t i=0;i<NDIM;++i)
475 if (currentGradient[i] > maxComponents[i])
476 maxComponents[i] = currentGradient[i];
477 }
478
479 // apply the gathered updates and set remnant gradients for atomic annealing
480 for (std::map<atomId_t, Vector>::const_iterator iter = GatheredUpdates.begin();
481 iter != GatheredUpdates.end(); ++iter) {
482 const atomId_t &atomid = iter->first;
483 const Vector &update = iter->second;
484 atom* const walker = World::getInstance().getAtom(AtomById(atomid));
485 ASSERT( walker != NULL,
486 "ForceAnnealing() - walker with id "+toString(atomid)+" has suddenly disappeared.");
487 LOG(3, "DEBUG: Applying update " << update << " to atom #" << atomid
488 << ", namely " << *walker);
489 walker->setPosition( walker->getPosition() + update );
490 walker->setAtomicForce( RemnantGradient_per_atom[walker->getId()] );
491 }
492 }
493
494 /** Reset function to unset static entities and artificial velocities.
495 *
496 */
497 void reset()
498 {
499 currentDeltat = 0.;
500 currentStep = 0;
501 }
502
503private:
504 //!> contains the current step in relation to maxsteps
505 static size_t currentStep;
506 //!> contains the maximum number of steps, determines initial and final step with currentStep
507 size_t maxSteps;
508 static double currentDeltat;
509 //!> minimum deltat for internal while loop (adaptive step width)
510 static double MinimumDeltat;
511 //!> contains the maximum bond graph distance up to which shifts of a single atom are spread
512 const int max_distance;
513 //!> the shifted is dampened by this factor with the power of the bond graph distance to the shift causing atom
514 const double damping_factor;
515};
516
517template <class T>
518double ForceAnnealing<T>::currentDeltat = 0.;
519template <class T>
520size_t ForceAnnealing<T>::currentStep = 0;
521template <class T>
522double ForceAnnealing<T>::MinimumDeltat = 1e-8;
523
524#endif /* FORCEANNEALING_HPP_ */
Note: See TracBrowser for help on using the repository browser.