Loading...
Searching...
No Matches
Tunneling.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** The half-ring springs, the banded ring Hessian and the friction bath
13** are adapted from i-PI under the MIT licence.
14** i-PI Copyright (C) 2014-2015 i-PI developers
15** Algorithms implemented by Yair Litman and Mariana Rossi, 2017.
16** Friction bath: J. Chem. Phys. 156, 194106 (2022).
17*/
18#include "eon/Tunneling.h"
19#include "eon/EonLogger.h"
20#include "eon/LowestEigenmode.h"
22#include "eon/Parameters.h"
23#include "eon/PotentialOwner.h"
25
26#include <Eigen/Eigenvalues>
27#include <Eigen/LU>
28#include <Eigen/QR>
29
30#include <algorithm>
31#include <cmath>
32#include <cstdint>
33#include <deque>
34#include <limits>
35#include <numbers>
36#include <numeric>
37#include <optional>
38#include <stdexcept>
39#include <utility>
40
41namespace eonc::tunneling {
42
43namespace {
44BatchPotential ownedEvaluation(const BatchPotential &fallback,
45 const RateInstantonOptions &options,
46 long scratch, long beadCount = 0) {
47 if (!options.ownedPotential)
48 return fallback;
49 return [owned = options.ownedPotential, scratch,
50 beadCount](const std::vector<VectorXd> &q, std::vector<double> &v,
51 std::vector<VectorXd> &g) {
52 std::vector<long> owners(q.size(), scratch);
53 if (beadCount > 0)
54 for (size_t j = 0; j < q.size(); ++j)
55 owners[j] = static_cast<long>(j % static_cast<size_t>(beadCount));
56 owned(q, v, g, owners);
57 };
58}
59} // namespace
60
61double massWeightedDistance(const Matter &a, const Matter &b) {
62 if (a.numberOfAtoms() != b.numberOfAtoms()) {
63 throw std::invalid_argument("the structures hold different atom counts");
64 }
65 const AtomMatrix dr = a.pbc(b.getPositions() - a.getPositions());
66 const auto mass = a.getMasses();
67 double sum = 0.0;
68 for (long i = 0; i < a.numberOfAtoms(); ++i) {
69 if (mass(i) <= 0.0) {
70 throw std::invalid_argument(
71 "every atom needs a positive mass for a mass-weighted path");
72 }
73 sum += mass(i) * dr.row(i).squaredNorm();
74 }
75 return std::sqrt(sum);
76}
77
78std::vector<double>
79massWeightedPath(const std::vector<std::shared_ptr<Matter>> &band) {
80 std::vector<double> s{0.0};
81 s.reserve(band.size());
82 for (size_t i = 1; i < band.size(); ++i) {
83 s.push_back(s.back() + massWeightedDistance(*band[i - 1], *band[i]));
84 }
85 return s;
86}
87
88Profile::Profile(std::vector<double> s, std::vector<double> v)
89 : s_(std::move(s)),
90 v_(std::move(v)),
91 m_(s_.size(), 0.0) {
92 const size_t n = s_.size();
93 if (n < 2 || v_.size() != n) {
94 throw std::invalid_argument(
95 "a profile needs matching s and V with two points or more");
96 }
97 for (size_t k = 1; k < n; ++k) {
98 if (!(s_[k] > s_[k - 1])) {
99 throw std::invalid_argument(
100 "the path coordinate must increase along the band");
101 }
102 }
103 for (size_t k = 1; k + 1 < n; ++k) {
104 const double h0 = s_[k] - s_[k - 1];
105 const double h1 = s_[k + 1] - s_[k];
106 const double d0 = (v_[k] - v_[k - 1]) / h0;
107 const double d1 = (v_[k + 1] - v_[k]) / h1;
108 if (d0 * d1 <= 0.0) {
109 m_[k] = 0.0;
110 } else {
111 const double w1 = 2.0 * h1 + h0;
112 const double w2 = h1 + 2.0 * h0;
113 m_[k] = (w1 + w2) / (w1 / d0 + w2 / d1);
114 }
115 }
116}
117
118double Profile::operator()(double x) const {
119 x = std::clamp(x, s_.front(), s_.back());
120 auto it = std::upper_bound(s_.begin(), s_.end(), x);
121 size_t k = static_cast<size_t>(std::distance(s_.begin(), it));
122 k = std::clamp<size_t>(k == 0 ? 0 : k - 1, 0, s_.size() - 2);
123 const double h = s_[k + 1] - s_[k];
124 const double t = (x - s_[k]) / h;
125 const double t2 = t * t;
126 const double t3 = t2 * t;
127 return (2 * t3 - 3 * t2 + 1) * v_[k] + (t3 - 2 * t2 + t) * h * m_[k] +
128 (-2 * t3 + 3 * t2) * v_[k + 1] + (t3 - t2) * h * m_[k + 1];
129}
130
131double wellCurvature(const Profile &p, bool leftEnd) {
132 return 2.0 * wellFit(p, leftEnd)[0];
133}
134
135std::array<double, 2> wellFit(const Profile &p, bool leftEnd) {
136 const auto &s = p.s();
137 const auto &v = p.v();
138 const size_t n = s.size();
139 const double top = *std::max_element(v.begin(), v.end());
140 const double floor = leftEnd ? v.front() : v.back();
141 const double half = 0.5 * (top - floor);
142 // Sums for the normal equations of y = a x^2 + b x^3.
143 double s44 = 0, s45 = 0, s55 = 0, sy2 = 0, sy3 = 0;
144 size_t used = 0;
145 for (size_t j = 1; j < n; ++j) {
146 const size_t i = leftEnd ? j : n - 1 - j;
147 const double x = leftEnd ? s[i] - s.front() : s.back() - s[i];
148 const double y = v[i] - floor;
149 if (y > half) {
150 break;
151 }
152 const double x2 = x * x;
153 s44 += x2 * x2;
154 s45 += x2 * x2 * x;
155 s55 += x2 * x2 * x2;
156 sy2 += y * x2;
157 sy3 += y * x2 * x;
158 ++used;
159 }
160 if (used == 0) {
161 // The next image already stands above half the barrier: the parabola
162 // through it is all the band says about this well.
163 const size_t i = leftEnd ? 1 : n - 2;
164 const double x = leftEnd ? s[i] - s.front() : s.back() - s[i];
165 return {(v[i] - floor) / (x * x), 0.0};
166 }
167 if (used == 1) {
168 return {sy2 / s44, 0.0};
169 }
170 const double det = s44 * s55 - s45 * s45;
171 return {(sy2 * s55 - sy3 * s45) / det, (sy3 * s44 - sy2 * s45) / det};
172}
173
174double hbarOmega(double curvature) {
175 if (!(curvature > 0.0)) {
176 throw std::invalid_argument("a well needs a positive curvature");
177 }
178 return kHbar * std::sqrt(curvature);
179}
180
181double wkbAction(const Profile &p, double energy, int points) {
182 const double a = p.s().front();
183 const double b = p.s().back();
184 const double h = (b - a) / (points - 1);
185 double sum = 0.0;
186 for (int i = 0; i < points; ++i) {
187 const double gap = p(a + i * h) - energy;
188 const double f = gap > 0.0 ? std::sqrt(2.0 * gap) : 0.0;
189 sum += (i == 0 || i == points - 1) ? 0.5 * f : f;
190 }
191 return sum * h / kHbar;
192}
193
194double Splitting::asymmetry() const {
195 return delta + 0.5 * (hwProduct - hwReactant);
196}
197
198double Splitting::tlsEnergy() const { return std::hypot(asymmetry(), delta0); }
199
200Splitting wkbSplitting(const Profile &p, double hwReactant, double hwProduct) {
201 const auto &v = p.v();
202 Splitting out;
203 const double top = *std::max_element(v.begin(), v.end());
204 out.delta = v.back() - v.front();
205 out.barrier = top - v.front();
206 out.hwReactant = hwReactant;
207 out.hwProduct = hwProduct;
208 out.referenceEnergy =
209 std::max(v.front() + 0.5 * hwReactant, v.back() + 0.5 * hwProduct);
210 out.action = wkbAction(p, out.referenceEnergy);
211 const double hw = std::sqrt(hwReactant * hwProduct);
212 out.delta0 = hw / std::numbers::pi * std::exp(-out.action);
213 out.deepWells =
214 (top - v.front()) > hwReactant && (top - v.back()) > hwProduct;
215 return out;
216}
217
218namespace {
219
220std::vector<double> arcLengths(const std::vector<VectorXd> &path) {
221 std::vector<double> s(path.size(), 0.0);
222 for (size_t k = 1; k < path.size(); ++k) {
223 s[k] = s[k - 1] + (path[k] - path[k - 1]).norm();
224 }
225 return s;
226}
227
228VectorXd atArcLength(const std::vector<VectorXd> &path,
229 const std::vector<double> &s, double target) {
230 const auto it = std::upper_bound(s.begin(), s.end(), target);
231 const size_t k = std::clamp<size_t>(
232 static_cast<size_t>(std::distance(s.begin(), it)), 1, path.size() - 1);
233 const double seg = s[k] - s[k - 1];
234 const double t = seg > 0.0 ? (target - s[k - 1]) / seg : 0.0;
235 return path[k - 1] + std::clamp(t, 0.0, 1.0) * (path[k] - path[k - 1]);
236}
237
238// Crossings V(s) = e nearest the barrier top, one on each side.
239std::pair<double, double> turningPoints(const Profile &p, double sTop,
240 double energy) {
241 const double s0 = p.s().front();
242 const double s1 = p.s().back();
243 auto cross = [&](double from, double to) {
244 const int steps = 2000;
245 double a = from;
246 double b = to;
247 for (int k = 1; k <= steps; ++k) {
248 const double sk = from + (to - from) * static_cast<double>(k) / steps;
249 if (p(sk) <= energy) {
250 a = from + (to - from) * static_cast<double>(k - 1) / steps;
251 b = sk;
252 break;
253 }
254 if (k == steps) {
255 return to;
256 }
257 }
258 for (int k = 0; k < 60; ++k) {
259 const double m = 0.5 * (a + b);
260 if (p(m) > energy) {
261 a = m;
262 } else {
263 b = m;
264 }
265 }
266 return 0.5 * (a + b);
267 };
268 return {cross(sTop, s0), cross(sTop, s1)};
269}
270
271// int_{s-}^{s+} ds / sqrt(2 (V - E)). The cosine substitution keeps the
272// integrand finite at the turning points. Optional tables are the running
273// integral and the arc length at the end of each panel.
274double halfPeriod(const Profile &p, double sMinus, double sPlus, double energy,
275 std::vector<double> *cumulative = nullptr,
276 std::vector<double> *positions = nullptr) {
277 const int panels = 4000;
278 const double mid = 0.5 * (sMinus + sPlus);
279 const double half = 0.5 * (sPlus - sMinus);
280 double total = 0.0;
281 if (cumulative != nullptr) {
282 cumulative->assign(1, 0.0);
283 positions->assign(1, sMinus);
284 }
285 for (int k = 0; k < panels; ++k) {
286 const double phi =
287 std::numbers::pi * (static_cast<double>(k) + 0.5) / panels;
288 const double s = mid - half * std::cos(phi);
289 const double under = 2.0 * (p(s) - energy);
290 const double integrand =
291 half * std::sin(phi) / std::sqrt(std::max(under, 1e-300));
292 total += integrand * std::numbers::pi / panels;
293 if (cumulative != nullptr) {
294 cumulative->push_back(total);
295 positions->push_back(
296 mid - half * std::cos(std::numbers::pi * (k + 1.0) / panels));
297 }
298 }
299 return total;
300}
301
302} // namespace
303
304std::vector<VectorXd> ringFromPath(const std::vector<VectorXd> &path,
305 const std::vector<double> &energies,
306 double betaHbar, long beads,
307 RingSeed *seed) {
308 if (path.size() < 3 || path.size() != energies.size() || beads < 4 ||
309 !(betaHbar > 0.0)) {
310 throw std::invalid_argument(
311 "ringFromPath: a path of at least three points with energies, "
312 "N >= 4 and beta hbar > 0");
313 }
314 const long width = path.front().size();
315 for (const auto &q : path) {
316 if (q.size() != width) {
317 throw std::invalid_argument("ringFromPath: the path changes dimension");
318 }
319 }
320 const std::vector<double> s = arcLengths(path);
321 const Profile profile(s, energies);
322 double sTop = s.front();
323 double vTop = -std::numeric_limits<double>::infinity();
324 const int grid = 4000;
325 for (int k = 0; k <= grid; ++k) {
326 const double sk =
327 s.front() + (s.back() - s.front()) * static_cast<double>(k) / grid;
328 if (profile(sk) > vTop) {
329 vTop = profile(sk);
330 sTop = sk;
331 }
332 }
333 const double vLow = std::max(energies.front(), energies.back());
334 if (!(vTop > vLow)) {
335 throw std::invalid_argument("ringFromPath: the path has no barrier");
336 }
337 auto period = [&](double energy) {
338 const auto [sMinus, sPlus] = turningPoints(profile, sTop, energy);
339 return 2.0 * halfPeriod(profile, sMinus, sPlus, energy);
340 };
341 // The crossover along the path from a parabola through the three input
342 // points around the barrier top, not from the interpolant, whose slope is
343 // clamped to zero at the top node.
344 {
345 size_t top = 0;
346 for (size_t k = 1; k < energies.size(); ++k) {
347 if (energies[k] > energies[top]) {
348 top = k;
349 }
350 }
351 if (top == 0 || top + 1 == energies.size()) {
352 throw std::invalid_argument(
353 "ringFromPath: the barrier top is an end of the path");
354 }
355 const double h1 = s[top] - s[top - 1], h2 = s[top + 1] - s[top];
356 const double curvature =
357 2.0 *
358 (h1 * energies[top + 1] - (h1 + h2) * energies[top] +
359 h2 * energies[top - 1]) /
360 (h1 * h2 * (h1 + h2));
361 if (!(curvature < 0.0)) {
362 throw std::invalid_argument("ringFromPath: no curvature at the top");
363 }
364 const double tc = kHbar * std::sqrt(-curvature) / (2.0 * std::numbers::pi);
365 if (!(kHbar / betaHbar < tc)) {
366 throw std::invalid_argument(
367 "ringFromPath: the temperature is at or above the crossover along "
368 "this path");
369 }
370 }
371 // Orbit energies on a geometric grid above the lower end: the period
372 // grows only logarithmically as E approaches a well bottom. The period
373 // need not fall monotonically with E: a shoulder on the path, where V'
374 // nearly vanishes away from a well, makes it spike, and a bisection over
375 // the whole range then converges onto the spike for every beta hbar it
376 // spans. Every crossing of beta hbar on the grid is refined, and the
377 // one kept minimises theta(E) + beta E, theta = 2 x the WKB action: it
378 // dominates the steepest-descent integral the instanton evaluates.
379 const double span = vTop - vLow;
380 const double eBottom = vLow + 1e-14 * span;
381 // Geometric in the distance from the top over the upper half, where a
382 // flat-topped barrier keeps the crossing within a small fraction of the
383 // span, and geometric in the height above the lower end over the lower
384 // half, where the period diverges only logarithmically.
385 constexpr int kHalf = 200;
386 constexpr int kScan = 2 * kHalf + 1;
387 std::vector<double> levels(kScan + 1);
388 std::vector<double> gap(kScan + 1);
389 for (int k = 0; k <= kHalf; ++k) {
390 const double u = static_cast<double>(k) / kHalf;
391 levels[static_cast<size_t>(k)] =
392 vTop - span * std::pow(10.0, -9.0 + u * (9.0 + std::log10(0.5)));
393 levels[static_cast<size_t>(kScan - k)] =
394 vLow + span * std::pow(10.0, -14.0 + u * (14.0 + std::log10(0.5)));
395 }
396 for (int k = 0; k <= kScan; ++k) {
397 gap[static_cast<size_t>(k)] =
398 period(levels[static_cast<size_t>(k)]) - betaHbar;
399 }
400 const double beta = betaHbar / kHbar;
401 double energy = eBottom;
402 double best = std::numeric_limits<double>::infinity();
403 for (int k = 0; k < kScan; ++k) {
404 double a = levels[static_cast<size_t>(k)];
405 double b = levels[static_cast<size_t>(k + 1)];
406 double ga = gap[static_cast<size_t>(k)];
407 if ((ga > 0.0) == (gap[static_cast<size_t>(k + 1)] > 0.0)) {
408 continue;
409 }
410 for (int it = 0; it < 200 && std::abs(a - b) > 1e-15 * span; ++it) {
411 const double m = vLow + std::sqrt((a - vLow) * (b - vLow));
412 const double gm = period(m) - betaHbar;
413 if ((gm > 0.0) == (ga > 0.0)) {
414 a = m;
415 ga = gm;
416 } else {
417 b = m;
418 }
419 }
420 const double root = 0.5 * (a + b);
421 // A bracket around a jump of the turning point refines onto the jump,
422 // where the period is not beta hbar.
423 if (!(std::abs(period(root) - betaHbar) <= 1e-6 * betaHbar)) {
424 continue;
425 }
426 const double w = 2.0 * wkbAction(profile, root) + beta * root;
427 if (w < best) {
428 best = w;
429 energy = root;
430 }
431 }
432 // With no crossing the path does not reach a long enough orbit; the
433 // lowest one it holds is the start.
434 if (seed != nullptr) {
435 seed->energy = energy;
436 seed->period = period(energy);
437 seed->pathLow = vLow;
438 seed->reached = std::abs(seed->period - betaHbar) <= 1e-6 * betaHbar;
439 }
440 const auto [sMinus, sPlus] = turningPoints(profile, sTop, energy);
441 std::vector<double> tau;
442 std::vector<double> pos;
443 const double half = halfPeriod(profile, sMinus, sPlus, energy, &tau, &pos);
444 if (tau.size() < 2 || tau.size() != pos.size()) {
445 throw std::invalid_argument("ringFromPath: the orbit has no length");
446 }
447 // Bead j sits at imaginary time j * beta hbar / N on the way from the
448 // reactant-side turning point to the other side. The return repeats it.
449 std::vector<VectorXd> ring(static_cast<size_t>(beads), VectorXd::Zero(width));
450 for (long j = 0; j <= beads / 2; ++j) {
451 const double t =
452 std::min(half, half * 2.0 * static_cast<double>(j) / beads);
453 const auto it = std::upper_bound(tau.begin(), tau.end(), t);
454 const size_t k = std::clamp<size_t>(
455 static_cast<size_t>(std::distance(tau.begin(), it)), 1, tau.size() - 1);
456 const double seg = tau[k] - tau[k - 1];
457 const double w = seg > 0.0 ? (t - tau[k - 1]) / seg : 0.0;
458 const double sj =
459 pos[k - 1] + std::clamp(w, 0.0, 1.0) * (pos[k] - pos[k - 1]);
460 ring[static_cast<size_t>(j)] = atArcLength(path, s, sj);
461 if (j > 0 && j < beads - j) {
462 ring[static_cast<size_t>(beads - j)] = ring[static_cast<size_t>(j)];
463 }
464 }
465 return ring;
466}
467
468double wkbLogRateAlongPath(const Profile &profile, double beta,
469 double hwReactant) {
470 if (!(beta > 0.0) || !(hwReactant > 0.0)) {
471 throw std::invalid_argument(
472 "wkbLogRateAlongPath: beta and hbar omega must be positive");
473 }
474 const double vReactant = profile.v().front();
475 const double s0 = profile.s().front();
476 const double s1 = profile.s().back();
477 double vTop = vReactant;
478 double sTop = s0;
479 const int grid = 2000;
480 for (int k = 0; k <= grid; ++k) {
481 const double sk = s0 + (s1 - s0) * static_cast<double>(k) / grid;
482 const double vk = profile(sk);
483 if (vk >= vTop) {
484 vTop = vk;
485 sTop = sk;
486 }
487 }
488 const double barrier = vTop - vReactant;
489 if (!(barrier > 0.0)) {
490 throw std::invalid_argument(
491 "wkbLogRateAlongPath: no barrier above the reactant");
492 }
493 double ds = 1e-3 * (s1 - s0);
494 ds = std::min(ds, std::min(sTop - s0, s1 - sTop));
495 if (!(ds > 0.0)) {
496 throw std::invalid_argument(
497 "wkbLogRateAlongPath: the barrier top is at an end of the path");
498 }
499 const double curvature =
500 std::max(1e-12, -(profile(sTop + ds) - 2.0 * vTop + profile(sTop - ds)) /
501 (ds * ds));
502 const double hwBarrier = kHbar * std::sqrt(curvature);
503 // int P(E) exp(-beta E) dE from the reactant up to where the Boltzmann
504 // factor has died. E is measured from the reactant.
505 const double eMax = barrier + 40.0 / beta;
506 const int points = 600;
507 auto logAdd = [](double a, double b) {
508 if (a == -std::numeric_limits<double>::infinity()) {
509 return b;
510 }
511 const double m = std::max(a, b);
512 return m + std::log(std::exp(a - m) + std::exp(b - m));
513 };
514 double logTerms = -std::numeric_limits<double>::infinity();
515 double prevLog = -std::numeric_limits<double>::infinity();
516 double prevE = 0.0;
517 for (int k = 0; k <= points; ++k) {
518 const double energy = eMax * static_cast<double>(k) / points;
519 double theta = 0.0;
520 if (energy < barrier) {
521 theta = wkbAction(profile, vReactant + energy);
522 } else {
523 theta = -std::numbers::pi * (energy - barrier) / hwBarrier;
524 }
525 const double logP =
526 theta > 20.0 ? -2.0 * theta : -std::log1p(std::exp(2.0 * theta));
527 const double logF = logP - beta * energy;
528 if (k > 0) {
529 const double segment =
530 std::log(0.5 * (energy - prevE)) + logAdd(prevLog, logF);
531 logTerms = logAdd(logTerms, segment);
532 }
533 prevLog = logF;
534 prevE = energy;
535 }
536 const double logFlux = logTerms - std::log(2.0 * std::numbers::pi * kHbar);
537 return logFlux + std::log(2.0 * std::sinh(0.5 * beta * hwReactant));
538}
539
540Profile bandProfile(const std::vector<std::shared_ptr<Matter>> &band,
541 double referenceEnergy) {
542 std::vector<double> v;
543 v.reserve(band.size());
544 for (const auto &image : band) {
545 v.push_back(image->getPotentialEnergy() - referenceEnergy);
546 }
547 return Profile(massWeightedPath(band), std::move(v));
548}
549
550Splitting bandSplitting(const std::vector<std::shared_ptr<Matter>> &band,
551 double referenceEnergy) {
552 const Profile p = bandProfile(band, referenceEnergy);
553 return wkbSplitting(p, hbarOmega(wellCurvature(p, true)),
554 hbarOmega(wellCurvature(p, false)));
555}
556
557bool singleBarrier(const Profile &p) {
558 const auto &v = p.v();
559 long peaks = 0;
560 long valleys = 0;
561 int last = 0;
562 for (size_t k = 1; k < v.size(); ++k) {
563 const int step = v[k] > v[k - 1] ? 1 : (v[k] < v[k - 1] ? -1 : 0);
564 if (step == 0) {
565 continue;
566 }
567 peaks += (last == 1 && step == -1) ? 1 : 0;
568 valleys += (last == -1 && step == 1) ? 1 : 0;
569 last = step;
570 }
571 return peaks == 1 && valleys == 0;
572}
573
574Levels dvrLevels(const std::function<double(double)> &v, double sReactant,
575 double sProduct, double sTop, double hwReactant,
576 double hwProduct) {
577 if (!(hwReactant > 0.0) || !(hwProduct > 0.0) || !(sProduct > sReactant)) {
578 throw std::invalid_argument(
579 "dvrLevels: two wells with positive hbar omega along an increasing "
580 "path");
581 }
582 const double ellR = kHbar / std::sqrt(hwReactant);
583 const double ellP = kHbar / std::sqrt(hwProduct);
584 const double lo = sReactant - kDvrPadLengths * ellR;
585 const double hi = sProduct + kDvrPadLengths * ellP;
586 const long n = std::clamp<long>(
587 static_cast<long>(
588 std::ceil((hi - lo) * kDvrPointsPerLength / std::min(ellR, ellP))) +
589 1,
590 64, kDvrMaxPoints);
591 const double h = (hi - lo) / static_cast<double>(n - 1);
592 const double c = kHbar * kHbar / (2.0 * h * h);
593 MatrixXd hmat = MatrixXd::Zero(n, n);
594 for (long i = 0; i < n; ++i) {
595 hmat(i, i) = v(lo + static_cast<double>(i) * h) + 2.5 * c;
596 if (i + 1 < n) {
597 hmat(i, i + 1) = hmat(i + 1, i) = -4.0 * c / 3.0;
598 }
599 if (i + 2 < n) {
600 hmat(i, i + 2) = hmat(i + 2, i) = c / 12.0;
601 }
602 }
603 const Eigen::SelfAdjointEigenSolver<MatrixXd> es(hmat);
604 // The overlaps of the two lowest states on the reactant side; their
605 // leading eigenvector is the rotation onto the reactant-localised state.
606 Eigen::Matrix2d side = Eigen::Matrix2d::Zero();
607 for (long i = 0; i < n && lo + static_cast<double>(i) * h < sTop; ++i) {
608 const double a = es.eigenvectors()(i, 0);
609 const double b = es.eigenvectors()(i, 1);
610 side(0, 0) += a * a;
611 side(0, 1) += a * b;
612 side(1, 1) += b * b;
613 }
614 side(1, 0) = side(0, 1);
615 const Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> rotation(side);
616 const double cosine = rotation.eigenvectors()(0, 1);
617 const double sine = rotation.eigenvectors()(1, 1);
618 Levels out;
619 out.gap = es.eigenvalues()(1) - es.eigenvalues()(0);
620 out.asymmetry = out.gap * (cosine * cosine - sine * sine);
621 out.delta0 = 2.0 * out.gap * std::abs(cosine * sine);
622 return out;
623}
624
625namespace {
626
627// The cubic spline through (0, 0) and the given points, flat at 0 and
628// natural at the last point; past it, straight along its end slope.
629class FlatStartSpline {
630public:
631 FlatStartSpline(std::vector<double> x, std::vector<double> y)
632 : x_(std::move(x)),
633 y_(std::move(y)) {
634 const size_t m = x_.size() - 1;
635 for (size_t i = 0; i < m; ++i) {
636 if (!(x_[i + 1] > x_[i])) {
637 throw std::invalid_argument(
638 "a wall needs increasing distances past the minimum");
639 }
640 }
641 // Moments M_0 .. M_{m-1} from the tridiagonal system, M_m = 0.
642 std::vector<double> sub(m, 0.0), dia(m, 0.0), sup(m, 0.0), rhs(m, 0.0);
643 auto h = [&](size_t i) { return x_[i + 1] - x_[i]; };
644 auto slope = [&](size_t i) { return (y_[i + 1] - y_[i]) / h(i); };
645 dia[0] = 2.0 * h(0);
646 sup[0] = h(0);
647 rhs[0] = 6.0 * slope(0);
648 for (size_t i = 1; i < m; ++i) {
649 sub[i] = h(i - 1);
650 dia[i] = 2.0 * (h(i - 1) + h(i));
651 sup[i] = h(i);
652 rhs[i] = 6.0 * (slope(i) - slope(i - 1));
653 }
654 for (size_t i = 1; i < m; ++i) {
655 const double w = sub[i] / dia[i - 1];
656 dia[i] -= w * sup[i - 1];
657 rhs[i] -= w * rhs[i - 1];
658 }
659 m_.assign(m + 1, 0.0);
660 for (size_t i = m; i-- > 0;) {
661 m_[i] = (rhs[i] - (i + 1 < m ? sup[i] * m_[i + 1] : 0.0)) / dia[i];
662 }
663 endSlope_ = slope(m - 1) + m_[m - 1] * h(m - 1) / 6.0;
664 }
665 double operator()(double u) const {
666 if (u >= x_.back()) {
667 return y_.back() + endSlope_ * (u - x_.back());
668 }
669 const auto it = std::upper_bound(x_.begin(), x_.end(), u);
670 const size_t i =
671 std::clamp<size_t>(static_cast<size_t>(std::distance(x_.begin(), it)),
672 1, x_.size() - 1) -
673 1;
674 const double h = x_[i + 1] - x_[i];
675 const double a = x_[i + 1] - u;
676 const double b = u - x_[i];
677 return (m_[i] * a * a * a + m_[i + 1] * b * b * b) / (6.0 * h) +
678 (y_[i] - m_[i] * h * h / 6.0) * a / h +
679 (y_[i + 1] - m_[i + 1] * h * h / 6.0) * b / h;
680 }
681
682private:
683 std::vector<double> x_, y_, m_;
684 double endSlope_ = 0.0;
685};
686
687} // namespace
688
689Levels bandLevels(const Profile &p, const BandWalls *walls) {
690 const std::array<double, 2> fitR = wellFit(p, true);
691 const std::array<double, 2> fitP = wellFit(p, false);
692 const double hwR = hbarOmega(2.0 * fitR[0]);
693 const double hwP = hbarOmega(2.0 * fitP[0]);
694 const double s0 = p.s().front();
695 const double s1 = p.s().back();
696 double sTop = s0;
697 double vTop = -std::numeric_limits<double>::infinity();
698 constexpr int grid = 4000;
699 for (int k = 0; k <= grid; ++k) {
700 const double sk = s0 + (s1 - s0) * static_cast<double>(k) / grid;
701 if (p(sk) > vTop) {
702 vTop = p(sk);
703 sTop = sk;
704 }
705 }
706 // Past each end the well's fit, its parabola or its cubic, whichever is
707 // stiffer. A sampled wall adds the residual of its samples, a spline flat
708 // at the minimum: the fit already bends like the potential where the
709 // ground state lives, so the residual is small there and smooth beyond.
710 auto model = [](double u, const std::array<double, 2> &fit) {
711 return std::max(fit[0] * u * u - fit[1] * u * u * u, fit[0] * u * u);
712 };
713 auto residual = [&](const BandWall *wall, const std::array<double, 2> &fit,
714 double floor) -> std::optional<FlatStartSpline> {
715 if (wall == nullptr || wall->distance.empty()) {
716 return std::nullopt;
717 }
718 if (wall->distance.size() != wall->energy.size()) {
719 throw std::invalid_argument("a wall needs one energy per distance");
720 }
721 std::vector<double> x{0.0};
722 std::vector<double> y{0.0};
723 for (size_t k = 0; k < wall->distance.size(); ++k) {
724 x.push_back(wall->distance[k]);
725 y.push_back(wall->energy[k] - floor - model(wall->distance[k], fit));
726 }
727 return FlatStartSpline(std::move(x), std::move(y));
728 };
729 const std::optional<FlatStartSpline> wallR =
730 residual(walls ? &walls->reactant : nullptr, fitR, p.v().front());
731 const std::optional<FlatStartSpline> wallP =
732 residual(walls ? &walls->product : nullptr, fitP, p.v().back());
733 auto outer = [&](double u, const std::array<double, 2> &fit, double floor,
734 const std::optional<FlatStartSpline> &wall) {
735 return floor + model(u, fit) + (wall ? (*wall)(u) : 0.0);
736 };
737 auto v = [&](double s) {
738 if (s < s0) {
739 return outer(s0 - s, fitR, p.v().front(), wallR);
740 }
741 if (s > s1) {
742 return outer(s - s1, fitP, p.v().back(), wallP);
743 }
744 return p(s);
745 };
746 return dvrLevels(v, s0, s1, sTop, hwR, hwP);
747}
748
749BandWalls bandWalls(const std::vector<std::shared_ptr<Matter>> &band,
750 double referenceEnergy, long points) {
751 if (band.size() < 3 || points < 1) {
752 throw std::invalid_argument(
753 "bandWalls: a band of three images or more and a point per wall");
754 }
755 const Profile p = bandProfile(band, referenceEnergy);
756 auto wall = [&](const Matter &end, const Matter &next, double a) {
757 const double ell = kHbar / std::sqrt(hbarOmega(2.0 * a));
758 const AtomMatrix step = end.pbc(end.getPositions() - next.getPositions());
759 const auto mass = end.getMasses();
760 double norm2 = 0.0;
761 for (long i = 0; i < end.numberOfAtoms(); ++i) {
762 norm2 += mass(i) * step.row(i).squaredNorm();
763 }
764 if (!(norm2 > 0.0)) {
765 throw std::invalid_argument("bandWalls: an end segment has no length");
766 }
767 // One unit of mass-weighted length along the end segment, outward.
768 const AtomMatrix direction = step / std::sqrt(norm2);
769 BandWall out;
770 Matter probe(end);
771 for (long k = 1; k <= points; ++k) {
772 const double u = kDvrPadLengths * ell * static_cast<double>(k) /
773 static_cast<double>(points);
774 probe.setPositions(end.getPositions() + u * direction);
775 out.distance.push_back(u);
776 out.energy.push_back(probe.getPotentialEnergy() - referenceEnergy);
777 }
778 return out;
779 };
780 BandWalls out;
781 out.reactant = wall(*band.front(), *band[1], wellFit(p, true)[0]);
782 out.product =
783 wall(*band.back(), *band[band.size() - 2], wellFit(p, false)[0]);
784 return out;
785}
786
787namespace {
788
791constexpr long kDenseRing = 4096;
792
794constexpr double kTrackOverlap = 0.3;
797constexpr long kRitzCap = 400;
798
799using ColMajorXd =
800 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;
801
802// The open chain J with diagonal blocks A_k, each already holding the bead
803// Hessian plus 2 c I, and -c I between neighbours.
804// Block LU: D_1 = A_1, D_k = A_k - c^2 D_{k-1}^-1.
805class BlockChain {
806public:
807 BlockChain(double c, const std::vector<MatrixXd> &diag)
808 : c_(c) {
809 lu_.reserve(diag.size());
810 for (size_t k = 0; k < diag.size(); ++k) {
811 ColMajorXd d = diag[k];
812 if (k > 0) {
813 d -= c_ * c_ * lu_.back().inverse();
814 }
815 lu_.emplace_back(std::move(d));
816 const auto &f = lu_.back();
817 sign_ *= static_cast<int>(std::lround(f.permutationP().determinant()));
818 for (long i = 0; i < d.rows(); ++i) {
819 const double u = f.matrixLU()(i, i);
820 if (u == 0.0) {
821 throw std::runtime_error("instanton: singular chain Hessian block");
822 }
823 sign_ *= u < 0.0 ? -1 : 1;
824 logAbsDet_ += std::log(std::abs(u));
825 }
826 }
827 }
828 double logAbsDet() const { return logAbsDet_; }
829 int sign() const { return sign_; }
830 // x = J^-1 b, b and x stacked by bead.
831 std::vector<VectorXd> solve(const std::vector<VectorXd> &b) const {
832 const size_t m = b.size();
833 std::vector<VectorXd> y(m), x(m);
834 y[0] = b[0];
835 for (size_t k = 1; k < m; ++k) {
836 y[k] = b[k] + c_ * lu_[k - 1].solve(y[k - 1]);
837 }
838 x[m - 1] = lu_[m - 1].solve(y[m - 1]);
839 for (size_t k = m - 1; k-- > 0;) {
840 x[k] = lu_[k].solve(y[k] + c_ * x[k + 1]);
841 }
842 return x;
843 }
844 // Same recurrence, several right-hand sides per bead.
845 std::vector<MatrixXd> solve(const std::vector<MatrixXd> &b) const {
846 const size_t m = b.size();
847 std::vector<MatrixXd> y(m), x(m);
848 y[0] = b[0];
849 for (size_t k = 1; k < m; ++k) {
850 y[k] = b[k] + c_ * lu_[k - 1].solve(y[k - 1]);
851 }
852 x[m - 1] = lu_[m - 1].solve(y[m - 1]);
853 for (size_t k = m - 1; k-- > 0;) {
854 x[k] = lu_[k].solve(y[k] + c_ * x[k + 1]);
855 }
856 return x;
857 }
858
859private:
860 double c_;
861 std::vector<Eigen::PartialPivLU<ColMajorXd>> lu_;
862 double logAbsDet_ = 0.0;
863 int sign_ = 1;
864};
865
866// Spring of every link j (bead j to bead j + 1, the last closing the ring):
867// c, or c / w_j under link weights.
868std::vector<double> linkSprings(double c, size_t n,
869 const std::vector<double> *weight) {
870 std::vector<double> out(n, c);
871 if (weight == nullptr || weight->empty()) {
872 return out;
873 }
874 if (weight->size() != n) {
875 throw std::invalid_argument(
876 "link weights must be one positive value per bead");
877 }
878 for (size_t j = 0; j < n; ++j) {
879 if (!((*weight)[j] > 0.0)) {
880 throw std::invalid_argument(
881 "link weights must be one positive value per bead");
882 }
883 out[j] = c / (*weight)[j];
884 }
885 return out;
886}
887
888// Block LU of an open block-tridiagonal chain with given diagonal blocks
889// and -c_j I between bead j and j + 1. Solves, and the inertia and
890// log-determinant from the Schur complements (Haynsworth: the inertia of
891// the chain is the sum over its Schur blocks).
892class HaynsworthChain {
893public:
894 HaynsworthChain(double c, const std::vector<MatrixXd> &diag, bool spectrum,
895 const std::vector<double> *weight = nullptr)
896 : link_(linkSprings(c, diag.size(), weight)) {
897 lu_.reserve(diag.size());
898 for (size_t k = 0; k < diag.size(); ++k) {
899 const long f = diag[k].rows();
900 MatrixXd d = 0.5 * (diag[k] + diag[k].transpose());
901 if (k > 0) {
902 const MatrixXd inv = lu_.back().inverse();
903 const double ck = link_[k - 1];
904 d -= ck * ck * 0.5 * (inv + inv.transpose());
905 }
906 if (spectrum) {
907 const ColMajorXd sym = d;
908 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(
909 sym, Eigen::EigenvaluesOnly);
910 for (long i = 0; i < f; ++i) {
911 const double lam = es.eigenvalues()(i);
912 if (lam == 0.0) {
913 throw std::runtime_error("instanton: singular chain Hessian block");
914 }
915 if (lam < 0.0) {
916 ++negative_;
917 }
918 logAbsDet_ += std::log(std::abs(lam));
919 }
920 }
921 lu_.emplace_back(ColMajorXd(d));
922 }
923 }
924 double logAbsDet() const { return logAbsDet_; }
925 long negative() const { return negative_; }
926 std::vector<VectorXd> solve(const std::vector<VectorXd> &b) const {
927 const size_t m = b.size();
928 std::vector<VectorXd> y(m), x(m);
929 y[0] = b[0];
930 for (size_t k = 1; k < m; ++k) {
931 y[k] = b[k] + link_[k - 1] * lu_[k - 1].solve(y[k - 1]);
932 }
933 x[m - 1] = lu_[m - 1].solve(y[m - 1]);
934 for (size_t k = m - 1; k-- > 0;) {
935 x[k] = lu_[k].solve(y[k] + link_[k] * x[k + 1]);
936 }
937 return x;
938 }
939 double closingSpring() const { return link_.back(); }
940
941private:
942 std::vector<double> link_;
943 std::vector<Eigen::PartialPivLU<ColMajorXd>> lu_;
944 double logAbsDet_ = 0.0;
945 long negative_ = 0;
946};
947
948double dot(const std::vector<VectorXd> &a, const std::vector<VectorXd> &b) {
949 double s = 0.0;
950 for (size_t k = 0; k < a.size(); ++k) {
951 s += a[k].dot(b[k]);
952 }
953 return s;
954}
955
956void scale(std::vector<VectorXd> &a, double f) {
957 for (auto &v : a) {
958 v *= f;
959 }
960}
961
962// Point at arc-length fraction f along a polyline.
963VectorXd alongPolyline(const std::vector<VectorXd> &pts,
964 const std::vector<double> &cum, double f) {
965 const double target = f * cum.back();
966 const auto it = std::upper_bound(cum.begin(), cum.end(), target);
967 const size_t k = std::clamp<size_t>(
968 static_cast<size_t>(std::distance(cum.begin(), it)), 1, pts.size() - 1);
969 const double seg = cum[k] - cum[k - 1];
970 const double t = seg > 0.0 ? (target - cum[k - 1]) / seg : 0.0;
971 return pts[k - 1] + std::clamp(t, 0.0, 1.0) * (pts[k] - pts[k - 1]);
972}
973
974struct ActionEval {
975 double action = 0.0;
976 std::vector<double> v; // interior beads
977 std::vector<VectorXd> grad; // dS/dq over interior beads
978 std::vector<VectorXd> potGrad; // dV/dq over interior beads
979};
980
981ActionEval evaluateAction(const std::vector<VectorXd> &interior,
982 const VectorXd &start, const VectorXd &end,
983 double vStart, double vEnd, double dtau,
984 const BatchPotential &potential) {
985 ActionEval out;
986 potential(interior, out.v, out.potGrad);
987 const size_t m = interior.size();
988 if (out.v.size() != m || out.potGrad.size() != m) {
989 throw std::runtime_error("instanton: potential returned the wrong count");
990 }
991 auto bead = [&](size_t j) -> const VectorXd & {
992 return j == 0 ? start : (j == m + 1 ? end : interior[j - 1]);
993 };
994 double kinetic = 0.0;
995 for (size_t j = 0; j <= m; ++j) {
996 kinetic += (bead(j + 1) - bead(j)).squaredNorm();
997 }
998 double pot = 0.5 * (vStart + vEnd);
999 for (double vj : out.v) {
1000 pot += vj;
1001 }
1002 out.action = 0.5 * kinetic / dtau + dtau * pot;
1003 out.grad.resize(m);
1004 for (size_t j = 1; j <= m; ++j) {
1005 out.grad[j - 1] = (2.0 * bead(j) - bead(j - 1) - bead(j + 1)) / dtau +
1006 dtau * out.potGrad[j - 1];
1007 }
1008 return out;
1009}
1010
1011double largestBeadNorm(const std::vector<VectorXd> &g) {
1012 double m = 0.0;
1013 for (const auto &v : g) {
1014 m = std::max(m, v.norm());
1015 }
1016 return m;
1017}
1018
1019} // namespace
1020
1021double pathOmega(const MatrixXd &hessStart, const MatrixXd &hessEnd,
1022 const VectorXd &start, const VectorXd &end) {
1023 const VectorXd d = (end - start).normalized();
1024 const double k = std::max(d.dot(hessStart * d), d.dot(hessEnd * d));
1025 if (!(k > 0.0)) {
1026 throw std::invalid_argument(
1027 "pathOmega: no positive curvature along the path at either minimum");
1028 }
1029 return std::sqrt(k);
1030}
1031
1032Instanton optimizeInstanton(const VectorXd &start, const VectorXd &end,
1033 double betaHbar, std::vector<VectorXd> guess,
1034 const BatchPotential &potential,
1035 const InstantonOptions &options) {
1036 const long P = options.beads;
1037 if (P < 4 || !(betaHbar > 0.0) || start.size() != end.size()) {
1038 throw std::invalid_argument("optimizeInstanton: need P >= 4, beta hbar > 0 "
1039 "and ends of one dimension");
1040 }
1041 Instanton inst;
1042 inst.betaHbar = betaHbar;
1043 inst.dtau = betaHbar / static_cast<double>(P);
1044 const double dtau = inst.dtau;
1045
1046 std::vector<double> vEnds;
1047 std::vector<VectorXd> gEnds;
1048 potential({start, end}, vEnds, gEnds);
1049 if (vEnds.size() != 2) {
1050 throw std::runtime_error("instanton: potential returned the wrong count");
1051 }
1052 inst.asymmetry = vEnds[1] - vEnds[0];
1053
1054 // Beads along the guess (or the straight line) on a tanh kink centred at
1055 // beta hbar / 2 whose width follows the harmonic decay of a well.
1056 if (guess.size() < 2) {
1057 guess = {start, end};
1058 }
1059 std::vector<double> cum(guess.size(), 0.0);
1060 for (size_t k = 1; k < guess.size(); ++k) {
1061 cum[k] = cum[k - 1] + (guess[k] - guess[k - 1]).norm();
1062 }
1063 if (!(cum.back() > 0.0)) {
1064 throw std::invalid_argument("optimizeInstanton: the two minima coincide");
1065 }
1066 const double width = betaHbar / (2.0 * options.betaHbarOmega);
1067 std::vector<VectorXd> x(static_cast<size_t>(P - 1));
1068 for (long j = 1; j < P; ++j) {
1069 const double tau = static_cast<double>(j) * dtau - 0.5 * betaHbar;
1070 const double f = 0.5 * (1.0 + std::tanh(tau / width));
1071 x[static_cast<size_t>(j - 1)] = alongPolyline(guess, cum, f);
1072 }
1073
1074 // L-BFGS with a backtracking Armijo line search.
1075 ActionEval cur =
1076 evaluateAction(x, start, end, vEnds[0], vEnds[1], dtau, potential);
1077 std::deque<std::pair<std::vector<VectorXd>, std::vector<VectorXd>>> pairs;
1078 for (long it = 0; it < options.maxIterations; ++it) {
1079 inst.iterations = it;
1080 if (largestBeadNorm(cur.grad) / dtau < options.forceTolerance) {
1081 inst.converged = true;
1082 break;
1083 }
1084 std::vector<VectorXd> q = cur.grad;
1085 std::vector<double> alpha(pairs.size());
1086 for (size_t i = pairs.size(); i-- > 0;) {
1087 const double rho = 1.0 / dot(pairs[i].second, pairs[i].first);
1088 alpha[i] = rho * dot(pairs[i].first, q);
1089 for (size_t k = 0; k < q.size(); ++k) {
1090 q[k] -= alpha[i] * pairs[i].second[k];
1091 }
1092 }
1093 // Without history, half the inverse spring stiffness 2 / dtau.
1094 double gamma = dtau / 4.0;
1095 if (!pairs.empty()) {
1096 gamma = dot(pairs.back().first, pairs.back().second) /
1097 dot(pairs.back().second, pairs.back().second);
1098 }
1099 scale(q, gamma);
1100 for (size_t i = 0; i < pairs.size(); ++i) {
1101 const double rho = 1.0 / dot(pairs[i].second, pairs[i].first);
1102 const double beta = rho * dot(pairs[i].second, q);
1103 for (size_t k = 0; k < q.size(); ++k) {
1104 q[k] += (alpha[i] - beta) * pairs[i].first[k];
1105 }
1106 }
1107 // q is now the inverse-Hessian estimate times the gradient; step -q.
1108 double slope = -dot(cur.grad, q);
1109 if (!(slope < 0.0)) {
1110 pairs.clear();
1111 q = cur.grad;
1112 scale(q, dtau / 4.0);
1113 slope = -dot(cur.grad, q);
1114 }
1115 double step = 1.0;
1116 ActionEval next;
1117 std::vector<VectorXd> trial(x.size());
1118 bool accepted = false;
1119 for (int ls = 0; ls < 30; ++ls) {
1120 for (size_t k = 0; k < x.size(); ++k) {
1121 trial[k] = x[k] - step * q[k];
1122 }
1123 next = evaluateAction(trial, start, end, vEnds[0], vEnds[1], dtau,
1124 potential);
1125 // Near the minimum the action changes by less than its round-off;
1126 // there a step that shrinks the gradient is progress too.
1127 const bool armijo = next.action <= cur.action + 1e-4 * step * slope;
1128 const bool flat = std::abs(next.action - cur.action) <=
1129 1e-13 * std::max(1.0, std::abs(cur.action));
1130 if (armijo ||
1131 (flat && largestBeadNorm(next.grad) < largestBeadNorm(cur.grad))) {
1132 accepted = true;
1133 break;
1134 }
1135 step *= 0.5;
1136 }
1137 if (!accepted) {
1138 break;
1139 }
1140 std::vector<VectorXd> sk(x.size()), yk(x.size());
1141 for (size_t k = 0; k < x.size(); ++k) {
1142 sk[k] = trial[k] - x[k];
1143 yk[k] = next.grad[k] - cur.grad[k];
1144 }
1145 if (dot(sk, yk) > 0.0) {
1146 pairs.emplace_back(std::move(sk), std::move(yk));
1147 if (static_cast<long>(pairs.size()) > options.memory) {
1148 pairs.pop_front();
1149 }
1150 }
1151 x = std::move(trial);
1152 cur = std::move(next);
1153 }
1154 if (!inst.converged &&
1155 largestBeadNorm(cur.grad) / dtau < options.forceTolerance) {
1156 inst.converged = true;
1157 }
1158
1159 inst.path.reserve(static_cast<size_t>(P + 1));
1160 inst.path.push_back(start);
1161 inst.path.insert(inst.path.end(), x.begin(), x.end());
1162 inst.path.push_back(end);
1163 inst.energies.reserve(static_cast<size_t>(P + 1));
1164 inst.energies.push_back(vEnds[0]);
1165 inst.energies.insert(inst.energies.end(), cur.v.begin(), cur.v.end());
1166 inst.energies.push_back(vEnds[1]);
1167 const double sWell = betaHbar * 0.5 * (vEnds[0] + vEnds[1]);
1168 inst.action = (cur.action - sWell) / kHbar;
1169 double s0 = 0.0;
1170 for (long j = 0; j < P; ++j) {
1171 s0 += (inst.path[static_cast<size_t>(j + 1)] -
1172 inst.path[static_cast<size_t>(j)])
1173 .squaredNorm();
1174 }
1175 inst.s0 = s0 / dtau;
1176 inst.symmetricEnough = std::abs(inst.asymmetry) * betaHbar / kHbar < 0.1;
1177 return inst;
1178}
1179
1180void instantonSplitting(Instanton &inst, const BeadHessian &hessian,
1181 const MatrixXd &hessStart, const MatrixXd &hessEnd) {
1182 const long P = static_cast<long>(inst.path.size()) - 1;
1183 if (P < 4 || !(inst.dtau > 0.0)) {
1184 throw std::invalid_argument("instantonSplitting: no optimised path");
1185 }
1186 const double dtau = inst.dtau;
1187 const double c = 1.0 / dtau;
1188 const long n = inst.path.front().size();
1189 const MatrixXd spring = 2.0 * c * MatrixXd::Identity(n, n);
1190
1191 std::vector<MatrixXd> diag;
1192 diag.reserve(static_cast<size_t>(P - 1));
1193 for (long j = 1; j < P; ++j) {
1194 const MatrixXd h = hessian(j, inst.path[static_cast<size_t>(j)]);
1195 if (h.rows() != n || h.cols() != n) {
1196 throw std::runtime_error("instantonSplitting: bead Hessian size");
1197 }
1198 diag.push_back(spring + dtau * 0.5 * (h + h.transpose()));
1199 }
1200 // The inertia comes from the Schur blocks (Haynsworth), so a path with
1201 // two negative modes is not mistaken for a minimum by the determinant's
1202 // sign.
1203 const HaynsworthChain chain(c, diag, true);
1204
1205 auto wellLogDet = [&](const MatrixXd &h) {
1206 const std::vector<MatrixXd> d(static_cast<size_t>(P - 1),
1207 spring + dtau * 0.5 * (h + h.transpose()));
1208 const HaynsworthChain well(c, d, true);
1209 if (well.negative() > 0) {
1210 throw std::runtime_error(
1211 "instantonSplitting: a well Hessian is not positive definite");
1212 }
1213 return well.logAbsDet();
1214 };
1215 const double logDetWell = 0.5 * (wellLogDet(hessStart) + wellLogDet(hessEnd));
1216
1217 // The zero mode is the kink's translation in imaginary time, along the
1218 // discrete velocity v; det' J = det J (v^T J^-1 v) for v its eigenvector.
1219 std::vector<VectorXd> v(static_cast<size_t>(P - 1));
1220 for (long j = 1; j < P; ++j) {
1221 v[static_cast<size_t>(j - 1)] = inst.path[static_cast<size_t>(j + 1)] -
1222 inst.path[static_cast<size_t>(j - 1)];
1223 }
1224 scale(v, 1.0 / std::sqrt(dot(v, v)));
1225 const double vJv = dot(v, chain.solve(v));
1226 // A zero mode just below zero is one negative eigenvalue the prime
1227 // leaves out; any other negative eigenvalue is a second unstable mode.
1228 if (chain.negative() - (vJv < 0.0 ? 1 : 0) != 0) {
1229 throw std::runtime_error(
1230 "instantonSplitting: the path is not a minimum of the action "
1231 "(a negative mode besides the kink's translation)");
1232 }
1233 inst.zeroMode = 1.0 / vJv;
1234 const double logDetPrime = chain.logAbsDet() + std::log(std::abs(vJv));
1235
1236 // Next eigenvalue: inverse iteration orthogonal to v.
1237 std::vector<VectorXd> w(v.size());
1238 for (size_t k = 0; k < w.size(); ++k) {
1239 w[k].resize(n);
1240 for (long i = 0; i < n; ++i) {
1241 w[k](i) = std::sin(0.7 * static_cast<double>(k) +
1242 1.3 * static_cast<double>(i) + 0.1);
1243 }
1244 }
1245 double lambda1 = 0.0;
1246 for (int it = 0; it < 40; ++it) {
1247 const double proj = dot(v, w);
1248 for (size_t k = 0; k < w.size(); ++k) {
1249 w[k] -= proj * v[k];
1250 }
1251 scale(w, 1.0 / std::sqrt(dot(w, w)));
1252 std::vector<VectorXd> z = chain.solve(w);
1253 lambda1 = 1.0 / dot(w, z);
1254 w = std::move(z);
1255 }
1256 inst.modeSeparation = std::abs(lambda1 / inst.zeroMode);
1257
1258 inst.delta0 = 2.0 * kHbar *
1259 std::sqrt(inst.s0 / (2.0 * std::numbers::pi * kHbar * dtau)) *
1260 std::exp(0.5 * (logDetWell - logDetPrime) - inst.action);
1261}
1262
1263double zeroPointDifference(const MatrixXd &hessStart, const MatrixXd &hessEnd,
1264 long rigidModes) {
1265 if (hessStart.rows() != hessEnd.rows() || rigidModes < 0 ||
1266 rigidModes > hessStart.rows()) {
1267 throw std::invalid_argument("zeroPointDifference: Hessians of one size and "
1268 "a rigid count within it");
1269 }
1270 auto zeroPoint = [&](const MatrixXd &h) {
1271 const Eigen::SelfAdjointEigenSolver<MatrixXd> es(0.5 * (h + h.transpose()),
1272 Eigen::EigenvaluesOnly);
1273 std::vector<double> lam(es.eigenvalues().data(),
1274 es.eigenvalues().data() + es.eigenvalues().size());
1275 std::sort(lam.begin(), lam.end(),
1276 [](double a, double b) { return std::abs(a) < std::abs(b); });
1277 double sum = 0.0;
1278 for (size_t k = static_cast<size_t>(rigidModes); k < lam.size(); ++k) {
1279 sum += std::sqrt(std::max(lam[k], 0.0));
1280 }
1281 return 0.5 * kHbar * sum;
1282 };
1283 return zeroPoint(hessEnd) - zeroPoint(hessStart);
1284}
1285
1286EnergyBias::EnergyBias(const VectorXd &start, const VectorXd &end, double delta)
1287 : start_(start),
1288 d_(end - start),
1289 dd_(d_.squaredNorm()),
1290 delta_(delta) {
1291 if (start.size() != end.size() || !(dd_ > 0.0) || !std::isfinite(delta)) {
1292 throw std::invalid_argument(
1293 "EnergyBias: two distinct minima of one dimension and a finite delta");
1294 }
1295}
1296
1297double EnergyBias::xi(const VectorXd &q) const {
1298 return std::clamp((q - start_).dot(d_) / dd_, 0.0, 1.0);
1299}
1300
1301double EnergyBias::value(const VectorXd &q) const {
1302 const double x = xi(q);
1303 return delta_ * x * x * x * (10.0 + x * (-15.0 + 6.0 * x));
1304}
1305
1306VectorXd EnergyBias::gradient(const VectorXd &q) const {
1307 const double x = xi(q);
1308 return (delta_ * 30.0 * x * x * (1.0 - x) * (1.0 - x) / dd_) * d_;
1309}
1310
1311MatrixXd EnergyBias::hessian(const VectorXd &q) const {
1312 const double x = xi(q);
1313 return (delta_ * 60.0 * x * (1.0 - x) * (1.0 - 2.0 * x) / (dd_ * dd_)) *
1314 (d_ * d_.transpose());
1315}
1316
1317double crossoverTemperature(const MatrixXd &hessSaddle) {
1318 const Eigen::SelfAdjointEigenSolver<MatrixXd> es(
1319 0.5 * (hessSaddle + hessSaddle.transpose()));
1320 const double lambda = es.eigenvalues()(0);
1321 if (!(lambda < 0.0)) {
1322 throw std::invalid_argument(
1323 "crossoverTemperature: the saddle Hessian has no negative eigenvalue");
1324 }
1325 return kHbar * std::sqrt(-lambda) / (2.0 * std::numbers::pi * kBoltzmann);
1326}
1327
1328namespace {
1329
1330struct RingEval {
1331 double u = 0.0; // U_N
1332 std::vector<double> v; // V at each bead
1333 std::vector<VectorXd> grad; // dU_N/dq at each bead
1334 std::vector<VectorXd> physicalGrad; // dV/dq without springs or bath
1335};
1336
1337} // namespace
1338
1339void addFrictionBath(const std::vector<VectorXd> &q, double &u,
1340 std::vector<VectorXd> &grad,
1341 const std::vector<double> &eta) {
1342 const size_t n = q.size();
1343 if (n < 2 || eta.empty() || grad.size() != n) {
1344 return;
1345 }
1346 std::vector<double> s(n, eta.size() == 1 ? eta[0] : 0.0);
1347 if (eta.size() == n) {
1348 s = eta;
1349 } else if (eta.size() != 1) {
1350 throw std::invalid_argument(
1351 "addFrictionBath: eta is one value or one per bead");
1352 }
1353 for (double value : s) {
1354 if (!(value >= 0.0)) {
1355 throw std::invalid_argument("addFrictionBath: eta must be non-negative");
1356 }
1357 }
1358 const long f = q[0].size();
1359 std::vector<double> root(n);
1360 for (size_t j = 0; j < n; ++j) {
1361 root[j] = std::sqrt(s[j]);
1362 }
1363 std::vector<VectorXd> g(n, VectorXd::Zero(f));
1364 std::vector<double> mid(n, 0.0);
1365 for (size_t j = 1; j < n; ++j) {
1366 mid[j] = 0.5 * (root[j - 1] + root[j]);
1367 g[j] = g[j - 1] + mid[j] * (q[j] - q[j - 1]);
1368 }
1369 std::vector<VectorXd> dUdg(n, VectorXd::Zero(f));
1370 const double scale = 1.0 / std::sqrt(static_cast<double>(n));
1371 for (size_t k = 1; k < n; ++k) {
1372 const double omega =
1373 2.0 * std::abs(std::sin(std::numbers::pi * static_cast<double>(k) /
1374 static_cast<double>(n)));
1375 VectorXd real = VectorXd::Zero(f);
1376 VectorXd imag = VectorXd::Zero(f);
1377 for (size_t j = 0; j < n; ++j) {
1378 const double ang = -2.0 * std::numbers::pi * static_cast<double>(k * j) /
1379 static_cast<double>(n);
1380 real += std::cos(ang) * g[j];
1381 imag += std::sin(ang) * g[j];
1382 }
1383 real *= scale;
1384 imag *= scale;
1385 u += 0.5 * omega * (real.squaredNorm() + imag.squaredNorm());
1386 for (size_t j = 0; j < n; ++j) {
1387 const double ang = -2.0 * std::numbers::pi * static_cast<double>(k * j) /
1388 static_cast<double>(n);
1389 dUdg[j] += omega * scale * (std::cos(ang) * real + std::sin(ang) * imag);
1390 }
1391 }
1392 for (size_t j = n - 1; j >= 1; --j) {
1393 dUdg[j - 1] += dUdg[j];
1394 if (j == 1) {
1395 break;
1396 }
1397 }
1398 for (size_t j = 1; j < n; ++j) {
1399 grad[j] += mid[j] * dUdg[j];
1400 grad[j - 1] -= mid[j] * dUdg[j];
1401 }
1402}
1403
1404namespace {
1405
1406std::vector<double> frictionEta(const RateInstantonOptions &options,
1407 size_t beads) {
1408 if (!options.friction) {
1409 return {};
1410 }
1411 if (options.frictionExplicit) {
1412 if (options.frictionEtaBeads.size() != beads) {
1413 throw std::invalid_argument(
1414 "rate instanton: explicit friction needs one eta per bead");
1415 }
1416 return options.frictionEtaBeads;
1417 }
1418 if (!(options.frictionEta > 0.0)) {
1419 return {};
1420 }
1421 return {options.frictionEta};
1422}
1423
1424RingEval evaluateRing(
1425 const std::vector<VectorXd> &x, double c, const BatchPotential &potential,
1426 double energyShift = 0.0, const std::vector<double> &eta = {},
1427 const std::vector<double> &discretization = {},
1428 const std::shared_ptr<const PhysicalQuadraticBath> &physicalBath = {}) {
1429 RingEval out;
1430 std::vector<VectorXd> gv;
1431 potential(x, out.v, gv);
1432 for (double &v : out.v) {
1433 v -= energyShift;
1434 }
1435 const size_t n = x.size();
1436 if (out.v.size() != n || gv.size() != n) {
1437 throw std::runtime_error(
1438 "rate instanton: potential returned the wrong count");
1439 }
1440 out.grad.resize(n);
1441 double spring = 0.0;
1442 if (discretization.empty()) {
1443 for (size_t j = 0; j < n; ++j) {
1444 const VectorXd &prev = x[(j + n - 1) % n];
1445 const VectorXd &next = x[(j + 1) % n];
1446 out.grad[j] = gv[j] + c * (2.0 * x[j] - prev - next);
1447 spring += (next - x[j]).squaredNorm();
1448 out.u += out.v[j];
1449 }
1450 out.u += 0.5 * c * spring;
1451 } else {
1452 if (discretization.size() != n) {
1453 throw std::invalid_argument(
1454 "link weights must be one positive value per bead");
1455 }
1456 for (size_t j = 0; j < n; ++j) {
1457 const double wj = discretization[j];
1458 const double wp = discretization[(j + n - 1) % n];
1459 if (!(wj > 0.0) || !(wp > 0.0) || !std::isfinite(wj) ||
1460 !std::isfinite(wp)) {
1461 throw std::invalid_argument(
1462 "link weights must be one positive value per bead");
1463 }
1464 const VectorXd &prev = x[(j + n - 1) % n];
1465 const VectorXd &next = x[(j + 1) % n];
1466 const double cj = c / wj;
1467 const double cp = c / wp;
1468 out.grad[j] = gv[j] + cj * (x[j] - next) + cp * (x[j] - prev);
1469 out.u += out.v[j] + 0.5 * cj * (next - x[j]).squaredNorm();
1470 }
1471 }
1472 if (!eta.empty()) {
1473 addFrictionBath(x, out.u, out.grad, eta);
1474 }
1475 if (physicalBath) {
1476 const auto bath = physicalBath->evaluate(x, c);
1477 out.u += bath.energy;
1478 for (size_t j = 0; j < n; ++j)
1479 out.grad[j] += bath.gradient[j];
1480 }
1481 out.physicalGrad = std::move(gv);
1482 return out;
1483}
1484
1485MatrixXd physicalStaticCurvature(const MatrixXd &h, const VectorXd &q,
1486 const RateInstantonOptions &options) {
1487 if (!options.physicalBath)
1488 return h;
1489 return h + options.physicalBath->evaluate({q}, 1.0, true).hessian;
1490}
1491
1492// Lowest curvature of the ring Hessian over vectors odd under j -> N-j and
1493// orthogonal to the cycle mode x[j+1] - x[j-1], at a mirror-symmetric ring
1494// of even N. A search confined to the even sector cannot see these. The
1495// products move the ring off the mirror, so `potential` evaluates every bead.
1496// Returns +inf when no odd direction is left to probe, or no Lanczos step
1497// is allowed.
1498double lowestOddMode(const std::vector<VectorXd> &x, const RingEval &here,
1499 double c, const BatchPotential &potential,
1500 std::vector<VectorXd> &mode, long steps, double eps,
1501 const std::vector<double> &eta = {}) {
1502 if (steps < 1) {
1503 return std::numeric_limits<double>::infinity();
1504 }
1505 const size_t n = x.size();
1506 const size_t m = n / 2;
1507 std::vector<VectorXd> cycle(n);
1508 for (size_t j = 0; j < n; ++j) {
1509 cycle[j] = x[(j + 1) % n] - x[(j + n - 1) % n];
1510 }
1511 auto odd = [&](std::vector<VectorXd> &q) {
1512 q[0].setZero();
1513 q[m].setZero();
1514 for (size_t a = 1; a < m; ++a) {
1515 const VectorXd half = 0.5 * (q[a] - q[n - a]);
1516 q[a] = half;
1517 q[n - a] = -half;
1518 }
1519 };
1520 odd(cycle);
1521 const double cnorm = std::sqrt(dot(cycle, cycle));
1522 if (cnorm > 0.0) {
1523 scale(cycle, 1.0 / cnorm);
1524 }
1525 auto project = [&](std::vector<VectorXd> &q) {
1526 odd(q);
1527 if (cnorm > 0.0) {
1528 const double p = dot(q, cycle);
1529 for (size_t j = 0; j < n; ++j) {
1530 q[j] -= p * cycle[j];
1531 }
1532 }
1533 };
1534 auto hv = [&](const std::vector<VectorXd> &u) {
1535 std::vector<VectorXd> xp(n);
1536 for (size_t j = 0; j < n; ++j) {
1537 xp[j] = x[j] + eps * u[j];
1538 }
1539 const RingEval e = evaluateRing(xp, c, potential, 0.0, eta);
1540 std::vector<VectorXd> out(n);
1541 for (size_t j = 0; j < n; ++j) {
1542 out[j] = (e.grad[j] - here.grad[j]) / eps;
1543 }
1544 project(out);
1545 return out;
1546 };
1547 // Start from the bead displacements with opposite signs on the two
1548 // halves: two copies of the turning region moving against each other.
1549 VectorXd mean = VectorXd::Zero(x[0].size());
1550 for (const auto &b : x) {
1551 mean += b;
1552 }
1553 mean /= static_cast<double>(n);
1554 std::vector<VectorXd> q(n);
1555 for (size_t j = 0; j < n; ++j) {
1556 q[j] = (j < m ? 1.0 : -1.0) * (x[j] - mean);
1557 }
1558 project(q);
1559 const double qnorm = std::sqrt(dot(q, q));
1560 if (!(qnorm > 1e-12)) {
1561 return std::numeric_limits<double>::infinity();
1562 }
1563 scale(q, 1.0 / qnorm);
1564 std::vector<std::vector<VectorXd>> basis;
1565 std::vector<double> alpha, beta;
1566 for (long k = 0; k < steps; ++k) {
1567 basis.push_back(q);
1568 std::vector<VectorXd> w = hv(q);
1569 alpha.push_back(dot(w, q));
1570 for (const auto &b : basis) {
1571 const double p = dot(w, b);
1572 for (size_t j = 0; j < n; ++j) {
1573 w[j] -= p * b[j];
1574 }
1575 }
1576 project(w);
1577 const double bnorm = std::sqrt(dot(w, w));
1578 if (!(bnorm > 1e-12) || k + 1 == steps) {
1579 break;
1580 }
1581 beta.push_back(bnorm);
1582 scale(w, 1.0 / bnorm);
1583 q = std::move(w);
1584 }
1585 const long dim = static_cast<long>(alpha.size());
1586 MatrixXd t = MatrixXd::Zero(dim, dim);
1587 for (long i = 0; i < dim; ++i) {
1588 t(i, i) = alpha[static_cast<size_t>(i)];
1589 if (i + 1 < dim) {
1590 t(i, i + 1) = t(i + 1, i) = beta[static_cast<size_t>(i)];
1591 }
1592 }
1593 const Eigen::SelfAdjointEigenSolver<MatrixXd> es(t);
1594 const VectorXd y = es.eigenvectors().col(0);
1595 mode.assign(n, VectorXd::Zero(x[0].size()));
1596 for (long i = 0; i < dim; ++i) {
1597 for (size_t j = 0; j < n; ++j) {
1598 mode[j] += y(i) * basis[static_cast<size_t>(i)][j];
1599 }
1600 }
1601 project(mode);
1602 scale(mode, 1.0 / std::sqrt(dot(mode, mode)));
1603 return es.eigenvalues()(0);
1604}
1605
1606// Distance along +dir (sign = 1) or -dir (sign = -1) from the saddle at which
1607// V has dropped by `drop`, from a scan in steps of h; the lowest point found
1608// when V never drops that far.
1609// Energies along +dir (sign = 1) or -dir (sign = -1) from the saddle, in
1610// steps of h.
1611std::vector<double> scanFromSaddle(const VectorXd &saddle, const VectorXd &dir,
1612 double sign, double h, long maxPoints,
1613 const BatchPotential &potential) {
1614 if (!(h > 0.0) || !std::isfinite(h) || maxPoints < 1) {
1615 throw std::invalid_argument(
1616 "rate instanton: the scan from the saddle needs a positive step and "
1617 "at least one point");
1618 }
1619 std::vector<VectorXd> pts;
1620 for (long k = 1; k <= maxPoints; ++k) {
1621 pts.push_back(saddle + sign * h * static_cast<double>(k) * dir);
1622 }
1623 std::vector<double> v;
1624 std::vector<VectorXd> g;
1625 potential(pts, v, g);
1626 if (v.size() != pts.size()) {
1627 throw std::runtime_error(
1628 "rate instanton: potential returned the wrong count");
1629 }
1630 return v;
1631}
1632
1633double turningDistance(const VectorXd &saddle, const VectorXd &dir,
1634 double vSaddle, double drop, double sign, double h,
1635 long maxPoints, const BatchPotential &potential) {
1636 if (!(drop > 0.0)) {
1637 return 0.0;
1638 }
1639 const std::vector<double> v =
1640 scanFromSaddle(saddle, dir, sign, h, maxPoints, potential);
1641 double prevV = vSaddle, prevS = 0.0, best = 0.0, bestV = vSaddle;
1642 for (long k = 0; k < maxPoints; ++k) {
1643 const double sk = h * static_cast<double>(k + 1);
1644 const double vk = v[static_cast<size_t>(k)];
1645 if (vk <= vSaddle - drop) {
1646 const double t = (prevV - (vSaddle - drop)) / (prevV - vk);
1647 return prevS + t * (sk - prevS);
1648 }
1649 if (vk < bestV) {
1650 bestV = vk;
1651 best = sk;
1652 }
1653 if (vk > prevV + 1e-12 && k > 0) {
1654 break; // past the minimum on this side
1655 }
1656 prevV = vk;
1657 prevS = sk;
1658 }
1659 return best;
1660}
1661
1662double sideDrop(const VectorXd &saddle, const VectorXd &dir, double vSaddle,
1663 double sign, double h, long maxPoints,
1664 const BatchPotential &potential) {
1665 const std::vector<double> v =
1666 scanFromSaddle(saddle, dir, sign, h, maxPoints, potential);
1667 double lowest = vSaddle;
1668 for (long k = 0; k < maxPoints; ++k) {
1669 const double vk = v[static_cast<size_t>(k)];
1670 if (vk > lowest + 1e-12 && k > 0 && lowest < vSaddle) {
1671 return vSaddle - lowest; // found this side's minimum
1672 }
1673 lowest = std::min(lowest, vk);
1674 }
1675 return vSaddle - lowest; // still falling: the drop to the last point
1676}
1677
1678struct RingMode {
1679 double theta = 0.0;
1680 double residual = 0.0;
1681 std::vector<VectorXd> vector;
1682};
1683
1684// Lowest Ritz pairs of a symmetric ring operator, full reorthogonalisation.
1685// `steps` at the dimension is the whole spectrum.
1686std::vector<RingMode> lowestRingModes(
1687 const std::function<std::vector<VectorXd>(const std::vector<VectorXd> &)>
1688 &apply,
1689 std::vector<VectorXd> start, long steps) {
1690 const size_t n = start.size();
1691 const long f = start.empty() ? 0 : start.front().size();
1692 const double n0 = std::sqrt(dot(start, start));
1693 if (!(n0 > 0.0) || f < 1) {
1694 throw std::runtime_error("instantonRate: Lanczos was given a zero vector");
1695 }
1696 scale(start, 1.0 / n0);
1697 std::vector<std::vector<VectorXd>> basis;
1698 std::vector<double> alpha;
1699 std::vector<double> beta;
1700 std::vector<VectorXd> q = std::move(start);
1701 for (long k = 0; k < steps; ++k) {
1702 basis.push_back(q);
1703 std::vector<VectorXd> w = apply(q);
1704 alpha.push_back(dot(w, q));
1705 for (int pass = 0; pass < 2; ++pass) {
1706 for (const auto &b : basis) {
1707 const double p = dot(w, b);
1708 for (size_t j = 0; j < n; ++j) {
1709 w[j] -= p * b[j];
1710 }
1711 }
1712 }
1713 const double bnorm = std::sqrt(dot(w, w));
1714 if (!(bnorm > 1e-14) || k + 1 == steps) {
1715 break;
1716 }
1717 beta.push_back(bnorm);
1718 scale(w, 1.0 / bnorm);
1719 q = std::move(w);
1720 }
1721 const long m = static_cast<long>(alpha.size());
1722 MatrixXd tridiag = MatrixXd::Zero(m, m);
1723 for (long i = 0; i < m; ++i) {
1724 tridiag(i, i) = alpha[static_cast<size_t>(i)];
1725 if (i + 1 < m) {
1726 tridiag(i, i + 1) = tridiag(i + 1, i) = beta[static_cast<size_t>(i)];
1727 }
1728 }
1729 const Eigen::SelfAdjointEigenSolver<MatrixXd> es(tridiag);
1730 std::vector<RingMode> modes;
1731 modes.reserve(static_cast<size_t>(m));
1732 for (long i = 0; i < m; ++i) {
1733 RingMode mode;
1734 mode.theta = es.eigenvalues()(i);
1735 mode.vector.assign(n, VectorXd::Zero(f));
1736 const VectorXd y = es.eigenvectors().col(i);
1737 for (long s = 0; s < m; ++s) {
1738 for (size_t j = 0; j < n; ++j) {
1739 mode.vector[j] += y(s) * basis[static_cast<size_t>(s)][j];
1740 }
1741 }
1742 scale(mode.vector, 1.0 / std::sqrt(dot(mode.vector, mode.vector)));
1743 const std::vector<VectorXd> applied = apply(mode.vector);
1744 double residual = 0.0;
1745 for (size_t j = 0; j < n; ++j) {
1746 residual += (applied[j] - mode.theta * mode.vector[j]).squaredNorm();
1747 }
1748 mode.residual = std::sqrt(residual);
1749 modes.push_back(std::move(mode));
1750 }
1751 return modes;
1752}
1753
1754// Factored cyclic ring Hessian: the open chain plus the corner coupling
1755// M between bead 0 and bead N-1.
1756// det(H_open + P M P^T) = det(H_open) det(M) det(M^{-1} + P^T H_open^{-1} P),
1757// and |det M| = c^{2f}. A singular ring makes the last factor zero.
1758struct CyclicFactor {
1759 BlockChain open;
1760 Eigen::PartialPivLU<ColMajorXd> cornerLu;
1761 double c;
1762 long f;
1763 long n;
1764 double logAbs;
1765 bool singular;
1766
1767 CyclicFactor(double cIn, const std::vector<MatrixXd> &diag)
1768 : open(cIn, diag),
1769 c(cIn),
1770 f(diag.front().rows()),
1771 n(static_cast<long>(diag.size())),
1772 logAbs(0.0),
1773 singular(false) {
1774 const MatrixXd eye = MatrixXd::Identity(f, f);
1775 const MatrixXd zero = MatrixXd::Zero(f, f);
1776 std::vector<MatrixXd> rhs(static_cast<size_t>(n), zero);
1777 rhs.front() = eye;
1778 const std::vector<MatrixXd> fromFirst = open.solve(rhs);
1779 rhs.front() = zero;
1780 rhs.back() = eye;
1781 const std::vector<MatrixXd> fromLast = open.solve(rhs);
1782 MatrixXd corner(2 * f, 2 * f);
1783 corner.topLeftCorner(f, f) = fromFirst.front();
1784 corner.bottomLeftCorner(f, f) = fromFirst.back();
1785 corner.topRightCorner(f, f) = fromLast.front();
1786 corner.bottomRightCorner(f, f) = fromLast.back();
1787 corner.topRightCorner(f, f) -= eye / c;
1788 corner.bottomLeftCorner(f, f) -= eye / c;
1789 cornerLu.compute(ColMajorXd(corner));
1790 logAbs = open.logAbsDet() + 2.0 * static_cast<double>(f) * std::log(c);
1791 const MatrixXd &upper = cornerLu.matrixLU();
1792 // A pivot at round-off of the corner's own scale is a singular ring: a
1793 // zero mode leaves exactly that, never an exact zero.
1794 const double floor = 1e-12 * corner.cwiseAbs().maxCoeff();
1795 for (long i = 0; i < upper.rows(); ++i) {
1796 const double pivot = upper(i, i);
1797 if (!(std::abs(pivot) > floor)) {
1798 singular = true;
1799 logAbs = -std::numeric_limits<double>::infinity();
1800 return;
1801 }
1802 logAbs += std::log(std::abs(pivot));
1803 }
1804 }
1805
1806 std::vector<VectorXd> solve(const std::vector<VectorXd> &rhs) const {
1807 if (singular || static_cast<long>(rhs.size()) != n) {
1808 throw std::runtime_error("cyclic ring: singular");
1809 }
1810 std::vector<VectorXd> y = open.solve(rhs);
1811 VectorXd g(2 * f);
1812 g.head(f) = y.front();
1813 g.tail(f) = y.back();
1814 const VectorXd z = cornerLu.solve(g);
1815 std::vector<VectorXd> bump(static_cast<size_t>(n), VectorXd::Zero(f));
1816 bump.front() = z.head(f);
1817 bump.back() = z.tail(f);
1818 const std::vector<VectorXd> corr = open.solve(bump);
1819 for (long j = 0; j < n; ++j) {
1820 y[static_cast<size_t>(j)] -= corr[static_cast<size_t>(j)];
1821 }
1822 return y;
1823 }
1824};
1825
1826// J = T + G K G^T over the chain T: the closure blocks (-c I between the
1827// last bead and the first, c / w_{N-1} under link weights) when `closed`,
1828// and symmetric rank-one terms kappa_i u_i u_i^T. Woodbury gives J^{-1} b,
1829// the determinant lemma ln|det J| and Haynsworth the inertia, all
1830// O(N f^3), so the N f by N f matrix is never formed.
1831class WoodburyRing {
1832public:
1833 WoodburyRing(double c, const std::vector<MatrixXd> &diag, bool closed,
1834 const std::vector<std::vector<VectorXd>> &extras,
1835 const std::vector<double> &kappas, bool spectrum,
1836 const std::vector<double> *weight = nullptr)
1837 : n_(static_cast<long>(diag.size())),
1838 f_(diag.front().rows()),
1839 closed_(closed),
1840 chain_(c, diag, spectrum, weight),
1841 extras_(extras) {
1842 const long base = closed ? 2 * f_ : 0;
1843 const long m = base + static_cast<long>(extras.size());
1844 kinv_ = MatrixXd::Zero(m, m);
1845 MatrixXd k = MatrixXd::Zero(m, m);
1846 if (closed) {
1847 const double cl = chain_.closingSpring();
1848 kinv_.block(0, f_, f_, f_) = -MatrixXd::Identity(f_, f_) / cl;
1849 kinv_.block(f_, 0, f_, f_) = -MatrixXd::Identity(f_, f_) / cl;
1850 k.block(0, f_, f_, f_) = -cl * MatrixXd::Identity(f_, f_);
1851 k.block(f_, 0, f_, f_) = -cl * MatrixXd::Identity(f_, f_);
1852 }
1853 for (size_t i = 0; i < extras.size(); ++i) {
1854 const long r = base + static_cast<long>(i);
1855 kinv_(r, r) = 1.0 / kappas[i];
1856 k(r, r) = kappas[i];
1857 }
1858 if (m == 0) {
1859 ok_ = true;
1860 logAbsDet_ = chain_.logAbsDet();
1861 negative_ = chain_.negative();
1862 return;
1863 }
1864 gtg_ = MatrixXd::Zero(m, m);
1865 for (long col = 0; col < m; ++col) {
1866 gtg_.col(col) = pieces(chain_.solve(column(col)));
1867 }
1868 woodbury_.compute(ColMajorXd(kinv_ + gtg_));
1869 ok_ = gtg_.array().isFinite().all();
1870 if (spectrum) {
1871 const Eigen::PartialPivLU<ColMajorXd> lu(
1872 ColMajorXd(MatrixXd::Identity(m, m) + k * gtg_));
1873 double logDet = 0.0;
1874 for (long i = 0; i < m; ++i) {
1875 const double u = lu.matrixLU()(i, i);
1876 if (u == 0.0) {
1877 ok_ = false;
1878 logAbsDet_ = -std::numeric_limits<double>::infinity();
1879 return;
1880 }
1881 logDet += std::log(std::abs(u));
1882 }
1883 logAbsDet_ = chain_.logAbsDet() + logDet;
1884 // neg(J) = neg(T) + neg(S) - neg(-K^{-1}), S = -K^{-1} - G^T T^{-1} G.
1885 const ColMajorXd sMat = -kinv_ - gtg_;
1886 const ColMajorXd sSym = 0.5 * (sMat + sMat.transpose());
1887 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(
1888 sSym, Eigen::EigenvaluesOnly);
1889 const ColMajorXd kn = -kinv_;
1890 const Eigen::SelfAdjointEigenSolver<ColMajorXd> ek(
1891 kn, Eigen::EigenvaluesOnly);
1892 negative_ = chain_.negative() + (es.eigenvalues().array() < 0.0).count() -
1893 (ek.eigenvalues().array() < 0.0).count();
1894 }
1895 }
1896 bool ok() const { return ok_; }
1897 std::vector<VectorXd> solve(const std::vector<VectorXd> &b) const {
1898 std::vector<VectorXd> tb = chain_.solve(b);
1899 if (kinv_.rows() == 0) {
1900 return tb;
1901 }
1902 const VectorXd y = woodbury_.solve(pieces(tb));
1903 const std::vector<VectorXd> gy = chain_.solve(expand(y));
1904 for (size_t j = 0; j < tb.size(); ++j) {
1905 tb[j] -= gy[j];
1906 }
1907 return tb;
1908 }
1909 double logAbsDet() const { return logAbsDet_; }
1910 long negative() const { return negative_; }
1911
1912private:
1913 std::vector<VectorXd> column(long col) const {
1914 const long base = closed_ ? 2 * f_ : 0;
1915 if (col < base) {
1916 std::vector<VectorXd> g(static_cast<size_t>(n_), VectorXd::Zero(f_));
1917 g[static_cast<size_t>(col < f_ ? 0 : n_ - 1)](col % f_) = 1.0;
1918 return g;
1919 }
1920 return extras_[static_cast<size_t>(col - base)];
1921 }
1922 VectorXd pieces(const std::vector<VectorXd> &x) const {
1923 const long base = closed_ ? 2 * f_ : 0;
1924 VectorXd out(base + static_cast<long>(extras_.size()));
1925 if (closed_) {
1926 out.head(f_) = x[0];
1927 out.segment(f_, f_) = x[static_cast<size_t>(n_ - 1)];
1928 }
1929 for (size_t i = 0; i < extras_.size(); ++i) {
1930 out(base + static_cast<long>(i)) = dot(extras_[i], x);
1931 }
1932 return out;
1933 }
1934 std::vector<VectorXd> expand(const VectorXd &y) const {
1935 const long base = closed_ ? 2 * f_ : 0;
1936 std::vector<VectorXd> g(static_cast<size_t>(n_), VectorXd::Zero(f_));
1937 if (closed_) {
1938 g[0] += y.head(f_);
1939 g[static_cast<size_t>(n_ - 1)] += y.segment(f_, f_);
1940 }
1941 for (size_t i = 0; i < extras_.size(); ++i) {
1942 const double w = y(base + static_cast<long>(i));
1943 for (long j = 0; j < n_; ++j) {
1944 g[static_cast<size_t>(j)] += w * extras_[i][static_cast<size_t>(j)];
1945 }
1946 }
1947 return g;
1948 }
1949
1950 long n_, f_;
1951 bool closed_;
1952 HaynsworthChain chain_;
1953 std::vector<std::vector<VectorXd>> extras_;
1954 MatrixXd kinv_, gtg_;
1955 Eigen::PartialPivLU<ColMajorXd> woodbury_;
1956 bool ok_ = false;
1957 double logAbsDet_ = 0.0;
1958 long negative_ = 0;
1959};
1960
1961// Diagonal blocks of the closed ring (H + 2 c I) or of the half chain from
1962// one turning point to the other (end blocks H / 2 + c I).
1963std::vector<MatrixXd>
1964ringDiagonal(const std::vector<MatrixXd> &physical, double c, bool half,
1965 const std::vector<double> *weight = nullptr) {
1966 const long beads = static_cast<long>(physical.size());
1967 const long f = physical.front().rows();
1968 const bool weighted = weight != nullptr && !weight->empty();
1969 if (weighted && (half || static_cast<long>(weight->size()) != beads)) {
1970 throw std::invalid_argument(
1971 "link weights must be one positive value per bead");
1972 }
1973 std::vector<MatrixXd> diag(static_cast<size_t>(beads));
1974 for (long j = 0; j < beads; ++j) {
1975 const bool end = half && (j == 0 || j + 1 == beads);
1976 MatrixXd block = 0.5 * (physical[static_cast<size_t>(j)] +
1977 physical[static_cast<size_t>(j)].transpose());
1978 if (end) {
1979 block *= 0.5;
1980 }
1981 double add = end ? c : 2.0 * c;
1982 if (weighted) {
1983 const double wj = (*weight)[static_cast<size_t>(j)];
1984 const double wp = (*weight)[static_cast<size_t>((j + beads - 1) % beads)];
1985 if (!(wj > 0.0) || !(wp > 0.0) || !std::isfinite(wj) ||
1986 !std::isfinite(wp)) {
1987 throw std::invalid_argument(
1988 "link weights must be one positive value per bead");
1989 }
1990 add = c / wj + c / wp;
1991 }
1992 block += add * MatrixXd::Identity(f, f);
1993 diag[static_cast<size_t>(j)] = block;
1994 }
1995 return diag;
1996}
1997
1998// (diag - c neighbours) v for the closed ring or the open half chain.
1999std::vector<VectorXd>
2000applyDiagonal(const std::vector<MatrixXd> &diag, double c, bool closed,
2001 const std::vector<VectorXd> &v,
2002 const std::vector<double> *weight = nullptr) {
2003 const size_t n = v.size();
2004 const bool weighted = weight != nullptr && !weight->empty();
2005 if (weighted && (!closed || weight->size() != n)) {
2006 throw std::invalid_argument(
2007 "link weights must be one positive value per bead");
2008 }
2009 std::vector<VectorXd> out(n);
2010 for (size_t j = 0; j < n; ++j) {
2011 out[j] = diag[j] * v[j];
2012 const size_t prev = (j + n - 1) % n;
2013 const size_t next = (j + 1) % n;
2014 double cPrev = c;
2015 double cNext = c;
2016 if (weighted) {
2017 const double wp = (*weight)[prev];
2018 const double wj = (*weight)[j];
2019 if (!(wp > 0.0) || !(wj > 0.0)) {
2020 throw std::invalid_argument(
2021 "link weights must be one positive value per bead");
2022 }
2023 cPrev = c / wp;
2024 cNext = c / wj;
2025 }
2026 if (j > 0 || closed) {
2027 out[j] -= cPrev * v[prev];
2028 }
2029 if (j + 1 < n || closed) {
2030 out[j] -= cNext * v[next];
2031 }
2032 }
2033 return out;
2034}
2035
2036} // namespace
2037
2038namespace {
2039
2040void requireCyclicBlocks(double c, const std::vector<MatrixXd> &diag,
2041 const char *what) {
2042 if (!(c > 0.0) || diag.empty()) {
2043 throw std::invalid_argument(std::string(what) +
2044 ": need a positive spring constant and blocks");
2045 }
2046 const long f = diag.front().rows();
2047 const long n = static_cast<long>(diag.size());
2048 if (f < 1 || n < 2) {
2049 throw std::invalid_argument(std::string(what) +
2050 ": need at least two beads and one coordinate");
2051 }
2052 for (const auto &block : diag) {
2053 if (block.rows() != f || block.cols() != f) {
2054 throw std::invalid_argument(std::string(what) +
2055 ": the blocks differ in size");
2056 }
2057 }
2058}
2059
2060} // namespace
2061
2062RingSpectrum ringSpectrum(const std::vector<MatrixXd> &beadHessians, double c,
2063 const std::vector<VectorXd> &tau) {
2064 if (beadHessians.empty() || beadHessians.size() != tau.size()) {
2065 throw std::invalid_argument(
2066 "ringSpectrum: N bead Hessians and N tau blocks");
2067 }
2068 const std::vector<MatrixXd> diag = ringDiagonal(beadHessians, c, false);
2069 // Lifted by the spring, as the rate lifts it: a unit lift would leave
2070 // ln|1 + lambda_0| in det', a unit-dependent amount.
2071 const WoodburyRing ring(c, diag, true, {tau}, {c}, true);
2072 if (!ring.ok()) {
2073 throw std::runtime_error("ringSpectrum: singular ring");
2074 }
2075 RingSpectrum out;
2076 out.zeroEigenvalue = dot(tau, applyDiagonal(diag, c, true, tau));
2077 out.logDetPrime =
2078 ring.logAbsDet() - std::log(std::abs(c + out.zeroEigenvalue));
2079 out.negativeModes = ring.negative();
2080 return out;
2081}
2082
2083double cyclicRingLogAbsDet(double c, const std::vector<MatrixXd> &diag) {
2084 requireCyclicBlocks(c, diag, "cyclicRingLogAbsDet");
2085 return CyclicFactor(c, diag).logAbs;
2086}
2087
2088std::vector<VectorXd> cyclicRingSolve(double c,
2089 const std::vector<MatrixXd> &diag,
2090 const std::vector<VectorXd> &rhs) {
2091 requireCyclicBlocks(c, diag, "cyclicRingSolve");
2092 if (static_cast<long>(rhs.size()) != static_cast<long>(diag.size())) {
2093 throw std::invalid_argument(
2094 "cyclicRingSolve: one right-hand side per bead");
2095 }
2096 for (const auto &row : rhs) {
2097 if (row.size() != diag.front().rows()) {
2098 throw std::invalid_argument(
2099 "cyclicRingSolve: the right-hand side does not match the blocks");
2100 }
2101 }
2102 return CyclicFactor(c, diag).solve(rhs);
2103}
2104
2105namespace {
2106
2107// Central difference of dV/dq. One batch of 2 f displaced beads.
2108MatrixXd fdPhysicalHessian(const VectorXd &q, const BatchPotential &potential,
2109 double eps) {
2110 const long f = q.size();
2111 std::vector<VectorXd> pts;
2112 pts.reserve(static_cast<size_t>(2 * f));
2113 for (long a = 0; a < f; ++a) {
2114 VectorXd qp = q;
2115 VectorXd qm = q;
2116 qp[a] += eps;
2117 qm[a] -= eps;
2118 pts.push_back(std::move(qp));
2119 pts.push_back(std::move(qm));
2120 }
2121 std::vector<double> v;
2122 std::vector<VectorXd> g;
2123 potential(pts, v, g);
2124 if (static_cast<long>(g.size()) != 2 * f) {
2125 throw std::runtime_error(
2126 "rate instanton: the Hessian sample returned the wrong count");
2127 }
2128 MatrixXd h(f, f);
2129 for (long a = 0; a < f; ++a) {
2130 h.col(a) =
2131 (g[static_cast<size_t>(2 * a)] - g[static_cast<size_t>(2 * a + 1)]) /
2132 (2.0 * eps);
2133 }
2134 return (0.5 * (h + h.transpose())).eval();
2135}
2136
2137// Bofill mix of Powell's symmetric Broyden and SR1. H is d2V/dq2.
2138void bofillUpdate(MatrixXd &h, const VectorXd &dq, const VectorXd &dg) {
2139 const double dq2 = dq.squaredNorm();
2140 if (!(dq2 > 1e-24)) {
2141 return;
2142 }
2143 const VectorXd r = dg - h * dq;
2144 const double rq = r.dot(dq);
2145 const double r2 = r.squaredNorm();
2146 const double phi = r2 * dq2 > 1e-30 ? (rq * rq) / (r2 * dq2) : 0.0;
2147 const double inv = 1.0 / dq2;
2148 h.noalias() += (1.0 - phi) * inv *
2149 (r * dq.transpose() + dq * r.transpose() -
2150 (rq * inv) * (dq * dq.transpose()));
2151 if (std::abs(rq) > 1e-12 * std::sqrt(std::max(0.0, r2 * dq2))) {
2152 h.noalias() += (phi / rq) * (r * r.transpose());
2153 }
2154 h = (0.5 * (h + h.transpose())).eval();
2155}
2156
2157// Eigenvalues below -1e-6 of the largest |lambda|. Rigid-body directions
2158// sit at zero to round-off, and their sign carries no curvature; counting
2159// it would make the allowed count, and with it the update below, depend on
2160// noise in the last digits of the geometry.
2161long clearlyNegative(const VectorXd &lam) {
2162 if (lam.size() == 0) {
2163 return 0;
2164 }
2165 const double span = lam.cwiseAbs().maxCoeff();
2166 return (lam.array() < -1e-6 * span).count();
2167}
2168
2169long negativeEigenvalues(const MatrixXd &h) {
2170 const ColMajorXd sym = 0.5 * (h + h.transpose());
2171 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(sym,
2172 Eigen::EigenvaluesOnly);
2173 return clearlyNegative(es.eigenvalues());
2174}
2175
2176// A Bofill update that keeps the block's count of negative curvatures at
2177// `allowed`, the count the last exact (finite-difference) block had. A
2178// secant pair carries curvature along one direction only; on a block of
2179// many coordinates with noisy gradient differences it can open new
2180// negative directions the surface does not have, and those then steer the
2181// ring's index-1 step. Extra negative eigenvalues, the least negative
2182// first, are mirrored to |lambda|. A negative `allowed` leaves the update
2183// alone.
2184void inertiaKeepingUpdate(MatrixXd &h, const VectorXd &dq, const VectorXd &dg,
2185 long allowed) {
2186 bofillUpdate(h, dq, dg);
2187 if (allowed < 0) {
2188 return;
2189 }
2190 const ColMajorXd sym = 0.5 * (h + h.transpose());
2191 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(sym);
2192 const VectorXd lam = es.eigenvalues();
2193 const long negative = clearlyNegative(lam);
2194 if (negative <= allowed) {
2195 return;
2196 }
2197 VectorXd fixed = lam;
2198 // Ascending order: indices allowed .. negative - 1 are the extra ones.
2199 for (long i = allowed; i < negative; ++i) {
2200 fixed(i) = std::abs(lam(i));
2201 }
2202 h = es.eigenvectors() * fixed.asDiagonal() * es.eigenvectors().transpose();
2203}
2204
2205VectorXd packBeads(const std::vector<VectorXd> &x) {
2206 const long f = x.front().size();
2207 VectorXd flat(static_cast<long>(x.size()) * f);
2208 for (long j = 0; j < static_cast<long>(x.size()); ++j) {
2209 flat.segment(j * f, f) = x[static_cast<size_t>(j)];
2210 }
2211 return flat;
2212}
2213
2214void addPacked(std::vector<VectorXd> &x, const VectorXd &step) {
2215 const long f = x.front().size();
2216 for (long j = 0; j < static_cast<long>(x.size()); ++j) {
2217 x[static_cast<size_t>(j)] += step.segment(j * f, f);
2218 }
2219}
2220
2221double packedBeadNorm(const VectorXd &step, long f) {
2222 double big = 0.0;
2223 const long n = step.size() / f;
2224 for (long j = 0; j < n; ++j) {
2225 big = std::max(big, step.segment(j * f, f).norm());
2226 }
2227 return big;
2228}
2229
2230bool finiteBeads(const std::vector<VectorXd> &x) {
2231 for (const auto &q : x) {
2232 if (!q.array().isFinite().all()) {
2233 return false;
2234 }
2235 }
2236 return true;
2237}
2238
2239// Bead velocity times beta_N hbar: (q_{j+1} - q_{j-1}) / 2 on a uniform
2240// ring, the three-point derivative over the two time steps under link
2241// weights.
2242std::vector<VectorXd> beadVelocities(const std::vector<VectorXd> &x,
2243 const std::vector<double> *weight) {
2244 const size_t n = x.size();
2245 const bool weighted = weight != nullptr && !weight->empty();
2246 std::vector<VectorXd> out(n);
2247 for (size_t j = 0; j < n; ++j) {
2248 const size_t prev = (j + n - 1) % n;
2249 const size_t next = (j + 1) % n;
2250 if (!weighted) {
2251 out[j] = 0.5 * (x[next] - x[prev]);
2252 } else {
2253 const double a = (*weight)[prev];
2254 const double b = (*weight)[j];
2255 out[j] = (a * a * (x[next] - x[j]) + b * b * (x[j] - x[prev])) /
2256 (a * b * (a + b));
2257 }
2258 }
2259 return out;
2260}
2261
2262// Normalised bead velocity. Empty when the beads coincide.
2263VectorXd timeTranslation(const std::vector<VectorXd> &x,
2264 const std::vector<double> *weight = nullptr) {
2265 const long n = static_cast<long>(x.size());
2266 const long f = x.front().size();
2267 const std::vector<VectorXd> vel = beadVelocities(x, weight);
2268 VectorXd tau(n * f);
2269 for (long j = 0; j < n; ++j) {
2270 tau.segment(j * f, f) = vel[static_cast<size_t>(j)];
2271 }
2272 const double nrm = tau.norm();
2273 if (!(nrm > 0.0)) {
2274 return VectorXd();
2275 }
2276 tau /= nrm;
2277 return tau;
2278}
2279
2280// B_N, sum_j |q_{j+1} - q_j|^2: the squared speed of the ring's time shift
2281// times (beta_N hbar)^2. Link j of a weighted ring lasts w_j, so its
2282// velocity is the difference over w_j.
2283double ringSpeed(const std::vector<VectorXd> &x,
2284 const std::vector<double> &weight) {
2285 if (!weight.empty() && weight.size() != x.size()) {
2286 throw std::invalid_argument(
2287 "link weights must be one positive value per bead");
2288 }
2289 double b = 0.0;
2290 for (size_t j = 0; j < x.size(); ++j) {
2291 const double d = (x[(j + 1) % x.size()] - x[j]).squaredNorm();
2292 b += weight.empty() ? d : d / (weight[j] * weight[j]);
2293 }
2294 return b;
2295}
2296
2297struct Climb {
2298 long index = -1;
2299 double curvature = 0.0;
2300 long negative = 0;
2301};
2302
2303// Cosine between the turning points, opened by (1 - T / Tc) of the lower
2304// barrier, over each bead's imaginary time. The far turning point sits on
2305// bead 0.
2306std::vector<VectorXd> cosineSeed(const VectorXd &saddle, const VectorXd &dir,
2307 double lambda0, double temperature,
2308 double crossover, long nBeads,
2309 const BatchPotential &potential,
2310 const std::vector<double> &weight = {}) {
2311 if (!weight.empty() && static_cast<long>(weight.size()) != nBeads) {
2312 throw std::invalid_argument(
2313 "link weights must be one positive value per bead");
2314 }
2315 std::vector<double> v0;
2316 std::vector<VectorXd> g0;
2317 potential({saddle}, v0, g0);
2318 const double vS = v0.at(0);
2319 const double h = 0.25 * std::sqrt(2.0 * kBoltzmann * crossover / -lambda0);
2320 const long pts = 200;
2321 const double dPlus = sideDrop(saddle, dir, vS, 1.0, h, pts, potential);
2322 const double dMinus = sideDrop(saddle, dir, vS, -1.0, h, pts, potential);
2323 const double dMin = std::min(dPlus, dMinus);
2324 const double drop = (1.0 - temperature / crossover) *
2325 (dMin > 0.0 ? dMin : kBoltzmann * crossover);
2326 const double sPlus =
2327 turningDistance(saddle, dir, vS, drop, 1.0, h, pts, potential);
2328 const double sMinus =
2329 turningDistance(saddle, dir, vS, drop, -1.0, h, pts, potential);
2330 std::vector<VectorXd> guess(static_cast<size_t>(nBeads));
2331 double time = 0.0;
2332 for (long j = 0; j < nBeads; ++j) {
2333 const double ct =
2334 std::cos(2.0 * std::numbers::pi * time / static_cast<double>(nBeads));
2335 guess[static_cast<size_t>(j)] =
2336 saddle + dir * (ct >= 0.0 ? sPlus * ct : sMinus * ct);
2337 time += weight.empty() ? 1.0 : weight[static_cast<size_t>(j)];
2338 }
2339 return guess;
2340}
2341
2342// Index-1 Newton step through the block chain: a negative climb eigenvalue
2343// stays and a raw Newton step climbs it; a positive one is flipped, as is
2344// every other negative Ritz value off the cycle; a tiny one is parked at a
2345// spring-sized curvature. The cycle keeps its component of the step, on its
2346// own curvature, and is lifted to a spring-sized one only while that
2347// curvature is near zero; the rigid modes are projected out. Each flip is a
2348// rank-one term in the Woodbury correction, so the solve stays O(N f^3).
2349VectorXd chainIndexOneStep(const std::vector<RingMode> &ritz,
2350 const Climb &climb,
2351 const std::vector<MatrixXd> &diag, double spring,
2352 bool closed, const std::vector<VectorXd> &grad,
2353 const VectorXd &tau,
2354 const std::vector<std::vector<VectorXd>> &nullRing,
2355 const std::vector<double> *weight = nullptr,
2356 const std::vector<double> &eta = {},
2357 const MatrixXd &physicalBathHessian = MatrixXd()) {
2358 if (climb.index < 0 || ritz.empty() || grad.empty()) {
2359 return VectorXd();
2360 }
2361 const long f = grad.front().size();
2362 const long dim = static_cast<long>(grad.size()) * f;
2363 const double cut = -1e-8 * std::max(1.0, spring);
2364 const double tiny = 1e-8 * std::max(1.0, spring);
2365 const double parked = std::max(1.0, spring);
2366 std::vector<std::vector<VectorXd>> extras;
2367 std::vector<double> kappas;
2368 std::vector<VectorXd> tauRing;
2369 if (tau.size() == dim) {
2370 tauRing.assign(grad.size(), VectorXd::Zero(f));
2371 for (size_t j = 0; j < grad.size(); ++j) {
2372 tauRing[j] = tau.segment(static_cast<long>(j) * f, f);
2373 }
2374 // On a discrete ring the time shift has a small curvature of its own,
2375 // and the stationary ring is where Newton on that curvature leads; the
2376 // lift is only for a cycle too flat to solve with.
2377 double cycleCurvature = 0.0;
2378 for (const auto &m : ritz) {
2379 if (std::abs(dot(m.vector, tauRing)) > 0.5) {
2380 cycleCurvature = m.theta;
2381 break;
2382 }
2383 }
2384 if (std::abs(cycleCurvature) <= 1e-6 * std::max(1.0, spring)) {
2385 extras.push_back(tauRing);
2386 kappas.push_back(spring);
2387 }
2388 }
2389 // The rigid ring motions are lifted like the cycle.
2390 auto onNull = [&](const std::vector<VectorXd> &m) {
2391 for (const auto &r : nullRing) {
2392 if (std::abs(dot(m, r)) > 0.5) {
2393 return true;
2394 }
2395 }
2396 return false;
2397 };
2398 for (const auto &r : nullRing) {
2399 extras.push_back(r);
2400 kappas.push_back(spring);
2401 }
2402 for (size_t i = 0; i < ritz.size(); ++i) {
2403 if (!tauRing.empty() && std::abs(dot(ritz[i].vector, tauRing)) > 0.5) {
2404 continue;
2405 }
2406 if (onNull(ritz[i].vector)) {
2407 continue;
2408 }
2409 const double li = ritz[i].theta;
2410 const bool isClimb = static_cast<long>(i) == climb.index;
2411 if ((isClimb && li > 0.0) || (!isClimb && li < cut)) {
2412 extras.push_back(ritz[i].vector);
2413 kappas.push_back(-2.0 * li);
2414 } else if (!isClimb && std::abs(li) <= tiny) {
2415 extras.push_back(ritz[i].vector);
2416 kappas.push_back(parked - li);
2417 }
2418 }
2419 std::vector<VectorXd> rhs = grad;
2420 scale(rhs, -1.0);
2421 // The operator the step solves with: the ring plus every rank-one term.
2422 auto applyShifted = [&](const std::vector<VectorXd> &x) {
2423 std::vector<VectorXd> out = applyDiagonal(diag, spring, closed, x, weight);
2424 if (physicalBathHessian.size()) {
2425 const VectorXd added = physicalBathHessian * packBeads(x);
2426 for (size_t j = 0; j < out.size(); ++j)
2427 out[j] += added.segment(j * f, f);
2428 }
2429 if (!eta.empty()) {
2430 double energy = 0.0;
2431 addFrictionBath(x, energy, out, eta);
2432 }
2433 for (size_t i = 0; i < extras.size(); ++i) {
2434 const double w = kappas[i] * dot(extras[i], x);
2435 for (size_t j = 0; j < out.size(); ++j) {
2436 out[j] += w * extras[i][j];
2437 }
2438 }
2439 return out;
2440 };
2441 const double rhsNorm = std::sqrt(dot(rhs, rhs));
2442 std::vector<VectorXd> stepRing;
2443 bool solved = false;
2444 try {
2445 if (dim <= kDenseRing || !eta.empty() || physicalBathHessian.size()) {
2446 throw std::runtime_error("dense ring or nonlocal bath: dense solve");
2447 }
2448 const WoodburyRing ring(spring, diag, closed, extras, kappas, false,
2449 weight);
2450 if (ring.ok()) {
2451 stepRing = ring.solve(rhs);
2452 // Cutting the ring open can leave a Schur pivot near zero next to
2453 // the barrier, and the Woodbury solve then loses digits; iterative
2454 // refinement against the exact operator recovers them.
2455 for (int pass = 0; pass < 4; ++pass) {
2456 std::vector<VectorXd> r = applyShifted(stepRing);
2457 for (size_t j = 0; j < r.size(); ++j) {
2458 r[j] = rhs[j] - r[j];
2459 }
2460 const double rn = std::sqrt(dot(r, r));
2461 if (!std::isfinite(rn)) {
2462 break;
2463 }
2464 if (rn <= 1e-10 * std::max(1.0, rhsNorm)) {
2465 solved = true;
2466 break;
2467 }
2468 const std::vector<VectorXd> dx = ring.solve(r);
2469 for (size_t j = 0; j < stepRing.size(); ++j) {
2470 stepRing[j] += dx[j];
2471 }
2472 }
2473 }
2474 } catch (const std::runtime_error &) {
2475 solved = false;
2476 }
2477 if (!solved && dim <= kDenseRing) {
2478 // A small ring is cheap to solve densely when the chain cannot.
2479 const long n = static_cast<long>(grad.size());
2480 ColMajorXd jt = ColMajorXd::Zero(dim, dim);
2481 for (long col = 0; col < dim; ++col) {
2482 std::vector<VectorXd> e(static_cast<size_t>(n), VectorXd::Zero(f));
2483 e[static_cast<size_t>(col / f)](col % f) = 1.0;
2484 jt.col(col) = packBeads(applyShifted(e));
2485 }
2486 const Eigen::PartialPivLU<ColMajorXd> lu(jt);
2487 const VectorXd x = lu.solve(packBeads(rhs));
2488 stepRing.assign(static_cast<size_t>(n), VectorXd::Zero(f));
2489 for (long j = 0; j < n; ++j) {
2490 stepRing[static_cast<size_t>(j)] = x.segment(j * f, f);
2491 }
2492 solved = x.array().isFinite().all();
2493 }
2494 if (!solved && stepRing.empty()) {
2495 return VectorXd();
2496 }
2497 // The cycle component stays: a gradient along it has to be stepped out.
2498 VectorXd step = packBeads(stepRing);
2499 for (const auto &r : nullRing) {
2500 const VectorXd rf = packBeads(r);
2501 if (rf.size() == step.size()) {
2502 step -= step.dot(rf) * rf;
2503 }
2504 }
2505 if (!step.array().isFinite().all()) {
2506 return VectorXd();
2507 }
2508 return step;
2509}
2510
2511// Non-increasing isotonic regression (pool adjacent violators).
2512std::vector<double> pavaNonIncreasing(const std::vector<double> &values) {
2513 const long n = static_cast<long>(values.size());
2514 struct Block {
2515 long start;
2516 long end;
2517 double average;
2518 double weight;
2519 };
2520 std::vector<Block> blocks;
2521 blocks.reserve(static_cast<size_t>(n));
2522 for (long i = 0; i < n; ++i) {
2523 blocks.push_back(Block{i, i, -values[static_cast<size_t>(i)], 1.0});
2524 while (blocks.size() >= 2 &&
2525 blocks[blocks.size() - 2].average > blocks.back().average) {
2526 const Block b = blocks.back();
2527 blocks.pop_back();
2528 Block &a = blocks.back();
2529 const double w = a.weight + b.weight;
2530 a.average = (a.average * a.weight + b.average * b.weight) / w;
2531 a.end = b.end;
2532 a.weight = w;
2533 }
2534 }
2535 std::vector<double> out(static_cast<size_t>(n));
2536 for (const Block &b : blocks) {
2537 for (long i = b.start; i <= b.end; ++i) {
2538 out[static_cast<size_t>(i)] = -b.average;
2539 }
2540 }
2541 return out;
2542}
2543
2544// Beads 0..last move along the unit vector dir until that coordinate is
2545// monotone.
2546// The sense follows the two ends, so an arbitrary eigenvector sign is harmless.
2547void projectMonotonePrefix(std::vector<VectorXd> &q, long last,
2548 const VectorXd &dir) {
2549 if (last < 1 || q.empty() || dir.size() != q.front().size()) {
2550 return;
2551 }
2552 const long m = last;
2553 std::vector<double> s(static_cast<size_t>(m + 1));
2554 for (long j = 0; j <= m; ++j) {
2555 s[static_cast<size_t>(j)] = dir.dot(q[static_cast<size_t>(j)]);
2556 }
2557 std::vector<double> target;
2558 if (s.front() >= s.back()) {
2559 target = pavaNonIncreasing(s);
2560 } else {
2561 std::vector<double> flipped(s.size());
2562 for (size_t j = 0; j < s.size(); ++j) {
2563 flipped[j] = -s[j];
2564 }
2565 target = pavaNonIncreasing(flipped);
2566 for (double &v : target) {
2567 v = -v;
2568 }
2569 }
2570 for (long j = 0; j <= m; ++j) {
2571 q[static_cast<size_t>(j)] +=
2572 (target[static_cast<size_t>(j)] - s[static_cast<size_t>(j)]) * dir;
2573 }
2574}
2575
2582std::vector<std::vector<VectorXd>>
2583ringRigidBasis(const std::vector<VectorXd> &q,
2584 const std::vector<double> &sqrtMasses, const VectorXd &reference,
2585 const std::array<bool, 3> &rotations) {
2586 std::vector<std::vector<VectorXd>> out;
2587 const long nAtoms = static_cast<long>(sqrtMasses.size());
2588 if (nAtoms == 0 || q.empty() || reference.size() != 3 * nAtoms ||
2589 q.front().size() != 3 * nAtoms) {
2590 return out;
2591 }
2592 const long nb = static_cast<long>(q.size());
2593 // Cartesian positions and the ring's centre of mass.
2594 Eigen::Vector3d centre = Eigen::Vector3d::Zero();
2595 double total = 0.0;
2596 for (long j = 0; j < nb; ++j) {
2597 for (long k = 0; k < nAtoms; ++k) {
2598 const double sm = sqrtMasses[static_cast<size_t>(k)];
2599 const Eigen::Vector3d r =
2600 reference.segment<3>(3 * k) +
2601 q[static_cast<size_t>(j)].segment<3>(3 * k) / sm;
2602 centre += sm * sm * r;
2603 total += sm * sm;
2604 }
2605 }
2606 centre /= total;
2607 std::vector<int> kinds{0, 1, 2};
2608 for (int c = 0; c < 3; ++c) {
2609 if (rotations[static_cast<size_t>(c)]) {
2610 kinds.push_back(3 + c);
2611 }
2612 }
2613 const long dim = nb * 3 * nAtoms;
2614 MatrixXd g = MatrixXd::Zero(dim, static_cast<long>(kinds.size()));
2615 for (size_t col = 0; col < kinds.size(); ++col) {
2616 const int kind = kinds[col];
2617 for (long j = 0; j < nb; ++j) {
2618 for (long k = 0; k < nAtoms; ++k) {
2619 const double sm = sqrtMasses[static_cast<size_t>(k)];
2620 Eigen::Vector3d d = Eigen::Vector3d::Zero();
2621 if (kind < 3) {
2622 d(kind) = sm;
2623 } else {
2624 const Eigen::Vector3d r =
2625 reference.segment<3>(3 * k) +
2626 q[static_cast<size_t>(j)].segment<3>(3 * k) / sm;
2627 Eigen::Vector3d e = Eigen::Vector3d::Zero();
2628 e(kind - 3) = 1.0;
2629 d = sm * e.cross(r - centre);
2630 }
2631 g.block(j * 3 * nAtoms + 3 * k, static_cast<long>(col), 3, 1) = d;
2632 }
2633 }
2634 }
2635 // Unit columns and a relative cut, so that translations and rotations
2636 // compete as directions. A rotation about the axis of a ring that is
2637 // straight to round-off has a generator of round-off size; it is no
2638 // rigid motion and must not be scaled up into one.
2639 ColMajorXd gc(dim, g.cols());
2640 long kept = 0;
2641 const double largest = g.colwise().norm().maxCoeff();
2642 for (long col = 0; col < g.cols(); ++col) {
2643 const double norm = g.col(col).norm();
2644 if (norm > 1e-8 * largest) {
2645 gc.col(kept++) = g.col(col) / norm;
2646 }
2647 }
2648 if (kept == 0) {
2649 return out;
2650 }
2651 Eigen::ColPivHouseholderQR<ColMajorXd> qr(gc.leftCols(kept));
2652 qr.setThreshold(1e-8);
2653 const long rank = qr.rank();
2654 const ColMajorXd basis = qr.householderQ() * ColMajorXd::Identity(dim, rank);
2655 for (long r = 0; r < rank; ++r) {
2656 std::vector<VectorXd> u(static_cast<size_t>(nb));
2657 for (long j = 0; j < nb; ++j) {
2658 u[static_cast<size_t>(j)] =
2659 basis.col(r).segment(j * 3 * nAtoms, 3 * nAtoms);
2660 }
2661 out.push_back(std::move(u));
2662 }
2663 return out;
2664}
2665
2666struct NewtonOut {
2667 std::vector<VectorXd> beads;
2668 std::vector<double> energies;
2669 double ringPotential = 0.0;
2670 double bN = 0.0;
2671 long iterations = 0;
2672 bool converged = false;
2673 // Half ring, stationary, and not index 1. The odd-mode probe decides
2674 // whether the search continues on the whole ring.
2675 bool stalledHalf = false;
2676 // The beads fell together: B_N dropped below collapseFraction of the
2677 // starting ring, so the search left the bounce for a stationary point of
2678 // V.
2679 bool collapsed = false;
2680};
2681
2682// Index-1 Newton on one ring. `x` holds N beads. A half ring optimises beads
2683// 0..N/2 and mirrors them. Trust is the largest bead displacement.
2684NewtonOut newtonInstanton(std::vector<VectorXd> guess, double c,
2685 const MatrixXd &hessSaddle,
2686 const RateInstantonOptions &options,
2687 const BatchPotential &potential) {
2688 const long nBeads = options.beads;
2689 // Fold only an even ring that already matches under j -> N - j. An empty
2690 // guess is seeded into that shape before this call.
2691 // The folded Newton objective contains no bath term. Friction uses the
2692 // full objective so its energy and residual include the requested bath.
2693 // Link weights keep the whole ring.
2694 bool half = options.halfRing && options.discretization.empty() &&
2695 !options.friction && !options.physicalBath && nBeads % 2 == 0 &&
2696 static_cast<long>(guess.size()) == nBeads;
2697 if (half) {
2698 const long m = nBeads / 2;
2699 for (long j = 1; j < m; ++j) {
2700 if ((guess[static_cast<size_t>(j)] -
2701 guess[static_cast<size_t>(nBeads - j)])
2702 .norm() > 1e-8) {
2703 half = false;
2704 break;
2705 }
2706 }
2707 }
2708 if (half && !options.discretization.empty()) {
2709 throw std::invalid_argument("link weights need the full ring; a half ring "
2710 "keeps the uniform spring");
2711 }
2712 const std::vector<double> *linkWeight =
2713 options.discretization.empty() ? nullptr : &options.discretization;
2714 std::vector<VectorXd> x;
2715 if (half) {
2716 const long m = nBeads / 2;
2717 x.resize(static_cast<size_t>(m + 1));
2718 for (long j = 0; j <= m; ++j) {
2719 x[static_cast<size_t>(j)] = guess[static_cast<size_t>(j)];
2720 }
2721 } else {
2722 x = std::move(guess);
2723 }
2724 const long f = x.front().size();
2725 const std::vector<double> eta = frictionEta(options, x.size());
2726 const MatrixXd hS = (0.5 * (hessSaddle + hessSaddle.transpose())).eval();
2727 // The rigid quotient: translations and free rotations of the whole ring
2728 // about its centre of mass, from the current beads, orthonormalised.
2729 const long nAtoms = static_cast<long>(options.rigidSqrtMasses.size());
2730 const bool quotient = nAtoms > 0 && 3 * nAtoms == hS.rows() &&
2731 options.rigidReference.size() == 3 * nAtoms;
2732 auto ringRigid = [&](const std::vector<VectorXd> &q) {
2733 if (!quotient) {
2734 return std::vector<std::vector<VectorXd>>{};
2735 }
2736 return ringRigidBasis(q, options.rigidSqrtMasses, options.rigidReference,
2737 options.rigidRotations);
2738 };
2739 std::vector<std::vector<VectorXd>> nullRing;
2740 // A one-dimensional well is already the saddle curvature. In more
2741 // dimensions the turning points are not the saddle, so each bead starts
2742 // from its own curvature and the Bofill update carries it.
2743 std::vector<MatrixXd> physical;
2744 const auto beadPotential =
2745 ownedEvaluation(potential, options, 0, static_cast<long>(x.size()));
2746 const auto derivativePotential =
2747 ownedEvaluation(potential, options, potential_owner::derivative);
2748 auto physicalAt = [&](const VectorXd &q) -> MatrixXd {
2749 if (!options.physicalHessian)
2750 return fdPhysicalHessian(q, derivativePotential,
2751 options.physicalHessianStep);
2752 const MatrixXd h = options.physicalHessian(q);
2753 if (h.rows() != f || h.cols() != f || !h.allFinite() ||
2754 !h.isApprox(h.transpose(), 1e-12))
2755 throw std::invalid_argument(
2756 "rate instanton: invalid analytic physical Hessian");
2757 return h;
2758 };
2759 if (options.physicalHessian) {
2760 physical.resize(x.size());
2761 for (size_t j = 0; j < x.size(); ++j)
2762 physical[j] = physicalAt(x[j]);
2763 } else if (f == 1 || options.initialHessians != "finite_difference") {
2764 physical.assign(x.size(), hS);
2765 } else {
2766 physical.resize(x.size());
2767 for (size_t j = 0; j < x.size(); ++j) {
2768 physical[j] = physicalAt(x[j]);
2769 }
2770 }
2771 // Negative curvatures each bead block may carry between exact rebuilds.
2772 std::vector<long> allowedNegatives(x.size(), -1);
2773 auto recountNegatives = [&]() {
2774 if (f == 1) {
2775 return;
2776 }
2777 for (size_t j = 0; j < x.size(); ++j) {
2778 allowedNegatives[j] = negativeEigenvalues(physical[j]);
2779 }
2780 };
2781 recountNegatives();
2782
2783 struct Obj {
2784 std::vector<VectorXd> grad;
2785 std::vector<VectorXd> gradPot;
2786 std::vector<double> energies;
2787 double u = 0.0;
2788 };
2789 auto objective = [&](const std::vector<VectorXd> &q) {
2790 Obj out;
2791 if (half) {
2792 // The potential is evaluated on beads 0..N/2. The closed ring is that
2793 // chain plus its mirror, and the folded gradient is half the derivative
2794 // of the closed-ring energy.
2795 const long m = static_cast<long>(q.size()) - 1;
2796 const long n = 2 * m;
2797 std::vector<double> vu;
2798 std::vector<VectorXd> gu;
2799 beadPotential(q, vu, gu);
2800 for (double &vj : vu) {
2801 vj -= options.energyShift;
2802 }
2803 if (vu.size() != q.size() || gu.size() != q.size()) {
2804 throw std::runtime_error(
2805 "rate instanton: potential returned the wrong count");
2806 }
2807 std::vector<VectorXd> full(static_cast<size_t>(n));
2808 std::vector<double> vFull(static_cast<size_t>(n));
2809 std::vector<VectorXd> gFull(static_cast<size_t>(n));
2810 for (long j = 0; j <= m; ++j) {
2811 full[static_cast<size_t>(j)] = q[static_cast<size_t>(j)];
2812 vFull[static_cast<size_t>(j)] = vu[static_cast<size_t>(j)];
2813 gFull[static_cast<size_t>(j)] = gu[static_cast<size_t>(j)];
2814 }
2815 for (long j = 1; j < m; ++j) {
2816 full[static_cast<size_t>(n - j)] = q[static_cast<size_t>(j)];
2817 vFull[static_cast<size_t>(n - j)] = vu[static_cast<size_t>(j)];
2818 gFull[static_cast<size_t>(n - j)] = gu[static_cast<size_t>(j)];
2819 }
2820 std::vector<VectorXd> gRing(static_cast<size_t>(n));
2821 double uFull = 0.0;
2822 double springE = 0.0;
2823 for (long j = 0; j < n; ++j) {
2824 const long prev = (j + n - 1) % n;
2825 const long next = (j + 1) % n;
2826 gRing[static_cast<size_t>(j)] =
2827 gFull[static_cast<size_t>(j)] +
2828 c * (2.0 * full[static_cast<size_t>(j)] -
2829 full[static_cast<size_t>(prev)] -
2830 full[static_cast<size_t>(next)]);
2831 springE +=
2832 (full[static_cast<size_t>(next)] - full[static_cast<size_t>(j)])
2833 .squaredNorm();
2834 uFull += vFull[static_cast<size_t>(j)];
2835 }
2836 uFull += 0.5 * c * springE;
2837 out.u = 0.5 * uFull;
2838 out.grad.resize(q.size());
2839 out.grad.front() = 0.5 * gRing.front();
2840 out.grad.back() = 0.5 * gRing[static_cast<size_t>(m)];
2841 for (long j = 1; j < m; ++j) {
2842 out.grad[static_cast<size_t>(j)] =
2843 0.5 *
2844 (gRing[static_cast<size_t>(j)] + gRing[static_cast<size_t>(n - j)]);
2845 }
2846 out.gradPot = std::move(gu);
2847 out.energies = std::move(vu);
2848 } else {
2849 const RingEval ev =
2850 evaluateRing(q, c, beadPotential, options.energyShift,
2851 frictionEta(options, q.size()), options.discretization,
2852 options.physicalBath);
2853 out.u = ev.u;
2854 out.grad = ev.grad;
2855 out.gradPot = ev.physicalGrad;
2856 out.energies = ev.v;
2857 }
2858 return out;
2859 };
2860
2861 struct View {
2862 bool ok = false;
2863 std::vector<RingMode> ritz; // lowest Ritz pairs, ascending
2864 std::vector<MatrixXd> diag; // ring blocks the step solves with
2865 MatrixXd physicalBathHessian;
2866 VectorXd tau;
2867 Climb climb;
2868 double gmax = 0.0;
2869 };
2870 // Turning-point blocks store half the closed-ring derivative. The
2871 // residual that stops the climb is the closed-ring residual.
2872 auto closedGmax = [&](const Obj &ev) {
2873 if (!half || ev.grad.size() < 2) {
2874 return largestBeadNorm(ev.grad);
2875 }
2876 double big = 2.0 * ev.grad.front().norm();
2877 big = std::max(big, 2.0 * ev.grad.back().norm());
2878 const long last = static_cast<long>(ev.grad.size()) - 1;
2879 for (long j = 1; j < last; ++j) {
2880 big = std::max(big, ev.grad[static_cast<size_t>(j)].norm());
2881 }
2882 return big;
2883 };
2884 // Lowest modes of the ring Hessian from matrix-vector products alone,
2885 // started along the saddle's unstable direction on every bead.
2886 std::vector<VectorXd> ritzStart(x.size(), VectorXd::Zero(f));
2887 VectorXd climbDir(f);
2888 {
2889 const ColMajorXd hs0 = physicalStaticCurvature(hS, x.front(), options);
2890 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es0(hs0);
2891 climbDir = es0.eigenvectors().col(0);
2892 for (auto &v : ritzStart) {
2893 v = climbDir;
2894 }
2895 }
2896 // The climb follows the mode that overlaps the last one, as in dimer and
2897 // minimum-mode following: the lowest curvature can switch to another
2898 // channel, and climbing it walks the ring to a neighbouring saddle.
2899 std::vector<VectorXd> track = ritzStart;
2900 {
2901 const double n0 = std::sqrt(dot(track, track));
2902 if (n0 > 0.0) {
2903 scale(track, 1.0 / n0);
2904 }
2905 }
2906 // A half chain that folds back is a second bounce. The single instanton
2907 // is monotone in the saddle's unstable direction.
2908 if (half) {
2909 projectMonotonePrefix(x, static_cast<long>(x.size()) - 1, climbDir);
2910 }
2911 auto viewOf = [&](const Obj &ev) {
2912 if (options.physicalHessian) {
2913 for (size_t j = 0; j < x.size(); ++j)
2914 physical[j] = physicalAt(x[j]);
2915 recountNegatives();
2916 }
2917 nullRing = ringRigid(x);
2918 View v;
2919 if (options.physicalBath)
2920 v.physicalBathHessian =
2921 options.physicalBath->evaluate(x, c, true).hessian;
2922 const bool constantBath =
2923 eta.empty() || std::all_of(eta.begin(), eta.end(), [&](double value) {
2924 return value == eta.front();
2925 });
2926 v.tau = (half || !constantBath) ? VectorXd() : timeTranslation(x);
2927 // Physical curvature determines inertia. Known rigid motions enter the
2928 // quotient and the step solve without changing this operator.
2929 v.diag = ringDiagonal(physical, c, half, linkWeight);
2930 auto apply = [&](const std::vector<VectorXd> &vec) {
2931 std::vector<VectorXd> out =
2932 applyDiagonal(v.diag, c, !half, vec, linkWeight);
2933 if (v.physicalBathHessian.size()) {
2934 const VectorXd added = v.physicalBathHessian * packBeads(vec);
2935 for (size_t j = 0; j < out.size(); ++j)
2936 out[j] += added.segment(j * f, f);
2937 }
2938 if (!eta.empty()) {
2939 double energy = 0.0;
2940 addFrictionBath(vec, energy, out, eta);
2941 }
2942 return out;
2943 };
2944 if (v.tau.size() > 0) {
2945 std::vector<VectorXd> phase(x.size(), VectorXd::Zero(f));
2946 for (size_t j = 0; j < x.size(); ++j) {
2947 phase[j] = v.tau.segment(static_cast<long>(j) * f, f);
2948 }
2949 const auto residual = apply(phase);
2950 // A discrete time-shift direction can carry physical curvature.
2951 if (std::sqrt(dot(residual, residual)) > 1e-6 * std::max(1.0, c)) {
2952 v.tau.resize(0);
2953 }
2954 }
2955 const long dim = static_cast<long>(x.size()) * f;
2956 if (dim <= kDenseRing) {
2957 // A small ring takes its whole spectrum densely: every negative
2958 // curvature in every symmetry sector, exactly.
2959 const long nb = static_cast<long>(x.size());
2960 ColMajorXd big = ColMajorXd::Zero(dim, dim);
2961 for (long col = 0; col < dim; ++col) {
2962 std::vector<VectorXd> e(static_cast<size_t>(nb), VectorXd::Zero(f));
2963 e[static_cast<size_t>(col / f)](col % f) = 1.0;
2964 big.col(col) = packBeads(apply(e));
2965 }
2966 const ColMajorXd sym = 0.5 * (big + big.transpose());
2967 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(sym);
2968 v.ritz.clear();
2969 for (long i = 0; i < dim; ++i) {
2970 RingMode m;
2971 m.theta = es.eigenvalues()(i);
2972 m.residual = 0.0;
2973 m.vector.assign(static_cast<size_t>(nb), VectorXd::Zero(f));
2974 for (long j = 0; j < nb; ++j) {
2975 m.vector[static_cast<size_t>(j)] =
2976 es.eigenvectors().col(i).segment(j * f, f);
2977 }
2978 v.ritz.push_back(std::move(m));
2979 }
2980 } else {
2981 // The number of negative curvatures off the cycle, exactly, from the
2982 // inertia of the same chain with the cycle lifted by c.
2983 long negatives = 0;
2984 {
2985 std::vector<std::vector<VectorXd>> lift;
2986 std::vector<double> kap;
2987 if (v.tau.size() == dim) {
2988 std::vector<VectorXd> tauRing(x.size(), VectorXd::Zero(f));
2989 for (size_t j = 0; j < x.size(); ++j) {
2990 tauRing[j] = v.tau.segment(static_cast<long>(j) * f, f);
2991 }
2992 lift.push_back(std::move(tauRing));
2993 kap.push_back(c);
2994 }
2995 try {
2996 negatives =
2997 WoodburyRing(c, v.diag, !half, lift, kap, true, linkWeight)
2998 .negative();
2999 } catch (const std::runtime_error &) {
3000 negatives = 0;
3001 }
3002 }
3003 // Lanczos deepens until every one of those negative curvatures is a
3004 // resolved Ritz pair; a flip on an unresolved vector corrupts the step.
3005 // The ring spectrum reaches 4 c, so residuals scale with c.
3006 const double resolvedTol = 1e-8 * std::max(1.0, 4.0 * c);
3007 auto resolvedNegatives = [&](const std::vector<RingMode> &modes) {
3008 long count = 0;
3009 for (const auto &m : modes) {
3010 if (m.theta < 0.0 && m.residual <= resolvedTol) {
3011 ++count;
3012 }
3013 }
3014 return count;
3015 };
3016 long steps = std::min(dim, std::max(60L, 4 * (negatives + 2)));
3017 for (;;) {
3018 // J commutes with the ring's mirror about any bead, so a start that
3019 // is mirror-symmetric spans no antisymmetric mode at all; a fixed
3020 // pseudo-random admixture reaches every symmetry sector.
3021 std::vector<VectorXd> start = ritzStart;
3022 std::uint64_t h = 0x9E3779B97F4A7C15ULL;
3023 for (auto &bead : start) {
3024 for (long a2 = 0; a2 < bead.size(); ++a2) {
3025 h ^= h << 13;
3026 h ^= h >> 7;
3027 h ^= h << 17;
3028 bead(a2) += 1e-2 * (static_cast<double>(h >> 11) * 0x1.0p-53 - 0.5);
3029 }
3030 }
3031 v.ritz = lowestRingModes(apply, std::move(start), steps);
3032 if (steps >= std::min(dim, kRitzCap) ||
3033 resolvedNegatives(v.ritz) >= negatives) {
3034 break;
3035 }
3036 steps = std::min(std::min(dim, kRitzCap), 2 * steps);
3037 }
3038 // Only resolved pairs enter the classification and the flips.
3039 v.ritz.erase(std::remove_if(v.ritz.begin(), v.ritz.end(),
3040 [](const RingMode &m) {
3041 return m.residual >
3042 1e-6 *
3043 std::max(1.0, std::abs(m.theta));
3044 }),
3045 v.ritz.end());
3046 }
3047 v.ok = !v.ritz.empty();
3048 if (v.ok) {
3049 // Physical instabilities retain their sign independently of the
3050 // climb curvature. Only the matrix roundoff scale defines zero.
3051 double minimumWeight = 1.0;
3052 for (double weight : options.discretization) {
3053 minimumWeight = std::min(minimumWeight, weight);
3054 }
3055 double operatorBound = 0.0;
3056 for (const auto &block : v.diag) {
3057 operatorBound = std::max(operatorBound,
3058 block.cwiseAbs().rowwise().sum().maxCoeff() +
3059 2.0 * c / minimumWeight);
3060 }
3061 if (!eta.empty()) {
3062 operatorBound += 2.0 * (*std::max_element(eta.begin(), eta.end()));
3063 }
3064 if (dim <= kDenseRing) {
3065 operatorBound = 0.0;
3066 for (const auto &mode : v.ritz) {
3067 operatorBound = std::max(operatorBound, std::abs(mode.theta));
3068 }
3069 }
3070 const double cut =
3071 -64.0 * std::numeric_limits<double>::epsilon() * dim * operatorBound;
3072 v.climb = Climb{};
3073 std::vector<VectorXd> tauRing;
3074 if (v.tau.size() == dim) {
3075 tauRing.assign(x.size(), VectorXd::Zero(f));
3076 for (size_t j = 0; j < x.size(); ++j) {
3077 tauRing[j] = v.tau.segment(static_cast<long>(j) * f, f);
3078 }
3079 }
3080 auto onCycle = [&](const std::vector<VectorXd> &m) {
3081 if (!tauRing.empty() && std::abs(dot(m, tauRing)) > 0.5) {
3082 return true;
3083 }
3084 for (const auto &r : nullRing) {
3085 if (std::abs(dot(m, r)) > 0.5) {
3086 return true;
3087 }
3088 }
3089 return false;
3090 };
3091 double best = 0.0;
3092 long lowest = -1;
3093 for (size_t i = 0; i < v.ritz.size(); ++i) {
3094 if (onCycle(v.ritz[i].vector)) {
3095 continue;
3096 }
3097 if (lowest < 0 ||
3098 v.ritz[i].theta < v.ritz[static_cast<size_t>(lowest)].theta) {
3099 lowest = static_cast<long>(i);
3100 }
3101 if (v.ritz[i].theta < 0.0 && track.size() == v.ritz[i].vector.size()) {
3102 const double o = std::abs(dot(v.ritz[i].vector, track));
3103 if (o > best) {
3104 best = o;
3105 v.climb.index = static_cast<long>(i);
3106 }
3107 }
3108 }
3109 if (v.climb.index < 0 || best < kTrackOverlap) {
3110 v.climb.index = lowest;
3111 }
3112 if (v.climb.index >= 0) {
3113 v.climb.curvature = v.ritz[static_cast<size_t>(v.climb.index)].theta;
3114 }
3115 if (v.climb.curvature < 0.0) {
3116 for (size_t i = 0; i < v.ritz.size(); ++i) {
3117 if (onCycle(v.ritz[i].vector)) {
3118 continue;
3119 }
3120 if (v.ritz[i].theta + v.ritz[i].residual < cut) {
3121 ++v.climb.negative;
3122 }
3123 }
3124 }
3125 v.gmax = closedGmax(ev);
3126 if (v.climb.index >= 0) {
3127 ritzStart = v.ritz[static_cast<size_t>(v.climb.index)].vector;
3128 if (v.climb.curvature < 0.0) {
3129 track = ritzStart;
3130 if (track.size() == ritzStart.size() && dot(track, track) > 0.0) {
3131 scale(track, 1.0 / std::sqrt(dot(track, track)));
3132 }
3133 }
3134 }
3135 }
3136 return v;
3137 };
3138 auto done = [&](const View &v) {
3139 return v.ok && v.gmax < options.forceTolerance && v.climb.negative == 1 &&
3140 v.climb.curvature < 0.0;
3141 };
3142
3143 Obj cur = objective(x);
3144 double trust = options.maxStep;
3145 long entries = 0;
3146 bool converged = false;
3147 bool analyticPolishAttempted = false;
3148 bool stalledHalf = false;
3149 const double trustFloor = std::min(1e-4, options.maxStep);
3150 // Finite-difference rebuilds of the bead blocks when the search stalls.
3151 constexpr int kMaxHessianRefreshes = 3;
3152 int refreshes = 0;
3153 bool exactAtX = options.physicalHessian ||
3154 (f > 1 && options.initialHessians == "finite_difference");
3155 // Negative curvatures the last finite-difference blocks showed, and the
3156 // rebuilds a growing Bofill count has asked for.
3157 long exactNegatives = -1;
3158 long previousModeledNegatives = -1;
3159 constexpr int kMaxDriftRefreshes = 4;
3160 int driftRefreshes = 0;
3161 // B_N of the closed ring the beads describe.
3162 auto ringLength = [&](const std::vector<VectorXd> &q) {
3163 double b = 0.0;
3164 if (half) {
3165 for (size_t j = 0; j + 1 < q.size(); ++j) {
3166 b += 2.0 * (q[j + 1] - q[j]).squaredNorm();
3167 }
3168 } else {
3169 for (size_t j = 0; j < q.size(); ++j) {
3170 b += (q[(j + 1) % q.size()] - q[j]).squaredNorm();
3171 }
3172 }
3173 return b;
3174 };
3175 const double startLength = ringLength(x);
3176 bool collapsed = false;
3177 for (long it = 0; it < options.maxIterations; ++it) {
3178 ++entries;
3179 const double length = ringLength(x);
3180 if (startLength > 0.0 && length < options.collapseFraction * startLength) {
3181 collapsed = true;
3182 break;
3183 }
3184 if (f == 1) {
3185 for (size_t j = 0; j < x.size(); ++j) {
3186 physical[j] = physicalAt(x[j]);
3187 }
3188 }
3189 const View v = viewOf(cur);
3190 const bool modeledCountGrew = previousModeledNegatives >= 0 &&
3191 v.climb.negative > previousModeledNegatives;
3192 if (v.ok)
3193 previousModeledNegatives = v.climb.negative;
3194 EONC_LOG_DEBUG("[Instanton] Newton {}: U_N {:.10g} eV, largest residual "
3195 "{:.3e}, B_N {:.6e}, climb curvature {:.4e}, {} negative, "
3196 "trust {:.3e}",
3197 it, half ? 2.0 * cur.u : cur.u, v.gmax, length,
3198 v.climb.curvature, v.climb.negative, trust);
3199 // A converged gradient is classified with exact bead Hessians before it
3200 // counts. A Bofill block learns curvature only along the steps taken, so
3201 // it can miss a negative curvature as well as invent one: on a ring that
3202 // never moved off a mirror plane the held blocks kept one negative
3203 // curvature where the surface had three.
3204 if (f > 1 && v.ok && v.gmax < options.forceTolerance && !exactAtX) {
3205 for (size_t j = 0; j < x.size(); ++j) {
3206 physical[j] = physicalAt(x[j]);
3207 }
3208 exactAtX = true;
3209 continue;
3210 }
3211 const bool polishing = done(v) && options.physicalHessian &&
3212 !analyticPolishAttempted && v.gmax > 0.0;
3213 if (done(v) && !polishing) {
3214 converged = true;
3215 break;
3216 }
3217 if (polishing) {
3218 // An exact-curvature polish reduces residual-induced phase curvature.
3219 // Its trial obeys the trust rules and cannot increase the residual.
3220 analyticPolishAttempted = true;
3221 }
3222 // Bofill blocks copied from the saddle can grow negative curvatures the
3223 // surface does not have: on a 1203-coordinate Al slab the model's count
3224 // rose from 2 to 11 while every flip turned the ring downhill, and the
3225 // ring collapsed onto a minimum. More negatives than the last exact
3226 // blocks showed rebuild them from finite differences, a few times.
3227 if (f > 1 && v.ok) {
3228 if (exactAtX) {
3229 exactNegatives = v.climb.negative;
3230 } else if ((v.gmax < options.forceTolerance || modeledCountGrew) &&
3231 v.climb.negative > std::max(1L, exactNegatives) &&
3232 driftRefreshes < kMaxDriftRefreshes) {
3233 ++driftRefreshes;
3234 for (size_t j = 0; j < x.size(); ++j) {
3235 physical[j] = physicalAt(x[j]);
3236 }
3237 recountNegatives();
3238 exactAtX = true;
3239 EONC_LOG_DEBUG("[Instanton] Newton {}: {} negative curvatures in the "
3240 "Bofill blocks, rebuilt from finite differences",
3241 it, v.climb.negative);
3242 continue;
3243 }
3244 }
3245 // A shorter Newton step when the quadratic model does not match. A step
3246 // that only reduces the residual is a walk into a well.
3247 auto accept = [&](VectorXd dir) {
3248 if (dir.size() == 0 || !dir.array().isFinite().all()) {
3249 return false;
3250 }
3251 const double big = packedBeadNorm(dir, f);
3252 if (!(big > 0.0)) {
3253 return false;
3254 }
3255 std::vector<VectorXd> trial = x;
3256 addPacked(trial, dir);
3257 if (half) {
3258 projectMonotonePrefix(trial, static_cast<long>(trial.size()) - 1,
3259 climbDir);
3260 }
3261 if (!finiteBeads(trial)) {
3262 return false;
3263 }
3264 VectorXd taken(dir.size());
3265 for (size_t k = 0; k < x.size(); ++k) {
3266 taken.segment(static_cast<long>(k) * f, f) =
3267 trial[k] - x[static_cast<size_t>(k)];
3268 }
3269 if (!(packedBeadNorm(taken, f) > 0.0) ||
3270 !taken.array().isFinite().all()) {
3271 return false;
3272 }
3273 dir = taken;
3274 Obj next = objective(trial);
3275 if (!finiteBeads(next.grad) || !std::isfinite(next.u)) {
3276 return false;
3277 }
3278 bool ratioOk = false;
3279 double ratio = 0.0;
3280 if (v.ok && static_cast<long>(x.size()) * f == dir.size()) {
3281 const VectorXd gflat = packBeads(cur.grad);
3282 std::vector<VectorXd> dirRing(x.size(), VectorXd::Zero(f));
3283 for (size_t k = 0; k < x.size(); ++k) {
3284 dirRing[k] = dir.segment(static_cast<long>(k) * f, f);
3285 }
3286 auto model = applyDiagonal(v.diag, c, !half, dirRing, linkWeight);
3287 if (v.physicalBathHessian.size()) {
3288 const VectorXd added = v.physicalBathHessian * packBeads(dirRing);
3289 for (size_t j = 0; j < model.size(); ++j)
3290 model[j] += added.segment(j * f, f);
3291 }
3292 if (!eta.empty()) {
3293 double energy = 0.0;
3294 addFrictionBath(dirRing, energy, model, eta);
3295 }
3296 const VectorXd jd = packBeads(model);
3297 const double pred = gflat.dot(dir) + 0.5 * dir.dot(jd);
3298 const double actual = next.u - cur.u;
3299 // Predicted and actual changes below the energy resolution are
3300 // roundoff. Their ratio is not a disagreement with the model,
3301 // and rejecting it repeats one micro-step until the budget ends.
3302 const double unresolved = 1e-12 * std::max(1.0, std::abs(cur.u));
3303 if (std::abs(pred) <= unresolved) {
3304 const bool quiet = std::abs(actual) <= unresolved &&
3305 packedBeadNorm(dir, f) <= trustFloor;
3306 ratio = quiet ? 1.0 : 0.0;
3307 } else {
3308 ratio = actual / pred;
3309 }
3310 ratioOk = std::isfinite(ratio) && ratio >= 0.1 && ratio <= 3.0;
3311 // Near the saddle the predicted change sits at the round-off of
3312 // U_N and the ratio is noise; there the step stands on the residual.
3313 double magnitude = std::abs(cur.u);
3314 for (const double vj : cur.energies) {
3315 magnitude += std::abs(vj);
3316 }
3317 const double roundoff =
3318 1e3 * std::numeric_limits<double>::epsilon() * magnitude;
3319 if (!ratioOk && std::abs(pred) < roundoff &&
3320 closedGmax(next) <= closedGmax(cur)) {
3321 ratioOk = true;
3322 ratio = 1.0;
3323 }
3324 }
3325 if (!ratioOk) {
3326 return false;
3327 }
3328 if (polishing && closedGmax(next) > closedGmax(cur))
3329 return false;
3330 if (!options.physicalHessian)
3331 for (size_t k = 0; k < x.size(); ++k) {
3332 inertiaKeepingUpdate(physical[k], trial[k] - x[k],
3333 next.gradPot[k] - cur.gradPot[k],
3334 allowedNegatives[k]);
3335 }
3336 x = std::move(trial);
3337 cur = std::move(next);
3338 exactAtX = static_cast<bool>(options.physicalHessian);
3339 if (ratioOk && ratio > 0.75 && ratio < 1.25 &&
3340 packedBeadNorm(dir, f) >= 0.99 * trust) {
3341 trust = std::min(2.0 * trust, options.maxStep);
3342 }
3343 return true;
3344 };
3345 // A converged gradient is classified with exact bead Hessians, as
3346 // i-PI's hessian_final does: the Bofill blocks can carry negative
3347 // curvatures the surface does not have. A second negative curvature
3348 // that survives the rebuild is a higher-index stationary ring, where
3349 // the flipped Newton step vanishes; a trust-sized displacement down
3350 // that mode leaves it.
3351 if (v.ok && v.gmax < options.forceTolerance && v.climb.negative != 1 &&
3352 !exactAtX) {
3353 for (size_t j = 0; j < x.size(); ++j) {
3354 physical[j] = physicalAt(x[j]);
3355 }
3356 recountNegatives();
3357 exactAtX = true;
3358 continue;
3359 }
3360 if (v.ok && v.gmax < options.forceTolerance && v.climb.negative > 1) {
3361 long down = -1;
3362 for (size_t i = 0; i < v.ritz.size(); ++i) {
3363 const auto &m = v.ritz[i];
3364 if (static_cast<long>(i) == v.climb.index || !(m.theta < 0.0)) {
3365 continue;
3366 }
3367 bool held = false;
3368 if (v.tau.size() == static_cast<long>(x.size()) * f) {
3369 held = std::abs(packBeads(m.vector).dot(v.tau)) > 0.5;
3370 }
3371 for (const auto &r : nullRing) {
3372 held = held || std::abs(dot(m.vector, r)) > 0.5;
3373 }
3374 if (!held &&
3375 (down < 0 || m.theta < v.ritz[static_cast<size_t>(down)].theta)) {
3376 down = static_cast<long>(i);
3377 }
3378 }
3379 if (down >= 0) {
3380 trust = options.maxStep;
3381 // The Ritz vector has unit norm over every bead; scaled so its
3382 // largest bead moves the trust radius, as the Newton step is.
3383 VectorXd mode = packBeads(v.ritz[static_cast<size_t>(down)].vector);
3384 const double big = packedBeadNorm(mode, f);
3385 if (big > 0.0) {
3386 mode *= trust / big;
3387 if (accept(mode) || accept(-mode)) {
3388 continue;
3389 }
3390 }
3391 }
3392 }
3393 // A half ring that is stationary at the wrong index cannot see a mode
3394 // odd under the mirror. Leave it for the odd-mode probe instead of
3395 // spending the remaining iterations on this point.
3396 if (half && options.checkOddSector && exactAtX && v.ok &&
3397 v.gmax < options.forceTolerance && v.climb.negative != 1) {
3398 stalledHalf = true;
3399 break;
3400 }
3401 const VectorXd step =
3402 chainIndexOneStep(v.ritz, v.climb, v.diag, c, !half, cur.grad, v.tau,
3403 nullRing, linkWeight, eta, v.physicalBathHessian);
3404 bool moved = false;
3405 VectorXd dir = step;
3406 // Clip to the trust radius once, then halve that capped step.
3407 if (dir.size() > 0) {
3408 const double big0 = packedBeadNorm(dir, f);
3409 if (big0 > trust) {
3410 dir *= trust / big0;
3411 }
3412 }
3413 for (int bt = 0; bt < 4 && !moved; ++bt) {
3414 moved = accept(dir);
3415 dir *= 0.5;
3416 }
3417 if (!moved) {
3418 if (polishing) {
3419 converged = true;
3420 break;
3421 }
3422 trust = std::max(0.5 * trust, trustFloor);
3423 // At the trust floor the Bofill blocks no longer model the ring and
3424 // every step is refused; rebuild them from finite differences, 2 f
3425 // gradient calls per bead, a few times at most, and start the trust
3426 // region again.
3427 if (trust <= trustFloor && refreshes < kMaxHessianRefreshes) {
3428 ++refreshes;
3429 for (size_t j = 0; j < x.size(); ++j) {
3430 physical[j] = physicalAt(x[j]);
3431 }
3432 recountNegatives();
3433 trust = options.maxStep;
3434 }
3435 }
3436 }
3437 // A budget that ends on a converged gradient still classifies it with
3438 // exact blocks.
3439 if (!converged) {
3440 View last = viewOf(cur);
3441 if (f > 1 && last.ok && last.gmax < options.forceTolerance && !exactAtX) {
3442 const double eps = options.lanczosStep > 0.0 ? options.lanczosStep : 1e-4;
3443 for (size_t j = 0; j < x.size(); ++j) {
3444 physical[j] = fdPhysicalHessian(x[j], potential, eps);
3445 }
3446 last = viewOf(cur);
3447 }
3448 converged = done(last);
3449 }
3450
3451 NewtonOut out;
3452 out.iterations = entries;
3453 out.converged = converged;
3454 out.stalledHalf = stalledHalf;
3455 out.collapsed = collapsed;
3456 if (half) {
3457 const long m = static_cast<long>(x.size()) - 1;
3458 const long n = 2 * m;
3459 out.beads.resize(static_cast<size_t>(n));
3460 out.energies.assign(static_cast<size_t>(n), 0.0);
3461 for (long j = 0; j <= m; ++j) {
3462 out.beads[static_cast<size_t>(j)] = x[static_cast<size_t>(j)];
3463 out.energies[static_cast<size_t>(j)] =
3464 cur.energies[static_cast<size_t>(j)];
3465 }
3466 for (long j = 1; j < m; ++j) {
3467 out.beads[static_cast<size_t>(n - j)] = x[static_cast<size_t>(j)];
3468 out.energies[static_cast<size_t>(n - j)] =
3469 cur.energies[static_cast<size_t>(j)];
3470 }
3471 out.ringPotential = 2.0 * cur.u;
3472 } else {
3473 out.beads = std::move(x);
3474 out.ringPotential = cur.u;
3475 out.energies = std::move(cur.energies);
3476 }
3477 out.bN = ringSpeed(out.beads, options.discretization);
3478 return out;
3479}
3480
3481// A one-dimensional bead carries its own curvature, so the requested
3482// temperature is solved first. Below 0.75 Tc an empty guess that does not
3483// converge walks down from 0.85 Tc, and that walk replaces the first try.
3484RateInstanton optimizeRateByNewton(const VectorXd &saddle,
3485 const MatrixXd &hessSaddle, double beta,
3486 std::vector<VectorXd> guess,
3487 const BatchPotential &potential,
3488 const RateInstantonOptions &options) {
3489 const long nBeads = options.beads;
3490 if (nBeads < 4 || !(beta > 0.0) || hessSaddle.rows() != saddle.size()) {
3491 throw std::invalid_argument(
3492 "optimizeRateInstanton: need N >= 4, beta > 0 and a saddle Hessian "
3493 "of the saddle's dimension");
3494 }
3495 if (!options.discretization.empty() &&
3496 static_cast<long>(options.discretization.size()) != nBeads) {
3497 throw std::invalid_argument(
3498 "link weights must be one positive value per bead");
3499 }
3500 RateInstanton inst;
3501 inst.physicalBath = options.physicalBath;
3502 inst.discretization = options.discretization;
3503 inst.bathEta = frictionEta(options, options.beads);
3504 inst.beta = beta;
3505 inst.betaN = beta / static_cast<double>(nBeads);
3506 inst.temperature = 1.0 / (kBoltzmann * beta);
3507 inst.crossover = crossoverTemperature(
3508 options.physicalBath
3509 ? MatrixXd(options.physicalBath->fullHessian(saddle, hessSaddle))
3510 : hessSaddle);
3511 if (!(inst.temperature < inst.crossover)) {
3512 throw std::invalid_argument(
3513 "optimizeRateInstanton: T is at or above the crossover temperature; "
3514 "the ring collapses onto the saddle and steepest descent needs the "
3515 "parabolic barrier correction, of which classical transition-state "
3516 "theory is only the one-bead limit");
3517 }
3518
3519 const bool cool = static_cast<long>(guess.size()) != nBeads &&
3520 inst.temperature < 0.75 * inst.crossover;
3521 // A half ring cannot see modes odd under j -> N-j, so two copies of the
3522 // instanton are a stationary point it can accept or sit on. An unstable
3523 // odd mode there sends the search onto the whole ring from a kick along
3524 // that mode.
3525 auto probeOddSector = [&](NewtonOut &got, double spring) {
3526 const long nGot = static_cast<long>(got.beads.size());
3527 bool mirrored = (got.converged || got.stalledHalf) && options.halfRing &&
3528 options.discretization.empty() && options.checkOddSector &&
3529 nGot == nBeads && nGot % 2 == 0;
3530 for (long j = 1; mirrored && j < nGot / 2; ++j) {
3531 mirrored = (got.beads[static_cast<size_t>(j)] -
3532 got.beads[static_cast<size_t>(nGot - j)])
3533 .norm() <= 1e-8;
3534 }
3535 if (!mirrored) {
3536 return;
3537 }
3538 const Eigen::SelfAdjointEigenSolver<MatrixXd> es0(
3539 0.5 * (hessSaddle + hessSaddle.transpose()));
3540 const double barrierCurvature = std::abs(es0.eigenvalues()(0));
3541 const RingEval here =
3542 evaluateRing(got.beads, spring, potential, options.energyShift,
3543 frictionEta(options, got.beads.size()));
3544 std::vector<VectorXd> oddMode;
3545 const double oddCurv = lowestOddMode(
3546 got.beads, here, spring, potential, oddMode, options.lanczosFirst,
3547 options.lanczosStep, frictionEta(options, got.beads.size()));
3548 if (!(oddCurv < -1e-3 * barrierCurvature) ||
3549 oddMode.size() != got.beads.size()) {
3550 return;
3551 }
3552 std::vector<VectorXd> kicked = got.beads;
3553 const double kick = std::sqrt(2.0 / (inst.betaN * -oddCurv));
3554 for (size_t k = 0; k < kicked.size(); ++k) {
3555 kicked[k] += kick * oddMode[k];
3556 }
3557 RateInstantonOptions whole = options;
3558 whole.halfRing = false;
3559 const long before = got.iterations;
3560 got = newtonInstanton(std::move(kicked), spring, hessSaddle, whole,
3561 potential);
3562 got.iterations += before;
3563 };
3564 // One dimension solves the requested temperature before any walk. A
3565 // higher-dimensional empty guess below 0.75 Tc keeps the walk, which
3566 // starts from a curvature copied off the saddle.
3567 if (saddle.size() == 1 || !cool) {
3568 if (static_cast<long>(guess.size()) != nBeads) {
3569 const ColMajorXd hS = physicalStaticCurvature(
3570 0.5 * (hessSaddle + hessSaddle.transpose()), saddle, options);
3571 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(hS);
3572 guess = cosineSeed(saddle, es.eigenvectors().col(0), es.eigenvalues()(0),
3573 inst.temperature, inst.crossover, nBeads, potential,
3574 options.discretization);
3575 }
3576 const double bnh = inst.betaN * kHbar;
3577 const double spring = 1.0 / (bnh * bnh);
3578 NewtonOut got = newtonInstanton(std::move(guess), spring, hessSaddle,
3579 options, potential);
3580 probeOddSector(got, spring);
3581 inst.beads = got.beads;
3582 inst.energies = got.energies;
3583 inst.ringPotential = got.ringPotential;
3584 inst.bN = got.bN;
3585 inst.iterations = got.iterations;
3586 inst.converged = got.converged;
3587 inst.collapsed = got.collapsed;
3588 if (inst.converged || !cool) {
3589 return inst;
3590 }
3591 }
3592 {
3593 std::vector<double> temps;
3594 for (double t = 0.85 * inst.crossover; t > inst.temperature * 1.05;
3595 t *= 0.75) {
3596 temps.push_back(t);
3597 }
3598 temps.push_back(inst.temperature);
3599 std::vector<VectorXd> beads;
3600 RateInstanton last;
3601 // A one-dimensional first try spent part of the budget already; with
3602 // nothing left it is the answer.
3603 long used = saddle.size() == 1 ? inst.iterations : 0;
3604 if (used >= options.maxIterations) {
3605 return inst;
3606 }
3607 bool targetRan = false;
3608 const ColMajorXd hS = physicalStaticCurvature(
3609 0.5 * (hessSaddle + hessSaddle.transpose()), saddle, options);
3610 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(hS);
3611 for (size_t s = 0; s < temps.size(); ++s) {
3612 const long remain = options.maxIterations - used;
3613 if (remain <= 0) {
3614 break;
3615 }
3616 RateInstantonOptions opt = options;
3617 opt.maxIterations = remain;
3618 const bool target = s + 1 == temps.size();
3619 opt.checkOddSector = options.checkOddSector && target;
3620 const double betaStage = target ? beta : 1.0 / (kBoltzmann * temps[s]);
3621 std::vector<VectorXd> stageGuess = beads;
3622 if (static_cast<long>(stageGuess.size()) != nBeads) {
3623 stageGuess = cosineSeed(saddle, es.eigenvectors().col(0),
3624 es.eigenvalues()(0), temps[s], inst.crossover,
3625 nBeads, potential, options.discretization);
3626 }
3627 last = optimizeRateInstanton(saddle, hessSaddle, betaStage,
3628 std::move(stageGuess), potential, opt);
3629 used += last.iterations;
3630 if (last.collapsed) {
3631 break;
3632 }
3633 beads = last.beads;
3634 if (target) {
3635 targetRan = true;
3636 }
3637 }
3638 last.iterations = used;
3639 if (targetRan) {
3640 last.beta = beta;
3641 last.betaN = beta / static_cast<double>(nBeads);
3642 last.temperature = inst.temperature;
3643 last.crossover = inst.crossover;
3644 } else {
3645 last.converged = false;
3646 }
3647 return last;
3648 }
3649
3650 if (static_cast<long>(guess.size()) != nBeads) {
3651 const ColMajorXd hS = physicalStaticCurvature(
3652 0.5 * (hessSaddle + hessSaddle.transpose()), saddle, options);
3653 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(hS);
3654 guess = cosineSeed(saddle, es.eigenvectors().col(0), es.eigenvalues()(0),
3655 inst.temperature, inst.crossover, nBeads, potential);
3656 }
3657 const double bnh = inst.betaN * kHbar;
3658 const double spring = 1.0 / (bnh * bnh);
3659 NewtonOut got =
3660 newtonInstanton(std::move(guess), spring, hessSaddle, options, potential);
3661 // A half ring cannot see modes odd under j -> N-j, so two copies of the
3662 // instanton are a stationary point it can accept or sit on. An unstable
3663 // odd mode there sends the search onto the whole ring from a kick along
3664 // that mode.
3665 const long nGot = static_cast<long>(got.beads.size());
3666 bool mirrored = (got.converged || got.stalledHalf) && options.halfRing &&
3667 !options.friction && !options.physicalBath &&
3668 options.checkOddSector && nGot == nBeads && nGot % 2 == 0;
3669 for (long j = 1; mirrored && j < nGot / 2; ++j) {
3670 mirrored = (got.beads[static_cast<size_t>(j)] -
3671 got.beads[static_cast<size_t>(nGot - j)])
3672 .norm() <= 1e-8;
3673 }
3674 if (mirrored) {
3675 const Eigen::SelfAdjointEigenSolver<MatrixXd> es0(
3676 0.5 * (hessSaddle + hessSaddle.transpose()));
3677 const double barrierCurvature = std::abs(es0.eigenvalues()(0));
3678 const RingEval here =
3679 evaluateRing(got.beads, spring, potential, options.energyShift,
3680 frictionEta(options, got.beads.size()));
3681 std::vector<VectorXd> oddMode;
3682 const double oddCurv =
3683 lowestOddMode(got.beads, here, spring, potential, oddMode,
3684 options.lanczosFirst, options.lanczosStep);
3685 if (oddCurv < -1e-3 * barrierCurvature &&
3686 oddMode.size() == got.beads.size()) {
3687 std::vector<VectorXd> kicked = got.beads;
3688 const double kick = std::sqrt(2.0 / (inst.betaN * -oddCurv));
3689 for (size_t k = 0; k < kicked.size(); ++k) {
3690 kicked[k] += kick * oddMode[k];
3691 }
3692 RateInstantonOptions whole = options;
3693 whole.halfRing = false;
3694 const long before = got.iterations;
3695 got = newtonInstanton(std::move(kicked), spring, hessSaddle, whole,
3696 potential);
3697 got.iterations += before;
3698 }
3699 }
3700 inst.beads = got.beads;
3701 inst.energies = got.energies;
3702 inst.ringPotential = got.ringPotential;
3703 inst.bN = got.bN;
3704 inst.iterations = got.iterations;
3705 inst.converged = got.converged;
3706 inst.collapsed = got.collapsed;
3707 return inst;
3708}
3709
3710} // namespace
3711
3712namespace {
3713
3714struct SearchedRing {
3715 std::vector<VectorXd> beads;
3716 std::vector<double> energies;
3717 double ringPotential = 0.0;
3718 double bN = 0.0;
3719 long iterations = 0;
3720 bool converged = false;
3721};
3722
3723std::vector<VectorXd> activeBeadsOf(const std::vector<VectorXd> &full,
3724 bool fold) {
3725 if (!fold) {
3726 return full;
3727 }
3728 const long m = static_cast<long>(full.size()) / 2;
3729 return std::vector<VectorXd>(full.begin(), full.begin() + (m + 1));
3730}
3731
3732std::vector<VectorXd> expandMirrored(const std::vector<VectorXd> &active,
3733 long nBeads, bool fold) {
3734 if (!fold) {
3735 return active;
3736 }
3737 const long m = nBeads / 2;
3738 std::vector<VectorXd> full(static_cast<size_t>(nBeads));
3739 full[0] = active[0];
3740 full[static_cast<size_t>(m)] = active[static_cast<size_t>(m)];
3741 for (long j = 1; j < m; ++j) {
3742 full[static_cast<size_t>(j)] = active[static_cast<size_t>(j)];
3743 full[static_cast<size_t>(nBeads - j)] = active[static_cast<size_t>(j)];
3744 }
3745 return full;
3746}
3747
3748} // namespace
3749
3750void RingPolymerPotential::fixLayout(long nBeads, long dof, bool fold,
3751 const VectorXd &modeDir) {
3752 if (nBeads < 4 || dof < 1 || modeDir.size() != dof) {
3753 throw std::invalid_argument(
3754 "ring structure: need at least 4 beads and a mode of the bead "
3755 "dimension");
3756 }
3757 if (fold && nBeads % 2 != 0) {
3758 throw std::invalid_argument(
3759 "ring structure: a folded ring needs an even bead count");
3760 }
3761 nBeads_ = nBeads;
3762 dof_ = dof;
3763 fold_ = fold;
3764 nActive_ = fold ? (nBeads / 2 + 1) : nBeads;
3765 atomsPerBead_ = (dof + 2) / 3;
3766 usedOnLast_ = static_cast<int>(dof % 3 == 0 ? 3 : dof % 3);
3768 modeDir_ = modeDir;
3769 const double nrm = modeDir_.norm();
3770 if (!(nrm > 0.0)) {
3771 throw std::invalid_argument("ring structure: the saddle direction is zero");
3772 }
3773 modeDir_ /= nrm;
3774}
3775
3777 long dof, double spring,
3778 double energyShift,
3779 std::vector<double> eta, bool fold,
3780 VectorXd modeDir)
3782 beads_(std::move(beads)),
3783 spring_(spring),
3784 energyShift_(energyShift),
3785 eta_(std::move(eta)) {
3786 if (!(spring > 0.0) || !std::isfinite(spring)) {
3787 throw std::invalid_argument(
3788 "ring structure: the spring constant must be positive");
3789 }
3790 fixLayout(nBeads, dof, fold, modeDir);
3791}
3792
3793void RingPolymerPotential::packActive(const std::vector<VectorXd> &active,
3794 double *positions) const {
3795 if (static_cast<long>(active.size()) != nActive_ || positions == nullptr) {
3796 throw std::invalid_argument("ring structure: bead count does not match");
3797 }
3798 std::fill(positions, positions + 3 * nAtoms_, 0.0);
3799 for (long j = 0; j < nActive_; ++j) {
3800 if (active[static_cast<size_t>(j)].size() != dof_) {
3801 throw std::invalid_argument(
3802 "ring structure: bead dimension does not match");
3803 }
3804 long flat = 0;
3805 const double *src = active[static_cast<size_t>(j)].data();
3806 for (long a = 0; a < atomsPerBead_; ++a) {
3807 double *atom = positions + (j * atomsPerBead_ + a) * 3;
3808 const int nax = (a + 1 == atomsPerBead_) ? usedOnLast_ : 3;
3809 for (int ax = 0; ax < nax; ++ax, ++flat) {
3810 atom[ax] = src[flat];
3811 }
3812 }
3813 }
3814}
3815
3816std::vector<VectorXd>
3817RingPolymerPotential::unpack(const double *positions) const {
3818 if (positions == nullptr) {
3819 throw std::invalid_argument("ring structure: missing positions");
3820 }
3821 std::vector<VectorXd> active(static_cast<size_t>(nActive_),
3822 VectorXd::Zero(dof_));
3823 for (long j = 0; j < nActive_; ++j) {
3824 long flat = 0;
3825 for (long a = 0; a < atomsPerBead_; ++a) {
3826 const double *atom = positions + (j * atomsPerBead_ + a) * 3;
3827 const int nax = (a + 1 == atomsPerBead_) ? usedOnLast_ : 3;
3828 for (int ax = 0; ax < nax; ++ax, ++flat) {
3829 active[static_cast<size_t>(j)](flat) = atom[ax];
3830 }
3831 }
3832 }
3833 return active;
3834}
3835
3836void RingPolymerPotential::packMode(const VectorXd &dir,
3837 AtomMatrix &mode) const {
3838 if (mode.rows() != nAtoms_) {
3839 throw std::invalid_argument("ring mode: atom count does not match");
3840 }
3841 std::vector<VectorXd> beads(static_cast<size_t>(nActive_), dir);
3842 packActive(beads, mode.data());
3843 const double nrm = mode.norm();
3844 if (!(nrm > 0.0)) {
3845 throw std::invalid_argument("ring mode: the saddle direction is zero");
3846 }
3847 mode /= nrm;
3848}
3849
3850double RingPolymerPotential::writeForces(const std::vector<VectorXd> &grad,
3851 const double *positions,
3852 double *forces) const {
3853 std::fill(forces, forces + 3 * nAtoms_, 0.0);
3854 for (long j = 0; j < nActive_; ++j) {
3855 long flat = 0;
3856 const double *src = grad[static_cast<size_t>(j)].data();
3857 for (long a = 0; a < atomsPerBead_; ++a) {
3858 double *atom = forces + (j * atomsPerBead_ + a) * 3;
3859 const int nax = (a + 1 == atomsPerBead_) ? usedOnLast_ : 3;
3860 for (int ax = 0; ax < nax; ++ax, ++flat) {
3861 atom[ax] = -src[flat];
3862 }
3863 }
3864 }
3865 double extra = 0.0;
3866 constexpr double kAxis = 1.0e3;
3867 if (usedOnLast_ == 3) {
3868 return extra;
3869 }
3870 for (long j = 0; j < nActive_; ++j) {
3871 const long atom = j * atomsPerBead_ + atomsPerBead_ - 1;
3872 double *frc = forces + atom * 3;
3873 const double *pos = positions + atom * 3;
3874 for (int ax = usedOnLast_; ax < 3; ++ax) {
3875 extra += 0.5 * kAxis * pos[ax] * pos[ax];
3876 frc[ax] = -kAxis * pos[ax];
3877 }
3878 }
3879 return extra;
3880}
3881
3882void RingPolymerPotential::force(long nAtoms, const double *positions,
3883 const int *atomicNrs, double *forces,
3884 double *energy, double *variance,
3885 const double *box) {
3886 const double *pos[] = {positions};
3887 const int *nrs[] = {atomicNrs};
3888 double *frc[] = {forces};
3889 const double *boxes[] = {box};
3890 double var = 0.0;
3891 forceBatch(1, nAtoms, pos, nrs, frc, energy, variance ? &var : &var, boxes);
3892 if (variance) {
3893 *variance = var;
3894 }
3895 forceCallCounter -= 1;
3896}
3897
3898void RingPolymerPotential::forceBatch(long nSystems, long nAtoms,
3899 const double *const *positions,
3900 const int *const *atomicNrs,
3901 double *const *forces, double *energies,
3902 double *variances,
3903 const double *const *boxes) {
3904 static_cast<void>(atomicNrs);
3905 static_cast<void>(boxes);
3906 if (nSystems < 1 || nAtoms != nAtoms_ || positions == nullptr ||
3907 forces == nullptr || energies == nullptr) {
3908 throw std::invalid_argument(
3909 "ring structure: the atom count does not match the bead packing");
3910 }
3911 struct Item {
3912 std::vector<VectorXd> raw;
3913 std::vector<VectorXd> q;
3914 };
3915 std::vector<Item> items(static_cast<size_t>(nSystems));
3916 std::vector<VectorXd> all;
3917 all.reserve(static_cast<size_t>(nSystems * nActive_));
3918 for (long i = 0; i < nSystems; ++i) {
3919 items[static_cast<size_t>(i)].raw = unpack(positions[i]);
3920 items[static_cast<size_t>(i)].q = items[static_cast<size_t>(i)].raw;
3921 if (fold_) {
3922 projectMonotonePrefix(items[static_cast<size_t>(i)].q, nActive_ - 1,
3923 modeDir_);
3924 }
3925 all.insert(all.end(), items[static_cast<size_t>(i)].q.begin(),
3926 items[static_cast<size_t>(i)].q.end());
3927 }
3928 std::vector<double> vAll;
3929 std::vector<VectorXd> gAll;
3930 beads_(all, vAll, gAll);
3931 if (vAll.size() != all.size() || gAll.size() != all.size()) {
3932 throw std::runtime_error(
3933 "ring structure: the bead potential returned the wrong count");
3934 }
3935 size_t cursor = 0;
3936 const double kMono = std::max(4.0 * spring_, 1.0);
3937 for (long i = 0; i < nSystems; ++i) {
3938 const auto &q = items[static_cast<size_t>(i)].q;
3939 const auto &raw = items[static_cast<size_t>(i)].raw;
3940 std::vector<double> vActive(
3941 vAll.begin() + static_cast<std::ptrdiff_t>(cursor),
3942 vAll.begin() + static_cast<std::ptrdiff_t>(cursor + nActive_));
3943 std::vector<VectorXd> gActive(
3944 gAll.begin() + static_cast<std::ptrdiff_t>(cursor),
3945 gAll.begin() + static_cast<std::ptrdiff_t>(cursor + nActive_));
3946 cursor += static_cast<size_t>(nActive_);
3947 for (const auto &g : gActive) {
3948 if (g.size() != dof_) {
3949 throw std::runtime_error(
3950 "ring structure: a bead gradient has the wrong dimension");
3951 }
3952 }
3953 std::vector<VectorXd> fullQ = expandMirrored(q, nBeads_, fold_);
3954 std::vector<double> vFull(static_cast<size_t>(nBeads_));
3955 std::vector<VectorXd> gFull(static_cast<size_t>(nBeads_),
3956 VectorXd::Zero(dof_));
3957 if (!fold_) {
3958 vFull = std::move(vActive);
3959 gFull = std::move(gActive);
3960 } else {
3961 const long m = nBeads_ / 2;
3962 vFull[0] = vActive[0];
3963 gFull[0] = gActive[0];
3964 vFull[static_cast<size_t>(m)] = vActive[static_cast<size_t>(m)];
3965 gFull[static_cast<size_t>(m)] = gActive[static_cast<size_t>(m)];
3966 for (long j = 1; j < m; ++j) {
3967 vFull[static_cast<size_t>(j)] = vActive[static_cast<size_t>(j)];
3968 vFull[static_cast<size_t>(nBeads_ - j)] =
3969 vActive[static_cast<size_t>(j)];
3970 gFull[static_cast<size_t>(j)] = gActive[static_cast<size_t>(j)];
3971 gFull[static_cast<size_t>(nBeads_ - j)] =
3972 gActive[static_cast<size_t>(j)];
3973 }
3974 }
3975 auto replay = [&](const std::vector<VectorXd> &, std::vector<double> &v,
3976 std::vector<VectorXd> &g) {
3977 v = vFull;
3978 g = gFull;
3979 };
3980 const RingEval ev = evaluateRing(fullQ, spring_, replay, energyShift_, eta_,
3982 std::vector<VectorXd> reduced;
3983 if (!fold_) {
3984 reduced = ev.grad;
3985 } else {
3986 const long m = nBeads_ / 2;
3987 reduced.resize(static_cast<size_t>(m + 1));
3988 reduced[0] = ev.grad[0];
3989 reduced[static_cast<size_t>(m)] = ev.grad[static_cast<size_t>(m)];
3990 for (long j = 1; j < m; ++j) {
3991 reduced[static_cast<size_t>(j)] =
3992 ev.grad[static_cast<size_t>(j)] +
3993 ev.grad[static_cast<size_t>(nBeads_ - j)];
3994 }
3995 }
3996 double penalty = 0.0;
3997 if (fold_) {
3998 for (long j = 0; j < nActive_; ++j) {
3999 const VectorXd d =
4000 raw[static_cast<size_t>(j)] - q[static_cast<size_t>(j)];
4001 penalty += 0.5 * kMono * d.squaredNorm();
4002 reduced[static_cast<size_t>(j)] += kMono * d;
4003 }
4004 }
4005 const double axis = writeForces(reduced, positions[i], forces[i]);
4006 energies[i] = ev.u + penalty + axis;
4007 if (variances) {
4008 variances[i] = 0.0;
4009 }
4010 forceCallCounter += 1;
4011 }
4012}
4013
4014namespace {
4015
4016SearchedRing oneDimerSearch(const std::vector<VectorXd> &full, double c,
4017 const BatchPotential &potential,
4018 const RateInstantonOptions &options,
4019 const VectorXd &dir, bool fold,
4020 const std::vector<double> &eta) {
4021 auto pot = std::make_shared<RingPolymerPotential>(
4022 ownedEvaluation(potential, options, 0,
4023 fold ? options.beads / 2 + 1 : options.beads),
4024 options.beads, dir.size(), c, options.energyShift, eta, fold, dir);
4025 pot->setDiscretization(options.discretization);
4026 pot->setPhysicalBath(options.physicalBath);
4027 Parameters params;
4031 options.lanczosStep > 0.0 ? options.lanczosStep : 1.0e-4;
4035 "max_component";
4037 options.forceTolerance;
4041 options.maxIterations;
4043 options.forceTolerance;
4048
4049 auto matter = std::make_shared<Matter>(pot, params);
4050 matter->resize(pot->structureAtoms());
4051 matter->setPeriodic(false);
4052 matter->setMasses(VectorXd::Ones(pot->structureAtoms()));
4053 for (long i = 0; i < pot->structureAtoms(); ++i) {
4054 matter->setAtomicNr(i, 1);
4055 }
4056 const long atomsPer = pot->structureAtoms() / pot->activeBeads();
4057 const int used =
4058 static_cast<int>((dir.size() % 3 == 0) ? 3 : (dir.size() % 3));
4059 if (used < 3) {
4060 for (long j = 0; j < pot->activeBeads(); ++j) {
4061 const long atom = j * atomsPer + atomsPer - 1;
4062 for (int ax = used; ax < 3; ++ax) {
4063 matter->setFixed(atom, ax, 1);
4064 }
4065 }
4066 }
4067 VectorXd packed = VectorXd::Zero(3 * pot->structureAtoms());
4068 pot->packActive(activeBeadsOf(full, fold), packed.data());
4069 matter->setPositionsV(packed);
4070 AtomMatrix mode(pot->structureAtoms(), 3);
4071 pot->packMode(dir, mode);
4072 const double e0 = matter->getPotentialEnergy();
4073 MinModeSaddleSearch search(matter, mode, e0, params, pot);
4074 const int status = search.run(options.maxIterations);
4075
4076 std::vector<VectorXd> beads = expandMirrored(
4077 pot->unpack(matter->getPositions().data()), options.beads, fold);
4078 RingEval ev = evaluateRing(beads, c, potential, options.energyShift, eta,
4079 options.discretization, options.physicalBath);
4080 if (fold) {
4081 std::vector<VectorXd> projected = beads;
4082 projectMonotonePrefix(projected, options.beads / 2, dir);
4083 const long m = options.beads / 2;
4084 for (long j = 1; j < m; ++j) {
4085 projected[static_cast<size_t>(options.beads - j)] =
4086 projected[static_cast<size_t>(j)];
4087 }
4088 RingEval evFold = evaluateRing(projected, c, potential, options.energyShift,
4089 eta, options.discretization);
4090 if (largestBeadNorm(evFold.grad) <= largestBeadNorm(ev.grad)) {
4091 beads = std::move(projected);
4092 ev = std::move(evFold);
4093 }
4094 }
4095 SearchedRing out;
4096 out.beads = std::move(beads);
4097 out.energies = ev.v;
4098 out.ringPotential = ev.u;
4099 for (size_t j = 0; j < out.beads.size(); ++j) {
4100 const size_t next = (j + 1) % out.beads.size();
4101 out.bN += (out.beads[next] - out.beads[j]).squaredNorm();
4102 }
4103 out.iterations = search.getIterationCount();
4104 const double residual = largestBeadNorm(ev.grad);
4105 out.converged =
4106 search.getEigenvalue() < 0.0 && residual < options.forceTolerance;
4107 EONC_LOG_INFO("[Instanton] dimer status {} after {} iterations, largest "
4108 "residual {:.3e}, curvature {:.6f}",
4109 status, out.iterations, residual, search.getEigenvalue());
4110 return out;
4111}
4112
4113SearchedRing searchRingWithDimer(std::vector<VectorXd> full, double c,
4114 const BatchPotential &potential,
4115 const RateInstantonOptions &options,
4116 const VectorXd &dir, bool fold, double betaN,
4117 double barrierCurvature) {
4118 const std::vector<double> eta = frictionEta(options, full.size());
4119 SearchedRing out =
4120 oneDimerSearch(full, c, potential, options, dir, fold, eta);
4121 if (!fold || !options.checkOddSector || out.beads.size() != full.size()) {
4122 return out;
4123 }
4124 const RingEval here =
4125 evaluateRing(out.beads, c, potential, options.energyShift, eta,
4126 options.discretization);
4127 if (!(largestBeadNorm(here.grad) < options.forceTolerance)) {
4128 return out;
4129 }
4130 std::vector<VectorXd> oddMode;
4131 const double oddCurv =
4132 lowestOddMode(out.beads, here, c, potential, oddMode,
4133 options.lanczosFirst, options.lanczosStep, eta);
4134 if (!(oddCurv < -1.0e-3 * barrierCurvature) ||
4135 oddMode.size() != out.beads.size()) {
4136 return out;
4137 }
4138 std::vector<VectorXd> kicked = out.beads;
4139 const double kick = std::sqrt(2.0 / (betaN * -oddCurv));
4140 for (size_t k = 0; k < kicked.size(); ++k) {
4141 kicked[k] += kick * oddMode[k];
4142 }
4143 const long before = out.iterations;
4144 out = oneDimerSearch(kicked, c, potential, options, dir, false, eta);
4145 out.iterations += before;
4146 return out;
4147}
4148
4149} // namespace
4150
4152 const MatrixXd &hessSaddle, double beta,
4153 std::vector<VectorXd> guess,
4154 const BatchPotential &potential,
4155 const RateInstantonOptions &request) {
4156 if (request.physicalBath) {
4157 request.physicalBath->validate(saddle.size());
4158 if (request.friction || !request.discretization.empty() ||
4159 !request.rigidSqrtMasses.empty())
4160 throw std::invalid_argument(
4161 "physical quadratic bath requires uniform links and a retained "
4162 "coordinate basis without rigid generators");
4163 }
4164 if (!(request.physicalHessianStep > 0.0) ||
4165 !std::isfinite(request.physicalHessianStep)) {
4166 throw std::invalid_argument("optimizeRateInstanton: physicalHessianStep "
4167 "must be finite and positive "
4168 "in sqrt(amu) Angstrom");
4169 }
4170 const long N = request.beads;
4171 if (N < 4 || !(beta > 0.0) || hessSaddle.rows() != saddle.size()) {
4172 throw std::invalid_argument(
4173 "optimizeRateInstanton: need N >= 4, beta > 0 and a saddle Hessian "
4174 "of the saddle's dimension");
4175 }
4176 RateInstantonOptions options = request;
4177 // A friction bath couples every bead to every other, which the Newton
4178 // step's block-tridiagonal model cannot hold; the dimer needs gradients
4179 // only, and the rate takes the bath's curvature from the dense ring.
4180 const std::vector<double> bath = frictionEta(options, N);
4181 if (!bath.empty() && !options.discretization.empty()) {
4182 throw std::invalid_argument(
4183 "optimizeRateInstanton: the friction bath's frequencies are those of "
4184 "the uniform ring, so it takes no link weights");
4185 }
4186 RateInstanton inst;
4187 inst.physicalBath = options.physicalBath;
4188 inst.discretization = options.discretization;
4189 inst.bathEta = frictionEta(options, options.beads);
4190 inst.beta = beta;
4191 inst.betaN = beta / static_cast<double>(N);
4192 inst.temperature = 1.0 / (kBoltzmann * beta);
4194 options.physicalBath
4195 ? MatrixXd(options.physicalBath->fullHessian(saddle, hessSaddle))
4196 : hessSaddle);
4197 if (!(inst.temperature < inst.crossover)) {
4198 throw std::invalid_argument(
4199 "optimizeRateInstanton: T is at or above the crossover temperature; "
4200 "the ring collapses onto the saddle and steepest descent needs the "
4201 "parabolic barrier correction, of which classical transition-state "
4202 "theory is only the one-bead limit");
4203 }
4204 bool mirror = options.halfRing && options.discretization.empty() &&
4205 !options.friction && !options.physicalBath && N % 2 == 0;
4206 if (mirror && static_cast<long>(guess.size()) == N) {
4207 const long mid = N / 2;
4208 for (long j = 1; j < mid && mirror; ++j) {
4209 if ((guess[static_cast<size_t>(j)] - guess[static_cast<size_t>(N - j)])
4210 .norm() > 1e-8) {
4211 mirror = false;
4212 }
4213 }
4214 }
4215 const long active = mirror ? (N / 2 + 1) : N;
4216 // The nonlocal bath uses the dense Newton operator. Larger rings
4217 // use the dimer backend, whose products include the complete bath.
4218 const bool denseBath =
4219 options.physicalBath || !frictionEta(options, N).empty();
4220 if (options.newtonLimit > 0 &&
4221 active * saddle.size() <= options.newtonLimit &&
4222 (!denseBath || active * saddle.size() <= kDenseRing)) {
4223 return optimizeRateByNewton(saddle, hessSaddle, beta, std::move(guess),
4224 potential, options);
4225 }
4226 if (!options.discretization.empty()) {
4227 throw std::invalid_argument(
4228 "optimizeRateInstanton: link weights take the Newton search; "
4229 "minimum-mode following keeps the uniform ring");
4230 }
4231 const double bnh = inst.betaN * kHbar;
4232 const double c = 1.0 / (bnh * bnh);
4233
4234 const ColMajorXd saddleCurvature = physicalStaticCurvature(
4235 0.5 * (hessSaddle + hessSaddle.transpose()), saddle, options);
4236 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(saddleCurvature);
4237 const VectorXd dir = es.eigenvectors().col(0);
4238
4239 if (static_cast<long>(guess.size()) != N) {
4240 std::vector<double> v0;
4241 std::vector<VectorXd> g0;
4242 potential({saddle}, v0, g0);
4243 const double vS = v0.at(0);
4244 // Scan in steps of a quarter of the length over which the barrier's
4245 // curvature drops V by kB T_c.
4246 const double h = 0.25 * std::sqrt(2.0 * kBoltzmann * inst.crossover /
4247 -es.eigenvalues()(0));
4248 const long pts = 200;
4249 const double dPlus = sideDrop(saddle, dir, vS, 1.0, h, pts, potential);
4250 const double dMinus = sideDrop(saddle, dir, vS, -1.0, h, pts, potential);
4251 const double dMin = std::min(dPlus, dMinus);
4252 const double drop =
4253 (1.0 - inst.temperature / inst.crossover) *
4254 (std::isfinite(dMin) ? dMin : kBoltzmann * inst.crossover);
4255 const double sPlus =
4256 turningDistance(saddle, dir, vS, drop, 1.0, h, pts, potential);
4257 const double sMinus =
4258 turningDistance(saddle, dir, vS, drop, -1.0, h, pts, potential);
4259 guess.resize(static_cast<size_t>(N));
4260 for (long j = 0; j < N; ++j) {
4261 const double ct =
4262 std::cos(2.0 * std::numbers::pi * static_cast<double>(j) /
4263 static_cast<double>(N));
4264 guess[static_cast<size_t>(j)] =
4265 saddle + dir * (ct >= 0.0 ? sPlus * ct : sMinus * ct);
4266 }
4267 }
4268
4269 // An even count whose beads already match under j -> N-j is the
4270 // out-and-back instanton. The shared dimer sees one half of that ring.
4271 const bool wantMirror = options.halfRing && !options.friction &&
4272 !options.physicalBath &&
4273 options.discretization.empty() && N % 2 == 0;
4274 std::vector<VectorXd> x = std::move(guess);
4275 bool fold = false;
4276 if (wantMirror) {
4277 fold = true;
4278 const long m = N / 2;
4279 for (long j = 1; j < m; ++j) {
4280 if ((x[static_cast<size_t>(j)] - x[static_cast<size_t>(N - j)]).norm() >
4281 1e-8) {
4282 fold = false;
4283 break;
4284 }
4285 }
4286 }
4287 if (fold) {
4288 const long m = N / 2;
4289 for (long j = 1; j < m; ++j) {
4290 const size_t a = static_cast<size_t>(j);
4291 const size_t b = static_cast<size_t>(N - j);
4292 const VectorXd mid = 0.5 * (x[a] + x[b]);
4293 x[a] = mid;
4294 x[b] = mid;
4295 }
4296 projectMonotonePrefix(x, m, dir);
4297 for (long j = 1; j < m; ++j) {
4298 x[static_cast<size_t>(N - j)] = x[static_cast<size_t>(j)];
4299 }
4300 }
4301 const double barrierCurvature = std::abs(es.eigenvalues()(0));
4302 const SearchedRing found =
4303 searchRingWithDimer(std::move(x), c, potential, options, dir, fold,
4304 inst.betaN, barrierCurvature);
4305 inst.beads = found.beads;
4306 inst.energies = found.energies;
4307 inst.ringPotential = found.ringPotential;
4308 inst.bN = found.bN;
4309 inst.iterations = found.iterations;
4310 inst.converged = found.converged;
4311 return inst;
4312}
4313
4314namespace {
4315
4320std::vector<bool> nearestZero(const VectorXd &lam, long count, long first = 0) {
4321 std::vector<long> order(static_cast<size_t>(lam.size() - first));
4322 std::iota(order.begin(), order.end(), first);
4323 std::sort(order.begin(), order.end(), [&](long a, long b) {
4324 return std::abs(lam(a)) < std::abs(lam(b));
4325 });
4326 std::vector<bool> out(static_cast<size_t>(lam.size()), false);
4327 for (long k = 0; k < std::min<long>(count, static_cast<long>(order.size()));
4328 ++k) {
4329 out[static_cast<size_t>(order[static_cast<size_t>(k)])] = true;
4330 }
4331 return out;
4332}
4333
4334} // namespace
4335
4336namespace {
4337
4338// The principal moments, about the beads' common centre of mass, of the
4339// inertia restricted to the free rotation axes, sorted, those under 1e-8
4340// of the largest left out.
4341std::vector<double> rotationMoments(const std::vector<VectorXd> &beads,
4342 const RingRigidBodies &bodies) {
4343 const long nAtoms = static_cast<long>(bodies.sqrtMasses.size());
4344 Eigen::Vector3d centre = Eigen::Vector3d::Zero();
4345 double total = 0.0;
4346 auto position = [&](const VectorXd &q, long k) {
4347 return Eigen::Vector3d(bodies.reference.segment<3>(3 * k) +
4348 q.segment<3>(3 * k) /
4349 bodies.sqrtMasses[static_cast<size_t>(k)]);
4350 };
4351 for (const auto &q : beads) {
4352 for (long k = 0; k < nAtoms; ++k) {
4353 const double m = bodies.sqrtMasses[static_cast<size_t>(k)] *
4354 bodies.sqrtMasses[static_cast<size_t>(k)];
4355 centre += m * position(q, k);
4356 total += m;
4357 }
4358 }
4359 centre /= total;
4360 Eigen::Matrix3d inertia = Eigen::Matrix3d::Zero();
4361 for (const auto &q : beads) {
4362 for (long k = 0; k < nAtoms; ++k) {
4363 const double m = bodies.sqrtMasses[static_cast<size_t>(k)] *
4364 bodies.sqrtMasses[static_cast<size_t>(k)];
4365 const Eigen::Vector3d x = position(q, k) - centre;
4366 inertia += m * (x.squaredNorm() * Eigen::Matrix3d::Identity() -
4367 x * x.transpose());
4368 }
4369 }
4370 std::vector<int> axes;
4371 for (int c = 0; c < 3; ++c) {
4372 if (bodies.rotations[static_cast<size_t>(c)]) {
4373 axes.push_back(c);
4374 }
4375 }
4376 MatrixXd sub(static_cast<long>(axes.size()), static_cast<long>(axes.size()));
4377 for (size_t a = 0; a < axes.size(); ++a) {
4378 for (size_t b = 0; b < axes.size(); ++b) {
4379 sub(static_cast<long>(a), static_cast<long>(b)) =
4380 inertia(axes[a], axes[b]);
4381 }
4382 }
4383 const Eigen::SelfAdjointEigenSolver<MatrixXd> es(sub, Eigen::EigenvaluesOnly);
4384 const VectorXd &moments = es.eigenvalues();
4385 const double largest = moments.size() > 0 ? moments.maxCoeff() : 0.0;
4386 std::vector<double> out;
4387 for (long i = 0; i < moments.size(); ++i) {
4388 if (moments(i) > 1e-8 * largest) {
4389 out.push_back(moments(i));
4390 }
4391 }
4392 return out;
4393}
4394
4395} // namespace
4396
4397double logRotationalRatio(const std::vector<VectorXd> &beads,
4398 const RingRigidBodies &bodies) {
4399 const long nAtoms = static_cast<long>(bodies.sqrtMasses.size());
4400 const bool anyFree =
4401 bodies.rotations[0] || bodies.rotations[1] || bodies.rotations[2];
4402 if (nAtoms == 0 || !anyFree || beads.empty()) {
4403 return 0.0;
4404 }
4405 if (bodies.reference.size() != 3 * nAtoms) {
4406 throw std::invalid_argument(
4407 "logRotationalRatio: the reference needs three coordinates per atom");
4408 }
4409 for (const auto &q : beads) {
4410 if (q.size() != 3 * nAtoms) {
4411 throw std::invalid_argument(
4412 "logRotationalRatio: a bead needs three coordinates per atom");
4413 }
4414 }
4415 const std::vector<double> ring = rotationMoments(beads, bodies);
4416 const std::vector<double> reactant = rotationMoments(
4417 std::vector<VectorXd>(beads.size(), VectorXd::Zero(3 * nAtoms)), bodies);
4418 if (ring.size() != reactant.size()) {
4419 throw std::runtime_error("logRotationalRatio: the beads turn about " +
4420 std::to_string(ring.size()) +
4421 " axes and the reactant about " +
4422 std::to_string(reactant.size()));
4423 }
4424 double out = 0.0;
4425 for (size_t i = 0; i < ring.size(); ++i) {
4426 out += 0.5 * (std::log(ring[i]) - std::log(reactant[i]));
4427 }
4428 return out;
4429}
4430
4431double closedRingPotential(const std::vector<VectorXd> &beads, double spring,
4432 const BatchPotential &potential,
4433 const std::vector<double> &discretization) {
4434 if (beads.size() < 2 || !(spring > 0.0)) {
4435 throw std::invalid_argument(
4436 "closedRingPotential: need two beads and a positive spring");
4437 }
4438 return evaluateRing(beads, spring, potential, 0.0, {}, discretization).u;
4439}
4440
4441namespace {
4442
4443// The quadratic bath is K=T^T F^* Omega F T. Applying its gradient to
4444// coordinate basis vectors retains the same finite operator as the energy.
4445MatrixXd finiteBathKernel(long n, const std::vector<double> &eta,
4446 double &symmetryResidual) {
4447 MatrixXd kernel = MatrixXd::Zero(n, n);
4448 for (long col = 0; col < n; ++col) {
4449 std::vector<VectorXd> q(static_cast<size_t>(n), VectorXd::Zero(1));
4450 std::vector<VectorXd> g = q;
4451 q[static_cast<size_t>(col)](0) = 1.0;
4452 double energy = 0.0;
4453 addFrictionBath(q, energy, g, eta);
4454 for (long row = 0; row < n; ++row) {
4455 kernel(row, col) = g[static_cast<size_t>(row)](0);
4456 }
4457 }
4458 symmetryResidual = (kernel - kernel.transpose()).cwiseAbs().maxCoeff();
4459 const double tolerance = 64.0 * std::numeric_limits<double>::epsilon() * n *
4460 kernel.cwiseAbs().maxCoeff();
4461 if (!kernel.allFinite() || symmetryResidual > tolerance) {
4462 throw std::runtime_error("instantonRate: asymmetric finite bath kernel");
4463 }
4464 return (0.5 * (kernel + kernel.transpose())).eval();
4465}
4466
4467void bathFluctuations(RateInstanton &inst,
4468 const std::vector<MatrixXd> &physical,
4469 const std::vector<std::vector<VectorXd>> &rigid,
4470 const VectorXd &reactantValues,
4471 const std::vector<bool> &rigidReactant, double vReactant,
4472 double c) {
4473 const long n = static_cast<long>(inst.beads.size());
4474 const long f = inst.beads.front().size();
4475 const long dim = n * f;
4476 const double bnh = inst.betaN * kHbar;
4477 if (!(bnh > 0.0) || !std::isfinite(bnh) || !(inst.beta > 0.0) ||
4478 !std::isfinite(inst.beta)) {
4479 throw std::invalid_argument(
4480 "instantonRate: finite positive bath inverse temperature required");
4481 }
4482 if (!reactantValues.allFinite()) {
4483 throw std::runtime_error(
4484 "instantonRate: non-finite bath reactant spectrum");
4485 }
4486 MatrixXd bead = finiteBathKernel(n, inst.bathEta, inst.bathSymmetryResidual);
4487 for (long j = 0; j < n; ++j) {
4488 const long k = (j + 1) % n;
4489 const double w = inst.discretization.empty()
4490 ? 1.0
4491 : inst.discretization[static_cast<size_t>(j)];
4492 const double link = c / w;
4493 bead(j, j) += link;
4494 bead(k, k) += link;
4495 bead(j, k) -= link;
4496 bead(k, j) -= link;
4497 }
4498 const Eigen::SelfAdjointEigenSolver<ColMajorXd> eb(bead);
4499 if (eb.info() != Eigen::Success || !eb.eigenvalues().allFinite()) {
4500 throw std::runtime_error("instantonRate: bath bead eigensolver failed");
4501 }
4502 const double beadScale = bead.cwiseAbs().maxCoeff();
4503 const double beadTol =
4504 64.0 * std::numeric_limits<double>::epsilon() * n * beadScale;
4505 if (eb.eigenvalues()(0) < -beadTol) {
4506 throw std::runtime_error(
4507 "instantonRate: bath bead operator is not positive semidefinite");
4508 }
4509 // The reactant Hessian is constant over beads, so its eigenvalues add
4510 // to the exact eigenvalues of the scalar bead operator, including K.
4511 double reactantLogDet = 0.0;
4512 long reactantDim = 0;
4513 for (long k = 0; k < n; ++k) {
4514 const double mu = std::max(0.0, eb.eigenvalues()(k));
4515 for (long m = 0; m < f; ++m) {
4516 if (k == 0 && rigidReactant[static_cast<size_t>(m)]) {
4517 continue;
4518 }
4519 const double curvature =
4520 rigidReactant[static_cast<size_t>(m)] ? 0.0 : reactantValues(m);
4521 if ((!rigidReactant[static_cast<size_t>(m)] && !(curvature > 0.0)) ||
4522 !(curvature + mu > 0.0) || !std::isfinite(curvature + mu)) {
4523 throw std::runtime_error(
4524 "instantonRate: bath reactant curvature is not positive");
4525 }
4526 reactantLogDet += std::log(curvature + mu);
4527 ++reactantDim;
4528 }
4529 }
4530 inst.bathReactantLogAbsDet = reactantLogDet;
4531 inst.logZr = -inst.beta * vReactant - reactantDim * std::log(bnh) -
4532 0.5 * reactantLogDet;
4533
4534 ColMajorXd full = ColMajorXd::Zero(dim, dim);
4535 const MatrixXd eye = MatrixXd::Identity(f, f);
4536 for (long j = 0; j < n; ++j) {
4537 for (long k = 0; k < n; ++k) {
4538 full.block(j * f, k * f, f, f) = bead(j, k) * eye;
4539 }
4540 if (!physical[static_cast<size_t>(j)].allFinite()) {
4541 throw std::runtime_error(
4542 "instantonRate: non-finite physical bead Hessian");
4543 }
4544 full.block(j * f, j * f, f, f) += physical[static_cast<size_t>(j)];
4545 }
4546 // Only declared physical rigid generators leave this operator.
4547 ColMajorXd quotient = ColMajorXd::Identity(dim, dim);
4548 if (!rigid.empty()) {
4549 ColMajorXd generators(dim, static_cast<long>(rigid.size()));
4550 for (long j = 0; j < generators.cols(); ++j) {
4551 generators.col(j) = packBeads(rigid[static_cast<size_t>(j)]);
4552 }
4553 Eigen::ColPivHouseholderQR<ColMajorXd> qr(generators);
4554 if (qr.rank() != generators.cols()) {
4555 throw std::runtime_error(
4556 "instantonRate: dependent declared rigid generators");
4557 }
4558 const ColMajorXd q = qr.householderQ() * ColMajorXd::Identity(dim, dim);
4559 quotient = q.rightCols(dim - generators.cols());
4560 }
4561 const double fullResidual = (full - full.transpose()).cwiseAbs().maxCoeff();
4562 const double fullTolerance = 64.0 * std::numeric_limits<double>::epsilon() *
4563 dim * full.cwiseAbs().maxCoeff();
4564 if (!full.allFinite() || fullResidual > fullTolerance) {
4565 throw std::runtime_error(
4566 "instantonRate: asymmetric bath fluctuation operator");
4567 }
4568 const ColMajorXd reducedRaw = quotient.transpose() * full * quotient;
4569 const double reducedResidual =
4570 (reducedRaw - reducedRaw.transpose()).cwiseAbs().maxCoeff();
4571 const double reducedTolerance =
4572 64.0 * std::numeric_limits<double>::epsilon() * reducedRaw.rows() *
4573 reducedRaw.cwiseAbs().maxCoeff();
4574 if (!reducedRaw.allFinite() || reducedResidual > reducedTolerance) {
4575 throw std::runtime_error(
4576 "instantonRate: asymmetric reduced bath fluctuation operator");
4577 }
4578 inst.bathSymmetryResidual =
4579 std::max({inst.bathSymmetryResidual, fullResidual, reducedResidual});
4580 const ColMajorXd reduced =
4581 (0.5 * (reducedRaw + reducedRaw.transpose())).eval();
4582 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(reduced);
4583 if (es.info() != Eigen::Success || !es.eigenvalues().allFinite()) {
4584 throw std::runtime_error(
4585 "instantonRate: bath fluctuation eigensolver failed");
4586 }
4587 const VectorXd values = es.eigenvalues();
4588 const double span = values.cwiseAbs().maxCoeff();
4589 const double zeroTol =
4590 64.0 * std::numeric_limits<double>::epsilon() * values.size() * span;
4591 inst.bathRoundoffScale = zeroTol;
4592 inst.bathSignedCurvatures.assign(values.data(),
4593 values.data() + values.size());
4594 inst.negativeModes = 0;
4595 long nulls = 0;
4596 for (long i = 0; i < values.size(); ++i) {
4597 inst.negativeModes += values(i) < -zeroTol ? 1 : 0;
4598 nulls += std::abs(values(i)) <= zeroTol ? 1 : 0;
4599 }
4600 inst.negativeEigenvalue = std::min(0.0, values(0));
4601 VectorXd cycle = quotient.transpose() * timeTranslation(inst.beads);
4602 const double cycleNorm = cycle.norm();
4603 long phase = -1;
4604 double bestOverlap = 0.0;
4605 if (cycleNorm > 1e-8) {
4606 cycle /= cycleNorm;
4607 for (long i = 0; i < values.size(); ++i) {
4608 const double overlap = std::abs(es.eigenvectors().col(i).dot(cycle));
4609 if (std::abs(values(i)) <= zeroTol && overlap > 0.9 &&
4610 overlap > bestOverlap) {
4611 phase = i;
4612 bestOverlap = overlap;
4613 }
4614 }
4615 }
4616 // Integer bead shifts are a discrete symmetry, not a continuous zero mode.
4617 bool circulant = true;
4618 for (long j = 0; j < n; ++j) {
4619 for (long k = 0; k < n; ++k) {
4620 circulant =
4621 circulant &&
4622 std::abs(bead(j, k) - bead((j + 1) % n, (k + 1) % n)) <= beadTol;
4623 }
4624 }
4625 inst.phaseEigenResidual = phase >= 0
4626 ? (reduced * es.eigenvectors().col(phase) -
4627 values(phase) * es.eigenvectors().col(phase))
4628 .norm()
4629 : std::numeric_limits<double>::quiet_NaN();
4630 inst.phaseZeroVerified = phase >= 0 && nulls == 1 && circulant &&
4631 inst.phaseEigenResidual <= zeroTol;
4632 inst.zeroEigenvalue = phase >= 0 ? values(phase) : 0.0;
4633 inst.bathLogAbsDet = 0.0;
4634 for (long i = 0; i < values.size(); ++i) {
4635 if (std::abs(values(i)) > zeroTol) {
4636 inst.bathLogAbsDet += std::log(std::abs(values(i)));
4637 }
4638 }
4639 // This absolute Gaussian integral excludes contour and rate normalization.
4640 inst.logAbsoluteGaussianWeight =
4641 nulls == 0 ? -inst.betaN * inst.ringPotential -
4642 values.size() * std::log(bnh) - 0.5 * inst.bathLogAbsDet
4643 : std::numeric_limits<double>::quiet_NaN();
4644 inst.rateValid =
4645 inst.converged && inst.phaseZeroVerified && inst.negativeModes == 1;
4646 inst.rateValidity =
4647 !inst.converged
4648 ? "unconverged_bath_ring"
4649 : (nulls > 1
4650 ? "additional_bath_null_modes"
4651 : (!circulant
4652 ? "bead_dependent_operator_no_continuous_phase"
4653 : (inst.negativeModes != 1
4654 ? "non_index_one_bath_ring"
4655 : (inst.phaseZeroVerified
4656 ? "numerically_null_collective_phase"
4657 : "resolved_finite_bead_phase"))));
4658 if (!inst.rateValid) {
4659 const double invalid = std::numeric_limits<double>::quiet_NaN();
4660 inst.logRateTimesZr = inst.logRate = inst.rate = inst.effectiveBarrier =
4661 invalid;
4662 return;
4663 }
4664 const long kept = values.size() - 1;
4665 const double logProd = kept * std::log(bnh) + 0.5 * inst.bathLogAbsDet;
4666 inst.logRateTimesZr = -std::log(bnh) +
4667 0.5 * std::log(inst.bN / (2.0 * std::numbers::pi *
4668 inst.betaN * kHbar * kHbar)) -
4669 logProd - inst.betaN * inst.ringPotential;
4670 inst.logRate = inst.logRateTimesZr - inst.logZr;
4671 inst.rate = std::exp(inst.logRate) / kTimeUnitSeconds;
4672 inst.effectiveBarrier =
4673 -std::log(2.0 * std::numbers::pi * kHbar * inst.beta) / inst.beta -
4674 inst.logRate / inst.beta;
4675 if (!std::isfinite(inst.logRateTimesZr) || !std::isfinite(inst.logZr) ||
4676 !std::isfinite(inst.logRate)) {
4677 throw std::runtime_error("instantonRate: non-finite bath prefactor");
4678 }
4679}
4680
4681void physicalBathFluctuations(RateInstanton &inst,
4682 const std::vector<MatrixXd> &physical,
4683 const MatrixXd &reactant, double vReactant,
4684 double c) {
4685 const long n = inst.beads.size(), f = inst.beads.front().size(), dim = n * f;
4686 const auto bath = inst.physicalBath->evaluate(inst.beads, c, true);
4687 const std::vector<VectorXd> qr(n, VectorXd::Zero(f));
4688 const auto referenceBath = inst.physicalBath->evaluate(qr, c, true);
4689 ColMajorXd h = bath.hessian, hr = referenceBath.hessian;
4690 const MatrixXd eye = MatrixXd::Identity(f, f);
4691 for (long j = 0; j < n; ++j) {
4692 const long next = (j + 1) % n;
4693 h.block(j * f, j * f, f, f) += physical[j];
4694 hr.block(j * f, j * f, f, f) += reactant;
4695 for (auto *matrix : {&h, &hr}) {
4696 matrix->block(j * f, j * f, f, f) += c * eye;
4697 matrix->block(next * f, next * f, f, f) += c * eye;
4698 matrix->block(j * f, next * f, f, f) -= c * eye;
4699 matrix->block(next * f, j * f, f, f) -= c * eye;
4700 }
4701 }
4702 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(0.5 * (h + h.transpose()));
4703 const Eigen::SelfAdjointEigenSolver<ColMajorXd> er(0.5 *
4704 (hr + hr.transpose()));
4705 if (es.info() != Eigen::Success || er.info() != Eigen::Success ||
4706 !es.eigenvalues().allFinite() || !er.eigenvalues().allFinite() ||
4707 !(er.eigenvalues().minCoeff() > 0))
4708 throw std::runtime_error(
4709 "physical bath: invalid fluctuation or reactant spectrum");
4710 const VectorXd values = es.eigenvalues();
4711 const double zeroTol = 64 * std::numeric_limits<double>::epsilon() * dim *
4712 values.cwiseAbs().maxCoeff();
4713 inst.bathRoundoffScale = zeroTol;
4714 inst.bathSignedCurvatures.assign(values.data(),
4715 values.data() + values.size());
4716 inst.bathSymmetryResidual = (h - h.transpose()).cwiseAbs().maxCoeff();
4717 inst.negativeModes = 0;
4718 long zeros = 0, phase = -1;
4719 double overlap = 0;
4720 const VectorXd tau = timeTranslation(inst.beads);
4721 if (tau.size() != dim)
4722 throw std::runtime_error("physical bath: collapsed ring");
4723 for (long k = 0; k < dim; ++k) {
4724 inst.negativeModes += values[k] < -zeroTol;
4725 zeros += std::abs(values[k]) <= zeroTol;
4726 const double candidate = std::abs(es.eigenvectors().col(k).dot(tau));
4727 if (candidate > overlap) {
4728 overlap = candidate;
4729 phase = k;
4730 }
4731 }
4732 inst.negativeEigenvalue = values[0];
4733 inst.zeroEigenvalue = values[phase];
4734 inst.phaseEigenResidual = (h * es.eigenvectors().col(phase) -
4735 values[phase] * es.eigenvectors().col(phase))
4736 .norm();
4737 inst.phaseZeroVerified = zeros == 1 && std::abs(values[phase]) <= zeroTol &&
4738 overlap > 0.9 && inst.phaseEigenResidual <= zeroTol;
4739 const long bathDimension = inst.physicalBath->curvatures.size();
4740 double phaseMetric = 1.0, fullBN = inst.bN;
4741 const VectorXd retainedPhase = es.eigenvectors().col(phase);
4742 Eigen::MatrixXd sourceVariation(n * bathDimension, 1);
4743 for (long l = 0; l < n; ++l)
4744 sourceVariation.middleRows(l * bathDimension, bathDimension) =
4745 bath.sourceJacobians[l] * retainedPhase.segment(l * f, f);
4746 const Eigen::MatrixXd lifted = -bath.solveBath(sourceVariation);
4747 phaseMetric += lifted.squaredNorm();
4748 for (long j = 0; j < n; ++j) {
4749 fullBN +=
4750 (bath.bathPositions[(j + 1) % n] - bath.bathPositions[j]).squaredNorm();
4751 }
4752 if (!(fullBN > 0) || !std::isfinite(fullBN) || !std::isfinite(phaseMetric))
4753 throw std::runtime_error("physical bath: invalid lifted phase measure");
4755 "[Instanton] physical bath phase measure: bN_full {:.17g}, bN_retained "
4756 "{:.17g}, lift_metric {:.17g}, effective_bN {:.17g}",
4757 fullBN, inst.bN, phaseMetric, fullBN / phaseMetric);
4758 double logPrime = 0;
4759 for (long k = 0; k < dim; ++k)
4760 if (k != phase)
4761 logPrime += std::log(std::abs(values[k]));
4762 const double referenceDet = er.eigenvalues().array().log().sum();
4763 const double fullDimension = n * (f + inst.physicalBath->curvatures.size());
4764 const double logMeasure = fullDimension * std::log(inst.betaN * kHbar);
4765 inst.bathLogAbsDet =
4766 logPrime + bath.bathLogDeterminant + std::log(phaseMetric);
4767 inst.bathReactantLogAbsDet = referenceDet + referenceBath.bathLogDeterminant;
4768 inst.logZr =
4769 -inst.beta * vReactant - logMeasure - 0.5 * inst.bathReactantLogAbsDet;
4770 // For an exact phase zero, det' H_full=det D_bath det' S times
4771 // ||u_full||^2/||u_retained||^2. Use the full primitive link measure
4772 // with this lifted pseudodeterminant. At finite N the link measure
4773 // and the phase-eigenvector metric are distinct quadratures.
4774 inst.logRateTimesZr =
4775 -logMeasure +
4776 0.5 * std::log(fullBN /
4777 (2 * std::numbers::pi * inst.betaN * kHbar * kHbar)) -
4778 0.5 * inst.bathLogAbsDet - inst.betaN * inst.ringPotential;
4779 inst.rateValid =
4780 inst.converged && inst.phaseZeroVerified && inst.negativeModes == 1;
4781 inst.rateValidity =
4782 !inst.converged
4783 ? "unconverged_physical_bath_ring"
4784 : (!inst.phaseZeroVerified
4785 ? "unverified_physical_bath_phase"
4786 : (inst.negativeModes != 1 ? "non_index_one_physical_bath_ring"
4787 : "physical_quadratic_bath"));
4788 if (!inst.rateValid) {
4789 const double invalid = std::numeric_limits<double>::quiet_NaN();
4790 inst.logRateTimesZr = inst.logRate = inst.rate = inst.effectiveBarrier =
4791 invalid;
4792 return;
4793 }
4794 inst.logRate = inst.logRateTimesZr - inst.logZr;
4795 inst.rate = std::exp(inst.logRate) / kTimeUnitSeconds;
4796 inst.effectiveBarrier =
4797 -std::log(2 * std::numbers::pi * kHbar * inst.beta) / inst.beta -
4798 inst.logRate / inst.beta;
4799 inst.classicalRate = inst.classicalLogRate =
4800 std::numeric_limits<double>::quiet_NaN();
4801}
4802
4803} // namespace
4804
4806 const MatrixXd &hessReactant, double vReactant,
4807 const MatrixXd &hessSaddle, double vSaddle, long rigidModes,
4808 long denseLimit, const RingRigidBodies &rigidBodies) {
4809 const long N = static_cast<long>(inst.beads.size());
4810 if (N < 4 || !(inst.betaN > 0.0)) {
4811 throw std::invalid_argument("instantonRate: no optimised ring");
4812 }
4813 const long f = inst.beads.front().size();
4814 if (rigidModes < 0 || rigidModes > f) {
4815 throw std::invalid_argument(
4816 "instantonRate: rigidModes exceeds the degrees of freedom");
4817 }
4818 const double bnh = inst.betaN * kHbar;
4819 const double c = 1.0 / (bnh * bnh);
4820 const MatrixXd eye = MatrixXd::Identity(f, f);
4821 const std::vector<double> *linkWeight =
4822 inst.discretization.empty() ? nullptr : &inst.discretization;
4823
4824 std::vector<MatrixXd> hBead(static_cast<size_t>(N));
4825 for (long j = 0; j < N; ++j) {
4826 const MatrixXd h = hessian(j, inst.beads[static_cast<size_t>(j)]);
4827 if (h.rows() != f || h.cols() != f) {
4828 throw std::runtime_error("instantonRate: bead Hessian size");
4829 }
4830 const double hTolerance = 64.0 * std::numeric_limits<double>::epsilon() *
4831 f * h.cwiseAbs().maxCoeff();
4832 if (!h.allFinite() ||
4833 (h - h.transpose()).cwiseAbs().maxCoeff() > hTolerance) {
4834 throw std::runtime_error(
4835 "instantonRate: asymmetric physical bead Hessian");
4836 }
4837 hBead[static_cast<size_t>(j)] = 0.5 * (h + h.transpose());
4838 }
4839 const std::vector<MatrixXd> diag = ringDiagonal(hBead, c, false, linkWeight);
4840
4841 if (inst.physicalBath) {
4842 if (rigidModes || !inst.discretization.empty() || !inst.bathEta.empty())
4843 throw std::invalid_argument(
4844 "physical bath fluctuations require retained coordinates and uniform "
4845 "links without scalar friction");
4846 physicalBathFluctuations(inst, hBead, hessReactant, vReactant, c);
4847 return;
4848 }
4849
4850 if (hessReactant.rows() != f || hessReactant.cols() != f ||
4851 !hessReactant.allFinite()) {
4852 throw std::runtime_error("instantonRate: invalid reactant Hessian");
4853 }
4854 const double reactantTolerance = 64.0 *
4855 std::numeric_limits<double>::epsilon() * f *
4856 hessReactant.cwiseAbs().maxCoeff();
4857 if ((hessReactant - hessReactant.transpose()).cwiseAbs().maxCoeff() >
4858 reactantTolerance) {
4859 throw std::runtime_error("instantonRate: asymmetric reactant Hessian");
4860 }
4861 const Eigen::SelfAdjointEigenSolver<MatrixXd> er(
4862 0.5 * (hessReactant + hessReactant.transpose()));
4863 if (er.info() != Eigen::Success || !er.eigenvalues().allFinite()) {
4864 throw std::runtime_error("instantonRate: reactant eigensolver failed");
4865 }
4866 const VectorXd &lr = er.eigenvalues();
4867 const std::vector<bool> rigidR = nearestZero(lr, rigidModes);
4868 MatrixXd nullBasis(f, 0);
4869 // The rigid vectors leave the product whether or not every bead Hessian
4870 // annihilates them exactly; a finite-difference Hessian never does, and
4871 // the reactant side drops the same modes at k = 0.
4872 for (long m = 0; m < lr.size(); ++m) {
4873 if (!rigidR[static_cast<size_t>(m)]) {
4874 continue;
4875 }
4876 nullBasis.conservativeResize(f, nullBasis.cols() + 1);
4877 nullBasis.col(nullBasis.cols() - 1) = er.eigenvectors().col(m);
4878 }
4879 if (rigidModes >= f) {
4880 throw std::runtime_error("instantonRate: every direction is a rigid mode");
4881 }
4882 // det' through the block chain: the cyclic zero mode and the rigid null
4883 // vectors leave the product by the determinant lemma, the inertia comes
4884 // from the Schur complements, and the N f by N f matrix is never formed.
4885 std::vector<VectorXd> cycle = beadVelocities(inst.beads, linkWeight);
4886 const double cycleNorm = dot(cycle, cycle);
4887 if (!(cycleNorm > 0.0)) {
4888 throw std::runtime_error(
4889 "instantonRate: the beads coincide, so the ring has collapsed");
4890 }
4891 scale(cycle, 1.0 / std::sqrt(cycleNorm));
4892 // The rigid null vectors, orthonormal.
4893 std::vector<std::vector<VectorXd>> rigid;
4894 if (!rigidBodies.sqrtMasses.empty()) {
4895 // The ring's own rigid motions; the lemma needs an orthonormal basis of
4896 // the null space, not the generators themselves.
4897 rigid = ringRigidBasis(inst.beads, rigidBodies.sqrtMasses,
4898 rigidBodies.reference, rigidBodies.rotations);
4899 if (static_cast<long>(rigid.size()) != nullBasis.cols()) {
4900 throw std::runtime_error("instantonRate: the ring has " +
4901 std::to_string(rigid.size()) +
4902 " rigid motions and the reactant " +
4903 std::to_string(nullBasis.cols()));
4904 }
4905 } else {
4906 for (long r = 0; r < nullBasis.cols(); ++r) {
4907 rigid.emplace_back(
4908 static_cast<size_t>(N),
4909 (nullBasis.col(r) / std::sqrt(static_cast<double>(N))).eval());
4910 }
4911 }
4912 for (double eta : inst.bathEta) {
4913 if (!(eta >= 0.0) || !std::isfinite(eta)) {
4914 throw std::invalid_argument(
4915 "instantonRate: bath eta must be finite and nonnegative");
4916 }
4917 }
4918 const bool weightedLinks =
4919 std::any_of(inst.discretization.begin(), inst.discretization.end(),
4920 [](double weight) { return weight != 1.0; });
4921 if (weightedLinks || std::any_of(inst.bathEta.begin(), inst.bathEta.end(),
4922 [](double eta) { return eta > 0.0; })) {
4923 bathFluctuations(inst, hBead, rigid, lr, rigidR, vReactant, c);
4924 if (hessSaddle.size() > 0) {
4926 hessReactant, hessSaddle, inst.beta, vSaddle - vReactant, rigidModes);
4927 if (rigidBodies.saddle.size() > 0) {
4928 inst.classicalLogRate +=
4929 logRotationalRatio({rigidBodies.saddle}, rigidBodies);
4930 }
4931 inst.classicalRate = std::exp(inst.classicalLogRate) / kTimeUnitSeconds;
4932 }
4933 return;
4934 }
4935 auto offRigid = [&](std::vector<VectorXd> &v) {
4936 for (const auto &u : rigid) {
4937 const double o = dot(u, v);
4938 for (long j = 0; j < N; ++j) {
4939 v[static_cast<size_t>(j)] -= o * u[static_cast<size_t>(j)];
4940 }
4941 }
4942 const double vn = std::sqrt(dot(v, v));
4943 if (!(vn > 1e-8)) {
4944 throw std::runtime_error(
4945 "instantonRate: a rigid motion of the ring lies along its cycle");
4946 }
4947 scale(v, 1.0 / vn);
4948 };
4949 offRigid(cycle);
4950 const long nDrop = 1 + nullBasis.cols();
4951
4952 // On a discrete ring the time shift is only nearly a symmetry, so the
4953 // central difference tau is not quite the eigenvector of J's near-zero
4954 // eigenvalue, and lifting tau would leave out cos^2 of their angle
4955 // times that eigenvalue rather than the eigenvalue itself. Inverse
4956 // iteration with the rigid modes lifted finds the eigenvector; tau stays
4957 // when the iteration fails or wanders off it.
4958 {
4959 const std::vector<double> rigidKappas(rigid.size(), c);
4960 const WoodburyRing lifted(c, diag, true, rigid, rigidKappas, false,
4961 linkWeight);
4962 std::vector<VectorXd> v = cycle;
4963 bool good = lifted.ok();
4964 for (int it = 0; good && it < 12; ++it) {
4965 std::vector<VectorXd> x = lifted.solve(v);
4966 for (const auto &b : x) {
4967 good = good && b.allFinite();
4968 }
4969 if (!good) {
4970 break;
4971 }
4972 offRigid(x);
4973 const double change = 1.0 - std::abs(dot(x, v));
4974 v = std::move(x);
4975 if (change < 1e-15) {
4976 break;
4977 }
4978 }
4979 if (good && std::abs(dot(v, cycle)) > 0.9) {
4980 cycle = std::move(v);
4981 }
4982 }
4983 // Each omitted direction is lifted by a spring-sized curvature c, far
4984 // above any physical near-zero eigenvalue, and the lift comes off the
4985 // log-determinant again: det(J + c u u^T) = (c + lambda) det' J for u the
4986 // eigenvector of lambda.
4987 std::vector<std::vector<VectorXd>> dropped{cycle};
4988 std::vector<double> kappas{c};
4989 for (auto &u : rigid) {
4990 dropped.push_back(std::move(u));
4991 kappas.push_back(c);
4992 }
4993 const WoodburyRing ring(c, diag, true, dropped, kappas, true, linkWeight);
4994 if (!ring.ok() || !std::isfinite(ring.logAbsDet())) {
4995 throw std::runtime_error(
4996 "instantonRate: the ring Hessian is singular and the zero mode was "
4997 "not removed with the rigid modes");
4998 }
4999 const auto phaseProduct = applyDiagonal(diag, c, true, cycle, linkWeight);
5000 inst.zeroEigenvalue = dot(cycle, phaseProduct);
5001 double phaseResidualSquared = 0.0, phaseOperatorBound = 0.0;
5002 for (long j = 0; j < N; ++j) {
5003 phaseResidualSquared +=
5004 (phaseProduct[j] - inst.zeroEigenvalue * cycle[j]).squaredNorm();
5005 const double offDiagonal =
5006 linkWeight ? c / (*linkWeight)[j] + c / (*linkWeight)[(j + N - 1) % N]
5007 : 2.0 * c;
5008 phaseOperatorBound =
5009 std::max(phaseOperatorBound,
5010 diag[j].cwiseAbs().rowwise().sum().maxCoeff() + offDiagonal);
5011 }
5012 inst.phaseEigenResidual = std::sqrt(phaseResidualSquared);
5013 const double phaseRoundoff = 64.0 * std::numeric_limits<double>::epsilon() *
5014 N * f * phaseOperatorBound;
5015 inst.phaseZeroVerified = std::abs(inst.zeroEigenvalue) <= phaseRoundoff &&
5016 inst.phaseEigenResidual <= phaseRoundoff;
5017 inst.negativeModes = ring.negative();
5018 double logAbsDet = ring.logAbsDet();
5019 const long dim = N * f;
5020 if (denseLimit < 0 || dim <= denseLimit) {
5021 // The lifted ring Hessian, dense: its eigenvalues give the determinant,
5022 // the inertia and the lowest mode directly, and check the block chain.
5023 ColMajorXd full = ColMajorXd::Zero(dim, dim);
5024 for (long j = 0; j < N; ++j) {
5025 full.block(j * f, j * f, f, f) = diag[static_cast<size_t>(j)];
5026 const long k = (j + 1) % N;
5027 full.block(j * f, k * f, f, f) -= c * eye;
5028 full.block(k * f, j * f, f, f) -= c * eye;
5029 }
5030 for (size_t d = 0; d < dropped.size(); ++d) {
5031 VectorXd u(dim);
5032 for (long j = 0; j < N; ++j) {
5033 u.segment(j * f, f) = dropped[d][static_cast<size_t>(j)];
5034 }
5035 full += kappas[d] * u * u.transpose();
5036 }
5037 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(full,
5038 Eigen::EigenvaluesOnly);
5039 const VectorXd lam = es.eigenvalues();
5040 const double inertiaTol = 64.0 * std::numeric_limits<double>::epsilon() *
5041 dim * lam.cwiseAbs().maxCoeff();
5042 double dense = 0.0, scaleSum = 0.0;
5043 long negative = 0;
5044 for (long i = 0; i < dim; ++i) {
5045 const double l = std::abs(lam(i));
5046 dense += std::log(l);
5047 scaleSum += std::abs(std::log(l));
5048 negative += lam(i) < -inertiaTol ? 1 : 0;
5049 }
5050 if (!(std::abs(dense - logAbsDet) <= 1e-6 * std::max(1.0, scaleSum))) {
5051 throw std::runtime_error(
5052 "instantonRate: the block-chain determinant disagrees with the "
5053 "dense ring Hessian");
5054 }
5055 logAbsDet = dense;
5056 inst.negativeEigenvalue = std::min(0.0, lam(0));
5057 inst.negativeModes = negative;
5058 } else {
5059 // The lowest ring eigenvalue, for the report, from products alone.
5060 auto applyFull = [&](const std::vector<VectorXd> &vec) {
5061 return applyDiagonal(diag, c, true, vec, linkWeight);
5062 };
5063 const long steps = std::min(dim, static_cast<long>(60));
5064 std::vector<VectorXd> start = cycle;
5065 std::uint64_t h = 0x9E3779B97F4A7C15ULL;
5066 for (auto &bead : start) {
5067 for (long a2 = 0; a2 < bead.size(); ++a2) {
5068 h ^= h << 13;
5069 h ^= h >> 7;
5070 h ^= h << 17;
5071 bead(a2) += 0.1 * (static_cast<double>(h >> 11) * 0x1.0p-53 - 0.5);
5072 }
5073 }
5074 const std::vector<RingMode> modes =
5075 lowestRingModes(applyFull, std::move(start), steps);
5076 inst.negativeEigenvalue = 0.0;
5077 for (const auto &mode : modes) {
5078 if (mode.theta < inst.negativeEigenvalue &&
5079 std::abs(dot(mode.vector, cycle)) < 0.5) {
5080 inst.negativeEigenvalue = mode.theta;
5081 }
5082 }
5083 // Only resolved eigenpairs inside the matrix roundoff scale can
5084 // account for numerical zeros outside the declared lifted directions.
5085 double operatorBound = 2.0 * c;
5086 for (const auto &block : diag) {
5087 operatorBound = std::max(
5088 operatorBound, block.cwiseAbs().rowwise().sum().maxCoeff() + 2.0 * c);
5089 }
5090 const double inertiaTol =
5091 64.0 * std::numeric_limits<double>::epsilon() * dim * operatorBound;
5092 long numericalZeros = 0;
5093 for (const auto &mode : modes) {
5094 bool lifted = false;
5095 for (const auto &direction : dropped) {
5096 lifted = lifted || std::abs(dot(mode.vector, direction)) > 0.5;
5097 }
5098 if (!lifted && mode.theta < 0.0 && std::abs(mode.theta) <= inertiaTol &&
5099 mode.residual <= inertiaTol) {
5100 ++numericalZeros;
5101 }
5102 }
5103 inst.negativeModes = std::max(0L, inst.negativeModes - numericalZeros);
5104 }
5105 // Along an eigenvector the lift adds c to its eigenvalue, so it comes off
5106 // as c + lambda_0 for the cycle (lambda_0 is not zero on a discrete ring)
5107 // and as c for the exact rigid zeros.
5108 const double logDetPrime = logAbsDet -
5109 std::log(std::abs(c + inst.zeroEigenvalue)) -
5110 static_cast<double>(nDrop - 1) * std::log(c);
5111 const double logProd =
5112 static_cast<double>(N * f - nDrop) * std::log(bnh) + 0.5 * logDetPrime;
5113
5114 inst.logRateTimesZr = -std::log(bnh) +
5115 0.5 * std::log(inst.bN / (2.0 * std::numbers::pi *
5116 inst.betaN * kHbar * kHbar)) -
5117 logProd - inst.betaN * inst.ringPotential;
5118 inst.logRotationRatio = logRotationalRatio(inst.beads, rigidBodies);
5119 inst.logRateTimesZr += inst.logRotationRatio;
5120
5121 for (long m = 0; m < lr.size(); ++m) {
5122 if (!rigidR[static_cast<size_t>(m)] && !(lr(m) > 0.0)) {
5123 throw std::runtime_error(
5124 "instantonRate: the reactant Hessian is not positive definite");
5125 }
5126 }
5127 // The rigid modes leave the centroid (k = 0) factor, as the ring's own
5128 // rigid modes leave its product; both carry them as free particles for
5129 // k > 0.
5130 double logZr = -inst.beta * vReactant;
5131 for (long k = 0; k < N; ++k) {
5132 const double sk = std::sin(std::numbers::pi * static_cast<double>(k) /
5133 static_cast<double>(N));
5134 for (long m = 0; m < lr.size(); ++m) {
5135 if (k == 0 && rigidR[static_cast<size_t>(m)]) {
5136 continue;
5137 }
5138 const double l = rigidR[static_cast<size_t>(m)] ? 0.0 : lr(m);
5139 logZr -= std::log(bnh) + 0.5 * std::log(l + 4.0 * c * sk * sk);
5140 }
5141 }
5142 inst.logZr = logZr;
5143 inst.rateValid = inst.converged && inst.negativeModes == 1;
5144 inst.rateValidity = !inst.converged
5145 ? "unconverged_ring"
5146 : (inst.negativeModes == 1 ? "collective_coordinate"
5147 : "non_index_one_ring");
5148 inst.logRate = inst.logRateTimesZr - logZr;
5149 inst.rate = std::exp(inst.logRate) / kTimeUnitSeconds;
5150 inst.effectiveBarrier =
5151 -std::log(2.0 * std::numbers::pi * kHbar * inst.beta) / inst.beta -
5152 inst.logRate / inst.beta;
5153 // An unconverged index-one input retains its numerical prefactor
5154 // diagnostic; rateValid prevents its use as a stationary physical rate.
5155 if (inst.negativeModes != 1) {
5156 const double invalid = std::numeric_limits<double>::quiet_NaN();
5157 inst.logRateTimesZr = inst.logRate = inst.rate = inst.effectiveBarrier =
5158 invalid;
5159 }
5160
5161 if (hessSaddle.size() > 0) {
5163 hessReactant, hessSaddle, inst.beta, vSaddle - vReactant, rigidModes);
5164 if (rigidBodies.saddle.size() > 0) {
5165 inst.classicalLogRate +=
5166 logRotationalRatio({rigidBodies.saddle}, rigidBodies);
5167 }
5168 inst.classicalRate = std::exp(inst.classicalLogRate) / kTimeUnitSeconds;
5169 }
5170}
5171
5173 const MatrixXd &generators,
5174 double fraction) {
5176 const long n = hess.rows();
5177 if (hess.cols() != n || generators.rows() != n || generators.cols() != 6) {
5178 throw std::invalid_argument(
5179 "rotationZeroModes: need a square Hessian and six generators");
5180 }
5181 const ColMajorXd h = 0.5 * (hess + hess.transpose());
5182 const ColMajorXd g = generators;
5183 const Eigen::ColPivHouseholderQR<ColMajorXd> qr(g);
5184 const long rank = qr.rank();
5185 if (rank >= n) {
5186 return out;
5187 }
5188 const ColMajorXd q = qr.householderQ() * ColMajorXd::Identity(n, n);
5189 const ColMajorXd z = q.rightCols(n - rank);
5190 const ColMajorXd reduced = z.transpose() * h * z;
5191 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(
5192 0.5 * (reduced + reduced.transpose()), Eigen::EigenvaluesOnly);
5193 out.softestVibration = es.eigenvalues()(0);
5194 for (int c = 0; c < 3; ++c) {
5195 const VectorXd r = generators.col(3 + c);
5196 const double rr = r.squaredNorm();
5197 if (!(rr > 0.0)) {
5198 continue;
5199 }
5200 const double rq = r.dot(h * r) / rr;
5201 if (out.softestVibration > 0.0) {
5202 out.residual[static_cast<size_t>(c)] = rq / out.softestVibration;
5203 out.zero[static_cast<size_t>(c)] =
5204 std::abs(rq) <= fraction * out.softestVibration;
5205 } else {
5206 out.residual[static_cast<size_t>(c)] =
5207 std::numeric_limits<double>::infinity();
5208 }
5209 }
5210 return out;
5211}
5212
5213void bofillKeepingInertia(MatrixXd &h, const VectorXd &dq, const VectorXd &dg,
5214 long allowedNegatives) {
5215 inertiaKeepingUpdate(h, dq, dg, allowedNegatives);
5216}
5217
5218RingChannel ringChannel(const std::vector<VectorXd> &beads,
5219 const VectorXd &saddle, const VectorXd &mode) {
5220 RingChannel out;
5221 const double mn = mode.norm();
5222 if (beads.size() < 2 || !(mn > 0.0)) {
5223 return out;
5224 }
5225 const VectorXd n = mode / mn;
5226 const size_t nb = beads.size();
5227 std::vector<double> s(nb);
5228 size_t jLo = 0, jHi = 0;
5229 for (size_t j = 0; j < nb; ++j) {
5230 s[j] = (beads[j] - saddle).dot(n);
5231 if (s[j] < s[jLo]) {
5232 jLo = j;
5233 }
5234 if (s[j] > s[jHi]) {
5235 jHi = j;
5236 }
5237 }
5238 out.sMin = s[jLo];
5239 out.sMax = s[jHi];
5240 const VectorXd chord = beads[jHi] - beads[jLo];
5241 const double cn = chord.norm();
5242 out.chordOverlap = cn > 0.0 ? std::abs(chord.dot(n)) / cn : 0.0;
5243 bool crossed = false;
5244 for (size_t j = 0; j < nb; ++j) {
5245 const size_t k = (j + 1) % nb;
5246 if ((s[j] < 0.0) == (s[k] < 0.0)) {
5247 continue;
5248 }
5249 const double t = s[j] / (s[j] - s[k]);
5250 const VectorXd p = beads[j] + t * (beads[k] - beads[j]) - saddle;
5251 const VectorXd across = p - p.dot(n) * n;
5252 out.crossingOffset = std::max(out.crossingOffset, across.norm());
5253 crossed = true;
5254 }
5255 out.belongs = crossed && out.sMin < 0.0 && out.sMax > 0.0 &&
5256 out.chordOverlap >= 0.5 &&
5257 out.crossingOffset <= out.sMax - out.sMin;
5258 return out;
5259}
5260
5261double parabolicFactor(double temperature, double crossover) {
5262 if (!(temperature > 0.0) || !(crossover > 0.0)) {
5263 throw std::invalid_argument(
5264 "parabolicFactor: temperature and crossover must be positive");
5265 }
5266 if (!(temperature > crossover)) {
5267 throw std::invalid_argument(
5268 "parabolicFactor: T is at or below the crossover; the factor "
5269 "diverges there");
5270 }
5271 // beta hbar omega_b / 2 = pi T_c / T, since T_c = hbar omega_b / (2 pi kB).
5272 const double phase = std::numbers::pi * crossover / temperature;
5273 const double s = std::sin(phase);
5274 if (!(s > 0.0)) {
5275 throw std::invalid_argument(
5276 "parabolicFactor: the sine of the barrier phase is not positive");
5277 }
5278 return phase / s;
5279}
5280
5281namespace {
5282
5283struct HarmonicSpectrum {
5284 VectorXd reactant;
5285 VectorXd saddle;
5286 std::vector<bool> rigidReactant;
5287 std::vector<bool> rigidSaddle;
5288};
5289
5290HarmonicSpectrum harmonicSpectrum(const MatrixXd &hessReactant,
5291 const MatrixXd &hessSaddle, double beta,
5292 double barrier, long rigidModes) {
5293 if (!(beta > 0.0) || !std::isfinite(beta) || !std::isfinite(barrier) ||
5294 hessReactant.size() == 0 || hessSaddle.size() == 0 ||
5295 hessReactant.rows() != hessReactant.cols() ||
5296 hessSaddle.rows() != hessSaddle.cols() ||
5297 hessReactant.rows() != hessSaddle.rows() || rigidModes < 0 ||
5298 rigidModes >= hessReactant.rows() || !hessReactant.allFinite() ||
5299 !hessSaddle.allFinite()) {
5300 throw std::invalid_argument(
5301 "harmonic TST: need finite beta > 0 and barrier, matching finite "
5302 "square Hessians, and fewer rigid modes than degrees of freedom");
5303 }
5304 if (beta > 1.0 &&
5305 std::abs(barrier) > std::numeric_limits<double>::max() / beta) {
5306 throw std::overflow_error("harmonic TST: beta times barrier overflows");
5307 }
5308 const ColMajorXd hr = 0.5 * hessReactant + 0.5 * hessReactant.transpose();
5309 const ColMajorXd hs = 0.5 * hessSaddle + 0.5 * hessSaddle.transpose();
5310 const Eigen::SelfAdjointEigenSolver<ColMajorXd> er(hr,
5311 Eigen::EigenvaluesOnly);
5312 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(hs,
5313 Eigen::EigenvaluesOnly);
5314 if (er.info() != Eigen::Success || es.info() != Eigen::Success ||
5315 !er.eigenvalues().allFinite() || !es.eigenvalues().allFinite()) {
5316 throw std::runtime_error("harmonic TST: Hessian eigensolver failed");
5317 }
5318 HarmonicSpectrum out{er.eigenvalues(), es.eigenvalues(), {}, {}};
5319 if (!(out.saddle(0) < 0.0)) {
5320 throw std::invalid_argument(
5321 "harmonic TST: the saddle Hessian has no negative eigenvalue");
5322 }
5323 out.rigidReactant = nearestZero(out.reactant, rigidModes);
5324 out.rigidSaddle = nearestZero(out.saddle, rigidModes, 1);
5325 for (long m = 0; m < out.reactant.size(); ++m) {
5326 if (!out.rigidReactant[static_cast<size_t>(m)] &&
5327 !(out.reactant(m) > 0.0)) {
5328 throw std::invalid_argument(
5329 "harmonic TST: the reactant Hessian has a non-positive "
5330 "vibrational eigenvalue");
5331 }
5332 }
5333 for (long m = 1; m < out.saddle.size(); ++m) {
5334 if (!out.rigidSaddle[static_cast<size_t>(m)] && !(out.saddle(m) > 0.0)) {
5335 throw std::invalid_argument(
5336 "harmonic TST: the saddle Hessian has a non-positive "
5337 "vibrational eigenvalue besides its unstable mode");
5338 }
5339 }
5340 return out;
5341}
5342
5343double finiteHarmonicLogRate(double rate) {
5344 if (!std::isfinite(rate)) {
5345 throw std::overflow_error("harmonic TST: non-finite logarithmic rate");
5346 }
5347 return rate;
5348}
5349
5350} // namespace
5351
5352double harmonicTstLogRate(const MatrixXd &hessReactant,
5353 const MatrixXd &hessSaddle, double beta,
5354 double barrier, long rigidModes) {
5355 const HarmonicSpectrum spectrum =
5356 harmonicSpectrum(hessReactant, hessSaddle, beta, barrier, rigidModes);
5357 const VectorXd &lr = spectrum.reactant;
5358 const VectorXd &ls = spectrum.saddle;
5359 double logRatio = 0.0;
5360 for (long m = 0; m < lr.size(); ++m) {
5361 if (!spectrum.rigidReactant[static_cast<size_t>(m)]) {
5362 logRatio += 0.5 * std::log(lr(m));
5363 }
5364 }
5365 // Eigenvalue 0 is the unstable mode, the most negative.
5366 for (long m = 1; m < ls.size(); ++m) {
5367 if (!spectrum.rigidSaddle[static_cast<size_t>(m)]) {
5368 logRatio -= 0.5 * std::log(ls(m));
5369 }
5370 }
5371 return finiteHarmonicLogRate(logRatio - std::log(2.0 * std::numbers::pi) -
5372 beta * barrier);
5373}
5374
5375double quantumHarmonicTstLogRate(const MatrixXd &hessReactant,
5376 const MatrixXd &hessSaddle, double beta,
5377 double barrier, long rigidModes) {
5378 const HarmonicSpectrum spectrum =
5379 harmonicSpectrum(hessReactant, hessSaddle, beta, barrier, rigidModes);
5380 const VectorXd &lr = spectrum.reactant;
5381 const VectorXd &ls = spectrum.saddle;
5382 const double bh = beta * kHbar;
5383 if (!(bh > 0.0) || !std::isfinite(bh)) {
5384 throw std::overflow_error(
5385 "harmonic TST: beta hbar is not finite and positive");
5386 }
5387 // ln(2 sinh(x / 2)) without overflow for large x, and without the
5388 // cancellation of 1 - exp(-x) for small x.
5389 auto logTwoSinhHalf = [bh](double omega) {
5390 if (omega > 1.0 && bh > std::numeric_limits<double>::max() / omega) {
5391 throw std::overflow_error("harmonic TST: beta hbar omega overflows");
5392 }
5393 const double x = bh * omega;
5394 if (!(x > 0.0)) {
5395 throw std::underflow_error("harmonic TST: beta hbar omega underflows");
5396 }
5397 return 0.5 * x + std::log(-std::expm1(-x));
5398 };
5399 double logRatio = 0.0;
5400 for (long m = 0; m < lr.size(); ++m) {
5401 if (!spectrum.rigidReactant[static_cast<size_t>(m)]) {
5402 logRatio += logTwoSinhHalf(std::sqrt(lr(m)));
5403 }
5404 }
5405 for (long m = 1; m < ls.size(); ++m) {
5406 if (!spectrum.rigidSaddle[static_cast<size_t>(m)]) {
5407 logRatio -= logTwoSinhHalf(std::sqrt(ls(m)));
5408 }
5409 }
5410 return finiteHarmonicLogRate(logRatio - std::log(2.0 * std::numbers::pi) -
5411 std::log(bh) - beta * barrier);
5412}
5413
5414} // namespace eonc::tunneling
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, eOnStorageOrder > MatrixXd
Definition Eigen.h:33
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
#define EONC_LOG_DEBUG(...)
Definition EonLogger.h:310
#define EONC_LOG_INFO(...)
Definition EonLogger.h:316
static const char MINMODE_DIMER[]
const AtomMatrix & getPositions() const
Definition Matter.cpp:378
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
long int numberOfAtoms() const
Definition Matter.cpp:343
AtomMatrix pbc(const AtomMatrix &diff) const
Definition Matter.cpp:943
Eigen::Matrix< double, Eigen::Dynamic, 1 > getMasses() const
Definition Matter.cpp:846
double getPotentialEnergy() const
Definition Matter.cpp:624
std::atomic< size_t > forceCallCounter
Definition Potential.h:57
Potential(PotType a_ptype)
Production default: construction-scope registry, else PotRegistry::get().
VectorXd gradient(const VectorXd &q) const
MatrixXd hessian(const VectorXd &q) const
EnergyBias(const VectorXd &start, const VectorXd &end, double delta)
double value(const VectorXd &q) const
double xi(const VectorXd &q) const
Energy along the path, interpolated as a monotone cubic (Fritsch and Carlson), flat at both ends beca...
Definition Tunneling.h:56
std::vector< double > m_
Definition Tunneling.h:64
std::vector< double > s_
Definition Tunneling.h:64
std::vector< double > v_
Definition Tunneling.h:64
Profile(std::vector< double > s, std::vector< double > v)
Definition Tunneling.cpp:88
const std::vector< double > & v() const
Definition Tunneling.h:61
double operator()(double x) const
const std::vector< double > & s() const
Definition Tunneling.h:60
void forceBatch(long nSystems, long nAtoms, const double *const *positions, const int *const *atomicNrs, double *const *forces, double *energies, double *variances, const double *const *boxes) override
double writeForces(const std::vector< VectorXd > &grad, const double *positions, double *forces) const
void packActive(const std::vector< VectorXd > &active, double *positions) const
std::vector< VectorXd > unpack(const double *positions) const
void packMode(const VectorXd &dir, AtomMatrix &mode) const
void force(long nAtoms, const double *positions, const int *atomicNrs, double *forces, double *energy, double *variance, const double *box) override
RingPolymerPotential(BatchPotential beads, long nBeads, long dof, double spring, double energyShift, std::vector< double > eta, bool fold, VectorXd modeDir)
void fixLayout(long nBeads, long dof, bool fold, const VectorXd &modeDir)
std::shared_ptr< const PhysicalQuadraticBath > physicalBath_
void * sym(Handle h, const char *name) noexcept
Definition DynLib.h:75
double squaredNorm(const Eigen::MatrixBase< A > &x)
double norm(const Eigen::MatrixBase< A > &x)
sqrt of the correctly rounded squared norm; IEEE sqrt is itself correctly rounded,...
double dot(const double *x, const double *y, std::size_t n)
Round-to-nearest-even value of the exact sum of x[i] * y[i].
AtomMatrix apply(const AtomMatrix &diff, const Matrix3d &cell, const Matrix3d &cellInverse)
Definition Matter.h:46
Rate rate(const std::vector< Plane > &planes, double beta)
k = (1/2) sqrt(2 / (pi beta)) exp(-beta F(s*)) / int_{s_0}^{s*} exp(-beta F(s)) ds,...
Definition PIQTST.cpp:213
constexpr long saddle
constexpr long reactant
constexpr long derivative
constexpr double eps
Definition SafeMath.h:19
std::function< MatrixXd(long j, const VectorXd &q)> BeadHessian
The mass-weighted Hessian d2V/dq2 at interior bead j (1..P-1).
Definition Tunneling.h:248
RingSpectrum ringSpectrum(const std::vector< MatrixXd > &beadHessians, double c, const std::vector< VectorXd > &tau)
The ring Hessian of bead Hessians beadHessians (d2V/dq2 at each of the N beads) and spring constant c...
constexpr double kDvrPadLengths
Oscillator lengths the grid reaches past each minimum.
Definition Tunneling.h:135
double zeroPointDifference(const MatrixXd &hessStart, const MatrixXd &hessEnd, long rigidModes)
Harmonic zero-point energy of the end minimum minus that of the start, in eV: (hbar / 2) times the di...
constexpr long kDvrMaxPoints
Largest grid; a longer path takes a coarser spacing.
Definition Tunneling.h:137
double cyclicRingLogAbsDet(double c, const std::vector< MatrixXd > &diag)
log|det| of the cyclic block-tridiagonal ring Hessian.
Splitting bandSplitting(const std::vector< std::shared_ptr< Matter > > &band, double referenceEnergy)
The splitting of a converged band, with the well frequencies from the band's curvature at each end.
void bofillKeepingInertia(MatrixXd &h, const VectorXd &dq, const VectorXd &dg, long allowedNegatives)
The Bofill update of a bead block (Powell symmetric Broyden and SR1 mixed by the angle between the se...
std::vector< VectorXd > cyclicRingSolve(double c, const std::vector< MatrixXd > &diag, const std::vector< VectorXd > &rhs)
Solves that same cyclic ring Hessian.
double closedRingPotential(const std::vector< VectorXd > &beads, double spring, const BatchPotential &potential, const std::vector< double > &discretization)
U_N of a closed ring.
constexpr long kDvrPointsPerLength
Grid points per oscillator length hbar / sqrt(hbar omega) of the stiffer well.
Definition Tunneling.h:133
void instantonRate(RateInstanton &inst, const RingBeadHessian &hessian, const MatrixXd &hessReactant, double vReactant, const MatrixXd &hessSaddle, double vSaddle, long rigidModes, long denseLimit, const RingRigidBodies &rigidBodies)
Fills the rate from the bead Hessians, the reactant minimum's Hessian and energy, and optionally the ...
BandWalls bandWalls(const std::vector< std::shared_ptr< Matter > > &band, double referenceEnergy, long points)
The walls of both ends of a band, after Khomenko et al.
double wkbAction(const Profile &p, double energy, int points)
(1/hbar) integral sqrt(2 (V(s) - E)) ds over the path where V > E.
double parabolicFactor(double temperature, double crossover)
(pi T_c / T) / sin(pi T_c / T).
void instantonSplitting(Instanton &inst, const BeadHessian &hessian, const MatrixXd &hessStart, const MatrixXd &hessEnd)
Fills delta0, zeroMode and modeSeparation from the bead Hessians and the Hessians of the two minima.
constexpr double kTimeUnitSeconds
One unit of time, sqrt(amu Angstrom^2 / eV), in seconds.
Definition Tunneling.h:350
double pathOmega(const MatrixXd &hessStart, const MatrixXd &hessEnd, const VectorXd &start, const VectorXd &end)
omega along the straight line between the minima from the curvature of each well there,...
std::function< MatrixXd(long j, const VectorXd &q)> RingBeadHessian
The mass-weighted Hessian d2V/dq2 at ring bead j (0..N-1).
Definition Tunneling.h:616
double logRotationalRatio(const std::vector< VectorXd > &beads, const RingRigidBodies &bodies)
ln of the classical rotational partition function of beads over that of as many copies of the referen...
bool singleBarrier(const Profile &p)
Whether a profile is one double well: its images rise to exactly one maximum between the two ends.
RateInstanton optimizeRateInstanton(const VectorXd &saddle, const MatrixXd &hessSaddle, double beta, std::vector< VectorXd > guess, const BatchPotential &potential, const RateInstantonOptions &request)
Finds the rate instanton at inverse temperature beta (1 / eV).
RingChannel ringChannel(const std::vector< VectorXd > &beads, const VectorXd &saddle, const VectorXd &mode)
The channel test above for a ring of beads, a saddle and its unstable mode (normalised inside).
void addFrictionBath(const std::vector< VectorXd > &q, double &u, std::vector< VectorXd > &grad, const std::vector< double > &eta)
Position-independent (one eta) or bead-wise friction on a closed ring.
constexpr double kHbar
hbar in eV^0.5 amu^0.5 Angstrom, correctly rounded from the exact SI values (h = 6....
Definition Tunneling.h:39
Splitting wkbSplitting(const Profile &p, double hwReactant, double hwProduct)
delta0 = (hbar omega / pi) exp(-S) with the Landau and Lifshitz prefactor.
double harmonicTstLogRate(const MatrixXd &hessReactant, const MatrixXd &hessSaddle, double beta, double barrier, long rigidModes)
ln(k) for classical harmonic transition-state theory, k in 1/time.
double wellCurvature(const Profile &p, bool leftEnd)
d2V/ds2 at one end of the path, in eV / (amu Angstrom^2), from a least squares fit of a s^2 + b s^3 t...
double massWeightedDistance(const Matter &a, const Matter &b)
sqrt(sum_i m_i |b_i - a_i|^2) under the minimum image of a's cell.
Definition Tunneling.cpp:61
std::function< void(const std::vector< VectorXd > &q, std::vector< double > &v, std::vector< VectorXd > &grad)> BatchPotential
V (eV) and dV/dq (eV / (amu^0.5 Angstrom)) at every point of q, all in one call so a potential can sp...
Definition Tunneling.h:238
double quantumHarmonicTstLogRate(const MatrixXd &hessReactant, const MatrixXd &hessSaddle, double beta, double barrier, long rigidModes)
ln(k) for quantum harmonic transition-state theory, k in 1/time: (1 / (2 pi beta hbar)) prod_r 2 sinh...
double crossoverTemperature(const MatrixXd &hessSaddle)
T_c = hbar omega_b / (2 pi kB) from the mass-weighted Hessian at the saddle, in K; throws when the He...
std::vector< VectorXd > ringFromPath(const std::vector< VectorXd > &path, const std::vector< double > &energies, double betaHbar, long beads, RingSeed *seed)
Levels dvrLevels(const std::function< double(double)> &v, double sReactant, double sProduct, double sTop, double hwReactant, double hwProduct)
The levels of -hbar^2/2 d2/ds2 + V(s) at unit mass on a mass-weighted path coordinate s,...
double wkbLogRateAlongPath(const Profile &profile, double beta, double hwReactant)
ln(k), k in 1/time, for the one-dimensional thermal rate along profile.
Levels bandLevels(const Profile &p, const BandWalls *walls)
dvrLevels on a band: the profile between the images, and past each end the well's fit a s^2 + b s^3 c...
std::array< double, 2 > wellFit(const Profile &p, bool leftEnd)
{a, b} of that fit, s measured inward from the end: wellCurvature is 2 a.
Profile bandProfile(const std::vector< std::shared_ptr< Matter > > &band, double referenceEnergy)
The energy of a band against its mass-weighted arc length, measured from referenceEnergy.
double hbarOmega(double curvature)
hbar omega in eV for a mass-weighted curvature.
RotationZeroModes rotationZeroModes(const MatrixXd &hess, const MatrixXd &generators, double fraction)
std::vector< double > massWeightedPath(const std::vector< std::shared_ptr< Matter > > &band)
Cumulative mass-weighted arc length at each image of a band.
Definition Tunneling.cpp:79
Instanton optimizeInstanton(const VectorXd &start, const VectorXd &end, double betaHbar, std::vector< VectorXd > guess, const BatchPotential &potential, const InstantonOptions &options)
Minimises the action from guess (P + 1 beads, ends at the minima, or empty for a tanh kink along the ...
constexpr double kBoltzmann
Boltzmann constant in eV / K, correctly rounded from the exact 1.380649e-23 J / K.
Definition Tunneling.h:43
static dimer_options_t & dimer_options(Parameters &p)
static saddle_search_options_t & saddle_search_options(Parameters &p)
static main_options_t & main_options(Parameters &p)
static optimizer_options_t & optimizer_options(Parameters &p)
DimerRotationBackend rotation_backend
One well's outer wall: increasing mass-weighted distances outward from the minimum along the reaction...
Definition Tunneling.h:150
std::vector< double > distance
Definition Tunneling.h:151
std::vector< double > energy
Definition Tunneling.h:152
long maxIterations
L-BFGS iterations.
Definition Tunneling.h:230
double forceTolerance
largest per-bead |dS/dq| / dtau, eV / (amu^0.5 Angstrom)
Definition Tunneling.h:231
long beads
P: segments from one minimum to the other.
Definition Tunneling.h:227
long memory
L-BFGS correction pairs.
Definition Tunneling.h:233
double betaHbarOmega
beta hbar omega of the stiffer end along the path; sets the imaginary time
Definition Tunneling.h:228
double asymmetry
V(end) - V(start), eV.
Definition Tunneling.h:259
std::vector< double > energies
V at every bead, eV.
Definition Tunneling.h:252
double zeroMode
the eigenvalue det' leaves out
Definition Tunneling.h:257
double action
(S - S_well) / hbar
Definition Tunneling.h:255
double s0
integral of |dq/dtau|^2 dtau
Definition Tunneling.h:256
bool symmetricEnough
beta |asymmetry| < 0.1: the propagator ratio reads delta0 only when the wells lie within a small frac...
Definition Tunneling.h:264
double modeSeparation
The second smallest eigenvalue of J over the zero mode's: small means the kink is not isolated in ima...
Definition Tunneling.h:267
double betaHbar
imaginary time the path spans
Definition Tunneling.h:253
double dtau
betaHbar / P
Definition Tunneling.h:254
double delta0
tunnelling splitting, eV
Definition Tunneling.h:258
std::vector< VectorXd > path
P + 1 beads, ends at the minima.
Definition Tunneling.h:251
The two lowest levels of a one-dimensional double well, in eV.
Definition Tunneling.h:124
OwnedBatchPotential ownedPotential
Stable bead identities and bounded derivative scratch slots.
Definition Tunneling.h:387
std::shared_ptr< const PhysicalQuadraticBath > physicalBath
Fixed physical quadratic bath, eliminated on the same primitive ring.
Definition Tunneling.h:391
std::vector< double > rigidSqrtMasses
Rigid motions of the ring: a translation, or one rotation about the ring's centre of mass,...
Definition Tunneling.h:447
double maxStep
largest bead move per step, amu^0.5 Angstrom
Definition Tunneling.h:405
double energyShift
subtracted from every bead potential, eV
Definition Tunneling.h:421
std::int64_t newtonLimit
Active coordinates at or below this take the Newton step.
Definition Tunneling.h:430
long beads
N, beads on the ring.
Definition Tunneling.h:395
double forceTolerance
largest per-bead |dU_N/dq|, eV / (amu^0.5 Angstrom)
Definition Tunneling.h:397
bool halfRing
Even N, when the guess already matches under j -> N - j: evaluate the potential from one turning poin...
Definition Tunneling.h:411
double lanczosStep
finite-difference step, amu^0.5 Angstrom
Definition Tunneling.h:404
bool friction
Litman friction bath on the rate ring.
Definition Tunneling.h:453
std::vector< double > discretization
Empty keeps every spring equal.
Definition Tunneling.h:425
long maxIterations
translation steps
Definition Tunneling.h:396
double physicalHessianStep
Central physical bead-Hessian displacement in sqrt(amu) Angstrom.
Definition Tunneling.h:403
long negativeModes
eigenvalues below the zero mode
Definition Tunneling.h:524
double zeroEigenvalue
the eigenvalue left out
Definition Tunneling.h:523
bool rateValid
A physical rate requires a converged index-one stationary ring.
Definition Tunneling.h:519
double beta
1 / (kB T), 1 / eV
Definition Tunneling.h:497
std::shared_ptr< const PhysicalQuadraticBath > physicalBath
Definition Tunneling.h:494
std::vector< double > energies
V at every bead, eV.
Definition Tunneling.h:496
std::vector< double > discretization
Empty keeps every spring equal. Otherwise one positive weight per bead.
Definition Tunneling.h:504
double bN
sum_j |q_{j+1} - q_j|^2, amu Angstrom^2
Definition Tunneling.h:502
std::vector< double > bathEta
Resolved fixed bath coefficients: empty, one value or one per bead.
Definition Tunneling.h:506
double logRotationRatio
ln of the ring's rotational partition function over the reactant's, included in logRateTimesZr; zero ...
Definition Tunneling.h:534
double logRate
ln k, k in 1 / time
Definition Tunneling.h:536
std::vector< VectorXd > beads
N beads, q_N = q_0 implied.
Definition Tunneling.h:495
double classicalRate
Classical harmonic transition-state theory at the same T, 1 / s, when the saddle Hessian was given; i...
Definition Tunneling.h:543
double logRateTimesZr
ln(k Z_r), k in 1 / time
Definition Tunneling.h:531
double negativeEigenvalue
of the ring Hessian, 1 / time^2
Definition Tunneling.h:522
double effectiveBarrier
-kB T ln(2 pi hbar beta k): the barrier an Eyring rate would need, eV.
Definition Tunneling.h:539
Where a ring sits against the saddle it was seeded from, in mass-weighted coordinates.
Definition Tunneling.h:566
bool belongs
Beads on both sides of the dividing plane, the chord within 60 degrees of the mode,...
Definition Tunneling.h:579
double sMin
least s over the beads, amu^0.5 Angstrom
Definition Tunneling.h:567
double chordOverlap
|cos| of the angle between the chord joining the turning points and the unstable mode.
Definition Tunneling.h:571
double crossingOffset
Largest distance from the saddle, across the mode, of a point where the ring crosses the dividing pla...
Definition Tunneling.h:574
double sMax
greatest s over the beads
Definition Tunneling.h:568
The atoms behind a ring's mass-weighted coordinates, for its rigid motions: sqrt(m) per atom,...
Definition Tunneling.h:624
std::array< bool, 3 > rotations
Definition Tunneling.h:627
std::vector< double > sqrtMasses
Definition Tunneling.h:625
Closed ring of beads samples of path whose imaginary-time period is betaHbar.
Definition Tunneling.h:185
double pathLow
the higher of the path's two end energies
Definition Tunneling.h:188
Spectrum of a closed ring's Hessian without forming it.
Definition Tunneling.h:474
double logDetPrime
ln |det' J|: the product over every eigenvalue but the one along tau.
Definition Tunneling.h:476
long negativeModes
Eigenvalues below zero, the one along tau left out.
Definition Tunneling.h:478
std::array< bool, 3 > zero
Definition Tunneling.h:599
double softestVibration
lowest eigenvalue on the complement
Definition Tunneling.h:601
std::array< double, 3 > residual
Definition Tunneling.h:600
bool deepWells
Both barriers stand above hbar omega; below that WKB is not the right tool and the number is reported...
Definition Tunneling.h:92
double hwReactant
hbar omega of the reactant well, eV
Definition Tunneling.h:85
double delta0
tunnelling splitting, eV
Definition Tunneling.h:89
double barrier
path maximum above the reactant, eV
Definition Tunneling.h:84
double asymmetry() const
The diagonal term of the two-level Hamiltonian, the difference of the two local ground states: delta ...
double referenceEnergy
the level tunnelling happens at, eV
Definition Tunneling.h:87
double action
the WKB exponent, dimensionless
Definition Tunneling.h:88
double tlsEnergy() const
sqrt(asymmetry()^2 + delta0^2), eV
double hwProduct
hbar omega of the product well, eV
Definition Tunneling.h:86
double delta
product minus reactant, eV
Definition Tunneling.h:83