46 long scratch,
long beadCount = 0) {
50 beadCount](
const std::vector<VectorXd> &q, std::vector<double> &v,
51 std::vector<VectorXd> &g) {
52 std::vector<long> owners(q.size(), scratch);
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);
63 throw std::invalid_argument(
"the structures hold different atom counts");
70 throw std::invalid_argument(
71 "every atom needs a positive mass for a mass-weighted path");
73 sum += mass(i) * dr.row(i).squaredNorm();
75 return std::sqrt(sum);
80 std::vector<double> s{0.0};
81 s.reserve(band.size());
82 for (
size_t i = 1; i < band.size(); ++i) {
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");
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");
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) {
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);
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];
132 return 2.0 *
wellFit(p, leftEnd)[0];
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);
143 double s44 = 0, s45 = 0, s55 = 0, sy2 = 0, sy3 = 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;
152 const double x2 = x * x;
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};
168 return {sy2 / s44, 0.0};
170 const double det = s44 * s55 - s45 * s45;
171 return {(sy2 * s55 - sy3 * s45) / det, (sy3 * s44 - sy2 * s45) / det};
175 if (!(curvature > 0.0)) {
176 throw std::invalid_argument(
"a well needs a positive curvature");
178 return kHbar * std::sqrt(curvature);
182 const double a = p.
s().front();
183 const double b = p.
s().back();
184 const double h = (b - a) / (points - 1);
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;
191 return sum * h /
kHbar;
201 const auto &v = p.
v();
203 const double top = *std::max_element(v.begin(), v.end());
204 out.
delta = v.back() - v.front();
209 std::max(v.front() + 0.5 * hwReactant, v.back() + 0.5 * hwProduct);
211 const double hw = std::sqrt(hwReactant * hwProduct);
212 out.
delta0 = hw / std::numbers::pi * std::exp(-out.
action);
214 (top - v.front()) > hwReactant && (top - v.back()) > hwProduct;
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();
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]);
239std::pair<double, double> turningPoints(
const Profile &p,
double sTop,
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;
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;
258 for (
int k = 0; k < 60; ++k) {
259 const double m = 0.5 * (a + b);
266 return 0.5 * (a + b);
268 return {cross(sTop, s0), cross(sTop, s1)};
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);
281 if (cumulative !=
nullptr) {
282 cumulative->assign(1, 0.0);
283 positions->assign(1, sMinus);
285 for (
int k = 0; k < panels; ++k) {
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));
305 const std::vector<double> &energies,
306 double betaHbar,
long beads,
308 if (path.size() < 3 || path.size() != energies.size() || beads < 4 ||
310 throw std::invalid_argument(
311 "ringFromPath: a path of at least three points with energies, "
312 "N >= 4 and beta hbar > 0");
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");
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) {
327 s.front() + (s.back() - s.front()) *
static_cast<double>(k) / grid;
328 if (profile(sk) > vTop) {
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");
337 auto period = [&](
double energy) {
338 const auto [sMinus, sPlus] = turningPoints(profile, sTop, energy);
339 return 2.0 * halfPeriod(profile, sMinus, sPlus, energy);
346 for (
size_t k = 1; k < energies.size(); ++k) {
347 if (energies[k] > energies[top]) {
351 if (top == 0 || top + 1 == energies.size()) {
352 throw std::invalid_argument(
353 "ringFromPath: the barrier top is an end of the path");
355 const double h1 = s[top] - s[top - 1], h2 = s[top + 1] - s[top];
356 const double curvature =
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");
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 "
379 const double span = vTop - vLow;
380 const double eBottom = vLow + 1e-14 * span;
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)));
396 for (
int k = 0; k <= kScan; ++k) {
397 gap[
static_cast<size_t>(k)] =
398 period(levels[
static_cast<size_t>(k)]) - betaHbar;
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)) {
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)) {
420 const double root = 0.5 * (a + b);
423 if (!(std::abs(period(root) - betaHbar) <= 1e-6 * betaHbar)) {
426 const double w = 2.0 *
wkbAction(profile, root) + beta * root;
434 if (seed !=
nullptr) {
436 seed->
period = period(energy);
438 seed->
reached = std::abs(seed->
period - betaHbar) <= 1e-6 * betaHbar;
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");
449 std::vector<VectorXd> ring(
static_cast<size_t>(beads), VectorXd::Zero(width));
450 for (
long j = 0; j <= beads / 2; ++j) {
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;
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)];
470 if (!(beta > 0.0) || !(hwReactant > 0.0)) {
471 throw std::invalid_argument(
472 "wkbLogRateAlongPath: beta and hbar omega must be positive");
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;
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);
488 const double barrier = vTop - vReactant;
489 if (!(barrier > 0.0)) {
490 throw std::invalid_argument(
491 "wkbLogRateAlongPath: no barrier above the reactant");
493 double ds = 1e-3 * (s1 - s0);
494 ds = std::min(ds, std::min(sTop - s0, s1 - sTop));
496 throw std::invalid_argument(
497 "wkbLogRateAlongPath: the barrier top is at an end of the path");
499 const double curvature =
500 std::max(1e-12, -(profile(sTop + ds) - 2.0 * vTop + profile(sTop - ds)) /
502 const double hwBarrier =
kHbar * std::sqrt(curvature);
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()) {
511 const double m = std::max(a, b);
512 return m + std::log(std::exp(a - m) + std::exp(b - m));
514 double logTerms = -std::numeric_limits<double>::infinity();
515 double prevLog = -std::numeric_limits<double>::infinity();
517 for (
int k = 0; k <= points; ++k) {
518 const double energy = eMax *
static_cast<double>(k) / points;
520 if (energy < barrier) {
521 theta =
wkbAction(profile, vReactant + energy);
523 theta = -std::numbers::pi * (energy - barrier) / hwBarrier;
526 theta > 20.0 ? -2.0 * theta : -std::log1p(std::exp(2.0 * theta));
527 const double logF = logP - beta * energy;
529 const double segment =
530 std::log(0.5 * (energy - prevE)) + logAdd(prevLog, logF);
531 logTerms = logAdd(logTerms, segment);
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));
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);
551 double referenceEnergy) {
558 const auto &v = p.
v();
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);
567 peaks += (last == 1 && step == -1) ? 1 : 0;
568 valleys += (last == -1 && step == 1) ? 1 : 0;
571 return peaks == 1 && valleys == 0;
575 double sProduct,
double sTop,
double hwReactant,
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 "
582 const double ellR =
kHbar / std::sqrt(hwReactant);
583 const double ellP =
kHbar / std::sqrt(hwProduct);
586 const long n = std::clamp<long>(
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;
597 hmat(i, i + 1) = hmat(i + 1, i) = -4.0 * c / 3.0;
600 hmat(i, i + 2) = hmat(i + 2, i) = c / 12.0;
603 const Eigen::SelfAdjointEigenSolver<MatrixXd> es(hmat);
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);
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);
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);
629class FlatStartSpline {
631 FlatStartSpline(std::vector<double> x, std::vector<double> 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");
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); };
647 rhs[0] = 6.0 * slope(0);
648 for (
size_t i = 1; i < m; ++i) {
650 dia[i] = 2.0 * (h(i - 1) + h(i));
652 rhs[i] = 6.0 * (slope(i) - slope(i - 1));
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];
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];
663 endSlope_ = slope(m - 1) + m_[m - 1] * h(m - 1) / 6.0;
665 double operator()(
double u)
const {
666 if (u >= x_.back()) {
667 return y_.back() + endSlope_ * (u - x_.back());
669 const auto it = std::upper_bound(x_.begin(), x_.end(), u);
671 std::clamp<size_t>(
static_cast<size_t>(std::distance(x_.begin(), it)),
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;
683 std::vector<double> x_, y_, m_;
684 double endSlope_ = 0.0;
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();
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;
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);
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()) {
719 throw std::invalid_argument(
"a wall needs one energy per distance");
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) {
725 y.push_back(wall->
energy[k] - floor - model(wall->
distance[k], fit));
727 return FlatStartSpline(std::move(x), std::move(y));
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);
737 auto v = [&](
double s) {
739 return outer(s0 - s, fitR, p.
v().front(), wallR);
742 return outer(s - s1, fitP, p.
v().back(), wallP);
746 return dvrLevels(v, s0, s1, sTop, hwR, hwP);
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");
756 auto wall = [&](
const Matter &end,
const Matter &next,
double a) {
762 norm2 += mass(i) * step.row(i).squaredNorm();
764 if (!(norm2 > 0.0)) {
765 throw std::invalid_argument(
"bandWalls: an end segment has no length");
768 const AtomMatrix direction = step / std::sqrt(norm2);
771 for (
long k = 1; k <= points; ++k) {
773 static_cast<double>(points);
783 wall(*band.back(), *band[band.size() - 2],
wellFit(p,
false)[0]);
791constexpr long kDenseRing = 4096;
794constexpr double kTrackOverlap = 0.3;
797constexpr long kRitzCap = 400;
800 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;
807 BlockChain(
double c,
const std::vector<MatrixXd> &diag)
809 lu_.reserve(diag.size());
810 for (
size_t k = 0; k < diag.size(); ++k) {
811 ColMajorXd d = diag[k];
813 d -= c_ * c_ * lu_.back().inverse();
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);
821 throw std::runtime_error(
"instanton: singular chain Hessian block");
823 sign_ *= u < 0.0 ? -1 : 1;
824 logAbsDet_ += std::log(std::abs(u));
828 double logAbsDet()
const {
return logAbsDet_; }
829 int sign()
const {
return sign_; }
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);
835 for (
size_t k = 1; k < m; ++k) {
836 y[k] = b[k] + c_ * lu_[k - 1].solve(y[k - 1]);
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]);
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);
849 for (
size_t k = 1; k < m; ++k) {
850 y[k] = b[k] + c_ * lu_[k - 1].solve(y[k - 1]);
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]);
861 std::vector<Eigen::PartialPivLU<ColMajorXd>> lu_;
862 double logAbsDet_ = 0.0;
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()) {
874 if (weight->size() != n) {
875 throw std::invalid_argument(
876 "link weights must be one positive value per bead");
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");
883 out[j] = c / (*weight)[j];
892class HaynsworthChain {
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());
902 const MatrixXd inv = lu_.back().inverse();
903 const double ck = link_[k - 1];
904 d -= ck * ck * 0.5 * (inv + inv.transpose());
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);
913 throw std::runtime_error(
"instanton: singular chain Hessian block");
918 logAbsDet_ += std::log(std::abs(lam));
921 lu_.emplace_back(ColMajorXd(d));
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);
930 for (
size_t k = 1; k < m; ++k) {
931 y[k] = b[k] + link_[k - 1] * lu_[k - 1].solve(y[k - 1]);
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]);
939 double closingSpring()
const {
return link_.back(); }
942 std::vector<double> link_;
943 std::vector<Eigen::PartialPivLU<ColMajorXd>> lu_;
944 double logAbsDet_ = 0.0;
948double dot(
const std::vector<VectorXd> &a,
const std::vector<VectorXd> &b) {
950 for (
size_t k = 0; k < a.size(); ++k) {
956void scale(std::vector<VectorXd> &a,
double f) {
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]);
976 std::vector<double> v;
977 std::vector<VectorXd> grad;
978 std::vector<VectorXd> potGrad;
981ActionEval evaluateAction(
const std::vector<VectorXd> &interior,
982 const VectorXd &start,
const VectorXd &end,
983 double vStart,
double vEnd,
double dtau,
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");
991 auto bead = [&](
size_t j) ->
const VectorXd & {
992 return j == 0 ? start : (j == m + 1 ? end : interior[j - 1]);
994 double kinetic = 0.0;
995 for (
size_t j = 0; j <= m; ++j) {
998 double pot = 0.5 * (vStart + vEnd);
999 for (
double vj : out.v) {
1002 out.action = 0.5 * kinetic / dtau + dtau * pot;
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];
1011double largestBeadNorm(
const std::vector<VectorXd> &g) {
1013 for (
const auto &v : g) {
1014 m = std::max(m, v.norm());
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));
1026 throw std::invalid_argument(
1027 "pathOmega: no positive curvature along the path at either minimum");
1029 return std::sqrt(k);
1033 double betaHbar, std::vector<VectorXd> guess,
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");
1043 inst.
dtau = betaHbar /
static_cast<double>(P);
1044 const double dtau = inst.
dtau;
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");
1056 if (guess.size() < 2) {
1057 guess = {start, end};
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();
1063 if (!(cum.back() > 0.0)) {
1064 throw std::invalid_argument(
"optimizeInstanton: the two minima coincide");
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);
1076 evaluateAction(x, start, end, vEnds[0], vEnds[1], dtau, potential);
1077 std::deque<std::pair<std::vector<VectorXd>, std::vector<VectorXd>>> pairs;
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];
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);
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];
1108 double slope = -dot(cur.grad, q);
1109 if (!(slope < 0.0)) {
1112 scale(q, dtau / 4.0);
1113 slope = -dot(cur.grad, q);
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];
1123 next = evaluateAction(trial, start, end, vEnds[0], vEnds[1], dtau,
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));
1131 (flat && largestBeadNorm(next.grad) < largestBeadNorm(cur.grad))) {
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];
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) {
1151 x = std::move(trial);
1152 cur = std::move(next);
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));
1167 const double sWell = betaHbar * 0.5 * (vEnds[0] + vEnds[1]);
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)])
1175 inst.
s0 = s0 / dtau;
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");
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);
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");
1198 diag.push_back(spring + dtau * 0.5 * (h + h.transpose()));
1203 const HaynsworthChain chain(c, diag,
true);
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");
1213 return well.logAbsDet();
1215 const double logDetWell = 0.5 * (wellLogDet(hessStart) + wellLogDet(hessEnd));
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)];
1224 scale(v, 1.0 / std::sqrt(dot(v, v)));
1225 const double vJv = dot(v, chain.solve(v));
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)");
1234 const double logDetPrime = chain.logAbsDet() + std::log(std::abs(vJv));
1237 std::vector<VectorXd> w(v.size());
1238 for (
size_t k = 0; k < w.size(); ++k) {
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);
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];
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);
1259 std::sqrt(inst.
s0 / (2.0 * std::numbers::pi *
kHbar * dtau)) *
1260 std::exp(0.5 * (logDetWell - logDetPrime) - inst.
action);
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");
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); });
1278 for (
size_t k =
static_cast<size_t>(rigidModes); k < lam.size(); ++k) {
1279 sum += std::sqrt(std::max(lam[k], 0.0));
1281 return 0.5 *
kHbar * sum;
1283 return zeroPoint(hessEnd) - zeroPoint(hessStart);
1289 dd_(
d_.squaredNorm()),
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");
1298 return std::clamp((q -
start_).dot(
d_) /
dd_, 0.0, 1.0);
1302 const double x =
xi(q);
1303 return delta_ * x * x * x * (10.0 + x * (-15.0 + 6.0 * x));
1307 const double x =
xi(q);
1308 return (
delta_ * 30.0 * x * x * (1.0 - x) * (1.0 - x) /
dd_) *
d_;
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());
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");
1325 return kHbar * std::sqrt(-lambda) / (2.0 * std::numbers::pi *
kBoltzmann);
1332 std::vector<double> v;
1333 std::vector<VectorXd> grad;
1334 std::vector<VectorXd> physicalGrad;
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) {
1346 std::vector<double> s(n, eta.size() == 1 ? eta[0] : 0.0);
1347 if (eta.size() == n) {
1349 }
else if (eta.size() != 1) {
1350 throw std::invalid_argument(
1351 "addFrictionBath: eta is one value or one per bead");
1353 for (
double value : s) {
1354 if (!(value >= 0.0)) {
1355 throw std::invalid_argument(
"addFrictionBath: eta must be non-negative");
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]);
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]);
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];
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);
1392 for (
size_t j = n - 1; j >= 1; --j) {
1393 dUdg[j - 1] += dUdg[j];
1398 for (
size_t j = 1; j < n; ++j) {
1399 grad[j] += mid[j] * dUdg[j];
1400 grad[j - 1] -= mid[j] * dUdg[j];
1406std::vector<double> frictionEta(
const RateInstantonOptions &options,
1408 if (!options.friction) {
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");
1416 return options.frictionEtaBeads;
1418 if (!(options.frictionEta > 0.0)) {
1421 return {options.frictionEta};
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 = {}) {
1430 std::vector<VectorXd> gv;
1431 potential(x, out.v, gv);
1432 for (
double &v : out.v) {
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");
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);
1450 out.u += 0.5 * c * spring;
1452 if (discretization.size() != n) {
1453 throw std::invalid_argument(
1454 "link weights must be one positive value per bead");
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");
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();
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];
1481 out.physicalGrad = std::move(gv);
1487 if (!options.physicalBath)
1489 return h + options.physicalBath->evaluate({q}, 1.0,
true).hessian;
1498double lowestOddMode(
const std::vector<VectorXd> &x,
const RingEval &here,
1500 std::vector<VectorXd> &mode,
long steps,
double eps,
1501 const std::vector<double> &eta = {}) {
1503 return std::numeric_limits<double>::infinity();
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];
1511 auto odd = [&](std::vector<VectorXd> &q) {
1514 for (
size_t a = 1; a < m; ++a) {
1515 const VectorXd half = 0.5 * (q[a] - q[n - a]);
1521 const double cnorm = std::sqrt(
dot(cycle, cycle));
1523 scale(cycle, 1.0 / cnorm);
1525 auto project = [&](std::vector<VectorXd> &q) {
1528 const double p =
dot(q, cycle);
1529 for (
size_t j = 0; j < n; ++j) {
1530 q[j] -= p * cycle[j];
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];
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;
1549 VectorXd mean = VectorXd::Zero(x[0].size());
1550 for (
const auto &b : x) {
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);
1559 const double qnorm = std::sqrt(
dot(q, q));
1560 if (!(qnorm > 1e-12)) {
1561 return std::numeric_limits<double>::infinity();
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) {
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) {
1577 const double bnorm = std::sqrt(
dot(w, w));
1578 if (!(bnorm > 1e-12) || k + 1 == steps) {
1581 beta.push_back(bnorm);
1582 scale(w, 1.0 / bnorm);
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)];
1590 t(i, i + 1) = t(i + 1, i) = beta[
static_cast<size_t>(i)];
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];
1602 scale(mode, 1.0 / std::sqrt(
dot(mode, mode)));
1603 return es.eigenvalues()(0);
1611std::vector<double> scanFromSaddle(
const VectorXd &saddle,
const VectorXd &dir,
1612 double sign,
double h,
long maxPoints,
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");
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);
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");
1633double turningDistance(
const VectorXd &saddle,
const VectorXd &dir,
1634 double vSaddle,
double drop,
double sign,
double h,
1636 if (!(drop > 0.0)) {
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);
1653 if (vk > prevV + 1e-12 && k > 0) {
1662double sideDrop(
const VectorXd &saddle,
const VectorXd &dir,
double vSaddle,
1663 double sign,
double h,
long maxPoints,
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;
1673 lowest = std::min(lowest, vk);
1675 return vSaddle - lowest;
1680 double residual = 0.0;
1681 std::vector<VectorXd> vector;
1686std::vector<RingMode> lowestRingModes(
1687 const std::function<std::vector<VectorXd>(
const std::vector<VectorXd> &)>
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");
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) {
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) {
1713 const double bnorm = std::sqrt(
dot(w, w));
1714 if (!(bnorm > 1e-14) || k + 1 == steps) {
1717 beta.push_back(bnorm);
1718 scale(w, 1.0 / bnorm);
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)];
1726 tridiag(i, i + 1) = tridiag(i + 1, i) = beta[
static_cast<size_t>(i)];
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) {
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];
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();
1748 mode.residual = std::sqrt(residual);
1749 modes.push_back(std::move(mode));
1758struct CyclicFactor {
1760 Eigen::PartialPivLU<ColMajorXd> cornerLu;
1767 CyclicFactor(
double cIn,
const std::vector<MatrixXd> &diag)
1770 f(diag.front().rows()),
1771 n(static_cast<long>(diag.size())),
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);
1778 const std::vector<MatrixXd> fromFirst = open.solve(rhs);
1781 const std::vector<MatrixXd> fromLast = open.solve(rhs);
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();
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)) {
1799 logAbs = -std::numeric_limits<double>::infinity();
1802 logAbs += std::log(std::abs(pivot));
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");
1810 std::vector<VectorXd> y = open.solve(rhs);
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)];
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()),
1840 chain_(c, diag, spectrum, weight),
1842 const long base = closed ? 2 * f_ : 0;
1843 const long m = base +
static_cast<long>(extras.size());
1844 kinv_ = MatrixXd::Zero(m, m);
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_);
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];
1860 logAbsDet_ = chain_.logAbsDet();
1861 negative_ = chain_.negative();
1864 gtg_ = MatrixXd::Zero(m, m);
1865 for (
long col = 0; col < m; ++col) {
1866 gtg_.col(col) = pieces(chain_.solve(column(col)));
1868 woodbury_.compute(ColMajorXd(kinv_ + gtg_));
1869 ok_ = gtg_.array().isFinite().all();
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);
1878 logAbsDet_ = -std::numeric_limits<double>::infinity();
1881 logDet += std::log(std::abs(u));
1883 logAbsDet_ = chain_.logAbsDet() + logDet;
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();
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) {
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) {
1909 double logAbsDet()
const {
return logAbsDet_; }
1910 long negative()
const {
return negative_; }
1913 std::vector<VectorXd> column(
long col)
const {
1914 const long base = closed_ ? 2 * f_ : 0;
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;
1920 return extras_[
static_cast<size_t>(col - base)];
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()));
1926 out.head(f_) = x[0];
1927 out.segment(f_, f_) = x[
static_cast<size_t>(n_ - 1)];
1929 for (
size_t i = 0; i < extras_.size(); ++i) {
1930 out(base +
static_cast<long>(i)) =
dot(extras_[i], x);
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_));
1939 g[
static_cast<size_t>(n_ - 1)] += y.segment(f_, f_);
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)];
1952 HaynsworthChain chain_;
1953 std::vector<std::vector<VectorXd>> extras_;
1955 Eigen::PartialPivLU<ColMajorXd> woodbury_;
1957 double logAbsDet_ = 0.0;
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");
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());
1981 double add = end ? c : 2.0 * c;
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");
1990 add = c / wj + c / wp;
1992 block += add * MatrixXd::Identity(f, f);
1993 diag[
static_cast<size_t>(j)] = block;
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");
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;
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");
2026 if (j > 0 || closed) {
2027 out[j] -= cPrev * v[prev];
2029 if (j + 1 < n || closed) {
2030 out[j] -= cNext * v[next];
2040void requireCyclicBlocks(
double c,
const std::vector<MatrixXd> &diag,
2042 if (!(c > 0.0) || diag.empty()) {
2043 throw std::invalid_argument(std::string(what) +
2044 ": need a positive spring constant and blocks");
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");
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");
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");
2068 const std::vector<MatrixXd> diag = ringDiagonal(beadHessians, c,
false);
2071 const WoodburyRing ring(c, diag,
true, {tau}, {c},
true);
2073 throw std::runtime_error(
"ringSpectrum: singular ring");
2076 out.
zeroEigenvalue = dot(tau, applyDiagonal(diag, c,
true, tau));
2084 requireCyclicBlocks(c, diag,
"cyclicRingLogAbsDet");
2085 return CyclicFactor(c, diag).logAbs;
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");
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");
2102 return CyclicFactor(c, diag).solve(rhs);
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) {
2118 pts.push_back(std::move(qp));
2119 pts.push_back(std::move(qm));
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");
2129 for (
long a = 0; a < f; ++a) {
2131 (g[
static_cast<size_t>(2 * a)] - g[
static_cast<size_t>(2 * a + 1)]) /
2134 return (0.5 * (h + h.transpose())).eval();
2138void bofillUpdate(
MatrixXd &h,
const VectorXd &dq,
const VectorXd &dg) {
2139 const double dq2 = dq.squaredNorm();
2140 if (!(dq2 > 1e-24)) {
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());
2154 h = (0.5 * (h + h.transpose())).eval();
2161long clearlyNegative(
const VectorXd &lam) {
2162 if (lam.size() == 0) {
2165 const double span = lam.cwiseAbs().maxCoeff();
2166 return (lam.array() < -1e-6 * span).count();
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());
2184void inertiaKeepingUpdate(
MatrixXd &h,
const VectorXd &dq,
const VectorXd &dg,
2186 bofillUpdate(h, dq, dg);
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) {
2197 VectorXd fixed = lam;
2199 for (
long i = allowed; i < negative; ++i) {
2200 fixed(i) = std::abs(lam(i));
2202 h = es.eigenvectors() * fixed.asDiagonal() * es.eigenvectors().transpose();
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)];
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);
2221double packedBeadNorm(
const VectorXd &step,
long f) {
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());
2230bool finiteBeads(
const std::vector<VectorXd> &x) {
2231 for (
const auto &q : x) {
2232 if (!q.array().isFinite().all()) {
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;
2251 out[j] = 0.5 * (x[next] - x[prev]);
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])) /
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)];
2272 const double nrm = tau.norm();
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");
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]);
2299 double curvature = 0.0;
2306std::vector<VectorXd> cosineSeed(
const VectorXd &saddle,
const VectorXd &dir,
2307 double lambda0,
double temperature,
2308 double crossover,
long nBeads,
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");
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));
2332 for (
long j = 0; j < nBeads; ++j) {
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)];
2349VectorXd chainIndexOneStep(
const std::vector<RingMode> &ritz,
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 = {},
2358 if (climb.index < 0 || ritz.empty() || grad.empty()) {
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);
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;
2384 if (std::abs(cycleCurvature) <= 1e-6 * std::max(1.0, spring)) {
2385 extras.push_back(tauRing);
2386 kappas.push_back(spring);
2390 auto onNull = [&](
const std::vector<VectorXd> &m) {
2391 for (
const auto &r : nullRing) {
2392 if (std::abs(
dot(m, r)) > 0.5) {
2398 for (
const auto &r : nullRing) {
2399 extras.push_back(r);
2400 kappas.push_back(spring);
2402 for (
size_t i = 0; i < ritz.size(); ++i) {
2403 if (!tauRing.empty() && std::abs(
dot(ritz[i].vector, tauRing)) > 0.5) {
2406 if (onNull(ritz[i].vector)) {
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);
2419 std::vector<VectorXd> rhs = grad;
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);
2430 double energy = 0.0;
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];
2441 const double rhsNorm = std::sqrt(
dot(rhs, rhs));
2442 std::vector<VectorXd> stepRing;
2443 bool solved =
false;
2445 if (dim <= kDenseRing || !eta.empty() || physicalBathHessian.size()) {
2446 throw std::runtime_error(
"dense ring or nonlocal bath: dense solve");
2448 const WoodburyRing ring(spring, diag, closed, extras, kappas,
false,
2451 stepRing = ring.solve(rhs);
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];
2460 const double rn = std::sqrt(
dot(r, r));
2461 if (!std::isfinite(rn)) {
2464 if (rn <= 1e-10 * std::max(1.0, rhsNorm)) {
2468 const std::vector<VectorXd> dx = ring.solve(r);
2469 for (
size_t j = 0; j < stepRing.size(); ++j) {
2470 stepRing[j] += dx[j];
2474 }
catch (
const std::runtime_error &) {
2477 if (!solved && dim <= kDenseRing) {
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));
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);
2492 solved = x.array().isFinite().all();
2494 if (!solved && stepRing.empty()) {
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;
2505 if (!step.array().isFinite().all()) {
2512std::vector<double> pavaNonIncreasing(
const std::vector<double> &values) {
2513 const long n =
static_cast<long>(values.size());
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();
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;
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;
2547void projectMonotonePrefix(std::vector<VectorXd> &q,
long last,
2548 const VectorXd &dir) {
2549 if (last < 1 || q.empty() || dir.size() != q.front().size()) {
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)]);
2557 std::vector<double> target;
2558 if (s.front() >= s.back()) {
2559 target = pavaNonIncreasing(s);
2561 std::vector<double> flipped(s.size());
2562 for (
size_t j = 0; j < s.size(); ++j) {
2565 target = pavaNonIncreasing(flipped);
2566 for (
double &v : target) {
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;
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) {
2592 const long nb =
static_cast<long>(q.size());
2594 Eigen::Vector3d centre = Eigen::Vector3d::Zero();
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;
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);
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();
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();
2629 d = sm * e.cross(r - centre);
2631 g.block(j * 3 * nAtoms + 3 * k,
static_cast<long>(col), 3, 1) = d;
2639 ColMajorXd gc(dim, g.cols());
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;
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);
2661 out.push_back(std::move(u));
2667 std::vector<VectorXd> beads;
2668 std::vector<double> energies;
2669 double ringPotential = 0.0;
2671 long iterations = 0;
2672 bool converged =
false;
2675 bool stalledHalf =
false;
2679 bool collapsed =
false;
2684NewtonOut newtonInstanton(std::vector<VectorXd> guess,
double c,
2688 const long nBeads = options.beads;
2694 bool half = options.halfRing && options.discretization.empty() &&
2695 !options.friction && !options.physicalBath && nBeads % 2 == 0 &&
2696 static_cast<long>(guess.size()) == nBeads;
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)])
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");
2712 const std::vector<double> *linkWeight =
2713 options.discretization.empty() ? nullptr : &options.discretization;
2714 std::vector<VectorXd> x;
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)];
2722 x = std::move(guess);
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();
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) {
2734 return std::vector<std::vector<VectorXd>>{};
2736 return ringRigidBasis(q, options.rigidSqrtMasses, options.rigidReference,
2737 options.rigidRotations);
2739 std::vector<std::vector<VectorXd>> nullRing;
2743 std::vector<MatrixXd> physical;
2744 const auto beadPotential =
2745 ownedEvaluation(potential, options, 0,
static_cast<long>(x.size()));
2746 const auto derivativePotential =
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");
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);
2766 physical.resize(x.size());
2767 for (
size_t j = 0; j < x.size(); ++j) {
2768 physical[j] = physicalAt(x[j]);
2772 std::vector<long> allowedNegatives(x.size(), -1);
2773 auto recountNegatives = [&]() {
2777 for (
size_t j = 0; j < x.size(); ++j) {
2778 allowedNegatives[j] = negativeEigenvalues(physical[j]);
2784 std::vector<VectorXd> grad;
2785 std::vector<VectorXd> gradPot;
2786 std::vector<double> energies;
2789 auto objective = [&](
const std::vector<VectorXd> &q) {
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;
2803 if (vu.size() != q.size() || gu.size() != q.size()) {
2804 throw std::runtime_error(
2805 "rate instanton: potential returned the wrong count");
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)];
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)];
2820 std::vector<VectorXd> gRing(
static_cast<size_t>(n));
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)]);
2832 (full[
static_cast<size_t>(next)] - full[
static_cast<size_t>(j)])
2834 uFull += vFull[
static_cast<size_t>(j)];
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)] =
2844 (gRing[
static_cast<size_t>(j)] + gRing[
static_cast<size_t>(n - j)]);
2846 out.gradPot = std::move(gu);
2847 out.energies = std::move(vu);
2850 evaluateRing(q, c, beadPotential, options.energyShift,
2851 frictionEta(options, q.size()), options.discretization,
2852 options.physicalBath);
2855 out.gradPot = ev.physicalGrad;
2856 out.energies = ev.v;
2863 std::vector<RingMode> ritz;
2864 std::vector<MatrixXd> diag;
2872 auto closedGmax = [&](
const Obj &ev) {
2873 if (!half || ev.grad.size() < 2) {
2874 return largestBeadNorm(ev.grad);
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());
2886 std::vector<VectorXd> ritzStart(x.size(), VectorXd::Zero(f));
2887 VectorXd climbDir(f);
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) {
2899 std::vector<VectorXd> track = ritzStart;
2901 const double n0 = std::sqrt(
dot(track, track));
2903 scale(track, 1.0 / n0);
2909 projectMonotonePrefix(x,
static_cast<long>(x.size()) - 1, climbDir);
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]);
2917 nullRing = ringRigid(x);
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();
2926 v.tau = (half || !constantBath) ? VectorXd() : timeTranslation(x);
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);
2939 double energy = 0.0;
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);
2949 const auto residual =
apply(phase);
2951 if (std::sqrt(
dot(residual, residual)) > 1e-6 * std::max(1.0, c)) {
2955 const long dim =
static_cast<long>(x.size()) * f;
2956 if (dim <= kDenseRing) {
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));
2966 const ColMajorXd
sym = 0.5 * (big + big.transpose());
2967 const Eigen::SelfAdjointEigenSolver<ColMajorXd> es(sym);
2969 for (
long i = 0; i < dim; ++i) {
2971 m.theta = es.eigenvalues()(i);
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);
2978 v.ritz.push_back(std::move(m));
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);
2992 lift.push_back(std::move(tauRing));
2997 WoodburyRing(c, v.diag, !half, lift, kap,
true, linkWeight)
2999 }
catch (
const std::runtime_error &) {
3006 const double resolvedTol = 1e-8 * std::max(1.0, 4.0 * c);
3007 auto resolvedNegatives = [&](
const std::vector<RingMode> &modes) {
3009 for (
const auto &m : modes) {
3010 if (m.theta < 0.0 && m.residual <= resolvedTol) {
3016 long steps = std::min(dim, std::max(60L, 4 * (negatives + 2)));
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) {
3028 bead(a2) += 1e-2 * (
static_cast<double>(h >> 11) * 0x1.0p-53 - 0.5);
3031 v.ritz = lowestRingModes(apply, std::move(start), steps);
3032 if (steps >= std::min(dim, kRitzCap) ||
3033 resolvedNegatives(v.ritz) >= negatives) {
3036 steps = std::min(std::min(dim, kRitzCap), 2 * steps);
3039 v.ritz.erase(std::remove_if(v.ritz.begin(), v.ritz.end(),
3040 [](
const RingMode &m) {
3043 std::max(1.0, std::abs(m.theta));
3047 v.ok = !v.ritz.empty();
3051 double minimumWeight = 1.0;
3052 for (
double weight : options.discretization) {
3053 minimumWeight = std::min(minimumWeight, weight);
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);
3062 operatorBound += 2.0 * (*std::max_element(eta.begin(), eta.end()));
3064 if (dim <= kDenseRing) {
3065 operatorBound = 0.0;
3066 for (
const auto &mode : v.ritz) {
3067 operatorBound = std::max(operatorBound, std::abs(mode.theta));
3071 -64.0 * std::numeric_limits<double>::epsilon() * dim * operatorBound;
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);
3080 auto onCycle = [&](
const std::vector<VectorXd> &m) {
3081 if (!tauRing.empty() && std::abs(
dot(m, tauRing)) > 0.5) {
3084 for (
const auto &r : nullRing) {
3085 if (std::abs(
dot(m, r)) > 0.5) {
3093 for (
size_t i = 0; i < v.ritz.size(); ++i) {
3094 if (onCycle(v.ritz[i].vector)) {
3098 v.ritz[i].theta < v.ritz[
static_cast<size_t>(lowest)].theta) {
3099 lowest =
static_cast<long>(i);
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));
3105 v.climb.index =
static_cast<long>(i);
3109 if (v.climb.index < 0 || best < kTrackOverlap) {
3110 v.climb.index = lowest;
3112 if (v.climb.index >= 0) {
3113 v.climb.curvature = v.ritz[
static_cast<size_t>(v.climb.index)].theta;
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)) {
3120 if (v.ritz[i].theta + v.ritz[i].residual < cut) {
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) {
3130 if (track.size() == ritzStart.size() &&
dot(track, track) > 0.0) {
3131 scale(track, 1.0 / std::sqrt(
dot(track, track)));
3138 auto done = [&](
const View &v) {
3139 return v.ok && v.gmax < options.forceTolerance && v.climb.negative == 1 &&
3140 v.climb.curvature < 0.0;
3143 Obj cur = objective(x);
3144 double trust = options.maxStep;
3146 bool converged =
false;
3147 bool analyticPolishAttempted =
false;
3148 bool stalledHalf =
false;
3149 const double trustFloor = std::min(1e-4, options.maxStep);
3151 constexpr int kMaxHessianRefreshes = 3;
3153 bool exactAtX = options.physicalHessian ||
3154 (f > 1 && options.initialHessians ==
"finite_difference");
3157 long exactNegatives = -1;
3158 long previousModeledNegatives = -1;
3159 constexpr int kMaxDriftRefreshes = 4;
3160 int driftRefreshes = 0;
3162 auto ringLength = [&](
const std::vector<VectorXd> &q) {
3165 for (
size_t j = 0; j + 1 < q.size(); ++j) {
3169 for (
size_t j = 0; j < q.size(); ++j) {
3170 b += (q[(j + 1) % q.size()] - q[j]).squaredNorm();
3175 const double startLength = ringLength(x);
3176 bool collapsed =
false;
3177 for (
long it = 0; it < options.maxIterations; ++it) {
3179 const double length = ringLength(x);
3180 if (startLength > 0.0 && length < options.collapseFraction * startLength) {
3185 for (
size_t j = 0; j < x.size(); ++j) {
3186 physical[j] = physicalAt(x[j]);
3189 const View v = viewOf(cur);
3190 const bool modeledCountGrew = previousModeledNegatives >= 0 &&
3191 v.climb.negative > previousModeledNegatives;
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, "
3197 it, half ? 2.0 * cur.u : cur.u, v.gmax, length,
3198 v.climb.curvature, v.climb.negative, trust);
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]);
3211 const bool polishing = done(v) && options.physicalHessian &&
3212 !analyticPolishAttempted && v.gmax > 0.0;
3213 if (done(v) && !polishing) {
3220 analyticPolishAttempted =
true;
3227 if (f > 1 && v.ok) {
3229 exactNegatives = v.climb.negative;
3230 }
else if ((v.gmax < options.forceTolerance || modeledCountGrew) &&
3231 v.climb.negative > std::max(1L, exactNegatives) &&
3232 driftRefreshes < kMaxDriftRefreshes) {
3234 for (
size_t j = 0; j < x.size(); ++j) {
3235 physical[j] = physicalAt(x[j]);
3239 EONC_LOG_DEBUG(
"[Instanton] Newton {}: {} negative curvatures in the "
3240 "Bofill blocks, rebuilt from finite differences",
3241 it, v.climb.negative);
3247 auto accept = [&](VectorXd dir) {
3248 if (dir.size() == 0 || !dir.array().isFinite().all()) {
3251 const double big = packedBeadNorm(dir, f);
3255 std::vector<VectorXd> trial = x;
3256 addPacked(trial, dir);
3258 projectMonotonePrefix(trial,
static_cast<long>(trial.size()) - 1,
3261 if (!finiteBeads(trial)) {
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)];
3269 if (!(packedBeadNorm(taken, f) > 0.0) ||
3270 !taken.array().isFinite().all()) {
3274 Obj next = objective(trial);
3275 if (!finiteBeads(next.grad) || !std::isfinite(next.u)) {
3278 bool ratioOk =
false;
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);
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);
3293 double energy = 0.0;
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;
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;
3308 ratio = actual / pred;
3310 ratioOk = std::isfinite(ratio) && ratio >= 0.1 && ratio <= 3.0;
3313 double magnitude = std::abs(cur.u);
3314 for (
const double vj : cur.energies) {
3315 magnitude += std::abs(vj);
3317 const double roundoff =
3318 1e3 * std::numeric_limits<double>::epsilon() * magnitude;
3319 if (!ratioOk && std::abs(pred) < roundoff &&
3320 closedGmax(next) <= closedGmax(cur)) {
3328 if (polishing && closedGmax(next) > closedGmax(cur))
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]);
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);
3351 if (v.ok && v.gmax < options.forceTolerance && v.climb.negative != 1 &&
3353 for (
size_t j = 0; j < x.size(); ++j) {
3354 physical[j] = physicalAt(x[j]);
3360 if (v.ok && v.gmax < options.forceTolerance && v.climb.negative > 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)) {
3368 if (v.tau.size() ==
static_cast<long>(x.size()) * f) {
3369 held = std::abs(packBeads(m.vector).dot(v.tau)) > 0.5;
3371 for (
const auto &r : nullRing) {
3372 held = held || std::abs(
dot(m.vector, r)) > 0.5;
3375 (down < 0 || m.theta < v.ritz[
static_cast<size_t>(down)].theta)) {
3376 down =
static_cast<long>(i);
3380 trust = options.maxStep;
3383 VectorXd mode = packBeads(v.ritz[
static_cast<size_t>(down)].vector);
3384 const double big = packedBeadNorm(mode, f);
3386 mode *= trust / big;
3387 if (accept(mode) || accept(-mode)) {
3396 if (half && options.checkOddSector && exactAtX && v.ok &&
3397 v.gmax < options.forceTolerance && v.climb.negative != 1) {
3401 const VectorXd step =
3402 chainIndexOneStep(v.ritz, v.climb, v.diag, c, !half, cur.grad, v.tau,
3403 nullRing, linkWeight, eta, v.physicalBathHessian);
3405 VectorXd dir = step;
3407 if (dir.size() > 0) {
3408 const double big0 = packedBeadNorm(dir, f);
3410 dir *= trust / big0;
3413 for (
int bt = 0; bt < 4 && !moved; ++bt) {
3414 moved = accept(dir);
3422 trust = std::max(0.5 * trust, trustFloor);
3427 if (trust <= trustFloor && refreshes < kMaxHessianRefreshes) {
3429 for (
size_t j = 0; j < x.size(); ++j) {
3430 physical[j] = physicalAt(x[j]);
3433 trust = options.maxStep;
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);
3448 converged = done(last);
3452 out.iterations = entries;
3453 out.converged = converged;
3454 out.stalledHalf = stalledHalf;
3455 out.collapsed = collapsed;
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)];
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)];
3471 out.ringPotential = 2.0 * cur.u;
3473 out.beads = std::move(x);
3474 out.ringPotential = cur.u;
3475 out.energies = std::move(cur.energies);
3477 out.bN = ringSpeed(out.beads, options.discretization);
3485 const MatrixXd &hessSaddle,
double beta,
3486 std::vector<VectorXd> guess,
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");
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");
3502 inst.discretization = options.discretization;
3503 inst.bathEta = frictionEta(options, options.beads);
3505 inst.betaN = beta /
static_cast<double>(nBeads);
3506 inst.temperature = 1.0 / (
kBoltzmann * beta);
3508 options.physicalBath
3509 ?
MatrixXd(options.physicalBath->fullHessian(saddle, 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");
3519 const bool cool =
static_cast<long>(guess.size()) != nBeads &&
3520 inst.temperature < 0.75 * inst.crossover;
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)])
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()) {
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];
3559 const long before = got.iterations;
3560 got = newtonInstanton(std::move(kicked), spring, hessSaddle, whole,
3562 got.iterations += before;
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);
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;
3585 inst.iterations = got.iterations;
3586 inst.converged = got.converged;
3587 inst.collapsed = got.collapsed;
3588 if (inst.converged || !cool) {
3593 std::vector<double> temps;
3594 for (
double t = 0.85 * inst.crossover; t > inst.temperature * 1.05;
3598 temps.push_back(inst.temperature);
3599 std::vector<VectorXd> beads;
3603 long used =
saddle.size() == 1 ? inst.iterations : 0;
3604 if (used >= options.maxIterations) {
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;
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);
3628 std::move(stageGuess), potential, opt);
3629 used += last.iterations;
3630 if (last.collapsed) {
3638 last.iterations = used;
3641 last.betaN = beta /
static_cast<double>(nBeads);
3642 last.temperature = inst.temperature;
3643 last.crossover = inst.crossover;
3645 last.converged =
false;
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);
3657 const double bnh = inst.betaN *
kHbar;
3658 const double spring = 1.0 / (bnh * bnh);
3660 newtonInstanton(std::move(guess), spring, hessSaddle, options, potential);
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)])
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];
3694 const long before = got.iterations;
3695 got = newtonInstanton(std::move(kicked), spring, hessSaddle, whole,
3697 got.iterations += before;
3700 inst.beads = got.beads;
3701 inst.energies = got.energies;
3702 inst.ringPotential = got.ringPotential;
3704 inst.iterations = got.iterations;
3705 inst.converged = got.converged;
3706 inst.collapsed = got.collapsed;
3714struct SearchedRing {
3715 std::vector<VectorXd> beads;
3716 std::vector<double> energies;
3717 double ringPotential = 0.0;
3719 long iterations = 0;
3720 bool converged =
false;
3723std::vector<VectorXd> activeBeadsOf(
const std::vector<VectorXd> &full,
3728 const long m =
static_cast<long>(full.size()) / 2;
3729 return std::vector<VectorXd>(full.begin(), full.begin() + (m + 1));
3732std::vector<VectorXd> expandMirrored(
const std::vector<VectorXd> &active,
3733 long nBeads,
bool fold) {
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)];
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 "
3757 if (fold && nBeads % 2 != 0) {
3758 throw std::invalid_argument(
3759 "ring structure: a folded ring needs an even bead count");
3764 nActive_ = fold ? (nBeads / 2 + 1) : nBeads;
3766 usedOnLast_ =
static_cast<int>(dof % 3 == 0 ? 3 : dof % 3);
3769 const double nrm =
modeDir_.norm();
3771 throw std::invalid_argument(
"ring structure: the saddle direction is zero");
3777 long dof,
double spring,
3779 std::vector<double> eta,
bool fold,
3782 beads_(std::move(beads)),
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");
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");
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");
3805 const double *src = active[
static_cast<size_t>(j)].data();
3809 for (
int ax = 0; ax < nax; ++ax, ++flat) {
3810 atom[ax] = src[flat];
3816std::vector<VectorXd>
3818 if (positions ==
nullptr) {
3819 throw std::invalid_argument(
"ring structure: missing positions");
3821 std::vector<VectorXd> active(
static_cast<size_t>(
nActive_),
3822 VectorXd::Zero(
dof_));
3823 for (
long j = 0; j <
nActive_; ++j) {
3826 const double *atom = positions + (j *
atomsPerBead_ + a) * 3;
3828 for (
int ax = 0; ax < nax; ++ax, ++flat) {
3829 active[
static_cast<size_t>(j)](flat) = atom[ax];
3839 throw std::invalid_argument(
"ring mode: atom count does not match");
3841 std::vector<VectorXd> beads(
static_cast<size_t>(
nActive_), dir);
3843 const double nrm = mode.norm();
3845 throw std::invalid_argument(
"ring mode: the saddle direction is zero");
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) {
3856 const double *src = grad[
static_cast<size_t>(j)].data();
3860 for (
int ax = 0; ax < nax; ++ax, ++flat) {
3861 atom[ax] = -src[flat];
3866 constexpr double kAxis = 1.0e3;
3870 for (
long j = 0; j <
nActive_; ++j) {
3872 double *frc = forces + atom * 3;
3873 const double *pos = positions + atom * 3;
3875 extra += 0.5 * kAxis * pos[ax] * pos[ax];
3876 frc[ax] = -kAxis * pos[ax];
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};
3891 forceBatch(1, nAtoms, pos, nrs, frc, energy, variance ? &var : &var, boxes);
3899 const double *
const *positions,
3900 const int *
const *atomicNrs,
3901 double *
const *forces,
double *energies,
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");
3912 std::vector<VectorXd> raw;
3913 std::vector<VectorXd> q;
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;
3922 projectMonotonePrefix(items[
static_cast<size_t>(i)].q,
nActive_ - 1,
3925 all.insert(all.end(), items[
static_cast<size_t>(i)].q.begin(),
3926 items[
static_cast<size_t>(i)].q.end());
3928 std::vector<double> vAll;
3929 std::vector<VectorXd> 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");
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");
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_));
3958 vFull = std::move(vActive);
3959 gFull = std::move(gActive);
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)];
3975 auto replay = [&](
const std::vector<VectorXd> &, std::vector<double> &v,
3976 std::vector<VectorXd> &g) {
3982 std::vector<VectorXd> reduced;
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)];
3996 double penalty = 0.0;
3998 for (
long j = 0; j <
nActive_; ++j) {
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;
4005 const double axis =
writeForces(reduced, positions[i], forces[i]);
4006 energies[i] = ev.u + penalty + axis;
4016SearchedRing oneDimerSearch(
const std::vector<VectorXd> &full,
double c,
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),
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);
4056 const long atomsPer =
pot->structureAtoms() /
pot->activeBeads();
4058 static_cast<int>((dir.size() % 3 == 0) ? 3 : (dir.size() % 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);
4067 VectorXd packed = VectorXd::Zero(3 * pot->structureAtoms());
4068 pot->packActive(activeBeadsOf(full, fold), packed.data());
4069 matter->setPositionsV(packed);
4071 pot->packMode(dir, mode);
4072 const double e0 = matter->getPotentialEnergy();
4073 MinModeSaddleSearch search(matter, mode, e0, params, pot);
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,
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)];
4088 RingEval evFold = evaluateRing(projected, c, potential, options.
energyShift,
4090 if (largestBeadNorm(evFold.grad) <= largestBeadNorm(ev.grad)) {
4091 beads = std::move(projected);
4092 ev = std::move(evFold);
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();
4103 out.iterations = search.getIterationCount();
4104 const double residual = largestBeadNorm(ev.grad);
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());
4113SearchedRing searchRingWithDimer(std::vector<VectorXd> full,
double c,
4116 const VectorXd &dir,
bool fold,
double betaN,
4117 double barrierCurvature) {
4118 const std::vector<double> eta = frictionEta(options, full.size());
4120 oneDimerSearch(full, c, potential, options, dir, fold, eta);
4121 if (!fold || !options.checkOddSector || out.beads.size() != full.size()) {
4124 const RingEval here =
4125 evaluateRing(out.beads, c, potential, options.energyShift, eta,
4126 options.discretization);
4127 if (!(largestBeadNorm(here.grad) < options.forceTolerance)) {
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()) {
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];
4143 const long before = out.iterations;
4144 out = oneDimerSearch(kicked, c, potential, options, dir,
false, eta);
4145 out.iterations += before;
4152 const MatrixXd &hessSaddle,
double beta,
4153 std::vector<VectorXd> guess,
4160 throw std::invalid_argument(
4161 "physical quadratic bath requires uniform links and a retained "
4162 "coordinate basis without rigid generators");
4166 throw std::invalid_argument(
"optimizeRateInstanton: physicalHessianStep "
4167 "must be finite and positive "
4168 "in sqrt(amu) Angstrom");
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");
4180 const std::vector<double> bath = frictionEta(options, N);
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");
4191 inst.
betaN = beta /
static_cast<double>(N);
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");
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)])
4215 const long active = mirror ? (N / 2 + 1) : N;
4218 const bool denseBath =
4219 options.
physicalBath || !frictionEta(options, N).empty();
4222 (!denseBath || active * saddle.size() <= kDenseRing)) {
4223 return optimizeRateByNewton(saddle, hessSaddle, beta, std::move(guess),
4224 potential, options);
4227 throw std::invalid_argument(
4228 "optimizeRateInstanton: link weights take the Newton search; "
4229 "minimum-mode following keeps the uniform ring");
4232 const double c = 1.0 / (bnh * bnh);
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);
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);
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);
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) {
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);
4274 std::vector<VectorXd> x = std::move(guess);
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() >
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]);
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)];
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;
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));
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()));
4329 out[
static_cast<size_t>(order[
static_cast<size_t>(k)])] =
true;
4341std::vector<double> rotationMoments(
const std::vector<VectorXd> &beads,
4343 const long nAtoms =
static_cast<long>(bodies.sqrtMasses.size());
4344 Eigen::Vector3d centre = Eigen::Vector3d::Zero();
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)]);
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);
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() -
4370 std::vector<int> axes;
4371 for (
int c = 0; c < 3; ++c) {
4372 if (bodies.rotations[
static_cast<size_t>(c)]) {
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]);
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));
4399 const long nAtoms =
static_cast<long>(bodies.
sqrtMasses.size());
4400 const bool anyFree =
4402 if (nAtoms == 0 || !anyFree || beads.empty()) {
4405 if (bodies.
reference.size() != 3 * nAtoms) {
4406 throw std::invalid_argument(
4407 "logRotationalRatio: the reference needs three coordinates per atom");
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");
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()));
4425 for (
size_t i = 0; i < ring.size(); ++i) {
4426 out += 0.5 * (std::log(ring[i]) - std::log(reactant[i]));
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");
4438 return evaluateRing(beads, spring, potential, 0.0, {}, discretization).u;
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;
4454 for (
long row = 0; row < n; ++row) {
4455 kernel(row, col) = g[
static_cast<size_t>(row)](0);
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");
4464 return (0.5 * (kernel + kernel.transpose())).eval();
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,
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");
4482 if (!reactantValues.allFinite()) {
4483 throw std::runtime_error(
4484 "instantonRate: non-finite bath reactant spectrum");
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()
4491 : inst.discretization[
static_cast<size_t>(j)];
4492 const double link = c / w;
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");
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");
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)]) {
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");
4526 reactantLogDet += std::log(curvature + mu);
4530 inst.bathReactantLogAbsDet = reactantLogDet;
4531 inst.logZr = -inst.beta * vReactant - reactantDim * std::log(bnh) -
4532 0.5 * reactantLogDet;
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;
4540 if (!physical[
static_cast<size_t>(j)].allFinite()) {
4541 throw std::runtime_error(
4542 "instantonRate: non-finite physical bead Hessian");
4544 full.block(j * f, j * f, f, f) += physical[
static_cast<size_t>(j)];
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)]);
4553 Eigen::ColPivHouseholderQR<ColMajorXd> qr(generators);
4554 if (qr.rank() != generators.cols()) {
4555 throw std::runtime_error(
4556 "instantonRate: dependent declared rigid generators");
4558 const ColMajorXd q = qr.householderQ() * ColMajorXd::Identity(dim, dim);
4559 quotient = q.rightCols(dim - generators.cols());
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");
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");
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");
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;
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;
4600 inst.negativeEigenvalue = std::min(0.0, values(0));
4601 VectorXd cycle = quotient.transpose() * timeTranslation(inst.beads);
4602 const double cycleNorm = cycle.norm();
4604 double bestOverlap = 0.0;
4605 if (cycleNorm > 1e-8) {
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) {
4612 bestOverlap = overlap;
4617 bool circulant =
true;
4618 for (
long j = 0; j < n; ++j) {
4619 for (
long k = 0; k < n; ++k) {
4622 std::abs(bead(j, k) - bead((j + 1) % n, (k + 1) % n)) <= beadTol;
4625 inst.phaseEigenResidual = phase >= 0
4626 ? (reduced * es.eigenvectors().col(phase) -
4627 values(phase) * es.eigenvectors().col(phase))
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)));
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();
4645 inst.converged && inst.phaseZeroVerified && inst.negativeModes == 1;
4648 ?
"unconverged_bath_ring"
4650 ?
"additional_bath_null_modes"
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 =
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 *
4669 logProd - inst.betaN * inst.ringPotential;
4670 inst.logRate = inst.logRateTimesZr - inst.logZr;
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");
4682 const std::vector<MatrixXd> &physical,
4683 const MatrixXd &reactant,
double vReactant,
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;
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;
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;
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))
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) {
4750 (bath.bathPositions[(j + 1) % n] - bath.bathPositions[j]).
squaredNorm();
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)
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;
4769 -inst.beta * vReactant - logMeasure - 0.5 * inst.bathReactantLogAbsDet;
4774 inst.logRateTimesZr =
4776 0.5 * std::log(fullBN /
4777 (2 * std::numbers::pi * inst.betaN *
kHbar *
kHbar)) -
4778 0.5 * inst.bathLogAbsDet - inst.betaN * inst.ringPotential;
4780 inst.converged && inst.phaseZeroVerified && inst.negativeModes == 1;
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 =
4794 inst.logRate = inst.logRateTimesZr - inst.logZr;
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();
4806 const MatrixXd &hessReactant,
double vReactant,
4807 const MatrixXd &hessSaddle,
double vSaddle,
long rigidModes,
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");
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");
4819 const double c = 1.0 / (bnh * bnh);
4820 const MatrixXd eye = MatrixXd::Identity(f, f);
4821 const std::vector<double> *linkWeight =
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");
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");
4837 hBead[
static_cast<size_t>(j)] = 0.5 * (h + h.transpose());
4839 const std::vector<MatrixXd> diag = ringDiagonal(hBead, c,
false, linkWeight);
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);
4850 if (hessReactant.rows() != f || hessReactant.cols() != f ||
4851 !hessReactant.allFinite()) {
4852 throw std::runtime_error(
"instantonRate: invalid reactant Hessian");
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");
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");
4866 const VectorXd &lr = er.eigenvalues();
4867 const std::vector<bool> rigidR = nearestZero(lr, rigidModes);
4872 for (
long m = 0; m < lr.size(); ++m) {
4873 if (!rigidR[
static_cast<size_t>(m)]) {
4876 nullBasis.conservativeResize(f, nullBasis.cols() + 1);
4877 nullBasis.col(nullBasis.cols() - 1) = er.eigenvectors().col(m);
4879 if (rigidModes >= f) {
4880 throw std::runtime_error(
"instantonRate: every direction is a rigid mode");
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");
4891 scale(cycle, 1.0 / std::sqrt(cycleNorm));
4893 std::vector<std::vector<VectorXd>> rigid;
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()));
4906 for (
long r = 0; r < nullBasis.cols(); ++r) {
4908 static_cast<size_t>(N),
4909 (nullBasis.col(r) / std::sqrt(
static_cast<double>(N))).eval());
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");
4918 const bool weightedLinks =
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) {
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)];
4942 const double vn = std::sqrt(dot(v, v));
4944 throw std::runtime_error(
4945 "instantonRate: a rigid motion of the ring lies along its cycle");
4950 const long nDrop = 1 + nullBasis.cols();
4959 const std::vector<double> rigidKappas(rigid.size(), c);
4960 const WoodburyRing lifted(c, diag,
true, rigid, rigidKappas,
false,
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();
4973 const double change = 1.0 - std::abs(dot(x, v));
4975 if (change < 1e-15) {
4979 if (good && std::abs(dot(v, cycle)) > 0.9) {
4980 cycle = std::move(v);
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);
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");
4999 const auto phaseProduct = applyDiagonal(diag, c,
true, cycle, linkWeight);
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]
5008 phaseOperatorBound =
5009 std::max(phaseOperatorBound,
5010 diag[j].cwiseAbs().rowwise().sum().maxCoeff() + offDiagonal);
5013 const double phaseRoundoff = 64.0 * std::numeric_limits<double>::epsilon() *
5014 N * f * phaseOperatorBound;
5018 double logAbsDet = ring.logAbsDet();
5019 const long dim = N * f;
5020 if (denseLimit < 0 || dim <= denseLimit) {
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;
5030 for (
size_t d = 0; d < dropped.size(); ++d) {
5032 for (
long j = 0; j < N; ++j) {
5033 u.segment(j * f, f) = dropped[d][
static_cast<size_t>(j)];
5035 full += kappas[d] * u * u.transpose();
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;
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;
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");
5060 auto applyFull = [&](
const std::vector<VectorXd> &vec) {
5061 return applyDiagonal(diag, c,
true, vec, linkWeight);
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) {
5071 bead(a2) += 0.1 * (
static_cast<double>(h >> 11) * 0x1.0p-53 - 0.5);
5074 const std::vector<RingMode> modes =
5075 lowestRingModes(applyFull, std::move(start), steps);
5077 for (
const auto &mode : modes) {
5079 std::abs(dot(mode.vector, cycle)) < 0.5) {
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);
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;
5098 if (!lifted && mode.theta < 0.0 && std::abs(mode.theta) <= inertiaTol &&
5099 mode.residual <= inertiaTol) {
5108 const double logDetPrime = logAbsDet -
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;
5115 0.5 * std::log(inst.
bN / (2.0 * std::numbers::pi *
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");
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)]) {
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);
5145 ?
"unconverged_ring"
5147 :
"non_index_one_ring");
5151 -std::log(2.0 * std::numbers::pi *
kHbar * inst.
beta) / inst.
beta -
5156 const double invalid = std::numeric_limits<double>::quiet_NaN();
5161 if (hessSaddle.size() > 0) {
5163 hessReactant, hessSaddle, inst.
beta, vSaddle - vReactant, rigidModes);
5164 if (rigidBodies.
saddle.size() > 0) {
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");
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();
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);
5194 for (
int c = 0; c < 3; ++c) {
5195 const VectorXd r = generators.col(3 + c);
5196 const double rr = r.squaredNorm();
5200 const double rq = r.dot(h * r) / rr;
5203 out.
zero[
static_cast<size_t>(c)] =
5206 out.
residual[
static_cast<size_t>(c)] =
5207 std::numeric_limits<double>::infinity();
5214 long allowedNegatives) {
5215 inertiaKeepingUpdate(h, dq, dg, allowedNegatives);
5219 const VectorXd &saddle,
const VectorXd &mode) {
5221 const double mn = mode.norm();
5222 if (beads.size() < 2 || !(mn > 0.0)) {
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]) {
5234 if (s[j] > 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)) {
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;
5262 if (!(temperature > 0.0) || !(crossover > 0.0)) {
5263 throw std::invalid_argument(
5264 "parabolicFactor: temperature and crossover must be positive");
5266 if (!(temperature > crossover)) {
5267 throw std::invalid_argument(
5268 "parabolicFactor: T is at or below the crossover; the factor "
5272 const double phase = std::numbers::pi * crossover / temperature;
5273 const double s = std::sin(phase);
5275 throw std::invalid_argument(
5276 "parabolicFactor: the sine of the barrier phase is not positive");
5283struct HarmonicSpectrum {
5286 std::vector<bool> rigidReactant;
5287 std::vector<bool> rigidSaddle;
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");
5305 std::abs(barrier) > std::numeric_limits<double>::max() / beta) {
5306 throw std::overflow_error(
"harmonic TST: beta times barrier overflows");
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");
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");
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");
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");
5343double finiteHarmonicLogRate(
double rate) {
5344 if (!std::isfinite(rate)) {
5345 throw std::overflow_error(
"harmonic TST: non-finite logarithmic rate");
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));
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));
5371 return finiteHarmonicLogRate(logRatio - std::log(2.0 * std::numbers::pi) -
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");
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");
5393 const double x = bh * omega;
5395 throw std::underflow_error(
"harmonic TST: beta hbar omega underflows");
5397 return 0.5 * x + std::log(-std::expm1(-x));
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)));
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)));
5410 return finiteHarmonicLogRate(logRatio - std::log(2.0 * std::numbers::pi) -
5411 std::log(bh) - beta * barrier);