Loading...
Searching...
No Matches
ImprovedDimer.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// An implementation of Johannes Kaestner and Paul Sherwood's improved dimer.
13// An attempt to keep to the variable names in their 2008 paper has been made.
14
15#include "eon/ImprovedDimer.h"
17#include "eon/HelperFunctions.h"
18#include "eon/LowestEigenmode.h"
19#include "eon/PotCapabilities.h"
20#include "eon/SafeMath.h"
21#include "eon/eonExceptions.hpp"
22
23#include <cmath>
24#include <exception>
25#include <thread>
26
27#include "eon/EonLogger.h"
28
29namespace {
30
31double atanRatioOrHalfPi(double num, double denom) {
32 if (!std::isfinite(num) || !std::isfinite(denom)) {
33 return 0.0;
34 }
35 if (std::abs(denom) < eonc::safemath::eps) {
36 if (std::abs(num) < eonc::safemath::eps) {
37 return 0.0;
38 }
39 return std::copysign(eonc::helpers::pi * 0.5, num);
40 }
41 return std::atan(num / denom);
42}
43
44} // namespace
45
46namespace eonc {
47
48ImprovedDimer::ImprovedDimer(std::shared_ptr<Matter> matter,
49 const Parameters &params,
50 std::shared_ptr<Potential> pot)
52 // Each dimer image gets its own potential for lock-free parallel evaluation.
53 std::shared_ptr<Potential> x1Pot = pot;
54 if (pot->needsPerImageInstance() && params.main_options().parallel) {
55 x1Pot = eonc::helpers::makeImagePotential(*pot, params);
56 }
57 x0 = std::make_shared<Matter>(pot, params);
58 x1 = std::make_shared<Matter>(x1Pot, params);
59 // Matter's copy assignment copies the potential too; keep x1's own
60 // instance so the two images can be evaluated at the same time.
61 *x0 = *matter;
62 *x1 = *matter;
63 x1->setPotential(x1Pot);
64 tau.resize(3 * matter->numberOfAtoms());
65 tau.setZero();
67
68 if (params.dimer_options().opt_method == OptType::CG) {
69 init_cg = true;
70 }
71}
72
73void ImprovedDimer::setReferenceMode(const VectorXd &ref) {
75 if (fixedReferenceMode.norm() > 1e-10) {
76 eonc::safemath::safe_normalize_inplace(fixedReferenceMode);
77 }
78 hasFixedReference = true;
79}
80
82
84 const AtomMatrix &direction) const {
85 VectorXd t =
86 VectorXd::Map(direction.data(), 3 * matter.numberOfAtoms()).array() *
87 matter.getFreeV().array();
88 if (t.norm() > 1e-10) {
89 eonc::safemath::safe_normalize_inplace(t);
90 } else {
91 t.resize(0);
92 }
93 return t;
94}
95
96void ImprovedDimer::evaluateWithProbe(const std::shared_ptr<Matter> &matter,
97 const AtomMatrix &direction) {
98 forward_.reset();
99 if (!matter->needsForceUpdate() || !pot->supportsBatchEvaluation() ||
100 usesAlternativeRotation(params.dimer_options().rotation_backend) ||
101 params.dimer_options().remove_rotation) {
102 return;
103 }
104 const VectorXd t = dimerDirection(*matter, direction);
105 if (t.size() == 0) {
106 return;
107 }
108 // The same expression compute() uses for x1, so the positions agree
109 // bit for bit when compute() runs on this centre and direction.
110 auto fwd = std::make_unique<Matter>(*matter);
111 fwd->setPotential(x1->getPotential());
112 fwd->setPositionsV(matter->getPositionsV() +
113 params.main_options().finiteDifference * t);
114 Matter *const both[] = {matter.get(), fwd.get()};
116 forward_ = std::move(fwd);
117}
118
119void ImprovedDimer::compute(std::shared_ptr<Matter> matter,
120 AtomMatrix initialDirectionAtomMatrix) {
121
122 VectorXd initialDirection = VectorXd::Map(initialDirectionAtomMatrix.data(),
123 3 * matter->numberOfAtoms());
124 tau = initialDirection.array() * matter->getFreeV().array();
125 rotationDidConverge = true;
127 // A forward image from evaluateWithProbe() serves this call only.
128 const std::unique_ptr<Matter> forward = std::move(forward_);
129 if (tau.norm() > 1e-10) {
130 eonc::safemath::safe_normalize_inplace(tau);
131 } else {
132 // Fallback if the tangent was zero on free atoms (unlikely but safe)
133 tau.setRandom();
134 tau = tau.array() * matter->getFreeV().array();
135 eonc::safemath::safe_normalize_inplace(tau);
136 }
137
138 // Track the best (most negative) curvature and corresponding mode
139 double bestNegativeCurvature = std::numeric_limits<double>::max();
140 VectorXd bestTau = tau;
141 VectorXd bestX0Positions;
142 VectorXd bestG0, bestG1;
143
144 // Reference mode tracking for OCINEB mode-switching prevention
145 VectorXd referenceMode = hasFixedReference ? fixedReferenceMode : tau;
146
147 {
148 // Keep x1's per-image potential across the copy (see the constructor).
149 auto x1Pot = x1->getPotential();
150 *x0 = *matter;
151 *x1 = *matter;
152 x1->setPotential(x1Pot);
153 }
154 VectorXd x0_r = x0->getPositionsV();
155 bestX0Positions = x0_r;
156
157 double delta = params.main_options().finiteDifference;
158 x1->setPositionsV(x0_r + delta * tau);
159 if (forward && !forward->needsForceUpdate() &&
160 forward->getPositions() == x1->getPositions()) {
161 x1->setEvaluation(forward->getForcesRaw(), forward->getPotentialEnergy());
162 }
163
164 // A batching potential evaluates both images in evaluatePair.
165 // evaluateTogether would clear the dirty flags first, and that
166 // function would then see nothing to do.
167 if (!pot->supportsBatchEvaluation()) {
168 Matter *const ends[] = {x0.get(), x1.get()};
170 }
171
172 bool canParallel = eonc::potAllowsSharedInstance(*pot) ||
173 (pot->needsPerImageInstance() &&
174 x0->getPotential().get() != x1->getPotential().get());
175 VectorXd g0, g1;
176 auto evaluatePair = [&]() {
177 // Prefer batched evaluation when the potential supports it.
178 // Else fall back to thread-parallel when the potential is thread-safe or
179 // wants per-image instances. Otherwise sequential.
180 if (pot->supportsBatchEvaluation()) {
181 long n = x0->numberOfAtoms();
182 bool x0dirty = x0->needsForceUpdate();
183 bool x1dirty = x1->needsForceUpdate();
184
185 if (x0dirty && x1dirty) {
186 auto nrs0 = x0->getAtomicNrs();
187 auto nrs1 = x1->getAtomicNrs();
188 auto box0 = x0->getCell();
189 auto box1 = x1->getCell();
190 const double *posVec[] = {x0->getPositions().data(),
191 x1->getPositions().data()};
192 const int *nrsVec[] = {nrs0.data(), nrs1.data()};
193 double *frcVec[] = {x0->forcesData(), x1->forcesData()};
194 double energies[2], vars[2];
195 const double *boxVec[] = {box0.data(), box1.data()};
196 pot->forceBatch(2, n, posVec, nrsVec, frcVec, energies, vars, boxVec);
197 x0->setComputedPotential(energies[0], vars[0]);
198 x1->setComputedPotential(energies[1], vars[1]);
199 } else if (x1dirty) {
200 auto nrs = x1->getAtomicNrs();
201 auto box = x1->getCell();
202 const double *posVec[] = {x1->getPositions().data()};
203 const int *nrsVec[] = {nrs.data()};
204 double *frcVec[] = {x1->forcesData()};
205 double energies[1], vars[1];
206 const double *boxVec[] = {box.data()};
207 pot->forceBatch(1, n, posVec, nrsVec, frcVec, energies, vars, boxVec);
208 x1->setComputedPotential(energies[0], vars[0]);
209 } else if (x0dirty) {
210 x0->getForcesRaw();
211 }
212 g0 = -x0->getForcesV();
213 g1 = -x1->getForcesV();
214 } else if (params.main_options().parallel && canParallel) {
215 std::exception_ptr t0Error;
216 std::thread t0([&] {
217 try {
218 g0 = -x0->getForcesV();
219 } catch (...) {
220 t0Error = std::current_exception();
221 }
222 });
223 try {
224 g1 = -x1->getForcesV();
225 } catch (...) {
226 t0.join();
227 throw;
228 }
229 t0.join();
230 if (t0Error)
231 std::rethrow_exception(t0Error);
232 } else {
233 g0 = -x0->getForcesV();
234 g1 = -x1->getForcesV();
235 }
236 };
237 evaluatePair();
238
239 // If we stepped into a high-energy wall, flip the tangent immediately
240 if (x1->getPotentialEnergy() - x0->getPotentialEnergy() > 10.0 * delta) {
241 tau = -tau;
242 x1->setPositionsV(x0_r + delta * tau);
243 QUILL_LOG_DEBUG(
244 log, "[IDimer] Initial tangent flipped due to high energy wall.");
245 }
246
247 // Optional: LOR / Lanczos / Davidson rotation backends (enum dispatch).
248 if (auto alt = runAlternativeRotation(
249 params.dimer_options().rotation_backend, matter, params, pot,
250 AtomMatrix::Map(tau.data(), matter->numberOfAtoms(), 3),
251 static_cast<quill::Logger *>(log))) {
252 C_tau = alt->eigenvalue;
253 tau = VectorXd::Map(alt->eigenvector.data(), 3 * matter->numberOfAtoms());
254 totalForceCalls += alt->forceCalls;
255 statsRotations = alt->rotations;
256 tau = tau.array() * matter->getFreeV().array();
257 eonc::safemath::safe_normalize_inplace(tau);
258 // The rotation moves neither matter nor its copy x0, so both keep
259 // the centre's evaluation; only the forward image follows the mode.
260 x0_r = matter->getPositionsV();
261 x1->setPositionsV(x0_r + delta * tau);
262 rotationDidConverge = alt->converged;
264 return;
265 }
266
267 // L-BFGS pairs belong to one estimate: the centre has moved, so the
268 // stored (s, y) are not the curvature here.
269 if (params.dimer_options().opt_method == OptType::LBFGS) {
270 s.clear();
271 y.clear();
272 rho.clear();
273 init_lbfgs = true;
274 }
275 // CG state belongs to the dimer, not to one centre. r2549 keeps
276 // init_cg, F_R_Old and thetaOld across translations, including after
277 // an estimate that rotated more than once. Resetting here makes the
278 // next rotation steepest descent.
279
280 VectorXd x1_rp, x1_r, tau_prime, tau_Old, g1_prime;
281 double phi_tol =
282 eonc::helpers::pi * (params.dimer_options().converged_angle / 180.0);
283 double phi_prime = 0.0;
284 double phi_min = 0.0;
285
286 statsRotations = 0;
287
288 // Use x1's potential for the trial rotation image (consistent with per-image)
289 auto x1p = std::make_shared<Matter>(x1->getPotential(), params);
290
291 // Melander, Laasonen, Jonsson, JCTC 11(3), 1055-1062, 2015
292 if (params.dimer_options().remove_rotation) {
294 AtomMatrix::Map(x0_r.data(), x0->numberOfAtoms(), 3), x1);
295 x1_r = x1->getPositionsV();
296 tau = x1->pbcV(x1_r - x0_r);
297 eonc::safemath::safe_normalize_inplace(tau);
298 x1_r = x0_r + tau * delta;
299 x1->setPositionsV(x1_r);
300 }
301
302 evaluatePair();
303
304 bestG0 = g0;
305 bestG1 = g1;
306
307 positions.clear();
308 gradients.clear();
309 positions.push_back(x0->getPositionsV());
310 positions.push_back(x1->getPositionsV());
311 gradients.push_back(g0);
312 gradients.push_back(g1);
313
314 do { // Rotation loop: converge phi or hit max rotations
315
316 // Rotational force, F_R
317 F_R = -2.0 * (g1 - g0) + 2.0 * ((g1 - g0).dot(tau)) * tau;
318 statsTorque = eonc::safemath::safe_div(F_R.norm(), delta * 2.0, 0.0);
319
320 // Determine step direction theta via selected optimizer
321 if (params.dimer_options().opt_method == OptType::SD) {
322 theta = eonc::safemath::safe_normalized(F_R);
323
324 } else if (params.dimer_options().opt_method == OptType::CG) {
325 if (init_cg) {
326 init_cg = false;
327 gamma = 0.0;
328 } else {
329 a = std::abs(F_R.dot(F_R_Old));
330 b = F_R_Old.squaredNorm();
331 gamma = (a < 0.5 * b)
333 : 0.0;
334 }
335
336 theta = (gamma == 0.0) ? F_R : F_R + thetaOld * gamma;
337 theta -= theta.dot(tau) * tau;
338 thetaOld = theta;
339 if (theta.norm() < eonc::safemath::eps) {
340 theta = F_R - F_R.dot(tau) * tau;
341 }
342 eonc::safemath::safe_normalize_inplace(theta);
343 F_R_Old = F_R;
344
345 } else if (params.dimer_options().opt_method == OptType::LBFGS) {
346 if (!init_lbfgs) {
347 VectorXd s0 = tau - tau_Old;
348 s.push_back(s0);
349 VectorXd y0 =
350 eonc::safemath::safe_div(1.0, delta, 0.0) * (F_R_Old - F_R);
351 y.push_back(y0);
352 rho.push_back(eonc::safemath::safe_recip(s0.dot(y0), 0.0));
353 } else {
354 init_lbfgs = false;
355 }
356
357 double H0 = 1.0 / 60.0;
358 size_t loopmax = s.size();
359 std::vector<double> alpha(loopmax);
360
361 VectorXd q = -F_R;
362 for (long i = static_cast<long>(loopmax) - 1; i >= 0; i--) {
363 alpha[i] = rho[i] * s[i].dot(q);
364 q -= alpha[i] * y[i];
365 }
366 VectorXd z = H0 * q;
367 for (size_t i = 0; i < loopmax; i++) {
368 double bv = rho[i] * y[i].dot(z);
369 z += s[i] * (alpha[i] - bv);
370 }
371
372 double vd = std::clamp(-eonc::safemath::safe_normalized(z).dot(
373 eonc::safemath::safe_normalized(F_R)),
374 -1.0, 1.0);
375 double angle =
377
378 if (angle > 87.0) {
379 s.clear();
380 y.clear();
381 rho.clear();
382 z = -F_R;
383 }
384
385 theta = -eonc::safemath::safe_normalized(z);
386 theta -= theta.dot(tau) * tau;
387 eonc::safemath::safe_normalize_inplace(theta);
388
389 thetaOld = theta;
390 F_R_Old = F_R;
391 tau_Old = tau;
392 }
393
394 // Curvature along tau
395 C_tau = eonc::safemath::safe_div((g1 - g0).dot(tau), delta, 0.0);
396
397 // Track best negative curvature for mode restoration
398 if (C_tau < bestNegativeCurvature) {
399 bestNegativeCurvature = C_tau;
400 bestTau = tau;
401 bestX0Positions = x0->getPositionsV();
402 bestG0 = g0;
403 bestG1 = g1;
405 }
406
407 // Estimate optimum rotation angle
408 double d_C_tau_d_phi =
409 2.0 * eonc::safemath::safe_div((g1 - g0).dot(theta), delta, 0.0);
410 phi_prime = -0.5 * atanRatioOrHalfPi(d_C_tau_d_phi, 2.0 * std::abs(C_tau));
411 statsAngle = phi_prime * (180.0 / eonc::helpers::pi);
412
413 double alignment = std::abs(tau.dot(referenceMode));
414
415 if (std::abs(phi_prime) > phi_tol) {
416 double b1 = 0.5 * d_C_tau_d_phi;
417
418 // Trial rotation to phi_prime
419 x0_r = x0->getPositionsV();
420 tau_prime = tau * std::cos(phi_prime) + theta * std::sin(phi_prime);
421 tau_prime = eonc::safemath::safe_normalized(tau_prime);
422 x1_rp = x0_r + tau_prime * delta;
423
424 *x1p = *x1;
425 x1p->setPositionsV(x1_rp);
426 g1_prime = -x1p->getForcesV();
427
428 positions.push_back(x1_rp);
429 gradients.push_back(g1_prime);
430
431 double C_tau_prime =
432 eonc::safemath::safe_div((g1_prime - g0).dot(tau_prime), delta, 0.0);
433
434 // Optimal rotation angle via Fourier interpolation
435 double a1 = eonc::safemath::safe_div(
436 C_tau - C_tau_prime + b1 * std::sin(2.0 * phi_prime),
437 1.0 - std::cos(2.0 * phi_prime), 0.0);
438 double a0 = 2.0 * (C_tau - a1);
439 phi_min = 0.5 * atanRatioOrHalfPi(b1, a1);
440
441 double C_tau_min = 0.5 * a0 + a1 * std::cos(2.0 * phi_min) +
442 b1 * std::sin(2.0 * phi_min);
443
444 // If curvature is being maximized, push over pi/2
445 if (C_tau_min > C_tau) {
446 phi_min += eonc::helpers::pi * 0.5;
447 C_tau_min = 0.5 * a0 + a1 * std::cos(2.0 * phi_min) +
448 b1 * std::sin(2.0 * phi_min);
449 }
450
451 // Keep phi_min in [-pi/2, pi/2] for accurate LBFGS
452 if (phi_min > eonc::helpers::pi * 0.5) {
453 phi_min -= eonc::helpers::pi;
454 }
455 statsAngle = phi_min * (180.0 / eonc::helpers::pi);
456
457 // Apply optimal rotation
458 tau = tau * std::cos(phi_min) + theta * std::sin(phi_min);
459 tau = eonc::safemath::safe_normalized(tau);
460 x1_r = x0_r + tau * delta;
461
462 // Melander, Laasonen, Jonsson, JCTC 11(3), 1055-1062, 2015
463 if (params.dimer_options().remove_rotation) {
464 x1->setPositionsV(x1_r);
466 AtomMatrix::Map(x0_r.data(), x0->numberOfAtoms(), 3), x1);
467 x1_r = x1->getPositionsV();
468 tau = x1_r - x0_r;
469 eonc::safemath::safe_normalize_inplace(tau);
470 x1_r = x0_r + tau * delta;
471 }
472
473 x1->setPositionsV(x1_r);
474 C_tau = C_tau_min;
475
476 // Interpolate g1 at phi_min from g1 and g1_prime (saves one force call)
477 double sin_pp = std::sin(phi_prime);
478 g1 = g1 * eonc::safemath::safe_div(std::sin(phi_prime - phi_min), sin_pp,
479 0.0) +
480 g1_prime * eonc::safemath::safe_div(std::sin(phi_min), sin_pp, 0.0) +
481 g0 * (1.0 - std::cos(phi_min) -
482 std::sin(phi_min) * std::tan(phi_prime * 0.5));
483
484 statsTorque = eonc::safemath::safe_div(F_R.norm(), 2.0 * delta, 0.0);
485 statsRotations += 1;
486 QUILL_LOG_INFO(
487 log,
488 "[IDimerRot] ----- --------- ---------- ------------------ "
489 "{:9.4f} {:7.3f} {:6.3f} {:4} {:5.3f}",
491 } else {
492 QUILL_LOG_INFO(
493 log,
494 "[IDimerRot] ----- --------- ---------- ------------------ "
495 "{:9.4f} {:7.3f} ------ ---- {:5.3f}",
496 C_tau, F_R.norm() / delta, alignment);
497 }
498
499 // Check for mode loss (OCINEB dimer refinement)
500 if (alignment < params.neb_options().climbing_image.ocineb.angle_tol &&
501 params.neb_options().climbing_image.ocineb.use_mmf) {
502 QUILL_LOG_WARNING(
503 log, "Terminating dimer due to lost mode (align {:.3f}).", alignment);
504 rotationDidConverge = false;
505
506 if (bestNegativeCurvature < 0.0) {
507 // Restore the best negative curvature state
508 C_tau = bestNegativeCurvature;
509 tau = bestTau;
510 // The rotation never moves the centre; reassigning it only when it
511 // differs keeps the evaluation the caller already paid for.
512 if (x0->getPositionsV() != bestX0Positions) {
513 x0->setPositionsV(bestX0Positions);
514 *matter = *x0;
515 }
516 x1->setPositionsV(bestX0Positions + delta * bestTau);
517 QUILL_LOG_DEBUG(
518 log, "Restored best negative curvature state: C_tau={:.4f}", C_tau);
520 } else {
521 QUILL_LOG_WARNING(
522 log, "Never found negative curvature. Final C_tau: {:.4f}", C_tau);
524 }
525 }
526
527 } while (std::abs(phi_prime) > std::abs(phi_tol) &&
528 std::abs(phi_min) > std::abs(phi_tol) &&
529 statsRotations < params.dimer_options().rotations_max);
530}
531
533
535 return AtomMatrix::Map(tau.data(), x0->numberOfAtoms(), 3);
536}
537
538} // namespace eonc
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
ImprovedDimer(std::shared_ptr< Matter > matter, const Parameters &params, std::shared_ptr< Potential > pot)
std::unique_ptr< Matter > forward_
std::shared_ptr< Matter > x1
void compute(std::shared_ptr< Matter > matter, AtomMatrix initialDirection) override
std::vector< VectorXd > s
VectorXd fixedReferenceMode
void setReferenceMode(const VectorXd &ref)
std::vector< VectorXd > positions
std::vector< VectorXd > gradients
VectorXd dimerDirection(const Matter &matter, const AtomMatrix &direction) const
std::shared_ptr< Matter > x0
std::vector< VectorXd > y
eonc::log::Scoped log
std::vector< double > rho
double getEigenvalue() override
AtomMatrix getEigenvector() override
void evaluateWithProbe(const std::shared_ptr< Matter > &matter, const AtomMatrix &direction) override
The probe is the forward image x0 + delta tau.
const Parameters & params
std::shared_ptr< Potential > pot
LowestEigenmode(std::shared_ptr< Potential > potPassed, const Parameters &parameters)
long int numberOfAtoms() const
Definition Matter.cpp:343
VectorXd getFreeV() const
Definition Matter.cpp:815
void rotationRemove(const AtomMatrix r1, std::shared_ptr< Matter > m2)
constexpr double pi
constexpr double safe_div(double num, double denom, double fallback=0.0)
Definition SafeMath.h:21
double safe_acos(double x)
Definition SafeMath.h:34
constexpr double eps
Definition SafeMath.h:19
constexpr double safe_recip(double x, double fallback=0.0)
Definition SafeMath.h:29
RAII resource manager for the ARTn C library with global synchronization.
constexpr bool usesAlternativeRotation(DimerRotationBackend backend) noexcept
bool potAllowsSharedInstance(const P &p) noexcept
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.
void evaluateTogether(Potential &pot, std::span< Matter *const > systems, bool threads, std::span< const long > owners)
Evaluates every system that needs a force update.
Definition Matter.cpp:998