Loading...
Searching...
No Matches
Dimer.cpp
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
12#include "eon/Dimer.h"
14#include "eon/HelperFunctions.h"
15#include "eon/SafeMath.h"
16
17#include <cassert>
18#include <cmath>
19#include <stdexcept>
20#include <thread>
21
22namespace eonc {
23
24namespace {
25
26// A NaN batch force makes torque NaN. Every rotation-exit comparison then
27// fails, including rotations_max, so the loop never returns.
28bool batchForcesFinite(long nAtoms, const double *forces, double energy) {
29 if (forces == nullptr || !std::isfinite(energy)) {
30 return false;
31 }
32 return Eigen::Map<const AtomMatrix>(forces, nAtoms, 3).allFinite();
33}
34
35void rejectNonFiniteBatch(long nAtoms, const double *forces, double energy) {
36 if (!batchForcesFinite(nAtoms, forces, energy)) {
37 throw std::runtime_error("Dimer::calcRotationalForceReturnCurvature: "
38 "non-finite batch forces");
39 }
40}
41
42double atanRatioOrHalfPi(double num, double denom) {
43 if (!std::isfinite(num) || !std::isfinite(denom)) {
44 return 0.0;
45 }
46 if (std::abs(denom) < eonc::safemath::eps) {
47 if (std::abs(num) < eonc::safemath::eps) {
48 return 0.0;
49 }
50 return std::copysign(eonc::helpers::pi * 0.5, num);
51 }
52 return std::atan(num / denom);
53}
54
55} // namespace
56
57Dimer::Dimer(std::shared_ptr<Matter> matter, const Parameters &params,
58 std::shared_ptr<Potential> pot)
60 // Give matterDimer its own potential for parallel force evaluation
61 auto dimerPot =
62 (pot->needsPerImageInstance() && params.main_options().parallel)
64 : pot;
65 matterCenter = std::make_shared<Matter>(pot, params);
66 matterDimer = std::make_shared<Matter>(dimerPot, params);
67 *matterCenter = *matter;
68 *matterDimer = *matter;
69 nAtoms = matter->numberOfAtoms();
70
71 direction.resize(nAtoms, 3);
72 rotationalPlane.resize(nAtoms, 3);
73 direction.setZero();
74 rotationalPlane.setZero();
76}
77
78void Dimer::compute(std::shared_ptr<Matter> matter,
79 AtomMatrix initialDirection) {
80 *matterCenter = *matter;
81
82 eonc::safemath::safe_normalize_inplace(initialDirection);
83 direction = initialDirection;
84
85 // Optional: LOR / Lanczos / Davidson (enum dispatch; classical falls
86 // through).
87 if (auto alt = runAlternativeRotation(params.dimer_options().rotation_backend,
88 matter, params, pot, direction,
89 static_cast<quill::Logger *>(log))) {
90 eigenvalue = alt->eigenvalue;
91 direction = alt->eigenvector;
92 totalForceCalls += alt->forceCalls;
93 statsRotations = alt->rotations;
94 eonc::safemath::safe_normalize_inplace(direction);
95 for (long i = 0; i < nAtoms; ++i) {
96 if (matterCenter->getFixed(i)) {
97 direction.row(i).setZero();
98 }
99 }
100 *matterCenter = *matter;
101 return;
102 }
103
104 long rotations = 0;
105 long forceCallsCenter = matterCenter->getForceCalls();
106 long forceCallsDimer = matterDimer->getForceCalls();
107 double curvature = 0.0;
108 double rotationAngle = 0.0;
109 double torque = 0.0;
110
111 AtomMatrix rotationalForce(nAtoms, 3);
112 AtomMatrix rotationalForceOld(nAtoms, 3);
113 AtomMatrix rotationalPlaneOld(nAtoms, 3);
114 rotationalForce.setZero();
115 rotationalForceOld.setZero();
116 rotationalPlaneOld.setZero();
117
118 statsAngle = 0;
119 double lengthRotationalForceOld = 0.0;
120
121 // Two force calls per rotation iteration
122 bool doneRotating = false;
123 while (!doneRotating) {
124 curvature = calcRotationalForceReturnCurvature(rotationalForce);
125
126 determineRotationalPlane(rotationalForce, rotationalForceOld,
127 rotationalPlaneOld, lengthRotationalForceOld);
128
129 torque = rotationalForce.norm();
130 // torque == 0 is a valid aligned dimer; isnormal(0) is false.
131 assert(std::isfinite(torque));
132
133 // Convergence: stop if torque is below threshold or max rotations reached
134 if ((torque > params.dimer_options().torque_max &&
135 rotations >= params.dimer_options().rotations_max) ||
136 (torque < params.dimer_options().torque_max &&
137 torque >= params.dimer_options().torque_min &&
138 rotations >= params.dimer_options().rotations_min) ||
139 (torque < params.dimer_options().torque_min)) {
140 doneRotating = true;
141 }
142
143 // A probe after acceptance would return rotation_angle off the
144 // direction whose curvature was just measured.
145 if (!doneRotating) {
146 double rotForce1 = matDot(rotationalForce, rotationalPlane);
147 rotate(params.dimer_options().rotation_angle);
148
149 curvature = calcRotationalForceReturnCurvature(rotationalForce);
150 double rotForce2 = matDot(rotationalForce, rotationalPlane);
151
152 double rotForceChange =
153 (rotForce1 - rotForce2) / params.dimer_options().rotation_angle;
154 double forceDimer = (rotForce1 + rotForce2) / 2.0;
155
156 rotationAngle =
157 atanRatioOrHalfPi(2.0 * forceDimer, rotForceChange) / 2.0 -
158 params.dimer_options().rotation_angle / 2.0;
159
160 if (rotForceChange < 0) {
161 rotationAngle += eonc::helpers::pi / 2.0;
162 }
163
164 rotate(rotationAngle);
165 rotationalPlaneOld = rotationalPlane;
166 rotations++;
167 }
168 QUILL_LOG_DEBUG(log,
169 "[DimerRot] ----- --------- ---------------- "
170 "--------- {:9.3e} {:9.3e} {:9.3e} ---------\n",
171 curvature, torque,
172 rotationAngle * (180.0 / eonc::helpers::pi));
173 }
174
175 statsTorque = torque;
176 statsCurvature = curvature;
177 eonc::safemath::safe_normalize_inplace(direction);
178 for (long i = 0; i < nAtoms; ++i) {
179 if (matterCenter->getFixed(i)) {
180 direction.row(i).setZero();
181 }
182 }
184 statsAngle *= (180.0 / eonc::helpers::pi);
185 statsRotations = rotations;
186 eigenvalue = curvature;
187
188 forceCallsCenter = matterCenter->getForceCalls() - forceCallsCenter;
189 forceCallsDimer = matterDimer->getForceCalls() - forceCallsDimer;
190 totalForceCalls += forceCallsCenter + forceCallsDimer;
191}
192
194
196
198 AtomMatrix posCenter = matterCenter->getPositions();
199
200 // Displace to get dimer configuration A
201 AtomMatrix posDimer =
202 posCenter + direction * params.main_options().finiteDifference;
203
204 // Optional rotation removal (Melander, Laasonen, Jonsson, JCTC 2015)
205 if (params.dimer_options().remove_rotation) {
206 matterDimer->setPositions(posDimer);
208 posDimer = matterDimer->getPositions();
209 direction = matterCenter->pbc(posDimer - posCenter);
210 eonc::safemath::safe_normalize_inplace(direction);
211 posDimer = posCenter + direction * params.main_options().finiteDifference;
212 }
213
214 // Obtain forces for dimer and center
215 matterDimer->setPositions(posDimer);
216 AtomMatrix forceA, forceCenter;
217 if (pot->supportsBatchEvaluation()) {
218 // Only batch systems that actually need recomputation.
219 bool centerDirty = matterCenter->needsForceUpdate();
220 bool dimerDirty = matterDimer->needsForceUpdate();
221
222 if (centerDirty && dimerDirty) {
223 // Both need eval -- batch together
224 auto nrs0 = matterCenter->getAtomicNrs();
225 auto nrs1 = matterDimer->getAtomicNrs();
226 auto box0 = matterCenter->getCell();
227 auto box1 = matterDimer->getCell();
228 const double *posVec[] = {matterCenter->getPositions().data(),
229 posDimer.data()};
230 const int *nrsVec[] = {nrs0.data(), nrs1.data()};
231 double *frcVec[] = {matterCenter->forcesData(),
232 matterDimer->forcesData()};
233 double energies[2], vars[2];
234 const double *boxVec[] = {box0.data(), box1.data()};
235 pot->forceBatch(2, nAtoms, posVec, nrsVec, frcVec, energies, vars,
236 boxVec);
237 rejectNonFiniteBatch(nAtoms, frcVec[0], energies[0]);
238 rejectNonFiniteBatch(nAtoms, frcVec[1], energies[1]);
239 matterCenter->setComputedPotential(energies[0], vars[0]);
240 matterDimer->setComputedPotential(energies[1], vars[1]);
241 } else if (dimerDirty) {
242 // Only dimer moved -- eval just dimer, center is cached
243 auto nrs = matterDimer->getAtomicNrs();
244 auto box = matterDimer->getCell();
245 const double *posVec[] = {posDimer.data()};
246 const int *nrsVec[] = {nrs.data()};
247 double *frcVec[] = {matterDimer->forcesData()};
248 double energies[1], vars[1];
249 const double *boxVec[] = {box.data()};
250 pot->forceBatch(1, nAtoms, posVec, nrsVec, frcVec, energies, vars,
251 boxVec);
252 rejectNonFiniteBatch(nAtoms, frcVec[0], energies[0]);
253 matterDimer->setComputedPotential(energies[0], vars[0]);
254 } else if (centerDirty) {
255 // Only center moved (rare)
256 matterCenter->getForces(); // through computePotential
257 }
258 // else: both cached, nothing to do
259 forceCenter = matterCenter->getForces();
260 forceA = matterDimer->getForces();
261 } else {
262 forceA = matterDimer->getForces();
263 forceCenter = matterCenter->getForces();
264 }
265 AtomMatrix forceB = 2.0 * forceCenter - forceA;
266
267 double projA = matDot(direction, forceA);
268 double projB = matDot(direction, forceB);
269
270 // Remove force component parallel to dimer
271 forceA = helpers::makeOrthogonal(forceA, direction);
272 forceB = helpers::makeOrthogonal(forceB, direction);
273
274 // Rotational force = orthogonal force difference
275 rotationalForce =
276 (forceA - forceB) / (2.0 * params.main_options().finiteDifference);
277
278 // Curvature along the dimer
279 return (projB - projA) / (2.0 * params.main_options().finiteDifference);
280}
281
282void Dimer::determineRotationalPlane(const AtomMatrix &rotationalForce,
283 AtomMatrix &rotationalForceOld,
284 const AtomMatrix &rotationalPlaneOld,
285 double &lengthRotationalForceOld) {
286 double gamma = 0.0;
287 double a = std::abs(matDot(rotationalForce, rotationalForceOld));
288 double b = rotationalForceOld.squaredNorm();
289 if (a < 0.5 * b) {
290 // Polak-Ribiere conjugate gradient direction
291 gamma = (rotationalForce.array() *
292 (rotationalForce - rotationalForceOld).array())
293 .sum() /
294 b;
295 }
296
297 // New rotational plane from current force and previous plane
299 rotationalForce + rotationalPlaneOld * lengthRotationalForceOld * gamma;
300
301 // Orthogonalize to dimer direction and normalize
302 lengthRotationalForceOld = rotationalPlane.norm();
304 eonc::safemath::safe_normalize_inplace(rotationalPlane);
305
306 rotationalForceOld = rotationalForce;
307}
308
309void Dimer::rotate(double rotationAngle) {
310 statsAngle += rotationAngle;
311
312 double cosA = std::cos(rotationAngle);
313 double sinA = std::sin(rotationAngle);
314
315 AtomMatrix newDirection = direction * cosA + rotationalPlane * sinA;
316 AtomMatrix newPlane = rotationalPlane * cosA - direction * sinA;
317 direction = std::move(newDirection);
318 rotationalPlane = std::move(newPlane);
319
320 eonc::safemath::safe_normalize_inplace(direction);
321 eonc::safemath::safe_normalize_inplace(rotationalPlane);
322
323 // Remove component from rotationalPlane parallel to direction
325 eonc::safemath::safe_normalize_inplace(rotationalPlane);
326}
327
328} // namespace eonc
double matDot(const AtomMatrix &a, const AtomMatrix &b)
SIMD-optimized dot product for contiguous Eigen matrices.
Definition Eigen.h:50
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
AtomMatrix direction
Definition Dimer.h:37
AtomMatrix rotationalPlane
Definition Dimer.h:38
std::shared_ptr< Matter > matterDimer
Definition Dimer.h:36
long nAtoms
Definition Dimer.h:40
double getEigenvalue() override
Definition Dimer.cpp:193
AtomMatrix getEigenvector() override
Definition Dimer.cpp:195
std::shared_ptr< Matter > matterCenter
Definition Dimer.h:35
void determineRotationalPlane(const AtomMatrix &rotationalForce, AtomMatrix &rotationalForceOld, const AtomMatrix &rotationalPlaneOld, double &lengthRotationalForceOld)
Determine rotational plane via conjugate gradient.
Definition Dimer.cpp:282
double eigenvalue
Definition Dimer.h:39
double calcRotationalForceReturnCurvature(AtomMatrix &rotationalForce)
Compute rotational force and return curvature along the dimer.
Definition Dimer.cpp:197
void rotate(double rotationAngle)
Rotate the dimer by the given angle (radians).
Definition Dimer.cpp:309
eonc::log::FileScoped log
Definition Dimer.h:34
void compute(std::shared_ptr< Matter > matter, AtomMatrix initialDirection) override
Definition Dimer.cpp:78
Dimer(std::shared_ptr< Matter > matter, const Parameters &params, std::shared_ptr< Potential > pot)
Definition Dimer.cpp:57
const Parameters & params
std::shared_ptr< Potential > pot
LowestEigenmode(std::shared_ptr< Potential > potPassed, const Parameters &parameters)
void rotationRemove(const AtomMatrix r1, std::shared_ptr< Matter > m2)
std::shared_ptr< Potential > makeImagePotential(const Potential &pot, const Parameters &params)
A separate instance of pot for one image of a band, dimer or pair of minimizations: a clone when the ...
constexpr double pi
AtomMatrix makeOrthogonal(const AtomMatrix v1, const AtomMatrix v2)
double safe_acos(double x)
Definition SafeMath.h:34
constexpr double eps
Definition SafeMath.h:19
RAII resource manager for the ARTn C library with global synchronization.
std::optional< DimerRotationResult > runAlternativeRotation(DimerRotationBackend backend, const std::shared_ptr< Matter > &matter, const Parameters &params, const std::shared_ptr< Potential > &pot, const AtomMatrix &initialDirection, quill::Logger *log=nullptr)
Run Lanczos, Davidson, or LOR.