source: src/Dynamics/ForceAnnealing.hpp@ 77d0cd

AutomationFragmentation_failures Candidate_v1.6.1 ChemicalSpaceEvaluator Exclude_Hydrogens_annealWithBondGraph ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_contraction-expansion Gui_displays_atomic_force_velocity PythonUI_with_named_parameters StoppableMakroAction TremoloParser_IncreasedPrecision
Last change on this file since 77d0cd was 77d0cd, checked in by Frederik Heber <frederik.heber@…>, 7 years ago

ForceAnnealing now uses BondVectors to optimize the structure from the perspective of the bond.

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