Loading...
Searching...
No Matches
LineIntegralNEB.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
6#pragma once
7#include <algorithm>
8#include <cmath>
9#include <limits>
10#include <stdexcept>
11
12#include "JacobiAction.h"
13#include "PotentialPath.h"
14
15namespace gpr::quantum {
16// Asgeirsson, Arnaldsson and Jonsson, JCP 148, 102334 (2018), Eqs. 10-22.
17// Coordinates, gradients and spring constants use the mass-weighted metric.
19 std::vector<Eigen::VectorXd> force;
20 std::vector<Eigen::VectorXd> actionForce;
24};
25namespace detail {
26inline Eigen::VectorXd lineIntegralUnitTangent(
27 const std::vector<Eigen::VectorXd>& q,
28 const std::vector<PotentialEvaluation>& values, std::size_t j)
29{
30 const double lower = values[j - 1].energy, current = values[j].energy,
31 upper = values[j + 1].energy;
32 Eigen::VectorXd tangent;
33 if (upper > current && current > lower)
34 tangent = q[j + 1] - q[j];
35 else if (upper < current && current < lower)
36 tangent = q[j] - q[j - 1];
37 else {
38 const double largest =
39 std::max(std::abs(upper - current), std::abs(lower - current));
40 const double smallest =
41 std::min(std::abs(upper - current), std::abs(lower - current));
42 if (largest == 0)
43 tangent = q[j + 1] - q[j - 1];
44 else if (upper > lower)
45 tangent =
46 (q[j + 1] - q[j]) + (smallest / largest) * (q[j] - q[j - 1]);
47 else
48 tangent =
49 (smallest / largest) * (q[j + 1] - q[j]) + (q[j] - q[j - 1]);
50 }
51 const double norm = tangent.norm();
52 if (!(norm > 0) || !std::isfinite(norm))
53 throw std::domain_error("A finite nonzero LI-NEB tangent is required");
54 return tangent / norm;
55}
56inline std::vector<Eigen::VectorXd> lineIntegralENOTangents(
57 const std::vector<Eigen::VectorXd>& q,
58 const std::vector<PotentialEvaluation>& values, std::size_t order = 3)
59{
60 const std::size_t n = q.size();
61 order = std::min(order, n - 1);
62 if (order < 1)
63 return std::vector<Eigen::VectorXd>(
64 n, Eigen::VectorXd::Zero(q.front().size()));
65 std::vector<double> alpha(n, 0.);
66 for (std::size_t i = 1; i < n; ++i)
67 alpha[i] = alpha[i - 1] + (q[i] - q[i - 1]).norm();
68 if (!(alpha.back() > 0) || !std::isfinite(alpha.back()))
69 throw std::domain_error(
70 "ENO tangent requires a finite nonzero path length");
71 for (double& x: alpha)
72 x /= alpha.back();
73 std::vector<std::vector<Eigen::VectorXd>> dd(
74 order + 1, std::vector<Eigen::VectorXd>(
75 n, Eigen::VectorXd::Zero(q.front().size())));
76 dd[0] = q;
77 for (std::size_t l = 1; l <= order; ++l)
78 for (std::size_t i = 0; i + l < n; ++i)
79 dd[l][i] =
80 (dd[l - 1][i + 1] - dd[l - 1][i]) / (alpha[i + l] - alpha[i]);
81 std::vector<Eigen::VectorXd> intervalDerivative(
82 n, Eigen::VectorXd::Zero(q.front().size()));
83 for (std::size_t i = 0; i + 1 < n; ++i) {
84 std::vector<Eigen::VectorXd> coefficient(
85 order + 1, Eigen::VectorXd::Zero(q.front().size()));
86 coefficient[0] = q[i] - alpha[i] * dd[1][i];
87 coefficient[1] = dd[1][i];
88 std::size_t k = i;
89 for (std::size_t l = 2; l <= order; ++l) {
90 const auto a = dd[l][k];
91 Eigen::VectorXd c;
92 std::size_t next = k;
93 if (k == 0)
94 c = a;
95 else if (k + l > n - 1) {
96 c = dd[l][k - 1];
97 next = k - 1;
98 } else {
99 const auto b = dd[l][k - 1];
100 if (a.norm() > b.norm()) {
101 c = b;
102 next = k - 1;
103 } else
104 c = a;
105 }
106 std::vector<double> product{1.};
107 for (std::size_t m = k; m < k + l; ++m) {
108 std::vector<double> expanded(product.size() + 1, 0.);
109 for (std::size_t p = 0; p < product.size(); ++p) {
110 expanded[p] -= alpha[m] * product[p];
111 expanded[p + 1] += product[p];
112 }
113 product = std::move(expanded);
114 }
115 for (std::size_t p = 0; p < product.size(); ++p)
116 coefficient[p] += product[p] * c;
117 k = next;
118 }
119 Eigen::VectorXd derivative = Eigen::VectorXd::Zero(q.front().size());
120 double power = 1.;
121 for (std::size_t p = 1; p < coefficient.size(); ++p) {
122 derivative += double(p) * power * coefficient[p];
123 power *= alpha[i];
124 }
125 intervalDerivative[i] = derivative;
126 }
127 intervalDerivative.back() = intervalDerivative[n - 2];
128 auto tangent = intervalDerivative;
129 for (std::size_t j = 1; j + 1 < n; ++j) {
130 const auto d1 = intervalDerivative[j - 1], d2 = intervalDerivative[j];
131 Eigen::VectorXd selected;
132 const double before = values[j - 1].energy, current = values[j].energy,
133 after = values[j + 1].energy;
134 if (after < current && current < before)
135 selected = d1;
136 else if (before <= current && current <= after)
137 selected = d2;
138 else {
139 const double largest =
140 std::max(std::abs(after - current), std::abs(before - current));
141 const double smallest =
142 std::min(std::abs(after - current), std::abs(before - current));
143 if (largest == 0)
144 selected = d1 + d2;
145 else if (after >= before)
146 selected = d2 * largest + d1 * smallest;
147 else
148 selected = d2 * smallest + d1 * largest;
149 }
150 const double norm = selected.norm();
151 if (!(norm > 0) || !std::isfinite(norm))
152 throw std::domain_error("ENO tangent is singular");
153 tangent[j] = selected / norm;
154 }
155 return tangent;
156}
157} // namespace detail
160 const std::vector<Eigen::VectorXd>& q,
161 const std::vector<PotentialEvaluation>& values, double energy,
162 double spring = 1., double contour = 10., double hbar = 1.,
164 bool jctcCompatible = false, double contourRight = 0.,
165 double actionForceCutoff = 1e-4)
166{
169 throw std::invalid_argument("Unknown LI-NEB action quadrature");
170 if (jctcCompatible && action != LineIntegralAction::MomentumTrapezoid)
171 throw std::invalid_argument(
172 "JCTC LI-NEB requires momentum-trapezoid action");
173 const std::size_t n = q.size();
174 if (n < 3 || values.size() != n || q.front().size() < 1 ||
175 !std::isfinite(energy) || !(spring > 0) || !(contour > 0) ||
176 !(hbar > 0) || !std::isfinite(spring) || !std::isfinite(contour) ||
177 !std::isfinite(hbar))
178 throw std::invalid_argument(
179 "Finite LI-NEB parameters and at least three matching images "
180 "required");
181 std::vector<double> xi(n), length(n - 1);
182 for (std::size_t j = 0; j < n; ++j) {
183 if (q[j].size() != q.front().size() ||
184 values[j].gradient.size() != q.front().size() ||
185 !q[j].allFinite() || !values[j].gradient.allFinite() ||
186 !std::isfinite(values[j].energy))
187 throw std::invalid_argument(
188 "Finite matching mass-coordinate energies and gradients "
189 "required");
190 if (j && j + 1 < n && !jctcCompatible) {
191 if (!(values[j].energy > energy))
192 throw std::domain_error(
193 "Interior LI-NEB image leaves the forbidden region");
194 }
195 xi[j] = std::sqrt(2 * std::max(0., values[j].energy - energy)) / hbar;
196 if (j) {
197 length[j - 1] = (q[j] - q[j - 1]).norm();
198 if (!(length[j - 1] > 0) || !std::isfinite(length[j - 1]))
199 throw std::domain_error(
200 "Distinct finite adjacent LI-NEB images required");
201 }
202 }
204 out.turningOrientationsQualified = true;
205 out.force.resize(n);
206 out.actionForce.assign(n, Eigen::VectorXd::Zero(q.front().size()));
209 auto contourValues = values;
210 contourValues.front().energy = energy;
211 contourValues.back().energy = energy;
212 exact = evaluateJacobiPath(q, contourValues, energy);
213 out.abbreviatedAction = exact.action;
214 } else {
215 for (std::size_t j = 0; j + 1 < n; ++j)
216 out.abbreviatedAction +=
217 .5 * hbar * (xi[j] + xi[j + 1]) * length[j];
218 }
219 const auto tangents = jctcCompatible
220 ? detail::lineIntegralENOTangents(q, values)
221 : std::vector<Eigen::VectorXd>{};
222 for (std::size_t j = 1; j + 1 < n; ++j) {
223 const Eigen::VectorXd left = (q[j] - q[j - 1]) / length[j - 1];
224 const Eigen::VectorXd right = (q[j + 1] - q[j]) / length[j];
225 const Eigen::VectorXd tangent =
226 jctcCompatible ? tangents[j]
227 : detail::lineIntegralUnitTangent(q, values, j);
228 Eigen::VectorXd actionForce;
230 actionForce = -exact.gradient[j] / hbar;
231 else {
232 const double gap = values[j].energy - energy;
233 Eigen::VectorXd potentialForce =
234 Eigen::VectorXd::Zero(q.front().size());
235 if (!jctcCompatible || gap >= actionForceCutoff)
236 potentialForce = -.5 * (length[j - 1] + length[j]) /
237 (hbar * hbar * xi[j]) * values[j].gradient;
238 actionForce = potentialForce - .5 * (xi[j] + xi[j - 1]) * left +
239 .5 * (xi[j + 1] + xi[j]) * right;
240 }
241 out.actionForce[j] = actionForce;
242 }
243 std::vector<Eigen::VectorXd> smoothed = out.actionForce;
244 if (jctcCompatible) {
245 std::vector<double> amplitude(n, 0.);
246 for (std::size_t j = 1; j + 1 < n; ++j)
247 amplitude[j] = out.actionForce[j].norm();
248 for (std::size_t j = 1; j + 1 < n; ++j) {
249 const std::size_t first = j > 1 ? j - 1 : 1,
250 last = std::min(j + 1, n - 2);
251 double mean = 0.;
252 for (std::size_t k = first; k <= last; ++k)
253 mean += amplitude[k];
254 mean /= double(last - first + 1);
255 if (amplitude[j] > 0)
256 smoothed[j] *= mean / amplitude[j];
257 else
258 smoothed[j].setZero();
259 const Eigen::VectorXd tangent = tangents[j];
260 const Eigen::VectorXd rawTransverse =
261 out.actionForce[j] - out.actionForce[j].dot(tangent) * tangent;
262 out.transverseForceSum += rawTransverse.norm();
263 out.force[j] = smoothed[j] - smoothed[j].dot(tangent) * tangent +
264 spring * (length[j] - length[j - 1]) * tangent;
265 }
266 } else {
267 for (std::size_t j = 1; j + 1 < n; ++j) {
268 const Eigen::VectorXd tangent =
269 detail::lineIntegralUnitTangent(q, values, j);
270 const Eigen::VectorXd raw = out.actionForce[j];
271 out.force[j] = raw - raw.dot(tangent) * tangent +
272 spring * (length[j] - length[j - 1]) * tangent;
273 out.transverseForceSum += (raw - raw.dot(tangent) * tangent).norm();
274 }
275 }
276 for (const std::size_t j: {std::size_t(0), n - 1}) {
277 const double norm = values[j].gradient.norm();
278 if (!(norm > 0))
279 throw std::domain_error(
280 "Turning contour requires a nonzero endpoint gradient");
281 const Eigen::VectorXd normal = values[j].gradient / norm;
282 const std::size_t adjacent = j == 0 ? 1 : n - 2;
283 const Eigen::VectorXd direction =
284 (q[adjacent] - q[j]) / (q[adjacent] - q[j]).norm();
285 Eigen::VectorXd pull;
286 if (jctcCompatible) {
287 pull = direction * smoothed[adjacent].norm();
288 } else
289 pull = spring * (q[j == 0 ? 1 : n - 2] - q[j]);
290 out.turningOrientationsQualified =
291 out.turningOrientationsQualified && normal.dot(direction) > 0;
292 // Knarr's contour endpoint uses force/|force|, hence this minus sign
293 // with the positive energy gradient drives V towards E on either side.
294 const double endpointContour =
295 j == 0 || contourRight == 0. ? contour : contourRight;
296 out.force[j] = pull - pull.dot(normal) * normal -
297 endpointContour * (values[j].energy - energy) * normal;
298 out.endpointEnergyError = std::max(out.endpointEnergyError,
299 std::abs(values[j].energy - energy));
300 }
301 for (const auto& f: out.force) {
302 if (!f.allFinite()) throw std::runtime_error("Nonfinite LI-NEB force");
303 out.maximumForce = std::max(out.maximumForce, f.norm());
304 }
305 return out;
306}
307
322// This positive normal/tangent metric changes search dynamics while preserving
323// the raw LI-NEB fixed points and all native convergence diagnostics.
324inline std::vector<Eigen::VectorXd> lineIntegralSearchForces(
325 const std::vector<Eigen::VectorXd>& q,
326 const std::vector<PotentialEvaluation>& values,
327 const LineIntegralNEBState& state, const LineIntegralNEBOptions& options)
328{
329 if (q.size() < 3 || values.size() != q.size() ||
330 state.force.size() != q.size())
331 throw std::invalid_argument(
332 "Matching LI-NEB search force nodes required");
333 const auto dimension = q.front().size();
334 for (std::size_t j = 0; j < q.size(); ++j)
335 if (dimension < 1 || q[j].size() != dimension ||
336 state.force[j].size() != dimension || !q[j].allFinite() ||
337 !state.force[j].allFinite() || !std::isfinite(values[j].energy))
338 throw std::invalid_argument(
339 "Finite matching LI-NEB search vectors required");
340 auto result = state.force;
341 if (!options.geometricPreconditioning) return result;
342 if (!(options.hbar > 0) || !std::isfinite(options.hbar) ||
343 !std::isfinite(options.energy))
344 throw std::invalid_argument(
345 "Finite positive LI-NEB search units required");
346 for (std::size_t j = 1; j + 1 < q.size(); ++j) {
347 const double length =
348 .5 * ((q[j] - q[j - 1]).norm() + (q[j + 1] - q[j]).norm());
349 const double scale =
350 options.hbar * std::sqrt(2 * (values[j].energy - options.energy)) /
351 length;
352 if (!(scale > 0) || !std::isfinite(scale))
353 throw std::domain_error(
354 "A resolved positive LI-NEB normal search scale is required");
355 const Eigen::VectorXd tangent =
356 detail::lineIntegralUnitTangent(q, values, j);
357 const Eigen::VectorXd parallel = tangent.dot(state.force[j]) * tangent;
358 result[j] = scale * (state.force[j] - parallel) + parallel;
359 if (!result[j].allFinite())
360 throw std::runtime_error(
361 "Nonfinite geometrically conditioned LI-NEB search force");
362 }
363 return result;
364}
366 std::vector<Eigen::VectorXd> path;
367 std::vector<PotentialEvaluation> native;
371 std::string failure;
372};
374 std::vector<Eigen::VectorXd> velocity;
376 std::size_t positiveSteps{}, negativeSteps{}, steps{};
378};
379using LineIntegralNEBBatch = std::function<std::vector<PotentialEvaluation>(
380 const std::vector<Eigen::VectorXd>&)>;
385// Native normal corrections restore trial interiors that cross V=E.
386// Only moved points are evaluated; every retained value belongs to its node.
388 std::vector<Eigen::VectorXd>& trial,
389 std::vector<PotentialEvaluation>& values,
390 const std::vector<PotentialEvaluation>& source,
391 const LineIntegralNEBOptions& options, const LineIntegralNEBBatch& native,
392 std::size_t maximumCorrections = 4)
393{
394 if (trial.size() < 3 || values.size() != trial.size() ||
395 source.size() != trial.size() || !native ||
396 !(options.maximumStep > 0) || !std::isfinite(options.maximumStep) ||
397 !(options.energyTolerance > 0) ||
398 !std::isfinite(options.energyTolerance) ||
399 !std::isfinite(options.energy))
400 throw std::invalid_argument(
401 "Matching native LI-NEB trial, source and finite restoration "
402 "controls required");
404 for (std::size_t iteration = 0; iteration <= maximumCorrections;
405 ++iteration) {
406 std::vector<Eigen::VectorXd> probes;
407 std::vector<std::size_t> indices;
408 for (std::size_t j = 1; j + 1 < trial.size(); ++j) {
409 if (!(source[j].energy > options.energy) ||
410 !std::isfinite(source[j].energy) ||
411 !std::isfinite(values[j].energy) ||
412 values[j].gradient.size() != trial[j].size() ||
413 !values[j].gradient.allFinite() || !trial[j].allFinite())
414 throw std::invalid_argument(
415 "Finite native interiors and a feasible source required");
416 if (values[j].energy > options.energy) continue;
417 if (iteration == maximumCorrections) return result;
418 const double norm2 = values[j].gradient.squaredNorm();
419 if (!(norm2 > 0) || !std::isfinite(norm2)) return result;
420 const double margin =
421 std::max(4 * options.energyTolerance,
422 .1 * (source[j].energy - options.energy));
423 Eigen::VectorXd step =
424 ((options.energy + margin - values[j].energy) / norm2) *
425 values[j].gradient;
426 const double length = step.norm();
427 if (!std::isfinite(length)) return result;
428 if (length > options.maximumStep)
429 step *= options.maximumStep / length;
430 probes.push_back(trial[j] + step);
431 indices.push_back(j);
432 }
433 if (indices.empty()) {
434 result.feasible = true;
435 return result;
436 }
437 const auto returned = native(probes);
438 ++result.batchEvaluations;
439 result.pointEvaluations += probes.size();
440 if (returned.size() != probes.size())
441 throw std::runtime_error(
442 "Native interior correction batch shape differs");
443 for (std::size_t k = 0; k < indices.size(); ++k)
444 if (!std::isfinite(returned[k].energy) ||
445 returned[k].gradient.size() != probes[k].size() ||
446 !returned[k].gradient.allFinite())
447 throw std::runtime_error(
448 "Native interior correction has no finite matching return");
449 for (std::size_t k = 0; k < indices.size(); ++k) {
450 trial[indices[k]] = probes[k];
451 values[indices[k]] = returned[k];
452 }
453 }
454 return result;
455}
457 const std::vector<Eigen::VectorXd>& initial,
458 const LineIntegralNEBBatch& potential,
459 const LineIntegralNEBOptions& options = {},
460 const std::function<void(const LineIntegralNEBResult&)>& retain = {},
461 LineIntegralFIREState* fireState = nullptr,
462 const std::function<bool(const std::vector<Eigen::VectorXd>&)>& earlyStop =
463 {})
464{
465 if (!potential || initial.size() < 3 || !(options.timeStep > 0) ||
466 !(options.maximumTimeStep >= options.timeStep) ||
467 !(options.maximumStep > 0) || !(options.forceTolerance > 0) ||
468 !(options.energyTolerance > 0) ||
469 !(options.initialMixing >= 0 && options.initialMixing <= 1) ||
470 !(options.minimumTimeStep >= 0 &&
471 options.minimumTimeStep <= options.timeStep) ||
472 !std::isfinite(options.initialMixing) ||
473 !std::isfinite(options.minimumTimeStep) ||
474 !std::isfinite(options.maximumTimeStep) ||
475 !std::isfinite(options.maximumStep) ||
476 !std::isfinite(options.forceTolerance) ||
477 !std::isfinite(options.energyTolerance) ||
478 !(options.actionForceCutoff >= 0) ||
479 !std::isfinite(options.actionForceCutoff) ||
480 !(options.endpointEnergyConvergeValue > 0) ||
481 !std::isfinite(options.endpointEnergyConvergeValue) ||
482 !(options.endpointGradientTolerance > 0) ||
483 !std::isfinite(options.endpointGradientTolerance) ||
484 !(options.transverseForceSumTolerance > 0) ||
485 !std::isfinite(options.transverseForceSumTolerance) ||
486 !(options.springForceFloor > 0) ||
487 !std::isfinite(options.springForceFloor) ||
488 !options.constraintUpdateInterval)
489 throw std::invalid_argument(
490 "Finite positive LI-NEB search controls required");
492 result.path = initial;
493 auto evaluate = [&](const auto& p) {
494 ++result.batchEvaluations;
495 result.evaluations += p.size();
496 return potential(p);
497 };
498 LineIntegralNEBOptions active = options;
499 auto state = [&](const auto& p, const auto& v) {
501 p, v, active.energy, active.spring, active.contour, active.hbar,
502 active.action, active.jctcCompatible, active.contourRight,
503 active.actionForceCutoff);
504 };
505 std::vector<Eigen::VectorXd> velocity(
506 initial.size(), Eigen::VectorXd::Zero(initial.front().size()));
507 double dt = options.timeStep, alpha = options.initialMixing;
508 std::size_t positive = 0, negative = 0, totalSteps = 0;
509 if (fireState && fireState->initialized) {
510 if (fireState->velocity.size() != initial.size() ||
511 !(fireState->timeStep > 0) || !std::isfinite(fireState->timeStep) ||
512 !(fireState->mixing >= 0 && fireState->mixing <= 1) ||
513 !std::isfinite(fireState->mixing))
514 throw std::invalid_argument(
515 "Finite matching LI-NEB FIRE state required");
516 for (std::size_t j = 0; j < initial.size(); ++j)
517 if (fireState->velocity[j].size() != initial.front().size() ||
518 !fireState->velocity[j].allFinite())
519 throw std::invalid_argument(
520 "Matching finite LI-NEB FIRE velocities required");
521 velocity = fireState->velocity;
522 dt = std::min(fireState->timeStep, options.maximumTimeStep);
523 if (options.minimumTimeStep > 0)
524 dt = std::max(dt, options.minimumTimeStep);
525 alpha = fireState->mixing;
526 positive = fireState->positiveSteps;
527 negative = fireState->negativeSteps;
528 totalSteps = fireState->steps;
529 if (options.jctcCompatible && fireState->constraintsInitialized) {
530 active.spring = fireState->spring;
531 active.contour = fireState->contourLeft;
532 active.contourRight = fireState->contourRight;
533 }
534 }
535 auto saveFireState = [&] {
536 if (!fireState) return;
537 fireState->velocity = velocity;
538 fireState->timeStep = dt;
539 fireState->mixing = alpha;
540 fireState->positiveSteps = positive;
541 fireState->negativeSteps = negative;
542 fireState->steps = totalSteps;
543 fireState->spring = active.spring;
544 fireState->contourLeft = active.contour;
545 fireState->contourRight = active.contourRight;
546 fireState->constraintsInitialized = options.jctcCompatible;
547 fireState->initialized = true;
548 };
549 result.native = evaluate(result.path);
550 result.state = state(result.path, result.native);
551 auto adaptJctcConstraints = [&] {
552 if (!options.jctcCompatible) return;
553 double pathLength = 0.;
554 for (std::size_t j = 1; j < result.path.size(); ++j)
555 pathLength += (result.path[j] - result.path[j - 1]).norm();
556 double averageActionForce = 0.;
557 for (std::size_t j = 1; j + 1 < result.state.actionForce.size(); ++j)
558 averageActionForce += result.state.actionForce[j].norm();
559 averageActionForce /= double(result.state.actionForce.size() - 2);
560 averageActionForce =
561 std::max(averageActionForce, options.springForceFloor);
562 active.spring = averageActionForce /
563 (pathLength / (10. * double(result.path.size())));
564 auto endpointKappa = [&](std::size_t j) {
565 const double maxForce =
566 std::max(1e-3, result.native[j].gradient.cwiseAbs().maxCoeff());
567 double kappa = .2 / (maxForce * dt * dt);
568 if (std::abs(result.native[j].energy - options.energy) <
569 options.endpointEnergyConvergeValue) {
570 const double cap = .2 * options.endpointGradientTolerance /
571 options.endpointEnergyConvergeValue;
572 kappa = std::min(kappa, cap);
573 }
574 return kappa;
575 };
576 active.contour = endpointKappa(0);
577 active.contourRight = endpointKappa(result.path.size() - 1);
578 };
579 auto searchForce = lineIntegralSearchForces(result.path, result.native,
580 result.state, active);
581 const bool storedConstraints = fireState && fireState->initialized &&
582 fireState->constraintsInitialized &&
583 options.jctcCompatible;
584 if (!storedConstraints) adaptJctcConstraints();
585 result.state = state(result.path, result.native);
586 searchForce = lineIntegralSearchForces(result.path, result.native,
587 result.state, active);
588 for (std::size_t iteration = 0; iteration <= options.maximumIterations;
589 ++iteration) {
590 result.iterations = iteration;
591 if (retain) retain(result);
592 const bool forceCriteria =
593 result.state.maximumForce < options.forceTolerance &&
594 (!options.jctcCompatible ||
595 result.state.transverseForceSum <
596 options.transverseForceSumTolerance);
597 const bool contourCriteria =
598 options.jctcCompatible ||
599 result.state.endpointEnergyError < options.energyTolerance;
600 if (earlyStop && earlyStop(result.path)) {
601 result.trustRegionExit = true;
602 result.failure = "LI-NEB native trust region exited";
603 saveFireState();
604 return result;
605 }
606 if (forceCriteria && contourCriteria) {
607 if (!result.state.turningOrientationsQualified) {
608 result.failure =
609 "LI-NEB turning orientation does not enter the forbidden "
610 "region";
611 saveFireState();
612 return result;
613 }
614 result.converged = true;
615 saveFireState();
616 return result;
617 }
618 if (iteration == options.maximumIterations) break;
619 if (options.jctcCompatible && totalSteps > 0 &&
620 totalSteps % options.constraintUpdateInterval == 0) {
621 adaptJctcConstraints();
622 result.state = state(result.path, result.native);
623 searchForce = lineIntegralSearchForces(result.path, result.native,
624 result.state, active);
625 }
626 auto base = result.path;
627 auto trial = base;
628 std::vector<Eigen::VectorXd> step(initial.size());
629 double scale = 1.;
630 if (options.jctcCompatible) {
631 double power = 0., velocitySquared = 0., forceSquared = 0.;
632 for (std::size_t j = 0; j < trial.size(); ++j) {
633 power += velocity[j].dot(searchForce[j]);
634 velocitySquared += velocity[j].squaredNorm();
635 forceSquared += searchForce[j].squaredNorm();
636 }
637 if (power > 0.) {
638 ++positive;
639 negative = 0;
640 if (positive > 5) {
641 dt = std::min(dt * 1.1, options.maximumTimeStep);
642 alpha *= .99;
643 }
644 } else {
645 positive = 0;
646 ++negative;
647 if (negative > 100) {
648 result.failure =
649 "LI-NEB FIRE exceeded the uphill-step limit";
650 saveFireState();
651 return result;
652 }
653 dt = options.minimumTimeStep > 0
654 ? std::max(dt * .5, options.minimumTimeStep)
655 : dt * .5;
656 alpha = options.initialMixing;
657 for (std::size_t j = 0; j < trial.size(); ++j) {
658 base[j] -= .5 * dt * velocity[j];
659 velocity[j].setZero();
660 }
661 }
662 for (std::size_t j = 0; j < trial.size(); ++j)
663 velocity[j] += dt * searchForce[j];
664 if (power > 0. && forceSquared > 0.) {
665 velocitySquared = 0.;
666 for (const auto& v: velocity)
667 velocitySquared += v.squaredNorm();
668 const double velocityNorm = std::sqrt(velocitySquared);
669 const double forceNorm = std::sqrt(forceSquared);
670 for (std::size_t j = 0; j < trial.size(); ++j)
671 velocity[j] =
672 (1. - alpha) * velocity[j] +
673 alpha * velocityNorm / forceNorm * searchForce[j];
674 }
675 double displacementSquared = 0.;
676 for (std::size_t j = 0; j < trial.size(); ++j) {
677 step[j] = dt * velocity[j];
678 displacementSquared += step[j].squaredNorm();
679 }
680 const double displacementNorm = std::sqrt(displacementSquared);
681 if (displacementNorm > options.maximumStep)
682 scale = options.maximumStep / displacementNorm;
683 } else {
684 double largest = 0.;
685 for (std::size_t j = 0; j < trial.size(); ++j) {
686 step[j] = dt * velocity[j] + .5 * dt * dt * searchForce[j];
687 largest = std::max(largest, step[j].norm());
688 }
689 scale = largest > options.maximumStep
690 ? options.maximumStep / largest
691 : 1.;
692 }
693 std::vector<PotentialEvaluation> next;
694 LineIntegralNEBState nextState;
695 bool accepted = false;
696 double fraction = scale;
697 const int maximumBacktracks = options.jctcCompatible ? 1 : 24;
698 for (int backtrack = 0; backtrack < maximumBacktracks; ++backtrack) {
699 for (std::size_t j = 0; j < trial.size(); ++j)
700 trial[j] = base[j] + fraction * step[j];
701 next = evaluate(trial);
702 try {
703 nextState = state(trial, next);
704 accepted = true;
705 break;
706 } catch (const std::domain_error&) {
707 fraction *= .5;
708 }
709 }
710 if (!accepted) {
711 result.failure =
712 "No admissible LI-NEB step in the forbidden region";
713 saveFireState();
714 return result;
715 }
716 auto nextSearchForce =
717 lineIntegralSearchForces(trial, next, nextState, active);
718 if (!options.jctcCompatible) {
719 double power = 0., vv = 0., ff = 0.;
720 for (std::size_t j = 0; j < trial.size(); ++j) {
721 velocity[j] += .5 * dt * (searchForce[j] + nextSearchForce[j]);
722 power += velocity[j].dot(nextSearchForce[j]);
723 vv += velocity[j].squaredNorm();
724 ff += nextSearchForce[j].squaredNorm();
725 }
726 if (power > 0 && fraction == scale) {
727 ++positive;
728 if (ff > 0)
729 for (std::size_t j = 0; j < trial.size(); ++j)
730 velocity[j] =
731 (1 - alpha) * velocity[j] +
732 alpha * std::sqrt(vv / ff) * nextSearchForce[j];
733 if (positive > 5) {
734 dt = std::min(dt * 1.1, options.maximumTimeStep);
735 alpha *= .99;
736 }
737 } else {
738 positive = 0;
739 dt = options.minimumTimeStep > 0
740 ? std::max(options.minimumTimeStep, dt * .5)
741 : dt * .5;
742 alpha = options.initialMixing;
743 for (auto& v: velocity)
744 v.setZero();
745 }
746 }
747 result.path = std::move(trial);
748 result.native = std::move(next);
749 result.state = std::move(nextState);
750 searchForce = std::move(nextSearchForce);
751 ++totalSteps;
752 if (!(dt > std::numeric_limits<double>::epsilon())) {
753 result.failure = "LI-NEB time step underflows";
754 saveFireState();
755 return result;
756 }
757 }
758 result.failure = "LI-NEB iteration limit";
759 saveFireState();
760 return result;
761}
762
765 std::vector<Eigen::VectorXd> ring;
766};
767// Linear-potential links integrate both action and imaginary time exactly.
768// The two turning energies are checked, then projected to E within tolerance.
770 double energy, std::size_t beads,
771 double hbar = 1.,
772 double boltzmann = 1.,
773 double tolerance = 1e-8)
774{
775 if (!result.converged || beads < 4 || beads % 2 || !(hbar > 0) ||
776 !(boltzmann > 0) || !std::isfinite(hbar) || !std::isfinite(boltzmann) ||
777 !(tolerance > 0) || !std::isfinite(tolerance) ||
778 !std::isfinite(energy) || result.path.size() < 3 ||
779 result.native.size() != result.path.size())
780 throw std::invalid_argument(
781 "Qualified LI-NEB path, positive constants and even bead count "
782 "required");
783 auto values = result.native;
784 for (auto j: {std::size_t(0), values.size() - 1}) {
785 if (std::abs(values[j].energy - energy) > tolerance)
786 throw std::domain_error("LI-NEB turning energy is not qualified");
787 const auto neighbour = j == 0 ? std::size_t(1) : values.size() - 2;
788 if (result.path[j].size() < 1 ||
789 result.path[neighbour].size() != result.path[j].size() ||
790 values[j].gradient.size() != result.path[j].size() ||
791 !values[j].gradient.allFinite() || !result.path[j].allFinite() ||
792 !result.path[neighbour].allFinite())
793 throw std::invalid_argument(
794 "Finite matching LI-NEB turning coordinates and gradients "
795 "required");
796 if (!(values[j].gradient.dot(result.path[neighbour] - result.path[j]) >
797 0))
798 throw std::domain_error(
799 "LI-NEB turning orientation does not enter the forbidden "
800 "region");
801 values[j].energy = energy;
802 }
803 std::vector<double> cumulative{0.};
805 for (std::size_t j = 0; j + 1 < values.size(); ++j) {
806 const auto link = jacobiSegment(result.path[j], result.path[j + 1],
807 values[j], values[j + 1], energy);
808 cumulative.push_back(cumulative.back() + link.traversalTime);
809 out.abbreviatedAction += 2 * link.action;
810 }
811 out.period = 2 * cumulative.back();
812 out.temperature = hbar / (boltzmann * out.period);
813 out.euclideanAction = out.abbreviatedAction + energy * out.period;
814 for (std::size_t bead = 0; bead < beads; ++bead) {
815 const double t =
816 out.period * double(std::min(bead, beads - bead)) / double(beads);
817 std::size_t j =
818 std::upper_bound(cumulative.begin(), cumulative.end(), t) -
819 cumulative.begin() - 1;
820 j = std::min(j, values.size() - 2);
821 const double u = std::clamp(
822 (t - cumulative[j]) / (cumulative[j + 1] - cumulative[j]), 0., 1.);
823 const double a = std::sqrt(values[j].energy - energy),
824 b = std::sqrt(values[j + 1].energy - energy);
825 const double fraction = u * (2 * a + (b - a) * u) / (a + b);
826 out.ring.push_back((1 - fraction) * result.path[j] +
827 fraction * result.path[j + 1]);
828 }
829 return out;
830}
831} // namespace gpr::quantum
@ x
Definition Enums.h:28
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
Models for quantum-path (instanton) searches: arc and tail actions, amplitude continuation.
std::function< std::vector< PotentialEvaluation >( const std::vector< Eigen::VectorXd > &)> LineIntegralNEBBatch
LineIntegralFeasibilityResult restoreLineIntegralInterior(std::vector< Eigen::VectorXd > &trial, std::vector< PotentialEvaluation > &values, const std::vector< PotentialEvaluation > &source, const LineIntegralNEBOptions &options, const LineIntegralNEBBatch &native, std::size_t maximumCorrections=4)
LineIntegralNEBResult optimizeLineIntegralNEB(const std::vector< Eigen::VectorXd > &initial, const LineIntegralNEBBatch &potential, const LineIntegralNEBOptions &options={}, const std::function< void(const LineIntegralNEBResult &)> &retain={}, LineIntegralFIREState *fireState=nullptr, const std::function< bool(const std::vector< Eigen::VectorXd > &)> &earlyStop={})
JacobiPathEvaluation evaluateJacobiPath(const std::vector< Eigen::VectorXd > &points, const std::vector< PotentialEvaluation > &native, double energy)
JacobiSegment jacobiSegment(const Eigen::VectorXd &left, const Eigen::VectorXd &right, const PotentialEvaluation &vl, const PotentialEvaluation &vr, double energy)
LineIntegralOrbit lineIntegralOrbit(const LineIntegralNEBResult &result, double energy, std::size_t beads, double hbar=1., double boltzmann=1., double tolerance=1e-8)
std::vector< Eigen::VectorXd > lineIntegralSearchForces(const std::vector< Eigen::VectorXd > &q, const std::vector< PotentialEvaluation > &values, const LineIntegralNEBState &state, const LineIntegralNEBOptions &options)
LineIntegralNEBState evaluateLineIntegralNEB(const std::vector< Eigen::VectorXd > &q, const std::vector< PotentialEvaluation > &values, double energy, double spring=1., double contour=10., double hbar=1., LineIntegralAction action=LineIntegralAction::MomentumTrapezoid, bool jctcCompatible=false, double contourRight=0., double actionForceCutoff=1e-4)
VecchiaResult evaluate(const Eigen::MatrixXd &points, const Eigen::VectorXd &y, double lengthscale, double noise, int max_neighbours)
double forceNorm(const Eigen::MatrixBase< Derived > &force, ConvergenceNormType norm)
Definition ForceNorm.h:45
std::vector< Eigen::VectorXd > gradient
std::vector< Eigen::VectorXd > velocity
std::vector< Eigen::VectorXd > path
std::vector< PotentialEvaluation > native
std::vector< Eigen::VectorXd > force
std::vector< Eigen::VectorXd > actionForce
std::vector< Eigen::VectorXd > ring