Loading...
Searching...
No Matches
NEBPath.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "NEBPath.h"
6
7#include <algorithm>
8#include <cmath>
9#include <limits>
10#include <numeric>
11#include <stdexcept>
12#include <string>
13#include <utility>
14
15#include "RgsaddleClient.h"
19#include "gpr/dimer/Dimer.h"
21
22namespace gpr {
23namespace neb {
24
25double saddleForceMagnitude(const Eigen::VectorXd& gradient)
26{
27 const auto norm = gradient.size() % 3 == 0
30 return gpr::forceNorm(gradient, norm);
31}
32
33namespace {
34
35struct InverseDistanceSystem {
36 int n_atoms = 0;
37 Eigen::Index dof = 0;
38 std::vector<std::pair<int, int>> pairs;
39 std::vector<Eigen::Index> active_columns;
40 const gpr::geometry::PairBox* box = nullptr;
41
42 [[nodiscard]] Eigen::Vector3d pairVector(const Eigen::VectorXd& x, int a,
43 int b) const
44 {
45 const Eigen::Vector3d Ra = x.segment<3>(3 * a);
46 const Eigen::Vector3d Rb = x.segment<3>(3 * b);
47 if (box == nullptr || !box->periodic()) return Rb - Ra;
48 return box->displacement(Ra, Rb);
49 }
50
51 [[nodiscard]] Eigen::VectorXd values(const Eigen::VectorXd& x) const
52 {
53 Eigen::VectorXd q(static_cast<Eigen::Index>(pairs.size()));
54 for (Eigen::Index row = 0;
55 row < static_cast<Eigen::Index>(pairs.size()); ++row) {
56 const auto& pair = pairs[static_cast<std::size_t>(row)];
57 const Eigen::Vector3d d = pairVector(x, pair.first, pair.second);
58 // Numerical floor (not a physical parameter): keep 1/r finite for a
59 // near-coincident pair so the retraction can pull the collision
60 // back instead of aborting. A huge 1/r still signals the collapse
61 // to the Newton solve. Throwing here defeated the retraction's
62 // purpose and crashed Baker 05/23 whose bands transiently bring a
63 // pair to ~0.
64 const double r = std::max(d.norm(), 1.0e-10);
65 q(row) = 1.0 / r;
66 }
67 return q;
68 }
69
70 [[nodiscard]] Eigen::MatrixXd jacobianActive(const Eigen::VectorXd& x) const
71 {
72 Eigen::MatrixXd Jfull =
73 Eigen::MatrixXd::Zero(static_cast<Eigen::Index>(pairs.size()), dof);
74 for (Eigen::Index row = 0;
75 row < static_cast<Eigen::Index>(pairs.size()); ++row) {
76 const auto& pair = pairs[static_cast<std::size_t>(row)];
77 const int a = pair.first;
78 const int b = pair.second;
79 const Eigen::Vector3d d = pairVector(x, a, b);
80 // Numerical floor (see values()): keep 1/r^3 finite for a
81 // near-coincident pair so the retraction Jacobian stays defined.
82 const double r2 = std::max(d.squaredNorm(), 1.0e-20);
83 const double inv_r3 = 1.0 / (r2 * std::sqrt(r2));
84 const Eigen::Vector3d grad_a = inv_r3 * d;
85 Jfull.block<1, 3>(row, 3 * a) = grad_a.transpose();
86 Jfull.block<1, 3>(row, 3 * b) = -grad_a.transpose();
87 }
88
89 Eigen::MatrixXd J(Jfull.rows(),
90 static_cast<Eigen::Index>(active_columns.size()));
91 for (Eigen::Index col = 0;
92 col < static_cast<Eigen::Index>(active_columns.size()); ++col) {
93 J.col(col) =
94 Jfull.col(active_columns[static_cast<std::size_t>(col)]);
95 }
96 return J;
97 }
98};
99
100InverseDistanceSystem makeInverseDistanceSystem(
101 int n_atoms, Eigen::Index dof, const std::vector<char>& moving_atoms,
102 const gpr::geometry::PairBox* box)
103{
104 if (n_atoms < 2) {
105 throw std::invalid_argument(
106 "NEBPath inverse-distance geodesic requires at least two atoms");
107 }
108 if (dof != static_cast<Eigen::Index>(3 * n_atoms)) {
109 throw std::invalid_argument(
110 "NEBPath inverse-distance geodesic atom count does not match "
111 "coordinates");
112 }
113 if (!moving_atoms.empty() &&
114 static_cast<int>(moving_atoms.size()) != n_atoms) {
115 throw std::invalid_argument(
116 "NEBPath inverse-distance moving-atom mask size mismatch");
117 }
118
119 InverseDistanceSystem system;
120 system.n_atoms = n_atoms;
121 system.dof = dof;
122 system.box = box;
123 system.pairs.reserve(static_cast<std::size_t>(n_atoms * (n_atoms - 1) / 2));
124 for (int a = 0; a < n_atoms; ++a) {
125 const bool a_active =
126 moving_atoms.empty() || moving_atoms[static_cast<std::size_t>(a)];
127 if (a_active) {
128 for (int c = 0; c < 3; ++c) {
129 system.active_columns.push_back(3 * a + c);
130 }
131 }
132 for (int b = a + 1; b < n_atoms; ++b) {
133 const bool b_active = moving_atoms.empty() ||
134 moving_atoms[static_cast<std::size_t>(b)];
135 if (a_active || b_active) system.pairs.emplace_back(a, b);
136 }
137 }
138 if (system.pairs.empty() || system.active_columns.empty()) {
139 throw std::invalid_argument(
140 "NEBPath inverse-distance geodesic has no active atom pairs");
141 }
142 return system;
143}
144
145Eigen::VectorXd solveInverseDistanceTarget(const InverseDistanceSystem& system,
146 const Eigen::VectorXd& start,
147 const Eigen::VectorXd& target)
148{
149 Eigen::VectorXd x = start;
150 Eigen::VectorXd best = x;
151 const double target_scale = std::max(1.0, target.norm());
152 const double residual_tol =
153 std::numeric_limits<double>::epsilon() * target_scale *
154 std::max<double>(
155 1.0,
156 static_cast<double>(target.size() + system.active_columns.size()));
157 double best_residual = (system.values(x) - target).norm();
158 if (best_residual <= residual_tol) return best;
159
160 const int max_newton_steps =
161 std::max<int>(1, static_cast<int>(system.active_columns.size()));
162 for (int iter = 0; iter < max_newton_steps; ++iter) {
163 const Eigen::VectorXd q = system.values(x);
164 const Eigen::VectorXd residual = target - q;
165 if (residual.norm() <= residual_tol) return x;
166 const Eigen::MatrixXd J = system.jacobianActive(x);
167 Eigen::JacobiSVD<Eigen::MatrixXd> svd(
168 J, Eigen::ComputeThinU | Eigen::ComputeThinV);
169 const Eigen::VectorXd singular = svd.singularValues();
170 if (singular.size() == 0) break;
171 const double sigma_max = singular.cwiseAbs().maxCoeff();
172 if (!(sigma_max > 0.0) || !std::isfinite(sigma_max)) break;
173 const double sv_cutoff =
174 std::numeric_limits<double>::epsilon() *
175 static_cast<double>(std::max(J.rows(), J.cols())) * sigma_max;
176 Eigen::VectorXd scaled = svd.matrixU().transpose() * residual;
177 for (Eigen::Index i = 0; i < singular.size(); ++i) {
178 scaled(i) =
179 (singular(i) > sv_cutoff) ? scaled(i) / singular(i) : 0.0;
180 }
181 const Eigen::VectorXd delta_active = svd.matrixV() * scaled;
182 if (delta_active.size() !=
183 static_cast<Eigen::Index>(system.active_columns.size()) ||
184 !delta_active.allFinite() || delta_active.norm() == 0.0) {
185 break;
186 }
187
188 bool accepted = false;
189 double alpha = 1.0;
190 for (int ls = 0; ls < std::numeric_limits<double>::digits; ++ls) {
191 Eigen::VectorXd trial = x;
192 for (Eigen::Index col = 0; col < delta_active.size(); ++col) {
193 trial(system.active_columns[static_cast<std::size_t>(col)]) +=
194 alpha * delta_active(col);
195 }
196 if (!trial.allFinite()) {
197 alpha *= 0.5;
198 continue;
199 }
200 const double trial_residual =
201 (system.values(trial) - target).norm();
202 if (std::isfinite(trial_residual) &&
203 trial_residual < best_residual) {
204 x = trial;
205 best = trial;
206 best_residual = trial_residual;
207 accepted = true;
208 break;
209 }
210 alpha *= 0.5;
211 }
212 if (!accepted || best_residual <= residual_tol) break;
213 }
214 return best;
215}
216
217double spacingDeviationFromCumulativeArc(const std::vector<double>& s,
218 int anchor_index)
219{
220 const int N = static_cast<int>(s.size());
221 if (N < 3) return 0.0;
222 const bool keep_anchor = anchor_index > 0 && anchor_index < N - 1;
223 const double L = s[N - 1] - s[0];
224 if (L <= std::numeric_limits<double>::min()) return 0.0;
225 const double h = L / static_cast<double>(N - 1);
226 const double left_length = keep_anchor ? s[anchor_index] - s[0] : 0.0;
227 const double right_length = keep_anchor ? s[N - 1] - s[anchor_index] : 0.0;
228 const double left_h =
229 keep_anchor ? left_length / static_cast<double>(anchor_index) : h;
230 const double right_h =
231 keep_anchor ? right_length / static_cast<double>(N - 1 - anchor_index)
232 : h;
233 double max_dev = 0.0;
234 if (keep_anchor) {
235 if (left_h > std::numeric_limits<double>::min()) {
236 for (int i = 0; i < anchor_index; ++i) {
237 max_dev = std::max(
238 max_dev, std::abs((s[i + 1] - s[i]) - left_h) / left_h);
239 }
240 }
241 if (right_h > std::numeric_limits<double>::min()) {
242 for (int i = anchor_index; i < N - 1; ++i) {
243 max_dev = std::max(
244 max_dev, std::abs((s[i + 1] - s[i]) - right_h) / right_h);
245 }
246 }
247 return max_dev;
248 }
249 for (int i = 0; i < N - 1; ++i) {
250 max_dev = std::max(max_dev, std::abs((s[i + 1] - s[i]) - h) / h);
251 }
252 return max_dev;
253}
254
255double targetArcForImage(const std::vector<double>& s, int image_idx,
256 int anchor_index)
257{
258 const int N = static_cast<int>(s.size());
259 const bool keep_anchor = anchor_index > 0 && anchor_index < N - 1;
260 const double L = s[N - 1] - s[0];
261 if (!keep_anchor) {
262 return s[0] +
263 static_cast<double>(image_idx) * L / static_cast<double>(N - 1);
264 }
265 if (image_idx < anchor_index) {
266 const double left_length = s[anchor_index] - s[0];
267 return s[0] + static_cast<double>(image_idx) * left_length /
268 static_cast<double>(anchor_index);
269 }
270 const double right_length = s[N - 1] - s[anchor_index];
271 return s[anchor_index] + static_cast<double>(image_idx - anchor_index) *
272 right_length /
273 static_cast<double>(N - 1 - anchor_index);
274}
275
276// Cumulative rest-length fractions of this arc, renormalised on each side of
277// an anchor so the anchor stays put. Empty when the lengths cannot be used.
278std::vector<double> restLengthSegmentTargets(
279 const std::vector<double>& s, const std::vector<double>& rest_lengths,
280 int anchor_index)
281{
282 const int N = static_cast<int>(s.size());
283 if (N < 2 || static_cast<int>(rest_lengths.size()) != N - 1) return {};
284 double total = 0.0;
285 for (double rest: rest_lengths)
286 total += rest;
287 if (!(total > 0.0) || !std::isfinite(total)) return {};
288
289 std::vector<double> fraction(static_cast<std::size_t>(N), 0.0);
290 for (int i = 1; i < N; ++i) {
291 fraction[static_cast<std::size_t>(i)] =
292 fraction[static_cast<std::size_t>(i - 1)] +
293 rest_lengths[static_cast<std::size_t>(i - 1)] / total;
294 }
295 fraction[static_cast<std::size_t>(N - 1)] = 1.0;
296
297 const bool keep_anchor = anchor_index > 0 && anchor_index < N - 1;
298 const double arc_length = s[static_cast<std::size_t>(N - 1)] - s[0];
299 std::vector<double> target(static_cast<std::size_t>(N - 1), 0.0);
300 if (!keep_anchor) {
301 for (int i = 0; i < N - 1; ++i) {
302 const double piece = fraction[static_cast<std::size_t>(i + 1)] -
303 fraction[static_cast<std::size_t>(i)];
304 target[static_cast<std::size_t>(i)] = piece * arc_length;
305 }
306 return target;
307 }
308
309 const double left_length = s[static_cast<std::size_t>(anchor_index)] - s[0];
310 const double right_length = s[static_cast<std::size_t>(N - 1)] -
311 s[static_cast<std::size_t>(anchor_index)];
312 const double anchor_fraction =
313 fraction[static_cast<std::size_t>(anchor_index)];
314 for (int i = 0; i < N - 1; ++i) {
315 const double piece = fraction[static_cast<std::size_t>(i + 1)] -
316 fraction[static_cast<std::size_t>(i)];
317 const double current =
318 s[static_cast<std::size_t>(i + 1)] - s[static_cast<std::size_t>(i)];
319 if (i < anchor_index) {
320 target[static_cast<std::size_t>(i)] =
321 (anchor_fraction > 0.0) ? piece / anchor_fraction * left_length
322 : current;
323 } else {
324 target[static_cast<std::size_t>(i)] =
325 (anchor_fraction < 1.0)
326 ? piece / (1.0 - anchor_fraction) * right_length
327 : current;
328 }
329 }
330 return target;
331}
332
333double deviationFromSegmentTargets(const std::vector<double>& s,
334 const std::vector<double>& target)
335{
336 double max_dev = 0.0;
337 for (int i = 0; i < static_cast<int>(target.size()); ++i) {
338 const double length_target = target[static_cast<std::size_t>(i)];
339 if (length_target <= std::numeric_limits<double>::min()) continue;
340 const double length =
341 s[static_cast<std::size_t>(i + 1)] - s[static_cast<std::size_t>(i)];
342 max_dev =
343 std::max(max_dev, std::abs(length - length_target) / length_target);
344 }
345 return max_dev;
346}
347
348double cumulativeTargetArc(const std::vector<double>& s,
349 const std::vector<double>& target, int image_idx)
350{
351 double arc = s[0];
352 for (int i = 0; i < image_idx; ++i)
353 arc += target[static_cast<std::size_t>(i)];
354 return arc;
355}
356
357} // namespace
358
359NEBPath::NEBPath(const Eigen::VectorXd& initial,
360 const Eigen::VectorXd& final_state, int n_images,
361 double spring_constant)
362 : spring_constant_(spring_constant)
363{
364 int total = n_images + 2; // including endpoints
365 images_.resize(total);
366 neb_forces_.resize(total);
367
368 // Endpoint images
369 images_[0].positions = initial;
370 images_[0].gradient = Eigen::VectorXd::Zero(initial.size());
371 images_[0].is_endpoint = true;
372 images_[total - 1].positions = final_state;
373 images_[total - 1].gradient = Eigen::VectorXd::Zero(final_state.size());
374 images_[total - 1].is_endpoint = true;
375
376 // Linear interpolation for intermediate images
377 for (int i = 1; i < total - 1; ++i) {
378 double t = static_cast<double>(i) / (total - 1);
379 images_[i].positions = (1.0 - t) * initial + t * final_state;
380 images_[i].gradient.resize(initial.size());
381 images_[i].gradient.setZero();
382 }
383
384 for (auto& f: neb_forces_) {
385 f.resize(initial.size());
386 f.setZero();
387 }
388}
389
390NEBPath::NEBPath(const EigenMatrix& image_positions, double spring_constant)
391 : spring_constant_(spring_constant)
392{
393 if (image_positions.rows() < 2 || image_positions.cols() == 0) {
394 throw std::invalid_argument(
395 "NEBPath image_positions must contain at least two non-empty rows");
396 }
397
398 const int total = static_cast<int>(image_positions.rows());
399 const int n_coords = static_cast<int>(image_positions.cols());
400 images_.resize(total);
401 neb_forces_.resize(total);
402
403 for (int i = 0; i < total; ++i) {
404 images_[i].positions = image_positions.row(i).transpose();
405 images_[i].gradient = Eigen::VectorXd::Zero(n_coords);
406 images_[i].is_endpoint = (i == 0 || i == total - 1);
407 }
408
409 for (auto& f: neb_forces_) {
410 f = Eigen::VectorXd::Zero(n_coords);
411 }
412}
413
414void NEBPath::setPeriodicCell(const std::array<double, 9>& cell)
415{
416 cell_ = cell;
417 periodic_ = gpr::geometry::cellIsMicLattice(cell_.data());
418 if (periodic_)
419 periodic_box_.reset(cell_.data());
420 else
421 periodic_box_ = gpr::geometry::PairBox();
422}
423
424void NEBPath::setMovingAtoms(std::vector<char> moving_atoms)
425{
426 if (!images_.empty() && !moving_atoms.empty() &&
427 static_cast<Eigen::Index>(moving_atoms.size() * 3) !=
428 images_[0].positions.size()) {
429 throw std::invalid_argument("NEBPath moving-atom mask size mismatch");
430 }
431 moving_atoms_ = std::move(moving_atoms);
432 for (int i = 1; i < numImages() - 1; ++i)
433 pinFixedAtoms(images_[i].positions);
434}
435
437{
438 external_fixed_atoms_ = present;
439}
440
441void NEBPath::setSpringCoordinates(std::vector<Eigen::Index> coordinates,
442 std::vector<double> weights)
443{
444 const Eigen::Index n_coordinates =
445 images_.empty() ? Eigen::Index(0) : images_.front().positions.size();
446 if (!weights.empty() && weights.size() != coordinates.size()) {
447 throw std::invalid_argument(
448 "NEBPath spring weights must match the spring coordinates");
449 }
450 std::vector<std::pair<Eigen::Index, double>> paired;
451 paired.reserve(coordinates.size());
452 for (std::size_t i = 0; i < coordinates.size(); ++i) {
453 const double weight = weights.empty() ? 1.0 : weights[i];
454 if (!std::isfinite(weight) || weight < 0.0) {
455 throw std::invalid_argument(
456 "NEBPath spring weights must be finite and non-negative");
457 }
458 paired.emplace_back(coordinates[i], weight);
459 }
460 std::sort(paired.begin(), paired.end(),
461 [](const std::pair<Eigen::Index, double>& a,
462 const std::pair<Eigen::Index, double>& b) {
463 return a.first < b.first;
464 });
465 for (std::size_t i = 1; i < paired.size(); ++i) {
466 if (paired[i].first == paired[i - 1].first) {
467 throw std::invalid_argument(
468 "NEBPath spring coordinates must be distinct");
469 }
470 }
471 if (!paired.empty() &&
472 (paired.front().first < 0 || paired.back().first >= n_coordinates)) {
473 throw std::invalid_argument(
474 "NEBPath spring coordinates must index the band coordinates");
475 }
476 spring_coordinates_.resize(paired.size());
477 spring_weights_.clear();
478 const bool weighted =
479 !weights.empty() &&
480 std::any_of(paired.begin(), paired.end(),
481 [](const std::pair<Eigen::Index, double>& item) {
482 return item.second != 1.0;
483 });
484 if (weighted) spring_weights_.resize(paired.size());
485 for (std::size_t i = 0; i < paired.size(); ++i) {
486 spring_coordinates_[i] = paired[i].first;
487 if (weighted) spring_weights_[i] = paired[i].second;
488 }
489}
490
492{
493 molecular_rigid_motion_ = enabled;
494}
495
497{
498 return molecular_rigid_motion_ && !periodic_ && allAtomsFree() &&
499 !images_.empty() && images_[0].positions.size() >= 6 &&
500 images_[0].positions.size() % 3 == 0;
501}
502
503void NEBPath::projectPhysicalVector(const Eigen::VectorXd& reference,
504 Eigen::Ref<Eigen::VectorXd> vector) const
505{
506 if (!molecularRigidMotion()) return;
507 if (reference.size() != vector.size() || reference.size() % 3 != 0 ||
508 !reference.allFinite() || !vector.allFinite())
509 throw std::invalid_argument("invalid molecular rigid projection input");
510 gpr::Coord coordinates(1, reference.size());
511 coordinates.row(0) = reference.transpose();
512 const Eigen::MatrixXd basis = dimer::rigid_motion_basis(coordinates);
513 const Eigen::VectorXd coefficients = basis.transpose() * vector;
514 vector.noalias() -= basis * coefficients;
515}
516
518 const Eigen::VectorXd& reference, const Eigen::VectorXd& geometry) const
519{
520 if (!molecularRigidMotion()) return geometry;
521 if (reference.size() != geometry.size() || reference.size() % 3 != 0 ||
522 !reference.allFinite() || !geometry.allFinite())
523 throw std::invalid_argument("invalid molecular rigid alignment input");
524 if ((reference.array() == geometry.array()).all()) return geometry;
525 const Eigen::VectorXd aligned =
527 // Retain exact coordinates when a rigid transform differs only by the
528 // roundoff of the centroid and covariance calculations.
529 const double resolution =
530 std::numeric_limits<double>::epsilon() *
531 static_cast<double>(reference.size()) *
532 std::max({1.0, reference.norm(), geometry.norm()});
533 if ((aligned - reference).norm() <= resolution) return reference;
534 if ((aligned - geometry).norm() <= resolution) return geometry;
535 return aligned;
536}
537
539{
540 if (!molecularRigidMotion()) return;
541 const Eigen::VectorXd reference = images_[0].positions;
542 for (int i = 1; i < numImages(); ++i) {
543 const Eigen::VectorXd aligned =
544 alignMolecularGeometry(reference, images_[i].positions);
545 if ((aligned.array() == images_[i].positions.array()).all()) continue;
546 images_[i].positions = aligned;
547 invalidateResampledImage(i);
548 neb_forces_[i].setZero();
549 }
550}
551
552void NEBPath::pinFixedAtoms(Eigen::Ref<Eigen::VectorXd> positions) const
553{
554 if (moving_atoms_.empty() || images_.empty()) return;
555 const Eigen::VectorXd& reference = images_[0].positions;
556 if (positions.size() != reference.size()) return;
557 for (int atom = 0; atom < static_cast<int>(moving_atoms_.size()); ++atom) {
558 if (moving_atoms_[static_cast<std::size_t>(atom)]) continue;
559 positions.segment<3>(3 * atom) = reference.segment<3>(3 * atom);
560 }
561}
562
563void NEBPath::maskFixedForce(Eigen::Ref<Eigen::VectorXd> force) const
564{
565 if (moving_atoms_.empty()) return;
566 if (force.size() != static_cast<Eigen::Index>(moving_atoms_.size() * 3))
567 return;
568 for (int atom = 0; atom < static_cast<int>(moving_atoms_.size()); ++atom) {
569 if (moving_atoms_[static_cast<std::size_t>(atom)]) continue;
570 force.segment<3>(3 * atom).setZero();
571 }
572}
573
574Eigen::VectorXd NEBPath::segmentDisplacement(const Eigen::VectorXd& from,
575 const Eigen::VectorXd& to) const
576{
577 if (molecularRigidMotion()) return alignMolecularGeometry(from, to) - from;
579 periodic_ ? &periodic_box_ : nullptr, from, to);
580}
581
582bool NEBPath::allAtomsFree() const
583{
584 return std::all_of(moving_atoms_.begin(), moving_atoms_.end(),
585 [](char moves) { return moves != 0; });
586}
587
588void NEBPath::removeNetTranslation(Eigen::VectorXd& delta) const
589{
590 // A free crystal has three translational zero modes. The minimum-image
591 // chord can still carry a net slide; the tangent and the spring live in
592 // the translation-free space, matching a band whose projected force has
593 // had the same slide removed. Fixed atoms pin the frame, so the slide
594 // is then a real displacement and stays; that holds as well for fixed
595 // atoms kept outside the band coordinates (a single adatom over a
596 // frozen surface), where removing the mean would erase the whole chord.
597 if (!periodic_ || external_fixed_atoms_ || !allAtomsFree() ||
598 delta.size() % 3 != 0)
599 return;
600 const int n_atoms = static_cast<int>(delta.size() / 3);
601 if (n_atoms == 0) return;
602 Eigen::Vector3d sum = Eigen::Vector3d::Zero();
603 for (int atom = 0; atom < n_atoms; ++atom)
604 sum += delta.segment<3>(3 * atom);
605 const Eigen::Vector3d mean = sum / static_cast<double>(n_atoms);
606 for (int atom = 0; atom < n_atoms; ++atom)
607 delta.segment<3>(3 * atom) -= mean;
608}
609
611{
612 const int total = numImages();
613 if (total < 2) return;
614 const Eigen::VectorXd initial = images_[0].positions;
615 const Eigen::VectorXd final_state = images_.back().positions;
616 const Eigen::VectorXd chord = segmentDisplacement(initial, final_state);
617 for (int i = 1; i < total - 1; ++i) {
618 const double t = static_cast<double>(i) / (total - 1);
619 if (periodic_)
620 images_[i].positions = initial + t * chord;
621 else
622 images_[i].positions = (1.0 - t) * initial + t * final_state;
623 images_[i].gradient = Eigen::VectorXd::Zero(initial.size());
624 images_[i].energy = 0.0;
625 images_[i].evaluated = false;
626 images_[i].is_endpoint = false;
627 pinFixedAtoms(images_[i].positions);
628 }
629}
630
631bool NEBPath::seedFromRuntime(RuntimeSeed kind, int n_atoms,
632 const std::vector<char>& moving_atoms,
633 double alpha)
634{
636 if (!runtime.load() || !runtime.hasPathSeeds()) {
637 throw std::runtime_error("rgsaddle path seed: " +
638 runtime.lastMessage());
639 }
640 const int n_int = numIntermediate();
641 const int64_t n_images = n_int + 2;
642 const Eigen::Index dof = 3 * static_cast<Eigen::Index>(n_atoms);
643 if (images_[0].positions.size() != dof ||
644 images_.back().positions.size() != dof) {
645 throw std::invalid_argument(
646 "rgsaddle path seed: endpoint size does not match n_atoms");
647 }
648 // rgsaddle marks the atoms it holds; moving_atoms marks the others.
649 std::vector<uint8_t> mask;
650 if (!moving_atoms.empty()) {
651 if (static_cast<int>(moving_atoms.size()) != n_atoms) {
652 throw std::invalid_argument(
653 "rgsaddle path seed: moving_atoms size does not match n_atoms");
654 }
655 mask.resize(moving_atoms.size());
656 for (size_t i = 0; i < moving_atoms.size(); ++i) {
657 mask[i] = moving_atoms[i] ? 0 : 1;
658 }
659 }
660 const uint8_t* mask_ptr = mask.empty() ? nullptr : mask.data();
661 const double* cell = periodic_ ? cell_.data() : nullptr;
662 std::vector<double> out(static_cast<size_t>(n_images * dof));
663 const double* reactant = images_[0].positions.data();
664 const double* product = images_.back().positions.data();
665 int status = -1;
666 if (kind == RuntimeSeed::Idpp) {
667 // Per-image L-BFGS. The former steepest-descent seed used the
668 // same iteration cap, force tolerance and step.
669 status =
670 runtime.idppFixedPath(n_images, n_atoms, reactant, product, cell,
671 mask_ptr, 200, 0.01, 0.1, out.data());
672 } else if (kind == RuntimeSeed::Collective) {
673 // No collective C entry. Alternating S-IDPP with the insertion
674 // stage skipped (short_iterations 0) relaxes the whole chain.
676 false, n_images, n_atoms, reactant, product, cell, mask_ptr, 0.33,
677 0, 500, 0.01, 0.05, spring_constant_, out.data());
678 } else {
679 // Unit IDPP spring, not the physical NEB spring. Inverse-distance
680 // is the --sidpp-geodesic blend, not rgsaddle_geodesic_path.
682 kind == RuntimeSeed::SidppInverseDistance, n_images, n_atoms,
683 reactant, product, cell, mask_ptr, alpha, 100, 500, 0.01, 0.05, 1.0,
684 out.data());
685 }
686 if (status != 0) {
687 throw std::runtime_error("rgsaddle path seed failed with status " +
688 std::to_string(status));
689 }
690 for (int i = 0; i < n_int; ++i) {
691 images_[i + 1].positions = Eigen::Map<const Eigen::VectorXd>(
692 out.data() + static_cast<size_t>(i + 1) * dof, dof);
693 }
694 return true;
695}
696
697void NEBPath::initializeIDPP(int n_atoms, bool collective)
698{
699 initializeIDPP(n_atoms, {}, collective);
700}
701
702void NEBPath::initializeIDPP(int n_atoms, const std::vector<char>& moving_atoms,
703 bool collective)
704{
705 int n_int = numIntermediate();
706 if (n_int <= 0 || n_atoms <= 0) return;
707
708 seedFromRuntime(collective ? RuntimeSeed::Collective : RuntimeSeed::Idpp,
709 n_atoms, moving_atoms, 0.0);
710}
711
712void NEBPath::initializeSIDPP(int n_atoms, double alpha)
713{
714 initializeSIDPP(n_atoms, {}, alpha);
715}
716
718 const std::vector<char>& moving_atoms,
719 double alpha)
720{
721 int n_int = numIntermediate();
722 if (n_int <= 0 || n_atoms <= 0) return;
723 // The IDPP interpolation relaxes on the image-dependent-pair-potential
724 // surface, whose spring is in normalized pair-distance units -- NOT the
725 // physical NEB spring constant (eV/A). Feeding the NEB k_max (energy-
726 // weighted, up to ~9.72) over-stiffens the IDPP relaxation and produces a
727 // distorted initial path that drops the band into a higher-saddle basin.
728 // Use the standard unit IDPP spring, decoupled from the NEB spring.
729 seedFromRuntime(RuntimeSeed::Sidpp, n_atoms, moving_atoms, alpha);
730}
731
732void NEBPath::initializeSIDPPGeodesic(int n_atoms, double alpha)
733{
734 initializeSIDPPGeodesic(n_atoms, {}, alpha);
735}
736
738 const std::vector<char>& moving_atoms,
739 double alpha)
740{
741 int n_int = numIntermediate();
742 if (n_int <= 0 || n_atoms <= 0) return;
743 // Same decoupled unit IDPP spring as initializeSIDPP: the geodesic
744 // inverse-distance relaxation runs on the normalized pair-distance
745 // surface, so feeding the physical NEB k_max (up to ~9.72) over-stiffens
746 // it and distorts the path into a higher-saddle basin.
747 seedFromRuntime(RuntimeSeed::SidppInverseDistance, n_atoms, moving_atoms,
748 alpha);
749}
750
751bool NEBPath::rawTangent(int i, Eigen::VectorXd& tau, Eigen::VectorXd& tau_plus,
752 double& own_weight) const
753{
754 // Improved tangent estimate (Henkelman & Jonsson, JCP 113, 2000)
755 tau_plus =
756 segmentDisplacement(images_[i].positions, images_[i + 1].positions);
757 Eigen::VectorXd tau_minus;
758 if (molecularRigidMotion()) {
759 tau_minus = -segmentDisplacement(images_[i].positions,
760 images_[i - 1].positions);
761 } else {
762 tau_minus =
763 segmentDisplacement(images_[i - 1].positions, images_[i].positions);
764 }
765 removeNetTranslation(tau_plus);
766 removeNetTranslation(tau_minus);
767 projectPhysicalVector(images_[i].positions, tau_plus);
768 projectPhysicalVector(images_[i].positions, tau_minus);
769
770 double e_i = images_[i].energy;
771 double e_plus = images_[i + 1].energy;
772 double e_minus = images_[i - 1].energy;
773
774 // A quiet NaN must not reach std::abs: that raises an invalid
775 // floating-point exception when traps are on. The explicit branch
776 // reports no tangent and does not compare the energies.
777 if (!std::isfinite(e_i) || !std::isfinite(e_plus) ||
778 !std::isfinite(e_minus)) {
779 return false;
780 }
781
782 // The image's own position enters the forward chord with weight -1
783 // and the backward chord with weight +1; own_weight is their sum under
784 // the weights the chords carry in the tangent.
785 if (e_plus > e_i && e_i > e_minus) {
786 tau = tau_plus;
787 own_weight = -1.0;
788 } else if (e_plus < e_i && e_i < e_minus) {
789 tau = tau_minus;
790 own_weight = 1.0;
791 } else {
792 double dE_max =
793 std::max(std::abs(e_plus - e_i), std::abs(e_minus - e_i));
794 double dE_min =
795 std::min(std::abs(e_plus - e_i), std::abs(e_minus - e_i));
796
797 if (e_plus > e_minus) {
798 tau = dE_max * tau_plus + dE_min * tau_minus;
799 own_weight = dE_min - dE_max;
800 } else {
801 tau = dE_min * tau_plus + dE_max * tau_minus;
802 own_weight = dE_max - dE_min;
803 }
804 }
805 return true;
806}
807
808Eigen::VectorXd NEBPath::tangent(int i) const
809{
810 if (i <= 0 || i >= numImages() - 1) {
811 return Eigen::VectorXd::Zero(images_[0].positions.size());
812 }
813
814 Eigen::VectorXd tau, tau_plus;
815 double own_weight = 0.0;
816 if (!rawTangent(i, tau, tau_plus, own_weight)) {
817 return Eigen::VectorXd::Zero(images_[i].positions.size());
818 }
819
820 // Zero-norm fallback to tau_plus, matching eOn NEBTangent
821 // normalizeTangent. The weighted-average branch can cancel to zero
822 // at a strict extremum with symmetric |dE| and anti-parallel
823 // position deltas; without the fallback Eigen normalize() produces
824 // NaN and poisons F_perp downstream.
825 double n = tau.norm();
826 if (n > 1e-10) {
827 tau /= n;
828 return tau;
829 }
830 Eigen::VectorXd fb = tau_plus;
831 double nf = fb.norm();
832 if (nf > 1e-10) {
833 fb /= nf;
834 }
835 return fb;
836}
837
838double NEBPath::tangentStiffness(int i) const
839{
840 if (i <= 0 || i >= numImages() - 1) return 0.0;
841 Eigen::VectorXd tau, tau_plus;
842 double own_weight = 0.0;
843 if (!rawTangent(i, tau, tau_plus, own_weight)) return 0.0;
844 const Eigen::VectorXd& gradient = images_[i].gradient;
845 const double length = tau.norm();
846 if (!(length > 1e-10) || gradient.size() != tau.size() ||
847 !gradient.allFinite())
848 return 0.0;
849 // d(tau_hat)/dx_i = own_weight / |t| (I - tau_hat tau_hat^T), and the
850 // band force holds (g . tau_hat) tau_hat once, or twice on a climbing
851 // image.
852 const double parallel = gradient.dot(tau) / length;
853 const double reflections = images_[i].is_climbing ? 2.0 : 1.0;
854 return -reflections * parallel * own_weight / length;
855}
856
857void NEBPath::setForceVariance(int i, const Eigen::VectorXd& variance)
858{
859 if (i < 0 || i >= static_cast<int>(images_.size())) return;
860 if (force_variance_.size() != images_.size()) {
861 force_variance_.assign(images_.size(), Eigen::VectorXd());
862 }
863 force_variance_[static_cast<std::size_t>(i)] = variance;
864}
865
867{
868 force_variance_.clear();
869}
870
872{
873 if (i < 0 || static_cast<std::size_t>(i) >= force_variance_.size()) {
874 return false;
875 }
876 const Eigen::VectorXd& v = force_variance_[static_cast<std::size_t>(i)];
877 return v.size() > 0 && (v.array() > 0.0).any();
878}
879
881{
882 // Energy-weighted variable spring constants. The constant-k
883 // formulation lets images bunch together in low-energy basins
884 // (the spring contracts equally everywhere; near the saddle the
885 // chain is stretched by the climb force without compensating
886 // stiffening). With variable k tied to image energy the springs
887 // stiffen where the band needs cohesion (around high-energy
888 // images, i.e. the saddle region) and slacken in the basins.
889 //
890 // Per-spring k between adjacent images j-1 and j:
891 // E_pair = max(E_j, E_{j-1})
892 // energy_range = E_max - E_ref
893 // if energy_range < 1e-10 or E_pair <= E_ref:
894 // k_pair = k_min
895 // else:
896 // alpha = clamp((E_max - E_pair) / energy_range, 0, 1)
897 // k_pair = (1 - alpha) * k_max + alpha * k_min
898 // with k_max = spring_constant_, k_min = 0.1 * k_max,
899 // E_ref = min(reactant.E, product.E), E_max = max over the path
900 // including endpoints. Saddle-adjacent springs get k_max (alpha
901 // = 0); basin-adjacent springs collapse to k_min (alpha = 1).
902 //
903 // Per-image NEB spring force with two distinct adjacent k's:
904 // F_spring(i) = (k_+ * d_+ - k_- * d_-) * tau
905 // where k_+ is the spring between images i and i+1, k_- between
906 // images i-1 and i.
907 const int n = numImages();
908 const double k_max = spring_constant_;
909 const double k_min =
910 (spring_constant_min_ >= 0.0) ? spring_constant_min_ : 0.1 * k_max;
911 // Energy weighting only on a fully measured (or fully legacy) profile.
912 // Enabling it on GP-OIE bands (measured endpoints, predicted interior)
913 // was tried on 2026-09-07 and rejected: eOn's rule weights against the
914 // lower endpoint, so on an exothermic cell (02_hcch, product 2.2 eV
915 // below the reactant) every image crowded onto the reactant plateau,
916 // the descent was left to two images, and the climbing image settled
917 // on a 0.107 eV plateau saddle while the 0.21 eV ridge sat unresolved
918 // between them. The band's resolution is set at refinement time by the
919 // chord-leak equidistribution instead (resamplePathByRestLengths).
920 const bool any_measured =
921 std::any_of(images_.begin(), images_.end(),
922 [](const Image& image) { return image.evaluated; });
923 const bool complete_measured_profile =
924 std::all_of(images_.begin(), images_.end(), [](const Image& image) {
925 return std::isfinite(image.energy) && image.evaluated;
926 });
927 const bool finite_legacy_profile =
928 !any_measured &&
929 std::all_of(images_.begin(), images_.end(), [](const Image& image) {
930 return std::isfinite(image.energy);
931 });
932 const bool use_energy_weighting =
933 energy_weighted_springs_ &&
934 (complete_measured_profile || finite_legacy_profile);
935
936 // eOn's weighted-spring strategy scales the stiffness over the full
937 // reaction-energy interval, using the lower endpoint as its reference.
938 // Ordered comparisons raise invalid on a quiet NaN, so the reduction
939 // runs only when every image energy is already known finite. That is
940 // also the only case that weights springs; kSpring does not read
941 // these values otherwise.
942 double E_ref = 0.0;
943 double E_max = 0.0;
944 if (use_energy_weighting) {
945 E_ref = std::min(images_[0].energy, images_[n - 1].energy);
946 E_max = E_ref;
947 for (int i = 0; i < n; ++i) {
948 E_max = std::max(E_max, images_[i].energy);
949 }
950 }
951 const double energy_range = E_max - E_ref;
952
953 auto kSpring = [&](int j) -> double {
954 // Spring between images j-1 and j; j is the "upper" image
955 // for index purposes. Valid for j in [1, n-1].
956 if (!use_energy_weighting) return k_max;
957 const double E_pair =
958 std::max(images_[j].energy, images_[j - 1].energy);
959 if (energy_range < 1e-10) return k_min;
960 if (E_pair <= E_ref) return k_min;
961 double alpha = (E_max - E_pair) / energy_range;
962 if (alpha < 0.0) alpha = 0.0;
963 if (alpha > 1.0) alpha = 1.0;
964 return (1.0 - alpha) * k_max + alpha * k_min;
965 };
966
967 for (int i = 1; i < n - 1; ++i) {
968 const Eigen::Index ncoord = images_[i].positions.size();
969 // Non-finite image energy: sized zero NEB gradient, and no abs
970 // of the energy differences inside tangent().
971 if (!std::isfinite(images_[i].energy) ||
972 !std::isfinite(images_[i - 1].energy) ||
973 !std::isfinite(images_[i + 1].energy)) {
974 neb_forces_[i] = Eigen::VectorXd::Zero(ncoord);
975 continue;
976 }
977 Eigen::VectorXd tau = tangent(i);
978 const Eigen::VectorXd& grad = images_[i].gradient;
979
980 // With a surrogate force variance the tangent component is removed in
981 // the Sigma^{-1} metric rather than the Euclidean one; the two agree
982 // exactly when the variance is uniform, so this is a strict
983 // generalisation of the classical projection above.
984 const bool anisotropic =
985 hasForceVariance(i) &&
986 force_variance_[static_cast<std::size_t>(i)].size() == grad.size();
987 // The isotropic branch keeps the original expressions verbatim.
988 // 2 P(F) - F is algebraically -grad + 2 (grad.tau) tau, but floating
989 // point addition does not associate, so routing the classical case
990 // through the general projection would move every existing trajectory
991 // in its last bits.
992 const auto perpendicular = [&](const Eigen::VectorXd& f) {
994 f, tau, force_variance_[static_cast<std::size_t>(i)]);
995 };
996
997 if (images_[i].is_climbing &&
998 climbing_curvature_direction_.size() == tau.size() &&
999 climbing_curvature_direction_.allFinite()) {
1000 tau = climbing_curvature_direction_;
1001 }
1002 if (images_[i].is_climbing) {
1003 // Climbing image: invert parallel component
1004 // F_CI = -grad + 2*(grad . tau)*tau
1005 if (anisotropic) {
1006 const Eigen::VectorXd force = -grad;
1007 neb_forces_[i] = 2.0 * perpendicular(force) - force;
1008 } else {
1009 double grad_parallel = grad.dot(tau);
1010 neb_forces_[i] = -grad + 2.0 * grad_parallel * tau;
1011 }
1012 } else {
1013 // Standard NEB: perpendicular true force + parallel spring force
1014 double grad_parallel = grad.dot(tau);
1015 // Not a ternary: one arm is an Eigen expression template and the
1016 // other a materialised vector, and the classical arm has to be the
1017 // original expression assigned straight into F_perp so it stays
1018 // bit-identical.
1019 Eigen::VectorXd F_perp;
1020 if (anisotropic) {
1021 F_perp = perpendicular(-grad);
1022 } else {
1023 F_perp = -grad + grad_parallel * tau;
1024 }
1025
1026 Eigen::VectorXd delta_plus = segmentDisplacement(
1027 images_[i].positions, images_[i + 1].positions);
1028 Eigen::VectorXd delta_minus = segmentDisplacement(
1029 images_[i - 1].positions, images_[i].positions);
1030 removeNetTranslation(delta_plus);
1031 removeNetTranslation(delta_minus);
1032 // The springs measure the whole chord, or the displacement of
1033 // the spring coordinates alone when a set is given.
1034 const bool restricted_springs = !spring_coordinates_.empty();
1035 // A missing weight vector is weight 1, the unweighted length.
1036 const auto spring_weight = [&](std::size_t n) {
1037 return spring_weights_.empty() ? 1.0 : spring_weights_[n];
1038 };
1039 const auto spring_length = [&](const Eigen::VectorXd& delta) {
1040 double sum = 0.0;
1041 for (std::size_t n = 0; n < spring_coordinates_.size(); ++n) {
1042 const double component = delta(spring_coordinates_[n]);
1043 const double weight = spring_weight(n);
1044 sum += weight * component * component;
1045 }
1046 return std::sqrt(sum);
1047 };
1048 const double d_plus = restricted_springs ? spring_length(delta_plus)
1049 : delta_plus.norm();
1050 const double d_minus = restricted_springs
1051 ? spring_length(delta_minus)
1052 : delta_minus.norm();
1053 double F_spring;
1054 if (static_cast<int>(spring_rest_lengths_.size()) == n - 1) {
1055 // Rest lengths: uniform k_max, each segment pulled toward
1056 // its own rest length, so the equilibrium spacing is the
1057 // rest length plus a common offset.
1058 const double rest_plus =
1059 spring_rest_lengths_[static_cast<std::size_t>(i)];
1060 const double rest_minus =
1061 spring_rest_lengths_[static_cast<std::size_t>(i - 1)];
1062 F_spring =
1063 k_max * ((d_plus - rest_plus) - (d_minus - rest_minus));
1064 } else if (use_geometric_spring_) {
1065 // Geometric (cubic-potential) spring: U_s = (k/3)
1066 // sum ||R_{i+1}-R_i||^3 -> F_par = k*(d_n^2 - d_p^2)
1067 // tau. Perpendicular cancels exactly; K_eff = 4 k s
1068 // scales linearly in image spacing so dense meshes
1069 // auto-soften. Uses a SINGLE k (= spring_constant_,
1070 // the k_max) instead of the energy-weighted taper.
1071 F_spring =
1072 spring_constant_ * (d_plus * d_plus - d_minus * d_minus);
1073 } else {
1074 const double k_plus = kSpring(i + 1);
1075 const double k_minus = kSpring(i);
1076 F_spring = k_plus * d_plus - k_minus * d_minus;
1077 }
1078
1079 if (restricted_springs) {
1080 // The spring acts along the tangent restricted to its
1081 // coordinates; a tangent with no component there leaves
1082 // nothing for the spring to act on.
1083 neb_forces_[i] = F_perp;
1084 const double restricted = spring_length(tau);
1085 if (restricted > 0.0) {
1086 const double scale = F_spring / restricted;
1087 for (std::size_t n = 0; n < spring_coordinates_.size();
1088 ++n) {
1089 const auto k = spring_coordinates_[n];
1090 neb_forces_[i](k) += scale * spring_weight(n) * tau(k);
1091 }
1092 }
1093 } else {
1094 neb_forces_[i] = F_perp + F_spring * tau;
1095 }
1096 }
1097 projectPhysicalVector(images_[i].positions, neb_forces_[i]);
1098 maskFixedForce(neb_forces_[i]);
1099 }
1100}
1101
1102void NEBPath::setSpringRestLengths(std::vector<double> rest_lengths)
1103{
1104 if (rest_lengths.empty()) {
1105 spring_rest_lengths_.clear();
1106 return;
1107 }
1108 if (static_cast<int>(rest_lengths.size()) != numImages() - 1) {
1109 throw std::invalid_argument(
1110 "NEBPath spring rest lengths need one entry per segment");
1111 }
1112 for (double rest: rest_lengths) {
1113 if (!(rest > 0.0) || !std::isfinite(rest)) {
1114 throw std::invalid_argument(
1115 "NEBPath spring rest lengths must be positive and finite");
1116 }
1117 }
1118 spring_rest_lengths_ = std::move(rest_lengths);
1119}
1120
1122{
1123 for (auto& img: images_) {
1124 img.is_climbing = false;
1125 }
1126 int hi = highestEnergyImageIndex();
1127 if (hi > 0 && hi < numImages() - 1) {
1128 images_[hi].is_climbing = true;
1129 }
1130}
1131
1133{
1134 // Highest finite interior energy. A non-finite value is not a
1135 // candidate, and with none the result is -1. A strict interior local
1136 // maximum wins only a tie at that highest energy, against a non-strict
1137 // shoulder; the lowest index breaks any remaining tie. A strict local
1138 // maximum does not outrank a strictly higher interior energy.
1139 if (numImages() <= 2) return -1;
1140 int best_peak = -1;
1141 double best_peak_e = -std::numeric_limits<double>::infinity();
1142 int best_any = -1;
1143 double best_any_e = -std::numeric_limits<double>::infinity();
1144 for (int i = 1; i < numImages() - 1; ++i) {
1145 const double e = images_[i].energy;
1146 if (!std::isfinite(e)) continue;
1147 if (best_any < 0 || e > best_any_e) {
1148 best_any_e = e;
1149 best_any = i;
1150 }
1151 const double e_prev = images_[i - 1].energy;
1152 const double e_next = images_[i + 1].energy;
1153 const bool local_max = std::isfinite(e_prev) && std::isfinite(e_next) &&
1154 e > e_prev && e > e_next;
1155 if (local_max && (best_peak < 0 || e > best_peak_e ||
1156 (e == best_peak_e && i < best_peak))) {
1157 best_peak_e = e;
1158 best_peak = i;
1159 }
1160 }
1161 if (best_peak >= 0 && !(best_any_e > best_peak_e)) return best_peak;
1162 return best_any;
1163}
1164
1166{
1167 // Continuity of the active CI prevents index thrash (which forces OCI
1168 // bursts to re-seed min-mode every outer), BUT it must never park the
1169 // climb on a lower saddle when a higher one exists: the saddle is the
1170 // band's global energy maximum, a property of the PES, not of the image
1171 // count. Keeping the CI on any local max made the choice resolution-
1172 // dependent -- a finer band exposes minor interior maxima near the
1173 // endpoints, and the prior CI sticks to one while the true peak sits far
1174 // higher (03_h2co at nimages=18: CI parked at a near-reactant bump,
1175 // forward barrier ~0 while the real TS image was ~3.4 eV). So keep the
1176 // prior CI only while it remains the band's highest-energy image; the
1177 // moment a higher peak appears, climb that one.
1178 if (numImages() <= 2) return -1;
1179 const int hi = highestEnergyImageIndex();
1180 if (preferred > 0 && preferred < numImages() - 1 && hi > 0 &&
1181 std::isfinite(images_[preferred].energy) &&
1182 images_[preferred].energy >= images_[hi].energy) {
1183 return preferred;
1184 }
1185 return hi;
1186}
1187
1189{
1190 // A strict interior local maximum wins over a higher shoulder that
1191 // is not strict. With no strict maximum, the highest finite interior
1192 // energy remains. Non-finite energies are not candidates. Ties keep
1193 // the highest energy, then the lowest index.
1194 if (numImages() <= 2) return -1;
1195 int best_peak = -1;
1196 double best_peak_e = -std::numeric_limits<double>::infinity();
1197 int best_any = -1;
1198 double best_any_e = -std::numeric_limits<double>::infinity();
1199 for (int i = 1; i < numImages() - 1; ++i) {
1200 const double e = images_[i].energy;
1201 if (!std::isfinite(e)) continue;
1202 if (best_any < 0 || e > best_any_e) {
1203 best_any_e = e;
1204 best_any = i;
1205 }
1206 const double e_prev = images_[i - 1].energy;
1207 const double e_next = images_[i + 1].energy;
1208 const bool local_max = std::isfinite(e_prev) && std::isfinite(e_next) &&
1209 e > e_prev && e > e_next;
1210 if (local_max && (best_peak < 0 || e > best_peak_e ||
1211 (e == best_peak_e && i < best_peak))) {
1212 best_peak_e = e;
1213 best_peak = i;
1214 }
1215 }
1216 return best_peak >= 0 ? best_peak : best_any;
1217}
1218
1220{
1221 if (numImages() <= 2) return -1;
1222 const int hi = highestLocalMaximumImageIndex();
1223 if (preferred > 0 && preferred < numImages() - 1 && hi > 0 &&
1224 std::isfinite(images_[preferred].energy) &&
1225 images_[preferred].energy >= images_[hi].energy) {
1226 return preferred;
1227 }
1228 return hi;
1229}
1230
1232{
1233 int n_int = numIntermediate();
1234 int n_coords = static_cast<int>(images_[0].positions.size());
1235 EigenMatrix R(n_int, n_coords);
1236 for (int i = 0; i < n_int; ++i) {
1237 R.row(i) = images_[i + 1].positions.transpose();
1238 }
1239 return R;
1240}
1241
1242void NEBPath::setFromObservation(const Observation& obs, int start_image)
1243{
1244 for (Eigen::Index row = 0; row < obs.R.rows(); ++row) {
1245 int img_idx = start_image + static_cast<int>(row);
1246 if (img_idx >= 0 && img_idx < numImages()) {
1247 images_[img_idx].energy = obs.E(row, 0);
1248 images_[img_idx].gradient =
1249 obs.G.row(row).transpose().cast<double>();
1250 images_[img_idx].evaluated = true;
1251 }
1252 }
1253}
1254
1256{
1257 const int N = numImages();
1258 if (N < 3) return 0.0;
1259
1260 double total = 0.0;
1261 std::vector<double> seg(N - 1, 0.0);
1262 for (int i = 0; i < N - 1; ++i) {
1263 seg[i] =
1264 segmentDisplacement(images_[i].positions, images_[i + 1].positions)
1265 .norm();
1266 total += seg[i];
1267 }
1268 if (total < 1e-30) return 0.0;
1269 const double h = total / static_cast<double>(N - 1);
1270 double max_dev = 0.0;
1271 for (int i = 0; i < N - 1; ++i) {
1272 max_dev = std::max(max_dev, std::abs(seg[i] - h) / h);
1273 }
1274 return max_dev;
1275}
1276
1278 const std::vector<Eigen::MatrixXd>& segment_metric_factors) const
1279{
1280 const int N = numImages();
1281 if (N < 3) return 0.0;
1282 const Eigen::Index dof = images_[0].positions.size();
1283 if (static_cast<int>(segment_metric_factors.size()) != N - 1) {
1284 throw std::invalid_argument(
1285 "NEBPath metric spacing requires one factor per segment");
1286 }
1287
1288 double total = 0.0;
1289 std::vector<double> seg(static_cast<std::size_t>(N - 1), 0.0);
1290 for (int i = 0; i < N - 1; ++i) {
1291 const Eigen::MatrixXd& B =
1292 segment_metric_factors[static_cast<std::size_t>(i)];
1293 if (B.cols() != dof || B.rows() == 0 || !B.allFinite()) {
1294 throw std::invalid_argument(
1295 "NEBPath metric factor has incompatible shape or non-finite "
1296 "entries");
1297 }
1298 const Eigen::VectorXd delta =
1299 segmentDisplacement(images_[i].positions, images_[i + 1].positions);
1300 seg[static_cast<std::size_t>(i)] = (B * delta).norm();
1301 total += seg[static_cast<std::size_t>(i)];
1302 }
1303 if (total <= std::numeric_limits<double>::min()) return 0.0;
1304 const double h = total / static_cast<double>(N - 1);
1305 double max_dev = 0.0;
1306 for (double length: seg) {
1307 max_dev = std::max(max_dev, std::abs(length - h) / h);
1308 }
1309 return max_dev;
1310}
1311
1313{
1314 const int N = numImages();
1315 if (N < 3) return 0.0;
1316
1317 // Cumulative arc length along the current chain.
1318 std::vector<double> s(N, 0.0);
1319 for (int i = 1; i < N; ++i) {
1320 s[i] = s[i - 1] + segmentDisplacement(images_[i - 1].positions,
1321 images_[i].positions)
1322 .norm();
1323 }
1324 return reparametrizeFromCumulativeArc(s);
1325}
1326
1328{
1329 const int N = numImages();
1330 if (N < 3) return 0.0;
1331
1332 std::vector<double> s(N, 0.0);
1333 for (int i = 1; i < N; ++i) {
1334 s[i] = s[i - 1] + segmentDisplacement(images_[i - 1].positions,
1335 images_[i].positions)
1336 .norm();
1337 }
1338 return reparametrizeFromCumulativeArc(s, anchor_index);
1339}
1340
1342 const std::vector<Eigen::MatrixXd>& segment_metric_factors)
1343{
1344 const int N = numImages();
1345 if (N < 3) return 0.0;
1346 const Eigen::Index dof = images_[0].positions.size();
1347 if (static_cast<int>(segment_metric_factors.size()) != N - 1) {
1348 throw std::invalid_argument(
1349 "NEBPath metric reparameterization requires one factor per "
1350 "segment");
1351 }
1352
1353 std::vector<double> s(N, 0.0);
1354 for (int i = 1; i < N; ++i) {
1355 const Eigen::MatrixXd& B =
1356 segment_metric_factors[static_cast<std::size_t>(i - 1)];
1357 if (B.cols() != dof || B.rows() == 0 || !B.allFinite()) {
1358 throw std::invalid_argument(
1359 "NEBPath metric factor has incompatible shape or non-finite "
1360 "entries");
1361 }
1362 const Eigen::VectorXd delta =
1363 segmentDisplacement(images_[i - 1].positions, images_[i].positions);
1364 s[i] = s[i - 1] + (B * delta).norm();
1365 }
1366 return reparametrizeFromCumulativeArc(s);
1367}
1368
1370 const std::vector<Eigen::MatrixXd>& segment_metric_factors,
1371 int anchor_index)
1372{
1373 const int N = numImages();
1374 if (N < 3) return 0.0;
1375 const Eigen::Index dof = images_[0].positions.size();
1376 if (static_cast<int>(segment_metric_factors.size()) != N - 1) {
1377 throw std::invalid_argument(
1378 "NEBPath metric reparameterization requires one factor per "
1379 "segment");
1380 }
1381
1382 std::vector<double> s(N, 0.0);
1383 for (int i = 1; i < N; ++i) {
1384 const Eigen::MatrixXd& B =
1385 segment_metric_factors[static_cast<std::size_t>(i - 1)];
1386 if (B.cols() != dof || B.rows() == 0 || !B.allFinite()) {
1387 throw std::invalid_argument(
1388 "NEBPath metric factor has incompatible shape or non-finite "
1389 "entries");
1390 }
1391 const Eigen::VectorXd delta =
1392 segmentDisplacement(images_[i - 1].positions, images_[i].positions);
1393 s[i] = s[i - 1] + (B * delta).norm();
1394 }
1395 return reparametrizeFromCumulativeArc(s, anchor_index);
1396}
1397
1399 const int n_atoms) const
1400{
1401 return inverseDistanceSegmentMetricFactors(n_atoms, {});
1402}
1403
1405 const int n_atoms, const std::vector<char>& moving_atoms) const
1406{
1407 const int N = numImages();
1408 if (N < 2) return {};
1409 if (n_atoms < 2) {
1410 throw std::invalid_argument(
1411 "NEBPath inverse-distance metric requires at least two atoms");
1412 }
1413 const Eigen::Index dof = images_[0].positions.size();
1414 if (dof != static_cast<Eigen::Index>(3 * n_atoms)) {
1415 throw std::invalid_argument(
1416 "NEBPath inverse-distance metric atom count does not match "
1417 "coordinates");
1418 }
1419 if (!moving_atoms.empty() &&
1420 static_cast<int>(moving_atoms.size()) != n_atoms) {
1421 throw std::invalid_argument(
1422 "NEBPath inverse-distance moving-atom mask size mismatch");
1423 }
1424 std::vector<std::pair<int, int>> active_pairs;
1425 active_pairs.reserve(static_cast<std::size_t>(n_atoms * (n_atoms - 1) / 2));
1426 for (int a = 0; a < n_atoms; ++a) {
1427 const bool a_active =
1428 moving_atoms.empty() || moving_atoms[static_cast<std::size_t>(a)];
1429 for (int b = a + 1; b < n_atoms; ++b) {
1430 const bool b_active = moving_atoms.empty() ||
1431 moving_atoms[static_cast<std::size_t>(b)];
1432 if (a_active || b_active) active_pairs.emplace_back(a, b);
1433 }
1434 }
1435 if (active_pairs.empty()) {
1436 throw std::invalid_argument(
1437 "NEBPath inverse-distance metric has no active atom pairs");
1438 }
1439 const Eigen::Index n_pairs = static_cast<Eigen::Index>(active_pairs.size());
1440 std::vector<Eigen::MatrixXd> factors(static_cast<std::size_t>(N - 1));
1441
1442 for (int seg = 0; seg < N - 1; ++seg) {
1443 Eigen::VectorXd midpoint;
1444 if (molecularRigidMotion()) {
1445 midpoint = images_[seg].positions +
1446 0.5 * segmentDisplacement(images_[seg].positions,
1447 images_[seg + 1].positions);
1448 } else {
1449 midpoint =
1450 0.5 * (images_[seg].positions + images_[seg + 1].positions);
1451 }
1452 if (midpoint.size() != dof || !midpoint.allFinite()) {
1453 throw std::invalid_argument(
1454 "NEBPath inverse-distance metric received invalid coordinates");
1455 }
1456
1457 Eigen::MatrixXd B = Eigen::MatrixXd::Zero(n_pairs, dof);
1458 Eigen::Index row = 0;
1459 for (const auto& pair: active_pairs) {
1460 const int a = pair.first;
1461 const int b = pair.second;
1462 const Eigen::Vector3d Ra = midpoint.segment<3>(3 * a);
1463 const Eigen::Vector3d Rb = midpoint.segment<3>(3 * b);
1464 const Eigen::Vector3d d = Rb - Ra;
1465 const double r2 = d.squaredNorm();
1466 if (r2 <= std::numeric_limits<double>::min()) {
1467 throw std::invalid_argument(
1468 "NEBPath inverse-distance metric has a degenerate atom "
1469 "pair");
1470 }
1471 const double inv_r3 = 1.0 / (r2 * std::sqrt(r2));
1472 const Eigen::Vector3d grad_a = inv_r3 * d;
1473 B.block<1, 3>(row, 3 * a) = grad_a.transpose();
1474 B.block<1, 3>(row, 3 * b) = -grad_a.transpose();
1475 ++row;
1476 }
1477 factors[static_cast<std::size_t>(seg)] = std::move(B);
1478 }
1479
1480 return factors;
1481}
1482
1483void NEBPath::invalidateResampledImage(int index)
1484{
1485 const Eigen::Index dof = images_[0].positions.size();
1486 images_[index].energy = 0.0;
1487 if (images_[index].gradient.size() == dof) {
1488 images_[index].gradient.setZero();
1489 }
1490 images_[index].evaluated = false;
1491 images_[index].posterior_variance = std::numeric_limits<double>::infinity();
1492 if (static_cast<std::size_t>(index) < force_variance_.size()) {
1493 force_variance_[static_cast<std::size_t>(index)].resize(0);
1494 }
1495}
1496
1501
1503 int n_atoms, const std::vector<char>& moving_atoms)
1504{
1506 n_atoms, moving_atoms, -1);
1507}
1508
1510 int n_atoms, const std::vector<char>& moving_atoms, int anchor_index)
1511{
1512 const int N = numImages();
1513 if (N < 3) return 0.0;
1514 const Eigen::Index dof = images_[0].positions.size();
1515 const auto system = makeInverseDistanceSystem(
1516 n_atoms, dof, moving_atoms, periodic_ ? &periodic_box_ : nullptr);
1517 const bool keep_anchor = anchor_index > 0 && anchor_index < N - 1;
1518
1519 std::vector<Eigen::VectorXd> orig(static_cast<std::size_t>(N));
1520 std::vector<Eigen::VectorXd> q(static_cast<std::size_t>(N));
1521 for (int i = 0; i < N; ++i) {
1522 orig[static_cast<std::size_t>(i)] = images_[i].positions;
1523 if (orig[static_cast<std::size_t>(i)].size() != dof ||
1524 !orig[static_cast<std::size_t>(i)].allFinite()) {
1525 throw std::invalid_argument(
1526 "NEBPath inverse-distance geodesic received invalid "
1527 "coordinates");
1528 }
1529 q[static_cast<std::size_t>(i)] =
1530 system.values(orig[static_cast<std::size_t>(i)]);
1531 }
1532
1533 std::vector<double> s(static_cast<std::size_t>(N), 0.0);
1534 for (int i = 1; i < N; ++i) {
1535 s[static_cast<std::size_t>(i)] = s[static_cast<std::size_t>(i - 1)] +
1536 (q[static_cast<std::size_t>(i)] -
1537 q[static_cast<std::size_t>(i - 1)])
1538 .norm();
1539 }
1540 const double total = s.back() - s.front();
1541 if (total <= std::numeric_limits<double>::min()) return 0.0;
1542 // Rest lengths are fractions of this q-space arc, including on each side
1543 // of an anchor. Without them the chain stays equally spaced in q.
1544 const std::vector<double> rest_targets =
1545 restLengthSegmentTargets(s, spring_rest_lengths_, anchor_index);
1546 const double max_dev =
1547 rest_targets.empty()
1548 ? spacingDeviationFromCumulativeArc(s, anchor_index)
1549 : deviationFromSegmentTargets(s, rest_targets);
1550 if (max_dev <= std::sqrt(std::numeric_limits<double>::epsilon())) {
1551 return max_dev;
1552 }
1553
1554 for (int j = 1; j < N - 1; ++j) {
1555 if (keep_anchor && j == anchor_index) continue;
1556 const double s_target = rest_targets.empty()
1557 ? targetArcForImage(s, j, anchor_index)
1558 : cumulativeTargetArc(s, rest_targets, j);
1559 int k = 0;
1560 while (k < N - 2 && s[static_cast<std::size_t>(k + 1)] < s_target) {
1561 ++k;
1562 }
1563 const double denom =
1564 s[static_cast<std::size_t>(k + 1)] - s[static_cast<std::size_t>(k)];
1565 const double alpha =
1566 (denom > std::numeric_limits<double>::min())
1567 ? (s_target - s[static_cast<std::size_t>(k)]) / denom
1568 : 0.0;
1569 const Eigen::VectorXd q_target =
1570 q[static_cast<std::size_t>(k)] +
1571 alpha * (q[static_cast<std::size_t>(k + 1)] -
1572 q[static_cast<std::size_t>(k)]);
1573 const Eigen::VectorXd start =
1574 orig[static_cast<std::size_t>(k)] +
1575 alpha * segmentDisplacement(orig[static_cast<std::size_t>(k)],
1576 orig[static_cast<std::size_t>(k + 1)]);
1577 images_[j].positions = alignMolecularGeometry(
1578 orig[static_cast<std::size_t>(j)],
1579 solveInverseDistanceTarget(system, start, q_target));
1580 pinFixedAtoms(images_[j].positions);
1581 invalidateResampledImage(j);
1582 }
1583
1584 for (int i = 1; i < N - 1; ++i) {
1585 if (neb_forces_[i].size() == dof) {
1586 neb_forces_[i].setZero();
1587 }
1588 }
1589
1590 return max_dev;
1591}
1592
1594 int n_atoms, const std::vector<char>& moving_atoms,
1595 const Eigen::VectorXd& positions, const Eigen::VectorXd& cartesian_step,
1596 const std::array<double, 9>* cell)
1597{
1598 if (positions.size() != cartesian_step.size()) {
1599 throw std::invalid_argument(
1600 "NEBPath inverse-distance geodesic step size mismatch");
1601 }
1602 if (!positions.allFinite() || !cartesian_step.allFinite()) {
1603 throw std::invalid_argument(
1604 "NEBPath inverse-distance geodesic step received invalid "
1605 "coordinates");
1606 }
1607 gpr::geometry::PairBox periodic_box;
1608 const bool periodic =
1609 cell != nullptr && gpr::geometry::cellIsMicLattice(cell->data());
1610 if (periodic) periodic_box.reset(cell->data());
1611 const auto system =
1612 makeInverseDistanceSystem(n_atoms, positions.size(), moving_atoms,
1613 periodic ? &periodic_box : nullptr);
1614 Eigen::VectorXd active_step(
1615 static_cast<Eigen::Index>(system.active_columns.size()));
1616 Eigen::VectorXd start = positions;
1617 for (Eigen::Index col = 0; col < active_step.size(); ++col) {
1618 const Eigen::Index full_col =
1619 system.active_columns[static_cast<std::size_t>(col)];
1620 active_step(col) = cartesian_step(full_col);
1621 start(full_col) += cartesian_step(full_col);
1622 }
1623 const Eigen::VectorXd target =
1624 system.values(positions) +
1625 system.jacobianActive(positions) * active_step;
1626 return solveInverseDistanceTarget(system, start, target);
1627}
1628
1630 int n_atoms, const std::vector<char>& moving_atoms,
1631 const Eigen::VectorXd& left, const Eigen::VectorXd& right, double alpha,
1632 const std::array<double, 9>* cell)
1633{
1634 if (left.size() != right.size()) {
1635 throw std::invalid_argument(
1636 "NEBPath inverse-distance interpolation size mismatch");
1637 }
1638 if (!left.allFinite() || !right.allFinite() || !std::isfinite(alpha)) {
1639 throw std::invalid_argument(
1640 "NEBPath inverse-distance interpolation received invalid "
1641 "coordinates");
1642 }
1643 if (alpha < 0.0 || alpha > 1.0) {
1644 throw std::invalid_argument(
1645 "NEBPath inverse-distance interpolation requires alpha in [0, 1]");
1646 }
1647 if (alpha == 0.0) return left;
1648
1649 gpr::geometry::PairBox periodic_box;
1650 const bool periodic =
1651 cell != nullptr && gpr::geometry::cellIsMicLattice(cell->data());
1652 if (periodic) periodic_box.reset(cell->data());
1653 const auto system = makeInverseDistanceSystem(
1654 n_atoms, left.size(), moving_atoms, periodic ? &periodic_box : nullptr);
1655 Eigen::VectorXd right_active = left;
1656 Eigen::VectorXd start = left;
1657 for (Eigen::Index col = 0;
1658 col < static_cast<Eigen::Index>(system.active_columns.size()); ++col) {
1659 const Eigen::Index full_col =
1660 system.active_columns[static_cast<std::size_t>(col)];
1661 right_active(full_col) = right(full_col);
1662 if (periodic) {
1663 const Eigen::Index origin = full_col - full_col % 3;
1664 const Eigen::Vector3d from = left.segment<3>(origin);
1665 const Eigen::Vector3d to = right.segment<3>(origin);
1666 const Eigen::Vector3d chord = periodic_box.displacement(from, to);
1667 start(full_col) =
1668 left(full_col) + alpha * chord(static_cast<int>(full_col % 3));
1669 } else {
1670 start(full_col) =
1671 (1.0 - alpha) * left(full_col) + alpha * right(full_col);
1672 }
1673 }
1674 if (alpha == 1.0) return right_active;
1675
1676 const Eigen::VectorXd target = (1.0 - alpha) * system.values(left) +
1677 alpha * system.values(right_active);
1678 return solveInverseDistanceTarget(system, start, target);
1679}
1680
1681double NEBPath::reparametrizeFromCumulativeArc(const std::vector<double>& s)
1682{
1683 return reparametrizeFromCumulativeArc(s, -1);
1684}
1685
1686double NEBPath::reparametrizeFromCumulativeArc(const std::vector<double>& s,
1687 int anchor_index)
1688{
1689 const int N = numImages();
1690 if (N < 3) return 0.0;
1691 if (static_cast<int>(s.size()) != N) {
1692 throw std::invalid_argument(
1693 "NEBPath cumulative arc vector size must match the path");
1694 }
1695 for (double arc: s) {
1696 if (!std::isfinite(arc)) {
1697 throw std::invalid_argument(
1698 "NEBPath cumulative arc contains non-finite entries");
1699 }
1700 }
1701 for (int i = 1; i < N; ++i) {
1702 if (s[i] < s[i - 1]) {
1703 throw std::invalid_argument(
1704 "NEBPath cumulative arc must be non-decreasing");
1705 }
1706 }
1707
1708 const Eigen::Index dof = images_[0].positions.size();
1709 const double L = s[N - 1];
1710 if (L <= std::numeric_limits<double>::min()) return 0.0;
1711 const bool keep_anchor = anchor_index > 0 && anchor_index < N - 1;
1712
1713 // Target cumulative fractions c_j: the rest-length fractions when
1714 // spring rest lengths are set, equal spacing otherwise. With an anchor
1715 // each side keeps its own arc and the fractions are renormalised on it.
1716 std::vector<double> c(N, 0.0);
1717 if (static_cast<int>(spring_rest_lengths_.size()) == N - 1) {
1718 double total = 0.0;
1719 for (double rest: spring_rest_lengths_)
1720 total += rest;
1721 for (int i = 1; i < N; ++i)
1722 c[i] =
1723 c[i - 1] +
1724 spring_rest_lengths_[static_cast<std::size_t>(i - 1)] / total;
1725 } else {
1726 for (int i = 0; i < N; ++i)
1727 c[i] = static_cast<double>(i) / static_cast<double>(N - 1);
1728 }
1729 c[N - 1] = 1.0;
1730 std::vector<double> target(N - 1, 0.0);
1731 if (keep_anchor) {
1732 const double left_length = s[anchor_index] - s[0];
1733 const double right_length = s[N - 1] - s[anchor_index];
1734 const double c_a = c[anchor_index];
1735 for (int i = 0; i < N - 1; ++i) {
1736 if (i < anchor_index) {
1737 target[i] = (c_a > 0.0) ? (c[i + 1] - c[i]) / c_a * left_length
1738 : s[i + 1] - s[i];
1739 } else {
1740 target[i] = (c_a < 1.0)
1741 ? (c[i + 1] - c[i]) / (1.0 - c_a) * right_length
1742 : s[i + 1] - s[i];
1743 }
1744 }
1745 } else {
1746 for (int i = 0; i < N - 1; ++i)
1747 target[i] = (c[i + 1] - c[i]) * L;
1748 }
1749
1750 double max_dev = 0.0;
1751 for (int i = 0; i < N - 1; ++i) {
1752 if (target[i] > std::numeric_limits<double>::min()) {
1753 max_dev = std::max(
1754 max_dev, std::abs((s[i + 1] - s[i]) - target[i]) / target[i]);
1755 }
1756 }
1757
1758 std::vector<Eigen::VectorXd> orig(N);
1759 for (int i = 0; i < N; ++i)
1760 orig[i] = images_[i].positions;
1761
1762 // Piecewise-linear resampling: for interior image j, locate
1763 // segment [k, k+1] with s[k] <= s_target_j < s[k+1] and linearly
1764 // interpolate. Endpoint segments are exact (s[0] = 0, s[N-1] = L)
1765 // so j=1 and j=N-2 are not edge cases.
1766 for (int j = 1; j < N - 1; ++j) {
1767 if (keep_anchor && j == anchor_index) continue;
1768 double s_target = s[0];
1769 for (int i = 0; i < j; ++i)
1770 s_target += target[i];
1771 int k = 0;
1772 while (k < N - 2 && s[k + 1] < s_target)
1773 ++k;
1774 const double denom = s[k + 1] - s[k];
1775 const double alpha = (denom > std::numeric_limits<double>::min())
1776 ? (s_target - s[k]) / denom
1777 : 0.0;
1778 images_[j].positions = alignMolecularGeometry(
1779 orig[j],
1780 orig[k] + alpha * segmentDisplacement(orig[k], orig[k + 1]));
1781 pinFixedAtoms(images_[j].positions);
1782 invalidateResampledImage(j);
1783 }
1784
1785 // The cached NEB forces are now stale (positions moved); zero
1786 // them so a caller that forgets to call computeNEBForces() gets a
1787 // visibly-broken zero step rather than a silently wrong stale one.
1788 for (int i = 1; i < N - 1; ++i) {
1789 if (neb_forces_[i].size() == dof) {
1790 neb_forces_[i].setZero();
1791 }
1792 }
1793
1794 return max_dev;
1795}
1796
1797} // namespace neb
1798} // namespace gpr
@ x
Definition Enums.h:28
NEB path management: image chain, spring forces, climbing image.
void reset(const double cell[9])
Definition MinImage.h:180
bool periodic() const noexcept
Some axis is periodic.
Definition MinImage.h:198
void displacement(const double p[3], const double q[3], double dr[3]) const
Displacement from p to q. Cartesian q - p when the cell is zero.
Definition MinImage.h:210
static Eigen::VectorXd inverseDistanceGeodesicStep(int n_atoms, const std::vector< char > &moving_atoms, const Eigen::VectorXd &positions, const Eigen::VectorXd &cartesian_step, const std::array< double, 9 > *cell=nullptr)
Apply one inverse-distance internal-coordinate retraction.
Definition NEBPath.cpp:1593
std::vector< Eigen::MatrixXd > inverseDistanceSegmentMetricFactors(int n_atoms) const
Build segment metric factors for inverse-distance coordinates.
Definition NEBPath.cpp:1398
int highestEnergyImageIndex() const
Highest finite interior energy, or -1 when none exists.
Definition NEBPath.cpp:1132
double reparametrizeByArcLengthKeepingImage(int anchor_index)
Redistribute the two subchains while preserving one image.
Definition NEBPath.cpp:1327
void setForceVariance(int i, const Eigen::VectorXd &variance)
Definition NEBPath.cpp:857
void setSpringRestLengths(std::vector< double > rest_lengths)
Per-segment spring rest lengths (numImages()-1 entries).
Definition NEBPath.cpp:1102
double reparametrizeByArcLength()
Redistribute interior images uniformly along arc length.
Definition NEBPath.cpp:1312
int highestLocalMaximumImageIndex() const
Strict interior local maximum, else the highest finite energy.
Definition NEBPath.cpp:1188
void setFromObservation(const Observation &obs, int start_image=1)
Set energies and gradients for images from an Observation.
Definition NEBPath.cpp:1242
void setExternalFixedAtoms(bool present)
Definition NEBPath.cpp:436
NEBPath(const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int n_images, double spring_constant=0.1)
Initialize path with linear interpolation between endpoints.
Definition NEBPath.cpp:359
double maxSpacingDeviation() const
Maximum relative deviation of image spacing from uniform.
Definition NEBPath.cpp:1255
void maskFixedForce(Eigen::Ref< Eigen::VectorXd > force) const
Zero a force on fixed atoms.
Definition NEBPath.cpp:563
void setMolecularRigidMotion(bool enabled)
Definition NEBPath.cpp:491
int numImages() const
Definition NEBPath.h:338
void initializeIDPP(int n_atoms, bool collective=false)
Initialize from IDPP (image dependent pair potential) interpolation.
Definition NEBPath.cpp:697
void projectPhysicalVector(const Eigen::VectorXd &reference, Eigen::Ref< Eigen::VectorXd > vector) const
Definition NEBPath.cpp:503
double reparametrizeByMetricArcLength(const std::vector< Eigen::MatrixXd > &segment_metric_factors)
Redistribute interior images uniformly in a pullback metric.
Definition NEBPath.cpp:1341
void alignMolecularFrames()
Normalize seed frames before evaluation, invalidating changed images.
Definition NEBPath.cpp:538
void enableClimbingImage()
Enable climbing image on the highest-energy intermediate image.
Definition NEBPath.cpp:1121
void initializeSIDPP(int n_atoms, double alpha=0.33)
Initialize via Sequential IDPP (SIDPP). rgsaddle_sidpp_alternating_path. The spring on that call is t...
Definition NEBPath.cpp:712
bool hasForceVariance(int i) const
Definition NEBPath.cpp:871
void interpolateFromEndpoints()
Rebuild interior images on the chord between the current endpoints.
Definition NEBPath.cpp:610
void setSpringCoordinates(std::vector< Eigen::Index > coordinates, std::vector< double > weights={})
Band coordinates that carry the springs; empty means all.
Definition NEBPath.cpp:441
bool molecularRigidMotion() const
Definition NEBPath.cpp:496
void setMovingAtoms(std::vector< char > moving_atoms)
Definition NEBPath.cpp:424
double tangentStiffness(int i) const
Stiffness the tangent adds to image i across the path.
Definition NEBPath.cpp:838
void initializeSIDPPGeodesic(int n_atoms, double alpha=0.33)
Initialize via inverse-distance S-IDPP. rgsaddle_sidpp_alternating_inverse_distance_path....
Definition NEBPath.cpp:732
void pinFixedAtoms(Eigen::Ref< Eigen::VectorXd > positions) const
Copy reactant coordinates onto fixed atoms.
Definition NEBPath.cpp:552
double reparametrizeByInverseDistanceGeodesicArcLength(int n_atoms)
Redistribute the band by solving inverse-distance targets.
Definition NEBPath.cpp:1497
int numIntermediate() const
Definition NEBPath.h:342
void setPeriodicCell(const std::array< double, 9 > &cell)
Definition NEBPath.cpp:414
EigenMatrix intermediatePositions() const
Get all intermediate image positions as a matrix.
Definition NEBPath.cpp:1231
double reparametrizeByInverseDistanceGeodesicArcLengthKeepingImage(int n_atoms, const std::vector< char > &moving_atoms, int anchor_index)
Anchor-preserving inverse-distance geodesic reparameterization.
Definition NEBPath.cpp:1509
double reparametrizeByMetricArcLengthKeepingImage(const std::vector< Eigen::MatrixXd > &segment_metric_factors, int anchor_index)
Metric pullback variant of reparametrizeByArcLengthKeepingImage().
Definition NEBPath.cpp:1369
int highestEnergyImageIndexPreferring(int preferred) const
Definition NEBPath.cpp:1165
void clearForceVariance()
Definition NEBPath.cpp:866
void computeNEBForces()
Compute NEB forces for all intermediate images.
Definition NEBPath.cpp:880
static Eigen::VectorXd inverseDistanceGeodesicInterpolate(int n_atoms, const std::vector< char > &moving_atoms, const Eigen::VectorXd &left, const Eigen::VectorXd &right, double alpha, const std::array< double, 9 > *cell=nullptr)
Interpolate between two geometries in inverse-distance space.
Definition NEBPath.cpp:1629
Eigen::VectorXd alignMolecularGeometry(const Eigen::VectorXd &reference, const Eigen::VectorXd &geometry) const
Proper rigid alignment with fixed atom correspondence; no reassignment.
Definition NEBPath.cpp:517
double maxMetricSpacingDeviation(const std::vector< Eigen::MatrixXd > &segment_metric_factors) const
Maximum relative spacing deviation measured in a pullback metric.
Definition NEBPath.cpp:1277
Image & image(int i)
Access image i.
Definition NEBPath.h:329
int highestLocalMaximumImageIndexPreferring(int preferred) const
Definition NEBPath.cpp:1219
int idppFixedPath(int64_t n_images, int64_t n_atoms, const double *reactant, const double *product, const double *cell, const uint8_t *mask, int64_t max_iterations, double grad_tol, double max_move, double *out)
int sidppAlternatingPath(bool inverse_distance, int64_t n_images, int64_t n_atoms, const double *reactant, const double *product, const double *cell, const uint8_t *mask, double alpha, int64_t short_iterations, int64_t final_iterations, double force_tol, double max_move, double spring, double *out)
rgsaddle_sidpp_alternating_path, or its inverse-distance variant.
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
Eigen::VectorXd kabschAlignProductToReactant(const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions)
Eigen::MatrixXd rigid_motion_basis(const gpr::Coord &R, bool rotations)
Build an orthonormal basis for rigid-body translations and rotations.
Definition Dimer.cpp:30
bool cellIsMicLattice(const double cell[9]) noexcept
Nonzero ASE 3x3 that is not the 25 A vacuum convention.
Definition MinImage.h:56
Eigen::VectorXd flatMinimumImageDisplacement(const PairBox *box, const Eigen::VectorXd &from, const Eigen::VectorXd &to)
Definition MinImage.h:259
The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition,...
double saddleForceMagnitude(const Eigen::VectorXd &gradient)
Definition NEBPath.cpp:25
Eigen::VectorXd projectPerpendicularDiagonal(const Eigen::VectorXd &force, const Eigen::VectorXd &tangent, const Eigen::VectorXd &force_variance)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
FieldMatrixd Coord
Definition Macros.h:35
double forceNorm(const Eigen::MatrixBase< Derived > &force, ConvergenceNormType norm)
Definition ForceNorm.h:45
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Observation data: energy, gradient and positions.
FieldMatrixd E
A single image on the NEB path.
Definition NEBPath.h:39