Loading...
Searching...
No Matches
InstantonJob.cpp
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
12#include "eon/InstantonJob.h"
13#include "eon/ConFileIO.h"
14#include "eon/EonLogger.h"
15#include "eon/Hessian.h"
16#include "eon/JobResult.h"
17#include "eon/Matter.h"
18#include "eon/PIQTST.h"
19#include "eon/PathIntegral.h"
21#include "eon/PotRegistry.h"
22#include "eon/Potential.h"
23#include "eon/PotentialOwner.h"
24#include "eon/RateRingSeed.h"
26#include "eon/Tunneling.h"
27
28#include <Eigen/QR>
29#include <Eigen/SVD>
30
31#include <algorithm>
32#include <array>
33#include <cmath>
34#include <filesystem>
35#include <fstream>
36#include <functional>
37#include <iomanip>
38#include <limits>
39#include <map>
40#include <memory>
41#include <optional>
42#include <sstream>
43#include <stdexcept>
44#include <string>
45#include <vector>
46
47namespace eonc {
48
49namespace {
50
52constexpr double kTimeUnitFs = 10.180505717871193;
53
57AtomMatrix wholePositions(const Matter &m) {
58 const AtomMatrix r = m.getPositions();
59 AtomMatrix diff = r;
60 diff.rowwise() -= r.row(0);
61 AtomMatrix out = m.pbc(diff);
62 out.rowwise() += r.row(0);
63 return out;
64}
65
68class MassWeighted {
69public:
70 explicit MassWeighted(const Matter &reference)
71 : ref_(reference) {
72 for (long i = 0; i < reference.numberOfAtoms(); ++i) {
73 if (reference.getFixed(i)) {
74 continue;
75 }
76 const double m = reference.getMass(i);
77 if (!(m > 0.0)) {
78 throw std::invalid_argument("instanton: a free atom without a mass");
79 }
80 free_.push_back(i);
81 sqrtMass_.push_back(std::sqrt(m));
82 }
83 if (free_.empty()) {
84 throw std::invalid_argument("instanton: every atom is fixed");
85 }
86 }
87 long dimension() const { return 3 * static_cast<long>(free_.size()); }
88 VectorXi freeAtoms() const {
89 VectorXi out(static_cast<long>(free_.size()));
90 for (size_t k = 0; k < free_.size(); ++k) {
91 out(static_cast<long>(k)) = static_cast<int>(free_[k]);
92 }
93 return out;
94 }
98 std::vector<double> spreadAbout(const std::vector<VectorXd> &beads,
99 VectorXd &centroid, long atoms) const {
100 centroid = VectorXd::Zero(dimension());
101 for (const auto &q : beads) {
102 centroid += q;
103 }
104 centroid /= static_cast<double>(std::max<size_t>(1, beads.size()));
105 std::vector<double> out(static_cast<size_t>(3 * atoms), 0.0);
106 for (size_t k = 0; k < free_.size(); ++k) {
107 for (int c = 0; c < 3; ++c) {
108 const long i = static_cast<long>(3 * k) + c;
109 double ss = 0.0;
110 for (const auto &q : beads) {
111 const double d = q(i) - centroid(i);
112 ss += d * d;
113 }
114 out[static_cast<size_t>(3 * free_[k] + c)] =
115 std::sqrt(ss /
116 static_cast<double>(std::max<size_t>(1, beads.size()))) /
117 sqrtMass_[k];
118 }
119 }
120 return out;
121 }
122 VectorXd toQ(const Matter &m) const {
123 const AtomMatrix d = ref_.pbc(m.getPositions() - ref_.getPositions());
124 VectorXd q(dimension());
125 for (size_t k = 0; k < free_.size(); ++k) {
126 for (int c = 0; c < 3; ++c) {
127 q(static_cast<long>(3 * k) + c) = sqrtMass_[k] * d(free_[k], c);
128 }
129 }
130 return q;
131 }
132 void place(const VectorXd &q, Matter &m) const {
133 AtomMatrix r = ref_.getPositions();
134 for (size_t k = 0; k < free_.size(); ++k) {
135 for (int c = 0; c < 3; ++c) {
136 r(free_[k], c) += q(static_cast<long>(3 * k) + c) / sqrtMass_[k];
137 }
138 }
139 m.setPositions(r);
140 }
143 MatrixXd rigidGenerators(const Matter &m) const {
144 const long n = dimension();
145 MatrixXd b = MatrixXd::Zero(n, 6);
146 const AtomMatrix r = wholePositions(m);
147 Eigen::RowVector3d com = Eigen::RowVector3d::Zero();
148 double total = 0.0;
149 for (size_t k = 0; k < free_.size(); ++k) {
150 const double w = sqrtMass_[k] * sqrtMass_[k];
151 com += w * r.row(free_[k]);
152 total += w;
153 }
154 com /= total;
155 for (size_t k = 0; k < free_.size(); ++k) {
156 const long i = static_cast<long>(3 * k);
157 const Eigen::Vector3d x = (r.row(free_[k]) - com).transpose();
158 for (int c = 0; c < 3; ++c) {
159 b(i + c, c) = sqrtMass_[k];
160 Eigen::Vector3d e = Eigen::Vector3d::Zero();
161 e(c) = 1.0;
162 b.block(i, 3 + c, 3, 1) = sqrtMass_[k] * e.cross(x);
163 }
164 }
165 return b;
166 }
171 void markRotationZeroModes(const MatrixXd &hess, const MatrixXd &generators,
172 double fraction, std::array<bool, 3> &keep,
173 std::array<double, 3> &residual) const {
174 const tunneling::RotationZeroModes z =
175 tunneling::rotationZeroModes(hess, generators, fraction);
176 keep = z.zero;
177 residual = z.residual;
178 }
183 MatrixXd rigidBasis(const Matter &m,
184 const std::array<bool, 3> &rotations) const {
185 if (static_cast<long>(free_.size()) != m.numberOfAtoms()) {
186 return {};
187 }
188 const MatrixXd g = rigidGenerators(m);
189 const long n = g.rows();
190 std::vector<int> cols{0, 1, 2};
191 for (int c = 0; c < 3; ++c) {
192 if (rotations[static_cast<size_t>(c)]) {
193 cols.push_back(3 + c);
194 }
195 }
196 MatrixXd b(n, static_cast<long>(cols.size()));
197 for (size_t k = 0; k < cols.size(); ++k) {
198 b.col(static_cast<long>(k)) = g.col(cols[k]);
199 }
200 const Eigen::ColPivHouseholderQR<MatrixXd> qr(b);
201 const long rank = qr.rank();
202 if (rank <= 0) {
203 return {};
204 }
205 return qr.householderQ() * MatrixXd::Identity(n, rank);
206 }
207 const std::vector<double> &sqrtMasses() const { return sqrtMass_; }
210 VectorXd referenceFree() const {
211 const AtomMatrix r = wholePositions(ref_);
212 VectorXd out(dimension());
213 for (size_t k = 0; k < free_.size(); ++k) {
214 for (int c = 0; c < 3; ++c) {
215 out(static_cast<long>(3 * k) + c) = r(free_[k], c);
216 }
217 }
218 return out;
219 }
220 VectorXd gradient(const AtomMatrix &forces) const {
221 VectorXd g(dimension());
222 for (size_t k = 0; k < free_.size(); ++k) {
223 for (int c = 0; c < 3; ++c) {
224 g(static_cast<long>(3 * k) + c) = -forces(free_[k], c) / sqrtMass_[k];
225 }
226 }
227 return g;
228 }
229
230private:
231 const Matter &ref_;
232 std::vector<long> free_;
233 std::vector<double> sqrtMass_;
234};
235
237bool cachedProfileMatchesSurface(const Matter &ref, const Matter &image) {
238 constexpr double inputTolerance = 1e-8; // Angstrom, including cell entries.
239 if (ref.numberOfAtoms() != image.numberOfAtoms() ||
240 ref.getPeriodic() != image.getPeriodic() || !ref.getCell().allFinite() ||
241 !image.getCell().allFinite() ||
242 (ref.getCell() - image.getCell()).cwiseAbs().maxCoeff() >
243 inputTolerance ||
244 !(ref.getAtomicNrs().array() == image.getAtomicNrs().array()).all()) {
245 return false;
246 }
247 const AtomMatrix delta = ref.pbc(image.getPositions() - ref.getPositions());
248 if (!delta.allFinite()) {
249 return false;
250 }
251 for (long i = 0; i < ref.numberOfAtoms(); ++i) {
252 if (ref.getFixedMask(i) != image.getFixedMask(i) ||
253 (ref.getFixed(i) &&
254 delta.row(i).cwiseAbs().maxCoeff() > inputTolerance)) {
255 return false;
256 }
257 }
258 return true;
259}
260
262void requireMatchingReferenceSurface(const Matter &ref, const Matter &image) {
263 if (!cachedProfileMatchesSurface(ref, image)) {
264 throw std::invalid_argument(
265 "instanton: reference surface differs in cell, species, constraints "
266 "or frozen positions");
267 }
268 for (long i = 0; i < ref.numberOfAtoms(); ++i) {
269 if (!(ref.getMass(i) > 0.0) || !std::isfinite(ref.getMass(i)) ||
270 ref.getMass(i) != image.getMass(i)) {
271 throw std::invalid_argument(
272 "instanton: reference surface differs in atomic masses");
273 }
274 }
275}
276
283void alignRigid(const Matter &ref, Matter &m, bool rotate) {
284 const long n = ref.numberOfAtoms();
285 for (long i = 0; i < n; ++i) {
286 if (ref.getFixed(i)) {
287 return;
288 }
289 }
290 AtomMatrix d = ref.pbc(m.getPositions() - ref.getPositions());
291 VectorXd w(n);
292 for (long i = 0; i < n; ++i) {
293 w(i) = ref.getMass(i);
294 }
295 const double total = w.sum();
296 const Eigen::RowVector3d shift = (w.transpose() * d) / total;
297 d.rowwise() -= shift;
298 if (rotate) {
299 AtomMatrix x = wholePositions(ref);
300 const Eigen::RowVector3d com = (w.transpose() * x) / total;
301 x.rowwise() -= com;
302 const AtomMatrix y = x + d;
303 const Eigen::Matrix3d h = y.transpose() * w.asDiagonal() * x;
304 Eigen::JacobiSVD<Eigen::Matrix3d> svd(h, Eigen::ComputeFullU |
305 Eigen::ComputeFullV);
306 Eigen::Matrix3d fix = Eigen::Matrix3d::Identity();
307 fix(2, 2) = (svd.matrixV() * svd.matrixU().transpose()).determinant() < 0.0
308 ? -1.0
309 : 1.0;
310 const Eigen::Matrix3d rot = svd.matrixV() * fix * svd.matrixU().transpose();
311 d = (y * rot.transpose()) - x;
312 }
313 m.setPositions(ref.getPositions() + d);
314}
315
319void writeCentroid(const std::string &file, const std::vector<VectorXd> &beads,
320 const MassWeighted &mw, const Matter &reactant,
321 std::vector<io::ConMetadataValue> scalars) {
322 VectorXd centroid;
323 Matter frame(reactant);
325 meta.spreads = mw.spreadAbout(beads, centroid, reactant.numberOfAtoms());
326 mw.place(centroid, frame);
327 meta.frame_index = 0;
328 meta.write_con_forces = false;
329 double largest = 0.0;
330 for (const double s : meta.spreads) {
331 largest = std::max(largest, s);
332 }
333 scalars.push_back({"beads", static_cast<double>(beads.size())});
334 scalars.push_back({"spread_max", largest});
335 meta.scalars = std::move(scalars);
336 if (!io::io_ok(frame.matter2con(file, false, &meta))) {
337 throw std::runtime_error("instanton: cannot write " + file);
338 }
339}
340
342std::vector<VectorXd> doubledRing(const std::vector<VectorXd> &ring) {
343 const size_t n = ring.size();
344 std::vector<VectorXd> fine(2 * n);
345 for (size_t j = 0; j < n; ++j) {
346 fine[2 * j] = ring[j];
347 fine[2 * j + 1] = 0.5 * (ring[j] + ring[(j + 1) % n]);
348 }
349 return fine;
350}
351
352} // namespace
353
354namespace {
355
363void steepestDescentPath(const VectorXd &qSaddle, double vSaddle,
364 const MatrixXd &hSaddle,
365 const std::vector<double> &sqrtMass,
366 const tunneling::BatchPotential &evaluate,
367 std::vector<VectorXd> &pathQ,
368 std::vector<double> &pathV) {
369 constexpr double cartStep = 0.01;
370 constexpr double gradTol = 1e-3;
371 constexpr long maxSteps = 4000;
372 const long n = qSaddle.size();
373 const Eigen::SelfAdjointEigenSolver<MatrixXd> es(
374 0.5 * (hSaddle + hSaddle.transpose()));
375 const VectorXd mode = es.eigenvectors().col(0);
376 const double stiff = es.eigenvalues().cwiseAbs().maxCoeff();
377 // The largest Cartesian move of a mass-weighted displacement.
378 auto cartesian = [&](const VectorXd &dq) {
379 double big = 0.0;
380 for (long i = 0; i < n; ++i) {
381 const size_t a = static_cast<size_t>(i / 3);
382 const double m = a < sqrtMass.size() ? sqrtMass[a] : 1.0;
383 big = std::max(big, std::abs(dq(i)) / m);
384 }
385 return big;
386 };
387 auto capped = [&](VectorXd dq) {
388 const double big = cartesian(dq);
389 if (big > cartStep) {
390 dq *= cartStep / big;
391 }
392 return dq;
393 };
394 auto at = [&](const VectorXd &q, double &v, VectorXd &g) {
395 std::vector<VectorXd> one{q};
396 std::vector<double> vs;
397 std::vector<VectorXd> gs;
398 evaluate(one, vs, gs);
399 if (vs.empty() || gs.empty() || !std::isfinite(vs[0]) ||
400 !gs[0].array().isFinite().all()) {
401 return false;
402 }
403 v = vs[0];
404 g = gs[0];
405 return true;
406 };
407 std::vector<std::vector<VectorXd>> sideQ(2);
408 std::vector<std::vector<double>> sideV(2);
409 for (int side = 0; side < 2; ++side) {
410 const double big0 = cartesian(mode);
411 VectorXd q = qSaddle + (side == 0 ? -1.0 : 1.0) * (cartStep / big0) * mode;
412 double v = 0.0;
413 VectorXd g;
414 if (!at(q, v, g) || !(v < vSaddle)) {
415 continue;
416 }
417 sideQ[side].push_back(q);
418 sideV[side].push_back(v);
419 double alpha = stiff > 0.0 ? 1.0 / stiff : 1.0;
420 for (long k = 0; k < maxSteps && g.norm() > gradTol; ++k) {
421 bool lowered = false;
422 for (int halving = 0; halving < 30 && !lowered; ++halving) {
423 const VectorXd trial = q + capped(-alpha * g);
424 double vt = 0.0;
425 VectorXd gt;
426 if (at(trial, vt, gt) && vt < v) {
427 q = trial;
428 v = vt;
429 g = gt;
430 lowered = true;
431 alpha *= 1.2;
432 } else {
433 alpha *= 0.5;
434 }
435 }
436 if (!lowered) {
437 break;
438 }
439 sideQ[side].push_back(q);
440 sideV[side].push_back(v);
441 }
442 }
443 pathQ.assign(sideQ[0].rbegin(), sideQ[0].rend());
444 pathV.assign(sideV[0].rbegin(), sideV[0].rend());
445 pathQ.push_back(qSaddle);
446 pathV.push_back(vSaddle);
447 pathQ.insert(pathQ.end(), sideQ[1].begin(), sideQ[1].end());
448 pathV.insert(pathV.end(), sideV[1].begin(), sideV[1].end());
449 // The reactant sits at q = 0, and a path starts at the reactant end.
450 if (pathQ.back().norm() < pathQ.front().norm()) {
451 std::reverse(pathQ.begin(), pathQ.end());
452 std::reverse(pathV.begin(), pathV.end());
453 }
454}
455
458std::vector<std::string>
459runRate(const Parameters &params, const std::shared_ptr<Potential> &pot,
460 const Matter &reactant, const MassWeighted &mw,
461 const tunneling::BatchPotential &evaluateFull,
462 const tunneling::OwnedBatchPotential &evaluateFullOwned,
463 const std::function<MatrixXd(const VectorXd &, const std::string &)>
464 &hessianAtFull,
465 const std::function<MatrixXd(const VectorXd &)> &beadHessianAtFull,
466 const std::array<bool, 3> &rotationZero,
467 const std::array<double, 3> &rotationResidual) {
468 const auto &o = params.instanton_options();
469 const std::string resultsFile = "results.dat";
470 const std::string pathFile = "instanton.con";
471 std::vector<std::string> returnFiles{resultsFile};
472
473 Matter saddle(pot, params);
474 if (!io::io_ok(saddle.con2matter(o.saddle_filename))) {
475 throw std::runtime_error("instanton: cannot read " + o.saddle_filename);
476 }
477 if (saddle.numberOfAtoms() != reactant.numberOfAtoms()) {
478 throw std::runtime_error(
479 "instanton: the saddle and the reactant differ in atom count");
480 }
481 if (o.hessian_final != "recomputed") {
482 throw std::invalid_argument("instanton: hessian_final must be recomputed");
483 }
484 std::vector<double> temperatures = o.temperatures;
485 if (temperatures.empty()) {
486 temperatures.push_back(o.temperature);
487 }
488 for (const double t : temperatures) {
489 if (!(t > 0.0)) {
490 throw std::invalid_argument(
491 "instanton: mode rate needs [Instanton] temperature or "
492 "temperatures in K");
493 }
494 }
495 // Highest first, so each ring can start the colder one.
496 std::sort(temperatures.begin(), temperatures.end(), std::greater<>());
497 requireMatchingReferenceSurface(reactant, saddle);
498 const bool rotate = rotationZero[0] || rotationZero[1] || rotationZero[2];
499 alignRigid(reactant, saddle, rotate);
500 const long fullDimension = mw.dimension();
501 std::optional<tunneling::PhysicalBathModel> physicalModel;
502 if (!o.physical_bath_filename.empty()) {
503 physicalModel = tunneling::PhysicalBathModel::read(o.physical_bath_filename,
504 fullDimension);
505 if (o.pi_planes > 0 || o.friction != "none" || !o.discretization.empty())
506 throw std::invalid_argument("physical bath requires uniform links "
507 "without scalar friction or PI planes");
508 EONC_LOG_INFO("[Instanton] physical quadratic bath: {} retained, {} "
509 "integrated; model qualification: {}",
510 physicalModel->reactionBasis.cols(),
511 physicalModel->bathBasis.cols(),
512 physicalModel->qualification);
513 }
514 const long n =
515 physicalModel ? physicalModel->reactionBasis.cols() : fullDimension;
516 auto project = [&](const VectorXd &q) -> VectorXd {
517 return physicalModel ? physicalModel->project(q) : q;
518 };
519 auto frozen = [&](const VectorXd &q) -> VectorXd {
520 return physicalModel ? physicalModel->frozen(q) : q;
521 };
522 const VectorXd qSaddle = project(mw.toQ(saddle));
523 if (physicalModel && (frozen(qSaddle) - mw.toQ(saddle)).norm() > 1e-8)
524 throw std::invalid_argument(
525 "physical bath reaction space does not contain the supplied saddle");
526 tunneling::BatchPotential evaluate = [&](const std::vector<VectorXd> &q,
527 std::vector<double> &v,
528 std::vector<VectorXd> &g) {
529 if (physicalModel && physicalModel->potentialModel) {
530 v.resize(q.size());
531 g.resize(q.size());
532 for (size_t j = 0; j < q.size(); ++j) {
533 const auto value = physicalModel->potentialModel->evaluate(q[j]);
534 v[j] = value.value[0];
535 g[j] = value.jacobian.row(0).transpose();
536 }
537 return;
538 }
539 std::vector<VectorXd> full(q.size());
540 for (size_t j = 0; j < q.size(); ++j)
541 full[j] = frozen(q[j]);
542 evaluateFull(full, v, g);
543 if (physicalModel)
544 for (auto &gradient : g)
545 gradient = (physicalModel->reactionBasis.transpose() * gradient).eval();
546 };
547 auto projectHessian = [&](const MatrixXd &h) -> MatrixXd {
548 return physicalModel ? MatrixXd((physicalModel->reactionBasis.transpose() *
549 h * physicalModel->reactionBasis)
550 .eval())
551 : h;
552 };
553 auto hessianAt = [&](const VectorXd &q, const std::string &file) -> MatrixXd {
554 if (physicalModel && physicalModel->potentialModel)
555 return physicalModel->potentialModel->evaluate(q).hessians[0];
556 return projectHessian(hessianAtFull(frozen(q), file));
557 };
558 auto beadHessianAt = [&](const VectorXd &q) -> MatrixXd {
559 if (physicalModel && physicalModel->potentialModel)
560 return physicalModel->potentialModel->evaluate(q).hessians[0];
561 return projectHessian(beadHessianAtFull(frozen(q)));
562 };
563 auto saveData = [&](const std::string &name, const std::string &suffix,
564 const auto &values) {
565 const std::string file = "instanton_" + name + suffix + ".dat";
566 std::ofstream stream(file, std::ios::out | std::ios::trunc);
567 stream << std::setprecision(std::numeric_limits<double>::max_digits10)
568 << values << '\n';
569 stream.close();
570 if (!stream) {
571 throw std::runtime_error("instanton: cannot write " + file);
572 }
573 returnFiles.push_back(file);
574 };
575 Matter reactantReference(reactant);
576 // Rate references require evaluations on the selected potential;
577 // energy and forces saved in an input file can describe another surface.
578 reactantReference.setPositions(reactantReference.getPositions());
579 saddle.setPositions(saddle.getPositions());
580 const bool fittedPotential = physicalModel && physicalModel->potentialModel;
581 if (!fittedPotential && pot->supportsBatchEvaluation()) {
582 const VectorXi rNumbers = reactantReference.getAtomicNrs();
583 const VectorXi sNumbers = saddle.getAtomicNrs();
584 const Matrix3d rBox = reactantReference.getPeriodic()
585 ? reactantReference.getCell()
586 : Matrix3d::Zero().eval();
587 const Matrix3d sBox =
588 saddle.getPeriodic() ? saddle.getCell() : Matrix3d::Zero().eval();
589 const double *positions[] = {reactantReference.getPositions().data(),
590 saddle.getPositions().data()};
591 const int *numbers[] = {rNumbers.data(), sNumbers.data()};
592 const double *boxes[] = {rBox.data(), sBox.data()};
593 double *forces[] = {reactantReference.forcesData(), saddle.forcesData()};
594 double energies[2], variances[2];
595 const long owners[] = {potential_owner::reactant, potential_owner::saddle};
596 pot->forceBatchOwned(2, reactantReference.numberOfAtoms(), positions,
597 numbers, forces, energies, variances, boxes, owners);
598 reactantReference.setComputedPotential(energies[0], variances[0]);
599 saddle.setComputedPotential(energies[1], variances[1]);
600 }
601 double vReactant =
602 fittedPotential
603 ? physicalModel->potentialModel->evaluate(VectorXd::Zero(n)).value[0]
604 : reactantReference.getPotentialEnergy();
605 double vSaddle =
606 fittedPotential
607 ? physicalModel->potentialModel->evaluate(qSaddle).value[0]
608 : saddle.getPotentialEnergy();
609 auto referenceForces = [&](const std::string &name, const Matter &matter) {
610 if (fittedPotential) {
611 EONC_LOG_INFO("[Instanton] {} reference uses the declared fitted "
612 "potential; no native reference force is claimed",
613 name);
614 return std::pair{std::numeric_limits<double>::quiet_NaN(),
615 std::numeric_limits<double>::quiet_NaN()};
616 }
617 const AtomMatrix forces = matter.getForcesFree();
618 double maximum = 0.0;
619 for (long j = 0; j < forces.rows(); ++j) {
620 maximum = std::max(maximum, forces.row(j).norm());
621 }
622 saveData(name, "_forces", forces);
623 EONC_LOG_INFO("[Instanton] {} reference free forces: norm {:.8g}, "
624 "maximum atomic norm {:.8g} eV/Angstrom",
625 name, forces.norm(), maximum);
626 return std::pair{forces.norm(), maximum};
627 };
628 // Potential energy evaluations cache the same physical forces, so these
629 // stationarity diagnostics require no additional potential calls.
630 const auto reactantForce = referenceForces("reactant", reactantReference);
631 const auto saddleForce = referenceForces("saddle", saddle);
632 const MatrixXd hReactant =
633 hessianAt(VectorXd::Zero(n), o.reactant_hessian_filename);
634 const MatrixXd hSaddle = hessianAt(qSaddle, o.saddle_hessian_filename);
635 MatrixXd referenceReactant = hReactant, referenceSaddle = hSaddle;
636 if (physicalModel) {
637 std::vector<double> values;
638 std::vector<VectorXd> gradients;
639 evaluate({VectorXd::Zero(n), qSaddle}, values, gradients);
640 const auto r =
641 physicalModel->bath->evaluate({VectorXd::Zero(n)}, 1.0, true);
642 const auto s = physicalModel->bath->evaluate({qSaddle}, 1.0, true);
643 if ((gradients[0] + r.gradient[0]).norm() >
644 physicalModel->stationaryTolerance ||
645 (gradients[1] + s.gradient[0]).norm() >
646 physicalModel->stationaryTolerance)
647 throw std::invalid_argument("physical bath model references are not "
648 "stationary within the declared tolerance");
649 vReactant = values[0] + r.energy;
650 vSaddle = values[1] + s.energy;
651 referenceReactant += r.hessian;
652 referenceSaddle += s.hessian;
653 }
654 // Retain the projected, mass-weighted references used by the rate
655 // calculation, including spectra that fail metastability validation.
656 auto saveReference = [&](const std::string &name, const MatrixXd &matrix) {
657 Eigen::SelfAdjointEigenSolver<MatrixXd> solver(matrix,
658 Eigen::EigenvaluesOnly);
659 if (solver.info() != Eigen::Success || !solver.eigenvalues().allFinite()) {
660 throw std::runtime_error("instanton: cannot diagonalize " + name +
661 " reference Hessian");
662 }
663 saveData(name, "_hessian", matrix);
664 saveData(name, "_eigenvalues", solver.eigenvalues());
665 EONC_LOG_INFO("[Instanton] {} reference: {} coordinates, {} negative "
666 "eigenvalues; projected mass-weighted matrix retained",
667 name, matrix.rows(),
668 (solver.eigenvalues().array() < 0.0).count());
669 };
670 saveReference("reactant", hReactant);
671 saveReference("saddle", hSaddle);
672 const VectorXd unstableMode =
673 Eigen::SelfAdjointEigenSolver<MatrixXd>(
674 0.5 * (referenceSaddle + referenceSaddle.transpose()))
675 .eigenvectors()
676 .col(0);
677 const double tc = tunneling::crossoverTemperature(
678 physicalModel
679 ? MatrixXd(physicalModel->bath->fullHessian(qSaddle, hSaddle))
680 : referenceSaddle);
681 const long rigidModes =
682 physicalModel ? 0 : mw.rigidBasis(reactant, rotationZero).cols();
683 if (temperatures.size() == 1) {
684 EONC_LOG_INFO("[Instanton] rate: {} beads at {:.4g} K, crossover {:.4g} K, "
685 "barrier {:.6f} eV, {} degrees of freedom, {} rigid modes",
686 o.beads, temperatures.front(), tc, vSaddle - vReactant, n,
687 rigidModes);
688 } else {
689 EONC_LOG_INFO("[Instanton] rate: {} beads at {} temperatures from {:.4g} K "
690 "down to {:.4g} K, crossover {:.4g} K, barrier {:.6f} eV, "
691 "{} degrees of freedom, {} rigid modes",
692 o.beads, temperatures.size(), temperatures.front(),
693 temperatures.back(), tc, vSaddle - vReactant, n, rigidModes);
694 }
695 EONC_LOG_INFO("[Instanton] rotation curvatures over the softest vibration "
696 "{:.3g}, {:.3g}, {:.3g} (zero modes at or below {:.3g})",
697 rotationResidual[0], rotationResidual[1], rotationResidual[2],
698 o.rotation_zero_fraction);
699
700 std::vector<std::pair<std::string, double>> extras{
701 {"instanton_crossover_K", tc},
702 {"reference_reactant_force_norm", reactantForce.first},
703 {"reference_reactant_max_force", reactantForce.second},
704 {"reference_saddle_force_norm", saddleForce.first},
705 {"reference_saddle_max_force", saddleForce.second},
706 {"barrier_classical", vSaddle - vReactant}};
707 if (physicalModel) {
708 extras.emplace_back("instanton_physical_bath_model", 1.0);
709 extras.emplace_back("instanton_fitted_potential",
710 fittedPotential ? 1.0 : 0.0);
711 extras.emplace_back("instanton_retained_coordinates", n);
712 extras.emplace_back("instanton_integrated_coordinates",
713 physicalModel->bathBasis.cols());
714 const std::string modelFile = "instanton_physical_bath_model.json";
715 if (std::filesystem::absolute(o.physical_bath_filename) !=
716 std::filesystem::absolute(modelFile)) {
717 std::ifstream input(o.physical_bath_filename);
718 std::ofstream output(modelFile);
719 output << input.rdbuf();
720 if (!input || !output)
721 throw std::runtime_error("cannot retain the physical bath model");
722 }
723 returnFiles.push_back(modelFile);
724 }
725 auto write = [&](RunStatus status) {
727 status, params.potential_options().potential,
728 pot->forceCallCounter.load(), false, 0.0);
729 env.provenance = provenanceForJob(params);
730 env.job_type = "instanton";
731 env.extras.emplace_back("force_calls",
732 static_cast<double>(env.force_calls));
733 for (const auto &kv : extras) {
734 env.extras.push_back(kv);
735 }
736 env.writeResultsDat(resultsFile);
737 };
738
739 // Both rate regimes require a metastable well and an index-one saddle
740 // on the same free coordinates before any path or ring is sampled.
741 auto validReferences = [&]() {
742 try {
743 static_cast<void>(tunneling::harmonicTstLogRate(
744 referenceReactant, referenceSaddle,
745 1.0 / (tunneling::kBoltzmann * temperatures.front()),
746 vSaddle - vReactant, rigidModes));
747 return true;
748 } catch (const std::exception &ex) {
749 EONC_LOG_ERROR("[Instanton] invalid rate reference: {}", ex.what());
751 return false;
752 }
753 };
754
755 // A band over the barrier seeds the ring and carries the
756 // one-dimensional WKB rate. An empty path leaves the saddle-mode seed.
757 std::vector<VectorXd> pathQ;
758 std::vector<double> pathV;
759 long sdPathForceCalls = 0;
760 std::unique_ptr<tunneling::Profile> profile;
761 double hwPath = 0.0;
762 if (!o.initial_path.empty()) {
763 const auto frames = readcon::read_all_frames(o.initial_path);
764 bool haveEnergies = true;
765 for (const auto &frame : frames) {
766 Matter image(reactant);
767 if (!io::io_ok(io::con2matter(image, frame))) {
768 throw std::runtime_error("instanton: cannot read " + o.initial_path);
769 }
770 if (image.numberOfAtoms() != reactant.numberOfAtoms()) {
771 throw std::runtime_error("instanton: " + o.initial_path +
772 " differs in atom count");
773 }
774 alignRigid(reactant, image, rotate);
775 pathQ.push_back(project(mw.toQ(image)));
776 const auto energy = frame.energy_opt();
777 haveEnergies = haveEnergies && !physicalModel && energy.has_value() &&
778 std::isfinite(*energy) &&
779 cachedProfileMatchesSurface(reactant, image);
780 pathV.push_back(energy.value_or(0.0));
781 }
782 if (pathQ.size() < 3) {
783 throw std::runtime_error("instanton: " + o.initial_path +
784 " holds fewer than three frames");
785 }
786 if (!validReferences()) {
787 return returnFiles;
788 }
789 if (!haveEnergies) {
790 const long before = pot->forceCallCounter.load();
791 std::vector<VectorXd> grads;
792 evaluate(pathQ, pathV, grads);
793 sdPathForceCalls = pot->forceCallCounter.load() - before;
794 } else {
795 sdPathForceCalls = 0;
796 }
797 std::vector<double> arc(pathQ.size(), 0.0);
798 for (size_t k = 1; k < pathQ.size(); ++k) {
799 arc[k] = arc[k - 1] + (pathQ[k] - pathQ[k - 1]).norm();
800 }
801 try {
802 profile = std::make_unique<tunneling::Profile>(std::move(arc), pathV);
803 } catch (const std::invalid_argument &ex) {
804 EONC_LOG_WARNING("[Instanton] {}; seeding from the saddle mode",
805 ex.what());
806 }
807 if (profile) {
808 try {
809 hwPath = tunneling::hbarOmega(tunneling::wellCurvature(*profile, true));
810 } catch (const std::exception &ex) {
811 EONC_LOG_WARNING("[Instanton] no reactant frequency along the path: {}",
812 ex.what());
813 }
814 }
815 }
816 if (o.initial_path.empty() && !validReferences()) {
817 return returnFiles;
818 }
819 // No band: the steepest-descent path out of the saddle carries the ring
820 // seed by the period condition. Cooling a cosine from the crossover finds
821 // the ring only where it grows continuously out of the saddle; where it
822 // does not, the search walks to a neighbouring saddle.
823 const bool needsSampledPath =
824 o.pi_planes > 0 ||
825 std::any_of(temperatures.begin(), temperatures.end(),
826 [tc](double temperature) { return temperature < tc; });
827 if (!profile && o.initial_ring.empty() && !physicalModel &&
828 needsSampledPath) {
829 pathQ.clear();
830 pathV.clear();
831 const long before = pot->forceCallCounter.load();
832 steepestDescentPath(qSaddle, vSaddle, hSaddle, mw.sqrtMasses(), evaluate,
833 pathQ, pathV);
834 sdPathForceCalls = pot->forceCallCounter.load() - before;
835 // A path read back from file is aligned frame by frame; this one is
836 // aligned the same way, so a job that reuses it starts from this ring.
837 for (auto &q : pathQ) {
838 Matter image(reactant);
839 mw.place(q, image);
840 alignRigid(reactant, image, rotate);
841 q = project(mw.toQ(image));
842 }
843 std::vector<double> arc(pathQ.size(), 0.0);
844 for (size_t k = 1; k < pathQ.size(); ++k) {
845 arc[k] = arc[k - 1] + (pathQ[k] - pathQ[k - 1]).norm();
846 }
847 if (pathQ.size() >= 3 && pathQ.size() == pathV.size()) {
848 std::vector<std::shared_ptr<Matter>> images;
849 std::vector<io::ConFrameMetadata> metas;
850 images.reserve(pathQ.size());
851 for (size_t k = 0; k < pathQ.size(); ++k) {
852 auto image = std::make_shared<Matter>(reactant);
853 mw.place(pathQ[k], *image);
855 meta.frame_index = static_cast<uint64_t>(k);
856 meta.energy = pathV[k];
857 meta.scalars.push_back({"arc_length", arc[k]});
858 metas.push_back(std::move(meta));
859 images.push_back(std::move(image));
860 }
861 const auto frames = io::buildNebPathFrames(images, metas);
862 if (frames.empty() ||
863 !io::io_ok(io::writeConFrames("instanton_sd_path.con", frames))) {
864 throw std::runtime_error(
865 "instanton: cannot write instanton_sd_path.con");
866 }
867 returnFiles.push_back("instanton_sd_path.con");
868 }
869 try {
870 profile = std::make_unique<tunneling::Profile>(std::move(arc), pathV);
871 hwPath = tunneling::hbarOmega(tunneling::wellCurvature(*profile, true));
872 EONC_LOG_INFO("[Instanton] steepest-descent path of {} points, {} "
873 "force calls",
874 pathQ.size(), pot->forceCallCounter.load() - before);
875 for (size_t k = 0; k < pathQ.size(); ++k) {
876 EONC_LOG_DEBUG("[Instanton] path {} s {:.6f} V - V_reactant {:.8f}", k,
877 profile->s()[k], pathV[k] - vReactant);
878 }
879 } catch (const std::exception &ex) {
880 EONC_LOG_WARNING("[Instanton] steepest-descent path unusable: {}; "
881 "seeding from the saddle mode",
882 ex.what());
883 if (!profile) {
884 pathQ.clear();
885 pathV.clear();
886 }
887 }
888 }
889
890 extras.emplace_back("sd_path_force_calls",
891 static_cast<double>(sdPathForceCalls));
892 const std::string tableFile = "rate_instanton.dat";
893 std::ofstream table(tableFile);
894 if (!table) {
895 throw std::runtime_error("instanton: cannot write " + tableFile);
896 }
897 table << "# T_K T_c_K beads converged iterations U_N_eV negative_modes "
898 "ln_k_per_s k_per_s ln_k_htst_per_s barrier_effective_eV "
899 "ln_k_wkb_path_per_s ln_k_parabolic_per_s parabolic_factor\n";
900 table << std::setprecision(10);
901 table.flush();
902 returnFiles.push_back(tableFile);
903 const double logSecond = std::log(tunneling::kTimeUnitSeconds);
904 const double nan = std::numeric_limits<double>::quiet_NaN();
905 auto wkbAt = [&](double beta) {
906 if (physicalModel)
907 return nan;
908 if (!(profile && hwPath > 0.0)) {
909 return nan;
910 }
911 try {
912 return tunneling::wkbLogRateAlongPath(*profile, beta, hwPath) - logSecond;
913 } catch (const std::exception &ex) {
914 EONC_LOG_WARNING("[Instanton] no WKB rate along the path: {}", ex.what());
915 return nan;
916 }
917 };
918
919 // A free cluster's rigid bodies: its rotational partition functions enter
920 // the rates as ratios of the ring's, or the saddle's, moments of inertia
921 // to the reactant's.
923 if (static_cast<long>(mw.sqrtMasses().size()) == reactant.numberOfAtoms()) {
924 freeBodies.sqrtMasses = mw.sqrtMasses();
925 freeBodies.reference = mw.referenceFree();
926 freeBodies.rotations = rotationZero;
927 freeBodies.saddle = qSaddle;
928 }
929
930 std::vector<VectorXd> ring;
931 if (!o.initial_ring.empty()) {
932 const auto positions =
933 tunneling::readRateRingSeed(o.initial_ring, reactant, o.beads);
934 for (const auto &xyz : positions) {
935 Matter image(reactant);
936 image.setPositions(xyz);
937 ring.push_back(project(mw.toQ(image)));
938 }
939 EONC_LOG_INFO("[Instanton] closed-ring geometry seed from {}; energies and "
940 "forces are evaluated on the selected potential",
941 o.initial_ring);
942 }
943 RunStatus status = RunStatus::GOOD;
944 bool rateFailed = false;
945 for (size_t ti = 0; ti < temperatures.size(); ++ti) {
946 const double temperature = temperatures[ti];
947 const double beta = 1.0 / (tunneling::kBoltzmann * temperature);
948 const bool last = ti + 1 == temperatures.size();
949 const double wkbLog = wkbAt(beta);
950 if (!(temperature < tc)) {
951 // The ring is not searched. Above T_c the rate is the parabolic
952 // barrier factor times quantum harmonic TST. At T_c the factor
953 // diverges and that temperature records no rate.
954 bool wrote = false;
955 if (temperature > tc) {
956 try {
957 const double factor = tunneling::parabolicFactor(temperature, tc);
958 const MatrixXd harmonicReactant =
959 physicalModel ? MatrixXd(physicalModel->bath->fullHessian(
960 VectorXd::Zero(n), hReactant))
961 : hReactant;
962 const MatrixXd harmonicSaddle =
963 physicalModel
964 ? MatrixXd(physicalModel->bath->fullHessian(qSaddle, hSaddle))
965 : hSaddle;
966 const double logQhtst =
968 harmonicReactant, harmonicSaddle, beta, vSaddle - vReactant,
969 rigidModes) +
970 (physicalModel
971 ? 0.0
972 : tunneling::logRotationalRatio({qSaddle}, freeBodies));
973 const double logPar = logQhtst + std::log(factor);
974 const double logPerSecond = logPar - logSecond;
975 if (!std::isfinite(logPerSecond) ||
976 logPerSecond > std::log(std::numeric_limits<double>::max())) {
977 throw std::runtime_error(
978 "instanton: non-finite parabolic rate; no rate is recorded");
979 }
980 const double kPar = std::exp(logPerSecond);
981 EONC_LOG_INFO("[Instanton] {:.4g} K is above the crossover {:.4g} "
982 "K; parabolic factor {:.6g}, ln(k s) = {:.4f}",
983 temperature, tc, factor, logPar - logSecond);
984 table << temperature << ' ' << tc << ' ' << o.beads
985 << " 0 0 nan 0 nan nan nan nan " << wkbLog << ' '
986 << (logPar - logSecond) << ' ' << factor << '\n';
987 if (last) {
988 extras.emplace_back("instanton_temperature_K", temperature);
989 extras.emplace_back("parabolic_factor", factor);
990 extras.emplace_back("rate_parabolic", kPar);
991 extras.emplace_back("rate_parabolic_log", logPar - logSecond);
992 if (std::isfinite(wkbLog)) {
993 extras.emplace_back("rate_wkb_path_log", wkbLog);
994 }
995 }
996 wrote = true;
997 } catch (const std::exception &ex) {
998 EONC_LOG_ERROR("[Instanton] no parabolic rate at {:.4g} K: {}",
999 temperature, ex.what());
1000 }
1001 }
1002 if (!wrote) {
1003 if (!(temperature > tc)) {
1004 EONC_LOG_ERROR("[Instanton] {:.4g} K is at the crossover temperature "
1005 "{:.4g} K; the parabolic factor diverges there",
1006 temperature, tc);
1007 }
1008 table << temperature << ' ' << tc << ' ' << o.beads
1009 << " 0 0 nan 0 nan nan nan nan " << wkbLog << " nan nan\n";
1010 rateFailed = true;
1012 if (last) {
1013 extras.emplace_back("instanton_temperature_K", temperature);
1014 if (std::isfinite(wkbLog)) {
1015 extras.emplace_back("rate_wkb_path_log", wkbLog);
1016 }
1017 }
1018 }
1019 table.flush();
1020 continue;
1021 }
1022
1024 if (physicalModel)
1025 ro.physicalBath = physicalModel->bath;
1026 ro.beads = o.beads;
1027 ro.maxIterations = o.max_iterations;
1028 ro.forceTolerance = o.force_tolerance;
1029 ro.halfRing = o.half_ring;
1030 ro.initialHessians = o.initial_hessians;
1031 ro.newtonLimit = o.newton_limit;
1032 ro.lanczosStep = o.lanczos_step;
1033 ro.physicalHessianStep = o.physical_hessian_step;
1034 ro.energyShift = fittedPotential ? 0.0 : o.energy_shift;
1035 if (!fittedPotential) {
1036 ro.ownedPotential = [&](const std::vector<VectorXd> &q,
1037 std::vector<double> &v, std::vector<VectorXd> &g,
1038 const std::vector<long> &owners) {
1039 std::vector<VectorXd> full(q.size());
1040 for (size_t j = 0; j < q.size(); ++j)
1041 full[j] = frozen(q[j]);
1042 evaluateFullOwned(full, v, g, owners);
1043 if (physicalModel)
1044 for (auto &gradient : g)
1045 gradient =
1046 (physicalModel->reactionBasis.transpose() * gradient).eval();
1047 };
1048 }
1049 tunneling::BatchPotential optimizerEvaluate = evaluate;
1050 if (fittedPotential) {
1051 const auto model = physicalModel->potentialModel;
1052 optimizerEvaluate =
1053 [model, shift = o.energy_shift](const std::vector<VectorXd> &q,
1054 std::vector<double> &v,
1055 std::vector<VectorXd> &g) {
1056 v.resize(q.size());
1057 g.resize(q.size());
1058 for (size_t j = 0; j < q.size(); ++j) {
1059 const auto value = model->evaluate(q[j], shift);
1060 v[j] = value.value[0];
1061 g[j] = value.jacobian.row(0).transpose();
1062 }
1063 };
1064 ro.physicalHessian = [model](const VectorXd &q) -> MatrixXd {
1065 return model->evaluate(q).hessians[0];
1066 };
1067 }
1068 ro.discretization = o.discretization;
1069 ro.friction = o.friction != "none";
1070 ro.frictionExplicit = o.friction == "explicit";
1071 ro.frictionEta = o.friction_eta;
1072 ro.frictionEtaBeads = o.friction_eta_beads;
1073 ro.collapseFraction = o.collapse_fraction;
1074 if (!physicalModel && !freeBodies.sqrtMasses.empty()) {
1075 ro.rigidSqrtMasses = freeBodies.sqrtMasses;
1076 ro.rigidReference = freeBodies.reference;
1077 ro.rigidRotations = freeBodies.rotations;
1078 }
1079 std::vector<VectorXd> guess = ring;
1080 if (guess.empty() && profile && !physicalModel) {
1081 try {
1083 guess = tunneling::ringFromPath(pathQ, pathV, beta * tunneling::kHbar,
1084 o.beads, &seed);
1085 EONC_LOG_INFO("[Instanton] seed orbit {:.6f} eV above the reactant, "
1086 "period {:.4g} against beta hbar {:.4g}; the path's "
1087 "higher end sits {:.6f} eV above the reactant",
1088 seed.energy - vReactant, seed.period,
1089 beta * tunneling::kHbar, seed.pathLow - vReactant);
1090 EONC_LOG_INFO("[Instanton] ring seeded from {} by the period condition",
1091 o.initial_path.empty() ? "the steepest-descent path"
1092 : o.initial_path);
1093 } catch (const std::invalid_argument &ex) {
1094 EONC_LOG_WARNING("[Instanton] {}; seeding from the saddle mode instead",
1095 ex.what());
1096 guess.clear();
1097 }
1098 }
1099 long ladderIterations = 0;
1100 // Lists of one value per bead belong to the full ring; a coarser rung
1101 // has no values for its beads, so the ladder is skipped.
1102 const bool beadLists =
1103 !o.discretization.empty() || o.friction == "explicit";
1104 if (guess.empty() && o.bead_ladder && beadLists) {
1105 EONC_LOG_INFO("[Instanton] bead_ladder skipped: discretization and "
1106 "explicit friction give one value per bead of the full "
1107 "ring");
1108 }
1109 if (guess.empty() && o.bead_ladder && o.beads >= 16 && !beadLists) {
1110 long coarse = o.beads / 4;
1111 if (coarse % 2 != 0) {
1112 ++coarse;
1113 }
1114 if (coarse < 4) {
1115 coarse = 4;
1116 }
1117 std::vector<VectorXd> rung;
1118 for (long nb = coarse; nb < o.beads; nb *= 2) {
1120 step.beads = nb;
1121 const tunneling::RateInstanton rungInst =
1122 tunneling::optimizeRateInstanton(qSaddle, hSaddle, beta, rung,
1123 optimizerEvaluate, step);
1124 ladderIterations += rungInst.iterations;
1125 EONC_LOG_INFO("[Instanton] ladder rung {} beads: U_N {:.6f} eV after "
1126 "{} iterations{}",
1127 nb, rungInst.ringPotential, rungInst.iterations,
1128 rungInst.converged ? "" : " (not converged)");
1129 rung = rungInst.beads;
1130 if (static_cast<long>(rung.size()) != nb) {
1131 rung.clear();
1132 break;
1133 }
1134 rung = doubledRing(rung);
1135 if (static_cast<long>(rung.size()) > o.beads) {
1136 rung.clear();
1137 break;
1138 }
1139 }
1140 if (static_cast<long>(rung.size()) == o.beads) {
1141 guess = std::move(rung);
1142 }
1143 }
1145 qSaddle, hSaddle, beta, guess, optimizerEvaluate, ro);
1146 inst.iterations += ladderIterations;
1147 EONC_LOG_INFO("[Instanton] {:.4g} K: ring U_N {:.6f} eV after {} "
1148 "iterations{}",
1149 temperature, inst.ringPotential, inst.iterations,
1150 inst.converged ? "" : " (not converged)");
1151 // A cooling walk whose budget ran out early returns the coldest ring
1152 // it reached, which belongs to that stage's temperature.
1153 const bool reached =
1154 std::abs(inst.temperature - temperature) <= 1e-9 * temperature;
1155 if (!reached) {
1156 EONC_LOG_WARNING("[Instanton] {:.4g} K: the cooling walk stopped at "
1157 "{:.4g} K; that ring is written under its own "
1158 "temperature",
1159 temperature, inst.temperature);
1160 inst.converged = false;
1161 }
1162
1163 if (inst.collapsed) {
1164 EONC_LOG_ERROR("[Instanton] {:.4g} K: the ring collapsed after {} "
1165 "iterations (B_N {:.3e}, every bead at one point near "
1166 "s = {:.4f}); the search left the bounce for a "
1167 "stationary point of V, no rate",
1168 temperature, inst.iterations, inst.bN,
1169 inst.beads.empty()
1170 ? 0.0
1171 : (inst.beads.front() - qSaddle).dot(unstableMode));
1172 }
1173 const tunneling::RingChannel channel =
1174 tunneling::ringChannel(inst.beads, qSaddle, unstableMode);
1175 EONC_LOG_INFO("[Instanton] {:.4g} K: ring spans s = {:.4f} to {:.4f} "
1176 "amu^0.5 A along the unstable mode, chord overlap {:.3f}, "
1177 "dividing-plane crossing {:.4f} amu^0.5 A off the saddle",
1178 temperature, channel.sMin, channel.sMax, channel.chordOverlap,
1179 channel.crossingOffset);
1180 if (inst.converged && !channel.belongs) {
1181 EONC_LOG_ERROR("[Instanton] {:.4g} K: the ring does not pass through "
1182 "the seeded saddle's channel (it must straddle the "
1183 "dividing plane, cross it within its own span of the "
1184 "saddle, and run within 60 degrees of the unstable "
1185 "mode); it belongs to another saddle, no rate",
1186 temperature);
1187 inst.converged = false;
1188 }
1189 bool rateOk = false;
1190 if (inst.converged) {
1191 // Bead Hessians on every stride-th bead of the ring, linear in
1192 // between, wrapping from the last anchor back to bead 0.
1193 const long stride = std::max<long>(1, o.hessian_stride);
1194 const long nBeads = o.beads;
1195 std::map<long, MatrixXd> anchors;
1196 // Bead N - j mirrors bead j on an out-and-back ring and shares its
1197 // Hessian.
1198 auto anchor = [&](long j) -> const MatrixXd & {
1199 const long n = static_cast<long>(inst.beads.size());
1200 if (j > n / 2 && (inst.beads[static_cast<size_t>(j)] -
1201 inst.beads[static_cast<size_t>(n - j)])
1202 .norm() <= 1e-10) {
1203 j = n - j;
1204 }
1205 auto it = anchors.find(j);
1206 if (it == anchors.end()) {
1207 it =
1208 anchors
1209 .emplace(j, beadHessianAt(inst.beads[static_cast<size_t>(j)]))
1210 .first;
1211 }
1212 return it->second;
1213 };
1214 auto beadHessian = [&](long j, const VectorXd &) -> MatrixXd {
1215 const long lo = (j / stride) * stride;
1216 if (j == lo) {
1217 return anchor(lo);
1218 }
1219 const long hi = lo + stride < nBeads ? lo + stride : 0;
1220 const long span = (hi == 0 ? nBeads : hi) - lo;
1221 const double t =
1222 static_cast<double>(j - lo) / static_cast<double>(span);
1223 return (1.0 - t) * anchor(lo) + t * anchor(hi);
1224 };
1225 try {
1227 bodies.sqrtMasses = ro.rigidSqrtMasses;
1228 bodies.reference = ro.rigidReference;
1229 bodies.rotations = ro.rigidRotations;
1230 bodies.saddle = qSaddle;
1232 inst, beadHessian, hReactant, vReactant - o.energy_shift, hSaddle,
1233 vSaddle - o.energy_shift, rigidModes, 4096, bodies);
1234 rateOk = inst.rateValid && std::isfinite(inst.logRate) &&
1235 inst.negativeModes == 1;
1236 if (!inst.rateValid) {
1237 EONC_LOG_ERROR("[Instanton] rate fluctuation validity: {}",
1238 inst.rateValidity);
1239 }
1240 if (!inst.bathSignedCurvatures.empty()) {
1241 std::ostringstream name;
1242 name << "instanton_fluctuations_" << std::setprecision(6)
1243 << temperature << "K.dat";
1244 std::ofstream spectrum(name.str());
1245 if (!spectrum) {
1246 throw std::runtime_error("instanton: cannot write " + name.str());
1247 }
1248 spectrum
1249 << std::setprecision(17)
1250 << "# Fixed quadratic bath; curvatures in eV/(amu Angstrom^2)\n"
1251 << "# rate_valid " << (inst.rateValid ? 1 : 0) << '\n'
1252 << "# validity " << inst.rateValidity << '\n'
1253 << "# phase_zero_verified " << (inst.phaseZeroVerified ? 1 : 0)
1254 << '\n'
1255 << "# log_abs_det " << inst.bathLogAbsDet << '\n'
1256 << "# reactant_log_abs_det " << inst.bathReactantLogAbsDet << '\n'
1257 << "# operator_symmetry_residual " << inst.bathSymmetryResidual
1258 << '\n'
1259 << "# algebraic_roundoff_scale " << inst.bathRoundoffScale << '\n'
1260 << "# phase_eigenpair_residual " << inst.phaseEigenResidual
1261 << '\n'
1262 << "# log_absolute_labelled_gaussian_weight "
1263 << inst.logAbsoluteGaussianWeight << '\n'
1264 << "# index signed_curvature\n";
1265 for (size_t i = 0; i < inst.bathSignedCurvatures.size(); ++i) {
1266 spectrum << i << ' ' << inst.bathSignedCurvatures[i] << '\n';
1267 }
1268 spectrum.flush();
1269 if (!spectrum) {
1270 throw std::runtime_error("instanton: cannot finish " + name.str());
1271 }
1272 returnFiles.push_back(name.str());
1273 }
1274 if (inst.negativeModes != 1) {
1275 EONC_LOG_ERROR("[Instanton] the ring Hessian has {} negative modes, "
1276 "not one: the ring is not a first-order saddle of U_N",
1277 inst.negativeModes);
1278 }
1279 } catch (const std::exception &ex) {
1280 EONC_LOG_ERROR("[Instanton] {}", ex.what());
1281 }
1282 }
1283 if (rateOk) {
1284 EONC_LOG_INFO("[Instanton] {:.4g} K: ln(k s) = {:.4f}, harmonic TST "
1285 "{:.4f}, effective barrier {:.4f} eV",
1286 temperature, inst.logRate - logSecond,
1287 inst.classicalLogRate - logSecond, inst.effectiveBarrier);
1288 }
1289 table << temperature << ' ' << tc << ' ' << o.beads << ' '
1290 << (inst.converged ? 1 : 0) << ' ' << inst.iterations << ' ';
1291 if (reached) {
1292 table << inst.ringPotential;
1293 } else {
1294 table << "nan";
1295 }
1296 table << ' ' << inst.negativeModes << ' ';
1297 if (rateOk) {
1298 table << inst.logRate - logSecond << ' ' << inst.rate << ' '
1299 << inst.classicalLogRate - logSecond << ' '
1300 << inst.effectiveBarrier;
1301 } else {
1302 table << "nan nan nan nan";
1303 }
1304 table << ' ' << wkbLog << " nan nan\n";
1305
1306 std::vector<std::string> files;
1307 if (last) {
1308 files.push_back(pathFile);
1309 }
1310 if (temperatures.size() > 1) {
1311 std::ostringstream name;
1312 name << std::defaultfloat << std::setprecision(6) << "instanton_"
1313 << temperature << "K.con";
1314 files.push_back(name.str());
1315 }
1316 if (!inst.beads.empty()) {
1317 const double spring = 1 / std::pow(inst.betaN * tunneling::kHbar, 2);
1318 const auto fullRing = physicalModel
1319 ? physicalModel->reconstruct(inst.beads, spring)
1320 : inst.beads;
1321 std::vector<double> fullEnergies = inst.energies;
1322 if (physicalModel) {
1323 const auto bathState =
1324 physicalModel->bath->evaluate(inst.beads, spring);
1325 for (size_t j = 0; j < inst.beads.size(); ++j) {
1326 VectorXd source;
1327 if (physicalModel->bath->source) {
1328 Eigen::MatrixXd jac;
1329 std::vector<Eigen::MatrixXd> hess;
1330 physicalModel->bath->source(inst.beads[j], source, jac, hess);
1331 } else
1332 source = physicalModel->bath->coupling.transpose() * inst.beads[j];
1333 const VectorXd &b = bathState.bathPositions[j];
1334 fullEnergies[j] += o.energy_shift + source.dot(b);
1335 if (physicalModel->bath->curvature)
1336 fullEnergies[j] +=
1337 .5 *
1338 b.dot(physicalModel->bath->curvatureAt(inst.beads[j], 0).value *
1339 b);
1340 else
1341 fullEnergies[j] += .5 * (physicalModel->bath->curvatures.array() *
1342 b.array().square())
1343 .sum();
1344 }
1345 }
1346 Matter frame(reactant);
1347 for (const auto &file : files) {
1348 for (size_t j = 0; j < inst.beads.size(); ++j) {
1349 mw.place(fullRing[j], frame);
1351 meta.frame_index = static_cast<uint64_t>(j);
1352 meta.energy = fullEnergies[j];
1353 meta.write_con_forces = false;
1354 meta.scalars = {
1355 {"imaginary_time_fs", static_cast<double>(j) * inst.betaN *
1356 tunneling::kHbar * kTimeUnitFs}};
1357 if (j == 0) {
1358 meta.scalars.push_back(
1359 {"instanton_temperature_K", inst.temperature});
1360 meta.scalars.push_back({"instanton_crossover_K", tc});
1361 meta.scalars.push_back(
1362 {"instanton_converged", inst.converged ? 1.0 : 0.0});
1363 if (rateOk) {
1364 meta.scalars.push_back(
1365 {"rate_instanton_log", inst.logRate - logSecond});
1366 meta.scalars.push_back(
1367 {"barrier_effective_instanton", inst.effectiveBarrier});
1368 }
1369 }
1370 if (!io::io_ok(frame.matter2con(file, j > 0, &meta))) {
1371 throw std::runtime_error("instanton: cannot write " + file);
1372 }
1373 }
1374 returnFiles.push_back(file);
1375 }
1376 }
1377 {
1378 const std::string centroidFile =
1379 last ? "instanton_centroid.con"
1380 : "instanton_centroid_" +
1381 files.back().substr(std::string("instanton_").size());
1382 const double spring = 1 / std::pow(inst.betaN * tunneling::kHbar, 2);
1383 const auto fullRing = physicalModel
1384 ? physicalModel->reconstruct(inst.beads, spring)
1385 : inst.beads;
1386 writeCentroid(centroidFile, fullRing, mw, reactant,
1387 {{"instanton_temperature_K", temperature},
1388 {"instanton_crossover_K", tc},
1389 {"instanton_converged", inst.converged ? 1.0 : 0.0}});
1390 returnFiles.push_back(centroidFile);
1391 }
1392
1393 ring = inst.beads;
1394 if (!last) {
1395 continue;
1396 }
1397 extras.emplace_back("instanton_temperature_K", temperature);
1398 extras.emplace_back("instanton_iterations",
1399 static_cast<double>(inst.iterations));
1400 extras.emplace_back("instanton_ring_potential", inst.ringPotential);
1401 extras.emplace_back("instanton_bN", inst.bN);
1402 extras.emplace_back("instanton_collapsed", inst.collapsed ? 1.0 : 0.0);
1403 extras.emplace_back("instanton_rate_valid", rateOk ? 1.0 : 0.0);
1404 extras.emplace_back("instanton_negative_modes",
1405 static_cast<double>(inst.negativeModes));
1406 extras.emplace_back("instanton_s_min", channel.sMin);
1407 extras.emplace_back("instanton_s_max", channel.sMax);
1408 extras.emplace_back("instanton_chord_overlap", channel.chordOverlap);
1409 extras.emplace_back("instanton_crossing_offset", channel.crossingOffset);
1410 if (std::isfinite(wkbLog)) {
1411 extras.emplace_back("rate_wkb_path_log", wkbLog);
1412 }
1413 if (rateOk) {
1414 extras.emplace_back("rate_instanton", inst.rate);
1415 extras.emplace_back("rate_instanton_log", inst.logRate - logSecond);
1416 extras.emplace_back("rate_htst", inst.classicalRate);
1417 extras.emplace_back("rate_htst_log", inst.classicalLogRate - logSecond);
1418 extras.emplace_back("barrier_effective_instanton", inst.effectiveBarrier);
1419 extras.emplace_back("instanton_zero_mode", inst.zeroEigenvalue);
1420 extras.emplace_back("instanton_rotation_ratio_log",
1421 inst.logRotationRatio);
1422 } else {
1423 rateFailed = true;
1424 status = inst.converged ? RunStatus::FAIL_POTENTIAL_FAILED
1426 }
1427 }
1428 if (!rateFailed) {
1429 status = RunStatus::GOOD;
1430 }
1431 if (o.pi_planes > 0) {
1432 const auto planeFiles = piqtst::runAfterInstanton(
1433 params, *pot, reactant, saddle, hSaddle, pathQ, temperatures, extras);
1434 returnFiles.insert(returnFiles.end(), planeFiles.begin(), planeFiles.end());
1435 }
1436 write(status);
1437 return returnFiles;
1438}
1439
1440} // namespace
1441
1442std::vector<std::string> InstantonJob::run(void) {
1443 const auto &o = params.instanton_options();
1444 if (o.mode != "rate" && !o.initial_ring.empty()) {
1445 throw std::invalid_argument("instanton: initial_ring requires mode rate");
1446 }
1447 pathintegral::requireTrotterSprings(o.springs, "instanton");
1448 std::vector<std::string> returnFiles;
1449 const std::string resultsFile = "results.dat";
1450 const std::string pathFile = "instanton.con";
1451 returnFiles.push_back(resultsFile);
1452
1453 auto reactant = std::make_unique<Matter>(pot, params);
1454 if (!io::io_ok(reactant->con2matter(o.reactant_filename))) {
1455 throw std::runtime_error("instanton: cannot read " + o.reactant_filename);
1456 }
1457 const MassWeighted mw(*reactant);
1458 const long n = mw.dimension();
1459 const VectorXd qStart = VectorXd::Zero(n);
1460
1461 // Bead evaluations: one batch per call, through forceBatch when the
1462 // potential spreads a batch over calculators.
1463 std::vector<std::unique_ptr<Matter>> pool;
1464 tunneling::OwnedBatchPotential evaluateOwned =
1465 [&](const std::vector<VectorXd> &q, std::vector<double> &v,
1466 std::vector<VectorXd> &grad, const std::vector<long> &owners) {
1467 if (owners.size() != q.size())
1468 throw std::invalid_argument(
1469 "instanton: potential owner count mismatch");
1470 while (pool.size() < q.size()) {
1471 pool.push_back(std::make_unique<Matter>(*reactant));
1472 }
1473 for (size_t j = 0; j < q.size(); ++j) {
1474 mw.place(q[j], *pool[j]);
1475 }
1476 v.resize(q.size());
1477 grad.resize(q.size());
1478 if (pot->supportsBatchEvaluation() && !q.empty()) {
1479 const long atoms = reactant->numberOfAtoms();
1480 std::vector<VectorXi> nrs(q.size());
1481 std::vector<Matrix3d> boxes(q.size());
1482 std::vector<const double *> posPtr, boxPtr;
1483 std::vector<const int *> nrsPtr;
1484 std::vector<double *> frcPtr;
1485 for (size_t j = 0; j < q.size(); ++j) {
1486 nrs[j] = pool[j]->getAtomicNrs();
1487 boxes[j] = pool[j]->getPeriodic() ? pool[j]->getCell()
1488 : Matrix3d::Zero().eval();
1489 }
1490 for (size_t j = 0; j < q.size(); ++j) {
1491 posPtr.push_back(pool[j]->getPositions().data());
1492 nrsPtr.push_back(nrs[j].data());
1493 frcPtr.push_back(pool[j]->forcesData());
1494 boxPtr.push_back(boxes[j].data());
1495 }
1496 std::vector<double> energies(q.size()), variances(q.size());
1497 pot->forceBatchOwned(static_cast<long>(q.size()), atoms,
1498 posPtr.data(), nrsPtr.data(), frcPtr.data(),
1499 energies.data(), variances.data(), boxPtr.data(),
1500 owners.data());
1501 for (size_t j = 0; j < q.size(); ++j) {
1502 pool[j]->setComputedPotential(energies[j], variances[j]);
1503 }
1504 }
1505 for (size_t j = 0; j < q.size(); ++j) {
1506 v[j] = pool[j]->getPotentialEnergy();
1507 grad[j] = mw.gradient(pool[j]->getForces());
1508 }
1509 };
1510
1511 tunneling::BatchPotential evaluate = [&](const std::vector<VectorXd> &q,
1512 std::vector<double> &v,
1513 std::vector<VectorXd> &grad) {
1514 evaluateOwned(q, v, grad,
1515 std::vector<long>(q.size(), potential_owner::auxiliary));
1516 };
1517
1518 // The first call is the reactant. Its Hessian decides which rotations
1519 // are zero modes; later beads reuse that decision.
1520 std::array<bool, 3> rotationZero{{false, false, false}};
1521 std::array<double, 3> rotationResidual{{0.0, 0.0, 0.0}};
1522 bool rotationsKnown = false;
1523 auto hessianWith = [&](const VectorXd &q, bool projectRotations,
1524 const std::string &filename = std::string{}) {
1525 Matter m(*reactant);
1526 mw.place(q, m);
1527 MatrixXd out;
1528 if (filename.empty()) {
1529 Hessian h(params, &m);
1530 h.writeHessianFile(false);
1531 out = h.getHessian(&m, mw.freeAtoms());
1532 } else {
1533 out = tunneling::readReferenceHessian(filename, m, n);
1534 EONC_LOG_INFO("[Instanton] reference Hessian read from {} with matching "
1535 "geometry and mass metric",
1536 filename);
1537 }
1538 if (out.rows() != n) {
1539 throw std::runtime_error("instanton: a bead Hessian failed");
1540 }
1541 if (!rotationsKnown) {
1542 mw.markRotationZeroModes(
1543 out, mw.rigidGenerators(m),
1544 params.instanton_options().rotation_zero_fraction, rotationZero,
1545 rotationResidual);
1546 rotationsKnown = true;
1547 }
1548 // A finite-difference Hessian of a free structure has small nonzero
1549 // rigid eigenvalues of either sign; project them to zero. At a point
1550 // that is not stationary, H r for a rotation r is the rotated gradient,
1551 // which on a ring bead balances the springs; ring beads keep it and
1552 // lose only their translations.
1553 const std::array<bool, 3> none{{false, false, false}};
1554 const MatrixXd rigid =
1555 mw.rigidBasis(m, projectRotations ? rotationZero : none);
1556 if (rigid.cols() > 0) {
1557 const MatrixXd p = MatrixXd::Identity(n, n) - rigid * rigid.transpose();
1558 out = p * out * p;
1559 }
1560 return out;
1561 };
1562 auto hessianAt = [&](const VectorXd &q) { return hessianWith(q, true); };
1563 auto beadHessianAt = [&](const VectorXd &q) {
1564 if (!rotationsKnown) {
1565 hessianWith(VectorXd::Zero(n), true);
1566 }
1567 return hessianWith(q, false);
1568 };
1569
1570 if (o.mode == "rate") {
1571 auto referenceHessianAt = [&](const VectorXd &q,
1572 const std::string &filename) {
1573 return hessianWith(q, true, filename);
1574 };
1575 return runRate(params, pot, *reactant, mw, evaluate, evaluateOwned,
1576 referenceHessianAt, beadHessianAt, rotationZero,
1577 rotationResidual);
1578 }
1579
1580 auto product = std::make_unique<Matter>(pot, params);
1581 if (!io::io_ok(product->con2matter(o.product_filename))) {
1582 throw std::runtime_error("instanton: cannot read " + o.product_filename);
1583 }
1584 if (reactant->numberOfAtoms() != product->numberOfAtoms()) {
1585 throw std::runtime_error("instanton: the minima differ in atom count");
1586 }
1587 requireMatchingReferenceSurface(*reactant, *product);
1588 const MatrixXd hStart = hessianAt(qStart);
1589 const bool rotate = rotationZero[0] || rotationZero[1] || rotationZero[2];
1590 alignRigid(*reactant, *product, rotate);
1591 const VectorXd qEnd = mw.toQ(*product);
1592
1593 // Starting path: a band from file, else the straight line.
1594 std::vector<VectorXd> guess;
1595 if (!o.initial_path.empty()) {
1596 const auto frames = readcon::read_all_frames(o.initial_path);
1597 for (const auto &frame : frames) {
1598 Matter m(*reactant);
1599 if (!io::io_ok(io::con2matter(m, frame))) {
1600 throw std::runtime_error("instanton: cannot read " + o.initial_path);
1601 }
1602 alignRigid(*reactant, m, rotate);
1603 guess.push_back(mw.toQ(m));
1604 }
1605 if (guess.size() >= 2) {
1606 guess.front() = qStart;
1607 guess.back() = qEnd;
1608 }
1609 }
1610
1611 const MatrixXd hEnd = hessianAt(qEnd);
1612 // Both Hessians lost the same rigid motions. The zero-point energy the
1613 // product well holds above the reactant's belongs in the asymmetry.
1614 const double zeroPoint = tunneling::zeroPointDifference(
1615 hStart, hEnd, mw.rigidBasis(*reactant, rotationZero).cols());
1616 const double omega = tunneling::pathOmega(hStart, hEnd, qStart, qEnd);
1617 const double betaHbar = o.beta_hbar_omega / omega;
1619 opt.beads = o.beads;
1620 opt.betaHbarOmega = o.beta_hbar_omega;
1621 opt.maxIterations = o.max_iterations;
1622 opt.forceTolerance = o.force_tolerance;
1623 EONC_LOG_INFO("[Instanton] {} beads over beta hbar = {:.4f} fs, {} degrees "
1624 "of freedom",
1625 o.beads, betaHbar * kTimeUnitFs, n);
1626
1627 // Minima of different energy tunnel on the surface with that difference
1628 // switched off along the path; the bias leaves both minima and their
1629 // Hessians alone.
1630 std::vector<double> vEnds;
1631 std::vector<VectorXd> gEnds;
1632 evaluate({qStart, qEnd}, vEnds, gEnds);
1633 const double dV = vEnds.at(1) - vEnds.at(0);
1634 const bool symmetrized = o.symmetrize && dV != 0.0;
1635 const tunneling::EnergyBias bias(qStart, qEnd, symmetrized ? dV : 0.0);
1636 const tunneling::BatchPotential surface = [&](const std::vector<VectorXd> &q,
1637 std::vector<double> &v,
1638 std::vector<VectorXd> &grad) {
1639 evaluate(q, v, grad);
1640 for (size_t j = 0; symmetrized && j < q.size(); ++j) {
1641 v[j] -= bias.value(q[j]);
1642 grad[j] -= bias.gradient(q[j]);
1643 }
1644 };
1646 tunneling::optimizeInstanton(qStart, qEnd, betaHbar, guess, surface, opt);
1647 inst.asymmetry = dV;
1648 for (size_t j = 0; j < inst.path.size(); ++j) {
1649 inst.energies[j] += bias.value(inst.path[j]);
1650 }
1651 EONC_LOG_INFO("[Instanton] action {:.6f} after {} iterations{}{}",
1652 inst.action, inst.iterations,
1653 inst.converged ? "" : " (not converged)",
1654 symmetrized ? ", wells levelled" : "");
1655
1656 bool splitOk = false;
1657 std::string failure;
1658 // beta |delta|: without the levelled surface, the propagator ratio reads
1659 // delta0 only when the wells lie within a small fraction of kB T of each
1660 // other.
1661 const double betaAsymmetry = std::abs(dV) * betaHbar / tunneling::kHbar;
1662 inst.symmetricEnough = betaAsymmetry < 0.1;
1663 const bool splittable = symmetrized || inst.symmetricEnough;
1664 if (inst.converged && !splittable) {
1665 EONC_LOG_WARNING("[Instanton] beta |delta| = {:.3g}: the wells differ by "
1666 "{:.4g} eV, too far for the splitting; the path and "
1667 "action are written, the splitting is not",
1668 betaAsymmetry, inst.asymmetry);
1669 }
1670 if (inst.converged && splittable) {
1671 const long stride = std::max<long>(1, o.hessian_stride);
1672 const long P = o.beads;
1673 std::map<long, MatrixXd> anchors;
1674 // The splitting is the J = 0 one: every bead loses its rotations, as the
1675 // two minima do. A closed rate ring keeps them on its beads, because
1676 // there a rotation of every bead at once is the zero mode it lifts.
1677 auto anchor = [&](long j) -> const MatrixXd & {
1678 auto it = anchors.find(j);
1679 if (it == anchors.end()) {
1680 const VectorXd &q = inst.path[static_cast<size_t>(j)];
1681 it = anchors.emplace(j, hessianAt(q) - bias.hessian(q)).first;
1682 }
1683 return it->second;
1684 };
1685 auto beadHessian = [&](long j, const VectorXd &) -> MatrixXd {
1686 if (stride == 1) {
1687 return anchor(j);
1688 }
1689 const long lo = 1 + ((j - 1) / stride) * stride;
1690 const long hi = std::min(lo + stride, P - 1);
1691 if (j == lo || hi == lo) {
1692 return anchor(lo);
1693 }
1694 const double t =
1695 static_cast<double>(j - lo) / static_cast<double>(hi - lo);
1696 return (1.0 - t) * anchor(lo) + t * anchor(hi);
1697 };
1698 try {
1699 tunneling::instantonSplitting(inst, beadHessian, hStart, hEnd);
1700 splitOk = std::isfinite(inst.delta0);
1701 } catch (const std::runtime_error &ex) {
1702 failure = ex.what();
1703 EONC_LOG_ERROR("[Instanton] {}", failure);
1704 }
1705 }
1706
1707 // The path, one frame per bead; the splitting on the first frame.
1708 const double kelvin = tunneling::kHbar / (tunneling::kBoltzmann * betaHbar);
1709 const double asymmetryZpe = inst.asymmetry + zeroPoint;
1710 Matter frame(*reactant);
1711 for (size_t j = 0; j < inst.path.size(); ++j) {
1712 mw.place(inst.path[j], frame);
1714 meta.frame_index = static_cast<uint64_t>(j);
1715 meta.energy = inst.energies[j];
1716 meta.write_con_forces = false;
1717 meta.scalars = {{"imaginary_time_fs",
1718 static_cast<double>(j) * inst.dtau * kTimeUnitFs}};
1719 if (j == 0) {
1720 meta.scalars.push_back({"instanton_action", inst.action});
1721 meta.scalars.push_back(
1722 {"instanton_beta_hbar_fs", betaHbar * kTimeUnitFs});
1723 meta.scalars.push_back({"instanton_temperature_K", kelvin});
1724 meta.scalars.push_back(
1725 {"instanton_converged", inst.converged ? 1.0 : 0.0});
1726 meta.scalars.push_back({"tunnel_asymmetry", inst.asymmetry});
1727 meta.scalars.push_back({"tunnel_asymmetry_zpe", asymmetryZpe});
1728 meta.scalars.push_back(
1729 {"instanton_symmetrized", symmetrized ? 1.0 : 0.0});
1730 meta.scalars.push_back(
1731 {"instanton_symmetric", inst.symmetricEnough ? 1.0 : 0.0});
1732 meta.scalars.push_back({"instanton_beta_asymmetry", betaAsymmetry});
1733 if (splitOk) {
1734 meta.scalars.push_back({"tunnel_splitting_instanton", inst.delta0});
1735 meta.scalars.push_back(
1736 {"tls_energy_instanton", std::hypot(asymmetryZpe, inst.delta0)});
1737 meta.scalars.push_back({"instanton_zero_mode", inst.zeroMode});
1738 meta.scalars.push_back(
1739 {"instanton_mode_separation", inst.modeSeparation});
1740 }
1741 }
1742 if (!io::io_ok(frame.matter2con(pathFile, j > 0, &meta))) {
1743 throw std::runtime_error("instanton: cannot write " + pathFile);
1744 }
1745 }
1746 returnFiles.push_back(pathFile);
1747 writeCentroid("instanton_centroid.con", inst.path, mw, *reactant,
1748 {{"instanton_temperature_K", kelvin},
1749 {"instanton_converged", inst.converged ? 1.0 : 0.0}});
1750 returnFiles.push_back("instanton_centroid.con");
1751
1752 // A converged path between wells too far apart is a result, not a
1753 // failure: the flags say why no splitting was written.
1754 const bool good = splitOk || (inst.converged && !splittable);
1755 const auto status = good ? RunStatus::GOOD
1756 : (inst.converged ? RunStatus::FAIL_POTENTIAL_FAILED
1759 status, params.potential_options().potential,
1760 pot->forceCallCounter.load(), false, 0.0);
1761 env.provenance = provenanceForJob(params);
1762 env.job_type = "instanton";
1763 env.extras.emplace_back("force_calls", static_cast<double>(env.force_calls));
1764 env.extras.emplace_back("instanton_iterations",
1765 static_cast<double>(inst.iterations));
1766 env.extras.emplace_back("instanton_action", inst.action);
1767 env.extras.emplace_back("instanton_temperature_K", kelvin);
1768 env.extras.emplace_back("tunnel_asymmetry", inst.asymmetry);
1769 env.extras.emplace_back("tunnel_asymmetry_zpe", asymmetryZpe);
1770 env.extras.emplace_back("instanton_beta_asymmetry", betaAsymmetry);
1771 env.extras.emplace_back("instanton_symmetric",
1772 inst.symmetricEnough ? 1.0 : 0.0);
1773 env.extras.emplace_back("instanton_symmetrized", symmetrized ? 1.0 : 0.0);
1774 if (splitOk) {
1775 env.extras.emplace_back("tunnel_splitting_instanton", inst.delta0);
1776 env.extras.emplace_back("tls_energy_instanton",
1777 std::hypot(asymmetryZpe, inst.delta0));
1778 env.extras.emplace_back("instanton_mode_separation", inst.modeSeparation);
1779 }
1780 env.writeResultsDat(resultsFile);
1781 return returnFiles;
1782}
1783
1784} // namespace eonc
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, eOnStorageOrder > MatrixXd
Definition Eigen.h:33
Eigen::Matrix< double, 3, 3, eOnStorageOrder > Matrix3d
Definition Eigen.h:35
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
#define EONC_LOG_DEBUG(...)
Definition EonLogger.h:310
#define EONC_LOG_ERROR(...)
Definition EonLogger.h:328
#define EONC_LOG_WARNING(...)
Definition EonLogger.h:322
#define EONC_LOG_INFO(...)
Definition EonLogger.h:316
VectorXi getAtomicNrs() const
Definition Matter.cpp:786
const AtomMatrix & getPositions() const
Definition Matter.cpp:378
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
bool getPeriodic() const noexcept
Definition Matter.h:338
Matrix3d getCell() const
Definition Matter.cpp:345
long int numberOfAtoms() const
Definition Matter.cpp:343
AtomMatrix pbc(const AtomMatrix &diff) const
Definition Matter.cpp:943
double getMass(long int atom) const
Definition Matter.cpp:548
std::array< bool, 3 > getFixedMask(long int atom) const
Per-axis CON column-4 mask (bit0=x, bit1=y, bit2=z).
Definition Matter.cpp:590
int getFixed(long int atom) const
1 if every Cartesian axis of the atom is fixed, else 0.
Definition Matter.cpp:575
const instanton_options_t & instanton_options() const
const potential_options_t & potential_options() const
void writeHessianFile(bool on) noexcept
Whether a finished Hessian goes to hessian.dat (on by default).
Definition Hessian.h:61
MatrixXd getHessian(Matter *matterIn, const VectorXi &atomsIn)
Definition Hessian.cpp:146
std::vector< std::string > run(void) override
Virtual run; used solely for dynamic dispatch.
std::shared_ptr< Potential > pot
Set when one Potential is shared across Matters, images, or a caller.
Definition Job.h:66
Parameters params
Definition Job.h:58
io::IoStatus matter2con(std::string filename, bool append=false, const io::ConFrameMetadata *metadata=nullptr)
Definition Matter.h:293
delta sigma(xi) between two minima, xi = (q - start) .
Definition Tunneling.h:308
VectorXd gradient(const VectorXd &q) const
MatrixXd hessian(const VectorXd &q) const
double value(const VectorXd &q) const
double norm(const Eigen::MatrixBase< A > &x)
sqrt of the correctly rounded squared norm; IEEE sqrt is itself correctly rounded,...
IoStatus writeConFrames(std::string filename, const std::vector< readcon::ConFrame > &frames)
Write already-built ConFrames to a multi-frame .con (temp or durable).
IoStatus con2matter(Matter &m, std::string filename)
std::vector< readcon::ConFrame > buildNebPathFrames(const std::vector< std::shared_ptr< Matter > > &path, const std::vector< ConFrameMetadata > &metadata_per_image)
Build NEB band ConFrames without writing (clone builder path of writeNebPath).
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
void requireTrotterSprings(const std::string &springs, const char *use)
Economised springs and a normal-mode GLE are refused.
std::vector< std::string > runAfterInstanton(const Parameters &params, Potential &pot, const Matter &reactant, const Matter &saddle, const MatrixXd &hSaddle, const std::vector< VectorXd > &pathQ, const std::vector< double > &temperatures, std::vector< std::pair< std::string, double > > &extras)
[Instanton] mode rate with pi_planes > 0: the planes and rate at each temperature,...
constexpr long saddle
constexpr long reactant
constexpr long auxiliary
double zeroPointDifference(const MatrixXd &hessStart, const MatrixXd &hessEnd, long rigidModes)
Harmonic zero-point energy of the end minimum minus that of the start, in eV: (hbar / 2) times the di...
void instantonRate(RateInstanton &inst, const RingBeadHessian &hessian, const MatrixXd &hessReactant, double vReactant, const MatrixXd &hessSaddle, double vSaddle, long rigidModes, long denseLimit, const RingRigidBodies &rigidBodies)
Fills the rate from the bead Hessians, the reactant minimum's Hessian and energy, and optionally the ...
double parabolicFactor(double temperature, double crossover)
(pi T_c / T) / sin(pi T_c / T).
void instantonSplitting(Instanton &inst, const BeadHessian &hessian, const MatrixXd &hessStart, const MatrixXd &hessEnd)
Fills delta0, zeroMode and modeSeparation from the bead Hessians and the Hessians of the two minima.
constexpr double kTimeUnitSeconds
One unit of time, sqrt(amu Angstrom^2 / eV), in seconds.
Definition Tunneling.h:350
double pathOmega(const MatrixXd &hessStart, const MatrixXd &hessEnd, const VectorXd &start, const VectorXd &end)
omega along the straight line between the minima from the curvature of each well there,...
double logRotationalRatio(const std::vector< VectorXd > &beads, const RingRigidBodies &bodies)
ln of the classical rotational partition function of beads over that of as many copies of the referen...
RateInstanton optimizeRateInstanton(const VectorXd &saddle, const MatrixXd &hessSaddle, double beta, std::vector< VectorXd > guess, const BatchPotential &potential, const RateInstantonOptions &request)
Finds the rate instanton at inverse temperature beta (1 / eV).
RingChannel ringChannel(const std::vector< VectorXd > &beads, const VectorXd &saddle, const VectorXd &mode)
The channel test above for a ring of beads, a saddle and its unstable mode (normalised inside).
constexpr double kHbar
hbar in eV^0.5 amu^0.5 Angstrom, correctly rounded from the exact SI values (h = 6....
Definition Tunneling.h:39
double harmonicTstLogRate(const MatrixXd &hessReactant, const MatrixXd &hessSaddle, double beta, double barrier, long rigidModes)
ln(k) for classical harmonic transition-state theory, k in 1/time.
double wellCurvature(const Profile &p, bool leftEnd)
d2V/ds2 at one end of the path, in eV / (amu Angstrom^2), from a least squares fit of a s^2 + b s^3 t...
std::function< void(const std::vector< VectorXd > &q, std::vector< double > &v, std::vector< VectorXd > &grad)> BatchPotential
V (eV) and dV/dq (eV / (amu^0.5 Angstrom)) at every point of q, all in one call so a potential can sp...
Definition Tunneling.h:238
double quantumHarmonicTstLogRate(const MatrixXd &hessReactant, const MatrixXd &hessSaddle, double beta, double barrier, long rigidModes)
ln(k) for quantum harmonic transition-state theory, k in 1/time: (1 / (2 pi beta hbar)) prod_r 2 sinh...
double crossoverTemperature(const MatrixXd &hessSaddle)
T_c = hbar omega_b / (2 pi kB) from the mass-weighted Hessian at the saddle, in K; throws when the He...
MatrixXd readReferenceHessian(const std::string &filename, const Matter &reference, long dimension)
Read a mass-weighted reference matrix bound to filename + ".con".
std::vector< VectorXd > ringFromPath(const std::vector< VectorXd > &path, const std::vector< double > &energies, double betaHbar, long beads, RingSeed *seed)
double wkbLogRateAlongPath(const Profile &profile, double beta, double hwReactant)
ln(k), k in 1/time, for the one-dimensional thermal rate along profile.
std::function< void( const std::vector< VectorXd > &q, std::vector< double > &v, std::vector< VectorXd > &grad, const std::vector< long > &owners)> OwnedBatchPotential
Explicit electronic-state owners for each evaluated geometry.
Definition Tunneling.h:243
double hbarOmega(double curvature)
hbar omega in eV for a mass-weighted curvature.
RotationZeroModes rotationZeroModes(const MatrixXd &hess, const MatrixXd &generators, double fraction)
std::vector< AtomMatrix > readRateRingSeed(const std::string &filename, const Matter &reference, long beads)
Read closed-ring geometry on the reference's ordered physical coordinates.
Instanton optimizeInstanton(const VectorXd &start, const VectorXd &end, double betaHbar, std::vector< VectorXd > guess, const BatchPotential &potential, const InstantonOptions &options)
Minimises the action from guess (P + 1 beads, ends at the minima, or empty for a tanh kink along the ...
constexpr double kBoltzmann
Boltzmann constant in eV / K, correctly rounded from the exact 1.380649e-23 J / K.
Definition Tunneling.h:43
RAII resource manager for the ARTn C library with global synchronization.
JobResultProvenance provenanceForJob(const Parameters &params)
Optimizer backend, engine identity, rgpot pin, and xts ABI from a job.
static JobResultEnvelope fromMinimization(RunStatus status, PotType pot, std::uint64_t fcalls, bool hasE, double energy)
Definition JobResult.h:251
std::optional< uint64_t > frame_index
Definition ConFileIO.h:72
std::vector< double > spreads
Per-atom root-mean-square spread of the position distribution about the written coordinates,...
Definition ConFileIO.h:90
std::vector< ConMetadataValue > scalars
Definition ConFileIO.h:79
std::optional< double > energy
Definition ConFileIO.h:73
std::optional< bool > write_con_forces
When set, this write includes or omits force sections regardless of Parameters.main_options()....
Definition ConFileIO.h:93
long maxIterations
L-BFGS iterations.
Definition Tunneling.h:230
double forceTolerance
largest per-bead |dS/dq| / dtau, eV / (amu^0.5 Angstrom)
Definition Tunneling.h:231
long beads
P: segments from one minimum to the other.
Definition Tunneling.h:227
double betaHbarOmega
beta hbar omega of the stiffer end along the path; sets the imaginary time
Definition Tunneling.h:228
double asymmetry
V(end) - V(start), eV.
Definition Tunneling.h:259
std::vector< double > energies
V at every bead, eV.
Definition Tunneling.h:252
double zeroMode
the eigenvalue det' leaves out
Definition Tunneling.h:257
double action
(S - S_well) / hbar
Definition Tunneling.h:255
bool symmetricEnough
beta |asymmetry| < 0.1: the propagator ratio reads delta0 only when the wells lie within a small frac...
Definition Tunneling.h:264
double modeSeparation
The second smallest eigenvalue of J over the zero mode's: small means the kink is not isolated in ima...
Definition Tunneling.h:267
double dtau
betaHbar / P
Definition Tunneling.h:254
double delta0
tunnelling splitting, eV
Definition Tunneling.h:258
std::vector< VectorXd > path
P + 1 beads, ends at the minima.
Definition Tunneling.h:251
static PhysicalBathModel read(const std::string &filename, long dimension)
std::shared_ptr< const PhysicalQuadraticBath > physicalBath
Fixed physical quadratic bath, eliminated on the same primitive ring.
Definition Tunneling.h:391
long beads
N, beads on the ring.
Definition Tunneling.h:395
Where a ring sits against the saddle it was seeded from, in mass-weighted coordinates.
Definition Tunneling.h:566
The atoms behind a ring's mass-weighted coordinates, for its rigid motions: sqrt(m) per atom,...
Definition Tunneling.h:624
std::vector< double > sqrtMasses
Definition Tunneling.h:625
Closed ring of beads samples of path whose imaginary-time period is betaHbar.
Definition Tunneling.h:185