52constexpr double kTimeUnitFs = 10.180505717871193;
60 diff.rowwise() -= r.row(0);
62 out.rowwise() += r.row(0);
70 explicit MassWeighted(
const Matter &reference)
76 const double m = reference.
getMass(i);
78 throw std::invalid_argument(
"instanton: a free atom without a mass");
81 sqrtMass_.push_back(std::sqrt(m));
84 throw std::invalid_argument(
"instanton: every atom is fixed");
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]);
98 std::vector<double> spreadAbout(
const std::vector<VectorXd> &beads,
99 VectorXd ¢roid,
long atoms)
const {
100 centroid = VectorXd::Zero(dimension());
101 for (
const auto &q : beads) {
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;
110 for (
const auto &q : beads) {
111 const double d = q(i) - centroid(i);
114 out[
static_cast<size_t>(3 * free_[k] + c)] =
116 static_cast<double>(std::max<size_t>(1, beads.size()))) /
122 VectorXd toQ(
const Matter &m)
const {
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);
132 void place(
const VectorXd &q, Matter &m)
const {
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];
143 MatrixXd rigidGenerators(
const Matter &m)
const {
144 const long n = dimension();
147 Eigen::RowVector3d com = Eigen::RowVector3d::Zero();
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]);
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();
162 b.block(i, 3 + c, 3, 1) = sqrtMass_[k] * e.cross(x);
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 =
177 residual = z.residual;
183 MatrixXd rigidBasis(
const Matter &m,
184 const std::array<bool, 3> &rotations)
const {
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);
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]);
200 const Eigen::ColPivHouseholderQR<MatrixXd> qr(b);
201 const long rank = qr.rank();
205 return qr.householderQ() * MatrixXd::Identity(n, rank);
207 const std::vector<double> &sqrtMasses()
const {
return sqrtMass_; }
210 VectorXd referenceFree()
const {
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);
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];
232 std::vector<long> free_;
233 std::vector<double> sqrtMass_;
237bool cachedProfileMatchesSurface(
const Matter &ref,
const Matter &image) {
238 constexpr double inputTolerance = 1e-8;
241 !image.
getCell().allFinite() ||
248 if (!delta.allFinite()) {
254 delta.row(i).cwiseAbs().maxCoeff() > inputTolerance)) {
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");
271 throw std::invalid_argument(
272 "instanton: reference surface differs in atomic masses");
283void alignRigid(
const Matter &ref,
Matter &m,
bool rotate) {
285 for (
long i = 0; i < n; ++i) {
292 for (
long i = 0; i < n; ++i) {
295 const double total = w.sum();
296 const Eigen::RowVector3d shift = (w.transpose() * d) / total;
297 d.rowwise() -= shift;
300 const Eigen::RowVector3d com = (w.transpose() * x) / total;
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
310 const Eigen::Matrix3d rot = svd.matrixV() * fix * svd.matrixU().transpose();
311 d = (y * rot.transpose()) - x;
319void writeCentroid(
const std::string &file,
const std::vector<VectorXd> &beads,
320 const MassWeighted &mw,
const Matter &reactant,
321 std::vector<io::ConMetadataValue> scalars) {
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);
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);
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]);
363void steepestDescentPath(
const VectorXd &qSaddle,
double vSaddle,
365 const std::vector<double> &sqrtMass,
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();
378 auto cartesian = [&](
const VectorXd &dq) {
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);
387 auto capped = [&](VectorXd dq) {
388 const double big = cartesian(dq);
389 if (big > cartStep) {
390 dq *= cartStep / big;
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()) {
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;
414 if (!at(q, v, g) || !(v < vSaddle)) {
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);
426 if (at(trial, vt, gt) && vt < v) {
439 sideQ[side].push_back(q);
440 sideV[side].push_back(v);
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());
450 if (pathQ.back().norm() < pathQ.front().norm()) {
451 std::reverse(pathQ.begin(), pathQ.end());
452 std::reverse(pathV.begin(), pathV.end());
458std::vector<std::string>
459runRate(
const Parameters ¶ms,
const std::shared_ptr<Potential> &
pot,
460 const Matter &reactant,
const MassWeighted &mw,
463 const std::function<
MatrixXd(
const VectorXd &,
const std::string &)>
465 const std::function<
MatrixXd(
const VectorXd &)> &beadHessianAtFull,
466 const std::array<bool, 3> &rotationZero,
467 const std::array<double, 3> &rotationResidual) {
469 const std::string resultsFile =
"results.dat";
470 const std::string pathFile =
"instanton.con";
471 std::vector<std::string> returnFiles{resultsFile};
475 throw std::runtime_error(
"instanton: cannot read " + o.saddle_filename);
478 throw std::runtime_error(
479 "instanton: the saddle and the reactant differ in atom count");
481 if (o.hessian_final !=
"recomputed") {
482 throw std::invalid_argument(
"instanton: hessian_final must be recomputed");
484 std::vector<double> temperatures = o.temperatures;
485 if (temperatures.empty()) {
486 temperatures.push_back(o.temperature);
488 for (
const double t : temperatures) {
490 throw std::invalid_argument(
491 "instanton: mode rate needs [Instanton] temperature or "
492 "temperatures in K");
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()) {
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);
515 physicalModel ? physicalModel->reactionBasis.cols() : fullDimension;
516 auto project = [&](
const VectorXd &q) -> VectorXd {
517 return physicalModel ? physicalModel->project(q) : q;
519 auto frozen = [&](
const VectorXd &q) -> VectorXd {
520 return physicalModel ? physicalModel->frozen(q) : q;
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");
527 std::vector<double> &v,
528 std::vector<VectorXd> &g) {
529 if (physicalModel && physicalModel->potentialModel) {
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();
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);
544 for (
auto &gradient : g)
545 gradient = (physicalModel->reactionBasis.transpose() * gradient).eval();
548 return physicalModel ?
MatrixXd((physicalModel->reactionBasis.transpose() *
549 h * physicalModel->reactionBasis)
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));
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)));
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)
571 throw std::runtime_error(
"instanton: cannot write " + file);
573 returnFiles.push_back(file);
575 Matter reactantReference(reactant);
578 reactantReference.setPositions(reactantReference.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();
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];
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]);
603 ? physicalModel->potentialModel->evaluate(VectorXd::Zero(n)).value[0]
604 : reactantReference.getPotentialEnergy();
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",
614 return std::pair{std::numeric_limits<double>::quiet_NaN(),
615 std::numeric_limits<double>::quiet_NaN()};
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());
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};
630 const auto reactantForce = referenceForces(
"reactant", reactantReference);
631 const auto saddleForce = referenceForces(
"saddle", saddle);
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;
637 std::vector<double> values;
638 std::vector<VectorXd> gradients;
639 evaluate({VectorXd::Zero(n), qSaddle}, values, gradients);
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;
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");
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",
668 (solver.eigenvalues().array() < 0.0).count());
670 saveReference(
"reactant", hReactant);
671 saveReference(
"saddle", hSaddle);
672 const VectorXd unstableMode =
673 Eigen::SelfAdjointEigenSolver<MatrixXd>(
674 0.5 * (referenceSaddle + referenceSaddle.transpose()))
679 ?
MatrixXd(physicalModel->bath->fullHessian(qSaddle, hSaddle))
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,
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);
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);
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}};
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");
723 returnFiles.push_back(modelFile);
728 pot->forceCallCounter.load(),
false, 0.0);
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);
736 env.writeResultsDat(resultsFile);
741 auto validReferences = [&]() {
744 referenceReactant, referenceSaddle,
746 vSaddle - vReactant, rigidModes));
748 }
catch (
const std::exception &ex) {
749 EONC_LOG_ERROR(
"[Instanton] invalid rate reference: {}", ex.what());
757 std::vector<VectorXd> pathQ;
758 std::vector<double> pathV;
759 long sdPathForceCalls = 0;
760 std::unique_ptr<tunneling::Profile> profile;
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) {
768 throw std::runtime_error(
"instanton: cannot read " + o.initial_path);
771 throw std::runtime_error(
"instanton: " + o.initial_path +
772 " differs in atom count");
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));
782 if (pathQ.size() < 3) {
783 throw std::runtime_error(
"instanton: " + o.initial_path +
784 " holds fewer than three frames");
786 if (!validReferences()) {
790 const long before =
pot->forceCallCounter.load();
791 std::vector<VectorXd> grads;
792 evaluate(pathQ, pathV, grads);
793 sdPathForceCalls =
pot->forceCallCounter.load() - before;
795 sdPathForceCalls = 0;
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();
802 profile = std::make_unique<tunneling::Profile>(std::move(arc), pathV);
803 }
catch (
const std::invalid_argument &ex) {
810 }
catch (
const std::exception &ex) {
816 if (o.initial_path.empty() && !validReferences()) {
823 const bool needsSampledPath =
825 std::any_of(temperatures.begin(), temperatures.end(),
826 [tc](
double temperature) { return temperature < tc; });
827 if (!profile && o.initial_ring.empty() && !physicalModel &&
831 const long before =
pot->forceCallCounter.load();
832 steepestDescentPath(qSaddle, vSaddle, hSaddle, mw.sqrtMasses(), evaluate,
834 sdPathForceCalls =
pot->forceCallCounter.load() - before;
837 for (
auto &q : pathQ) {
840 alignRigid(reactant, image, rotate);
841 q = project(mw.toQ(image));
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();
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);
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));
862 if (frames.empty() ||
864 throw std::runtime_error(
865 "instanton: cannot write instanton_sd_path.con");
867 returnFiles.push_back(
"instanton_sd_path.con");
870 profile = std::make_unique<tunneling::Profile>(std::move(arc), pathV);
872 EONC_LOG_INFO(
"[Instanton] steepest-descent path of {} points, {} "
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);
879 }
catch (
const std::exception &ex) {
881 "seeding from the saddle mode",
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);
895 throw std::runtime_error(
"instanton: cannot write " + tableFile);
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);
902 returnFiles.push_back(tableFile);
904 const double nan = std::numeric_limits<double>::quiet_NaN();
905 auto wkbAt = [&](
double beta) {
908 if (!(profile && hwPath > 0.0)) {
913 }
catch (
const std::exception &ex) {
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;
930 std::vector<VectorXd> ring;
931 if (!o.initial_ring.empty()) {
932 const auto positions =
934 for (
const auto &xyz : positions) {
937 ring.push_back(project(mw.toQ(image)));
939 EONC_LOG_INFO(
"[Instanton] closed-ring geometry seed from {}; energies and "
940 "forces are evaluated on the selected potential",
944 bool rateFailed =
false;
945 for (
size_t ti = 0; ti < temperatures.size(); ++ti) {
946 const double temperature = temperatures[ti];
948 const bool last = ti + 1 == temperatures.size();
949 const double wkbLog = wkbAt(beta);
950 if (!(temperature < tc)) {
955 if (temperature > tc) {
959 physicalModel ?
MatrixXd(physicalModel->bath->fullHessian(
960 VectorXd::Zero(n), hReactant))
964 ?
MatrixXd(physicalModel->bath->fullHessian(qSaddle, hSaddle))
966 const double logQhtst =
968 harmonicReactant, harmonicSaddle, beta, vSaddle - vReactant,
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");
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';
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);
997 }
catch (
const std::exception &ex) {
999 temperature, ex.what());
1003 if (!(temperature > tc)) {
1004 EONC_LOG_ERROR(
"[Instanton] {:.4g} K is at the crossover temperature "
1005 "{:.4g} K; the parabolic factor diverges there",
1008 table << temperature <<
' ' << tc <<
' ' << o.beads
1009 <<
" 0 0 nan 0 nan nan nan nan " << wkbLog <<
" nan nan\n";
1013 extras.emplace_back(
"instanton_temperature_K", temperature);
1014 if (std::isfinite(wkbLog)) {
1015 extras.emplace_back(
"rate_wkb_path_log", wkbLog);
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);
1044 for (
auto &gradient : g)
1046 (physicalModel->reactionBasis.transpose() * gradient).eval();
1050 if (fittedPotential) {
1051 const auto model = physicalModel->potentialModel;
1053 [model, shift = o.energy_shift](
const std::vector<VectorXd> &q,
1054 std::vector<double> &v,
1055 std::vector<VectorXd> &g) {
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();
1064 ro.physicalHessian = [model](
const VectorXd &q) ->
MatrixXd {
1065 return model->evaluate(q).hessians[0];
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;
1079 std::vector<VectorXd> guess = ring;
1080 if (guess.empty() && profile && !physicalModel) {
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,
1090 EONC_LOG_INFO(
"[Instanton] ring seeded from {} by the period condition",
1091 o.initial_path.empty() ?
"the steepest-descent path"
1093 }
catch (
const std::invalid_argument &ex) {
1099 long ladderIterations = 0;
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 "
1109 if (guess.empty() && o.bead_ladder && o.beads >= 16 && !beadLists) {
1110 long coarse = o.beads / 4;
1111 if (coarse % 2 != 0) {
1117 std::vector<VectorXd> rung;
1118 for (
long nb = coarse; nb < o.beads; nb *= 2) {
1123 optimizerEvaluate, step);
1124 ladderIterations += rungInst.iterations;
1125 EONC_LOG_INFO(
"[Instanton] ladder rung {} beads: U_N {:.6f} eV after "
1127 nb, rungInst.ringPotential, rungInst.iterations,
1128 rungInst.converged ?
"" :
" (not converged)");
1129 rung = rungInst.beads;
1130 if (
static_cast<long>(rung.size()) != nb) {
1134 rung = doubledRing(rung);
1135 if (
static_cast<long>(rung.size()) > o.beads) {
1140 if (
static_cast<long>(rung.size()) == o.beads) {
1141 guess = std::move(rung);
1145 qSaddle, hSaddle, beta, guess, optimizerEvaluate, ro);
1146 inst.iterations += ladderIterations;
1147 EONC_LOG_INFO(
"[Instanton] {:.4g} K: ring U_N {:.6f} eV after {} "
1149 temperature, inst.ringPotential, inst.iterations,
1150 inst.converged ?
"" :
" (not converged)");
1153 const bool reached =
1154 std::abs(inst.temperature - temperature) <= 1e-9 * temperature;
1157 "{:.4g} K; that ring is written under its own "
1159 temperature, inst.temperature);
1160 inst.converged =
false;
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,
1171 : (inst.beads.front() - qSaddle).dot(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",
1187 inst.converged =
false;
1189 bool rateOk =
false;
1190 if (inst.converged) {
1193 const long stride = std::max<long>(1, o.hessian_stride);
1194 const long nBeads = o.beads;
1195 std::map<long, MatrixXd> anchors;
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)])
1205 auto it = anchors.find(j);
1206 if (it == anchors.end()) {
1209 .emplace(j, beadHessianAt(inst.beads[
static_cast<size_t>(j)]))
1214 auto beadHessian = [&](
long j,
const VectorXd &) ->
MatrixXd {
1215 const long lo = (j / stride) * stride;
1219 const long hi = lo + stride < nBeads ? lo + stride : 0;
1220 const long span = (hi == 0 ? nBeads : hi) - lo;
1222 static_cast<double>(j - lo) /
static_cast<double>(span);
1223 return (1.0 - t) * anchor(lo) + t * anchor(hi);
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) {
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());
1246 throw std::runtime_error(
"instanton: cannot write " + name.str());
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)
1255 <<
"# log_abs_det " << inst.bathLogAbsDet <<
'\n'
1256 <<
"# reactant_log_abs_det " << inst.bathReactantLogAbsDet <<
'\n'
1257 <<
"# operator_symmetry_residual " << inst.bathSymmetryResidual
1259 <<
"# algebraic_roundoff_scale " << inst.bathRoundoffScale <<
'\n'
1260 <<
"# phase_eigenpair_residual " << inst.phaseEigenResidual
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';
1270 throw std::runtime_error(
"instanton: cannot finish " + name.str());
1272 returnFiles.push_back(name.str());
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);
1279 }
catch (
const std::exception &ex) {
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);
1289 table << temperature <<
' ' << tc <<
' ' << o.beads <<
' '
1290 << (inst.converged ? 1 : 0) <<
' ' << inst.iterations <<
' ';
1292 table << inst.ringPotential;
1296 table <<
' ' << inst.negativeModes <<
' ';
1298 table << inst.logRate - logSecond <<
' ' << inst.rate <<
' '
1299 << inst.classicalLogRate - logSecond <<
' '
1300 << inst.effectiveBarrier;
1302 table <<
"nan nan nan nan";
1304 table <<
' ' << wkbLog <<
" nan nan\n";
1306 std::vector<std::string> files;
1308 files.push_back(pathFile);
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());
1316 if (!inst.beads.empty()) {
1318 const auto fullRing = physicalModel
1319 ? physicalModel->reconstruct(inst.beads, spring)
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) {
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);
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)
1338 b.dot(physicalModel->bath->curvatureAt(inst.beads[j], 0).value *
1341 fullEnergies[j] += .5 * (physicalModel->bath->curvatures.array() *
1347 for (
const auto &file : files) {
1348 for (
size_t j = 0; j < inst.beads.size(); ++j) {
1349 mw.place(fullRing[j], frame);
1352 meta.energy = fullEnergies[j];
1353 meta.write_con_forces =
false;
1355 {
"imaginary_time_fs",
static_cast<double>(j) * inst.betaN *
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});
1364 meta.scalars.push_back(
1365 {
"rate_instanton_log", inst.logRate - logSecond});
1366 meta.scalars.push_back(
1367 {
"barrier_effective_instanton", inst.effectiveBarrier});
1370 if (!
io::io_ok(frame.matter2con(file, j > 0, &meta))) {
1371 throw std::runtime_error(
"instanton: cannot write " + file);
1374 returnFiles.push_back(file);
1378 const std::string centroidFile =
1379 last ?
"instanton_centroid.con"
1380 :
"instanton_centroid_" +
1381 files.back().substr(std::string(
"instanton_").size());
1383 const auto fullRing = physicalModel
1384 ? physicalModel->reconstruct(inst.beads, spring)
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);
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);
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);
1431 if (o.pi_planes > 0) {
1433 params, *
pot, reactant, saddle, hSaddle, pathQ, temperatures, extras);
1434 returnFiles.insert(returnFiles.end(), planeFiles.begin(), planeFiles.end());
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");
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);
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);
1457 const MassWeighted mw(*reactant);
1458 const long n = mw.dimension();
1459 const VectorXd qStart = VectorXd::Zero(n);
1463 std::vector<std::unique_ptr<Matter>> pool;
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));
1473 for (
size_t j = 0; j < q.size(); ++j) {
1474 mw.place(q[j], *pool[j]);
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();
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());
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(),
1501 for (
size_t j = 0; j < q.size(); ++j) {
1502 pool[j]->setComputedPotential(energies[j], variances[j]);
1505 for (
size_t j = 0; j < q.size(); ++j) {
1506 v[j] = pool[j]->getPotentialEnergy();
1507 grad[j] = mw.gradient(pool[j]->getForces());
1512 std::vector<double> &v,
1513 std::vector<VectorXd> &grad) {
1514 evaluateOwned(q, v, grad,
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{}) {
1528 if (filename.empty()) {
1534 EONC_LOG_INFO(
"[Instanton] reference Hessian read from {} with matching "
1535 "geometry and mass metric",
1538 if (out.rows() != n) {
1539 throw std::runtime_error(
"instanton: a bead Hessian failed");
1541 if (!rotationsKnown) {
1542 mw.markRotationZeroModes(
1543 out, mw.rigidGenerators(m),
1544 params.instanton_options().rotation_zero_fraction, rotationZero,
1546 rotationsKnown =
true;
1553 const std::array<bool, 3> none{{
false,
false,
false}};
1555 mw.rigidBasis(m, projectRotations ? rotationZero : none);
1556 if (rigid.cols() > 0) {
1557 const MatrixXd p = MatrixXd::Identity(n, n) - rigid * rigid.transpose();
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);
1567 return hessianWith(q,
false);
1570 if (o.mode ==
"rate") {
1571 auto referenceHessianAt = [&](
const VectorXd &q,
1572 const std::string &filename) {
1573 return hessianWith(q,
true, filename);
1575 return runRate(
params,
pot, *reactant, mw, evaluate, evaluateOwned,
1576 referenceHessianAt, beadHessianAt, rotationZero,
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);
1584 if (reactant->numberOfAtoms() != product->numberOfAtoms()) {
1585 throw std::runtime_error(
"instanton: the minima differ in atom count");
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);
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) {
1600 throw std::runtime_error(
"instanton: cannot read " + o.initial_path);
1602 alignRigid(*reactant, m, rotate);
1603 guess.push_back(mw.toQ(m));
1605 if (guess.size() >= 2) {
1606 guess.front() = qStart;
1607 guess.back() = qEnd;
1611 const MatrixXd hEnd = hessianAt(qEnd);
1615 hStart, hEnd, mw.rigidBasis(*reactant, rotationZero).cols());
1617 const double betaHbar = o.beta_hbar_omega / omega;
1619 opt.
beads = o.beads;
1623 EONC_LOG_INFO(
"[Instanton] {} beads over beta hbar = {:.4f} fs, {} degrees "
1625 o.beads, betaHbar * kTimeUnitFs, n);
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;
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]);
1648 for (
size_t j = 0; j < inst.
path.size(); ++j) {
1651 EONC_LOG_INFO(
"[Instanton] action {:.6f} after {} iterations{}{}",
1653 inst.
converged ?
"" :
" (not converged)",
1654 symmetrized ?
", wells levelled" :
"");
1656 bool splitOk =
false;
1657 std::string failure;
1666 "{:.4g} eV, too far for the splitting; the path and "
1667 "action are written, the splitting is not",
1671 const long stride = std::max<long>(1, o.hessian_stride);
1672 const long P = o.beads;
1673 std::map<long, MatrixXd> anchors;
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;
1685 auto beadHessian = [&](
long j,
const VectorXd &) ->
MatrixXd {
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) {
1695 static_cast<double>(j - lo) /
static_cast<double>(hi - lo);
1696 return (1.0 - t) * anchor(lo) + t * anchor(hi);
1700 splitOk = std::isfinite(inst.
delta0);
1701 }
catch (
const std::runtime_error &ex) {
1702 failure = ex.what();
1709 const double asymmetryZpe = inst.
asymmetry + zeroPoint;
1711 for (
size_t j = 0; j < inst.
path.size(); ++j) {
1712 mw.place(inst.
path[j], frame);
1717 meta.
scalars = {{
"imaginary_time_fs",
1718 static_cast<double>(j) * inst.
dtau * kTimeUnitFs}};
1722 {
"instanton_beta_hbar_fs", betaHbar * kTimeUnitFs});
1723 meta.
scalars.push_back({
"instanton_temperature_K", kelvin});
1725 {
"instanton_converged", inst.
converged ? 1.0 : 0.0});
1727 meta.
scalars.push_back({
"tunnel_asymmetry_zpe", asymmetryZpe});
1729 {
"instanton_symmetrized", symmetrized ? 1.0 : 0.0});
1732 meta.
scalars.push_back({
"instanton_beta_asymmetry", betaAsymmetry});
1734 meta.
scalars.push_back({
"tunnel_splitting_instanton", inst.
delta0});
1736 {
"tls_energy_instanton", std::hypot(asymmetryZpe, inst.
delta0)});
1743 throw std::runtime_error(
"instanton: cannot write " + pathFile);
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");
1754 const bool good = splitOk || (inst.converged && !splittable);
1760 pot->forceCallCounter.load(),
false, 0.0);
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);
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);
1780 env.writeResultsDat(resultsFile);
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, eOnStorageOrder > MatrixXd
Eigen::Matrix< double, 3, 3, eOnStorageOrder > Matrix3d
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
#define EONC_LOG_DEBUG(...)
#define EONC_LOG_ERROR(...)
#define EONC_LOG_WARNING(...)
#define EONC_LOG_INFO(...)
VectorXi getAtomicNrs() const
const AtomMatrix & getPositions() const
void setPositions(const AtomMatrix &pos)
bool getPeriodic() const noexcept
long int numberOfAtoms() const
AtomMatrix pbc(const AtomMatrix &diff) const
double getMass(long int atom) const
std::array< bool, 3 > getFixedMask(long int atom) const
Per-axis CON column-4 mask (bit0=x, bit1=y, bit2=z).
int getFixed(long int atom) const
1 if every Cartesian axis of the atom is fixed, else 0.
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).
MatrixXd getHessian(Matter *matterIn, const VectorXi &atomsIn)
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.
io::IoStatus matter2con(std::string filename, bool append=false, const io::ConFrameMetadata *metadata=nullptr)
delta sigma(xi) between two minima, xi = (q - start) .
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
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 ¶ms, 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,...
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.
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....
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...
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.
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.
RAII resource manager for the ARTn C library with global synchronization.
JobResultProvenance provenanceForJob(const Parameters ¶ms)
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)
long maxIterations
L-BFGS iterations.
double forceTolerance
largest per-bead |dS/dq| / dtau, eV / (amu^0.5 Angstrom)
long beads
P: segments from one minimum to the other.
double betaHbarOmega
beta hbar omega of the stiffer end along the path; sets the imaginary time
double asymmetry
V(end) - V(start), eV.
std::vector< double > energies
V at every bead, eV.
double zeroMode
the eigenvalue det' leaves out
double action
(S - S_well) / hbar
bool symmetricEnough
beta |asymmetry| < 0.1: the propagator ratio reads delta0 only when the wells lie within a small frac...
double modeSeparation
The second smallest eigenvalue of J over the zero mode's: small means the kink is not isolated in ima...
double delta0
tunnelling splitting, eV
std::vector< VectorXd > path
P + 1 beads, ends at the minima.
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.
long beads
N, beads on the ring.
Where a ring sits against the saddle it was seeded from, in mass-weighted coordinates.
The atoms behind a ring's mass-weighted coordinates, for its rigid motions: sqrt(m) per atom,...
std::vector< double > sqrtMasses
Closed ring of beads samples of path whose imaginary-time period is betaHbar.