Loading...
Searching...
No Matches
NEBOcinebController.cpp
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
13#include "eon/EonLogger.h"
14#include "eon/ForceNorm.h"
18#include "eon/eonExceptions.hpp"
19#include <algorithm>
20#include <cmath>
21#include <stdexcept>
22
23namespace eonc::neb {
24
27 auto &ci = params.neb_options().climbing_image;
28 auto &r = ci.ocineb;
29 return Config{
30 r.use_mmf,
31 r.trigger_force,
32 r.trigger_factor,
33 r.max_steps,
34 r.ci_stability_count,
35 r.angle_tol,
37 r.restore_unhelpful,
38 };
39}
40
43
45 std::string_view metric) {
46 if (metric == "norm")
47 return freeForces.norm();
48 if (metric == "max_atom")
49 return maxFreeAtomForceNorm(freeForces.data(), nullptr, freeForces.rows());
50 if (metric == "max_component")
51 return freeForces.size() == 0 ? 0.0 : freeForces.cwiseAbs().maxCoeff();
52 throw std::invalid_argument("OCINEB: unknown convergence metric");
53}
54
55void OCINEBController::initBaseline(double baseline_force) {
56 baseline_force_ = baseline_force;
57 current_threshold_ = std::max(baseline_force_ * cfg_.trigger_factor,
58 2.0 * cfg_.force_tolerance);
59}
60
61bool OCINEBController::shouldTrigger(double convForce, bool ci_active,
62 long climbingImage, long numImages,
63 int ciStabilityCounter) const {
64 if (!cfg_.use_mmf || !ci_active)
65 return false;
66 if (climbingImage <= 0 || climbingImage > numImages)
67 return false;
68 if (ciStabilityCounter <= static_cast<int>(cfg_.ci_stability_count))
69 return false;
70 if (convForce <= cfg_.force_tolerance)
71 return false;
72 return convForce < current_threshold_;
73}
74
75void OCINEBController::updateStability(long climbingImage) {
76 if (climbingImage == previousClimbingImage_) {
78 } else {
80 previousClimbingImage_ = climbingImage;
81 has_cached_mode_ = false;
82 }
83}
84
86 double convForce) {
87 auto *log = eonc::log::get();
88
89 QUILL_LOG_DEBUG(log,
90 "Triggering MMF. Force: {:.4f}, Threshold: {:.4f} "
91 "({:.2f}x baseline)",
92 convForce, current_threshold_,
94
95 // The dimer moves this image. updateForces() may then hop
96 // climbingImage to a neighbor; band CI force is that neighbor.
97 const long walked = neb.climbingImage;
98 AtomMatrix savedPositions = neb.path[walked]->getPositions();
99 const double previousWalkedForce =
100 forceMeasure(neb.path[walked]->getForcesFree(),
101 neb.params.optimizer_options().convergence_metric);
102 // The saved geometry is evaluated already; a restore puts its forces
103 // back instead of asking the potential again.
104 const AtomMatrix savedForces = neb.path[walked]->getForcesRaw();
105 const double savedEnergy = neb.path[walked]->getPotentialEnergy();
106
107 double alignment = 0.0;
108 int mmfResult = runDimer(neb, alignment);
109
110 // Always update forces after MMF
111 neb.movedAfterForceCall = true;
112 neb.updateForces();
113 double newForce = neb.convergenceForce();
114
115 // A positive-curvature walk can put the band force under tolerance
116 // while the climbing image sits in a well. Restore that image
117 // before accepting the band.
118 if (convergedClimb(newForce, cfg_.force_tolerance, mmfResult)) {
119 QUILL_LOG_DEBUG(log, "NEB converged after MMF. Force: {:.4f}", newForce);
120 return {newForce, true, false};
121 }
122
123 const double walkedForce =
124 forceMeasure(neb.path[walked]->getForcesFree(),
125 neb.params.optimizer_options().convergence_metric);
126 const bool mmfHelped =
127 walkHelped(walkedForce, previousWalkedForce, mmfResult);
128
129 if (mmfHelped) {
130 updateThresholdSuccess(previousWalkedForce, walkedForce);
131 QUILL_LOG_DEBUG(log,
132 "MMF helped (status={}, walked={}, now_ci={}). "
133 "Walked force: {:.4f} -> {:.4f} ({:.2f}x baseline). "
134 "Band CI force: {:.4f}. New threshold: {:.4f}",
135 mmfResult, walked, neb.climbingImage, previousWalkedForce,
136 walkedForce, walkedForce / baseline_force_, newForce,
138 } else {
139 // Frontiers OCI-NEB (doi:10.3389/fchem.2026.1807063, Algorithm 1)
140 // restores only on positive curvature (status -2). Alignment
141 // failure keeps the walked CI and applies the linear penalty.
142 // restore_unhelpful also restores on alignment reject / force
143 // increase on the walked image. Default false: the paper setting.
144 const bool restore = cfg_.restore_unhelpful || mmfResult == -2;
145 if (restore) {
146 neb.path[walked]->setPositions(savedPositions);
147 neb.path[walked]->setEvaluation(savedForces, savedEnergy);
148 neb.movedAfterForceCall = true;
149 has_cached_mode_ = false;
150 newForce = convForce;
151 }
152 updateThresholdBackoff(alignment);
153 QUILL_LOG_DEBUG(
154 log,
155 "MMF backoff (status={}, walked={}, now_ci={}). "
156 "Walked force: {:.4f} -> {:.4f}, band CI: {:.4f}, "
157 "Alignment: {:.3f}. {}New threshold: {:.4f} ({:.2f}x baseline)",
158 mmfResult, walked, neb.climbingImage, previousWalkedForce, walkedForce,
159 newForce, alignment, restore ? "Restored CI. " : "", current_threshold_,
161 }
162
163 if (mmfHelped) {
164 // A helpful walk changes the spacing for molecular and periodic paths.
165 // Reparameterization preserves endpoints and invalidates band secants.
167 std::span{neb.path.data(), neb.path.size()});
168 neb.movedAfterForceCall = true;
169 }
170
171 bool shouldReset =
172 mmfHelped || (savedPositions - neb.path[walked]->getPositions()).norm() >
173 neb.params.optimizer_options().max_move *
174 neb.params.neb_options().image_count;
175
176 if (shouldReset) {
177 QUILL_LOG_DEBUG(log, "Resetting optimization history.");
178 }
179
181
182 return {newForce, false, shouldReset};
183}
184
186 double &alignment) {
187 auto *log = eonc::log::get();
188 alignment = 0.0;
189
190 if (neb.climbingImage <= 0 || neb.climbingImage > neb.numImages) {
191 QUILL_LOG_WARNING(log, "Invalid climbing image for MMF: {}",
192 neb.climbingImage);
193 return -1;
194 }
195
196 AtomMatrix initialMode;
197 if (has_cached_mode_) {
198 initialMode = cached_mode_;
199 } else {
200 initialMode = *neb.tangent[neb.climbingImage];
201 }
202 double tangentNorm = initialMode.norm();
203 if (tangentNorm < 1e-8) {
204 QUILL_LOG_WARNING(log, "Tangent too small for MMF initialization");
205 return -1;
206 }
207 initialMode /= tangentNorm;
208
209 auto tempMinModeSearch = std::make_shared<MinModeSaddleSearch>(
210 neb.path[neb.climbingImage], initialMode,
211 neb.path[neb.climbingImage]->getPotentialEnergy(), neb.params, neb.pot);
212
213 int minModeStatus;
214 try {
215 minModeStatus = tempMinModeSearch->run(cfg_.max_steps);
216 } catch (const eonc::DimerModeRestoredException &) {
218 QUILL_LOG_DEBUG(log, "MMF: Dimer restored to best state");
219 } catch (const eonc::DimerModeLostException &) {
221 QUILL_LOG_WARNING(log, "Dimer lost mode during MMF refinement");
222 }
223
224 mmf_iterations_used_ += tempMinModeSearch->iteration;
225
226 double eigenvalue = tempMinModeSearch->getEigenvalue();
227 if (eigenvalue > 0.0) {
228 QUILL_LOG_WARNING(log,
229 "MMF skipped: Positive curvature detected (eig={:.4f}).",
230 eigenvalue);
231 return -2;
232 }
233
234 AtomMatrix finalModeMatrix = tempMinModeSearch->getEigenvector();
235 VectorXd finalMode =
236 VectorXd::Map(finalModeMatrix.data(), finalModeMatrix.size());
237 VectorXd currentTangent =
238 VectorXd::Map(neb.tangent[neb.climbingImage]->data(),
239 neb.tangent[neb.climbingImage]->size());
240 if (finalMode.size() != currentTangent.size()) {
241 QUILL_LOG_WARNING(log,
242 "MMF mode size {} != tangent size {}; skip alignment",
243 finalMode.size(), currentTangent.size());
244 alignment = 0.0;
245 } else if (finalMode.norm() == 0.0 || currentTangent.norm() == 0.0) {
246 alignment = 0.0;
247 } else {
248 alignment =
249 std::abs(finalMode.normalized().dot(currentTangent.normalized()));
250 }
251
252 if (minModeStatus == MinModeSaddleSearch::STATUS_GOOD ||
254 if (alignment < cfg_.angle_tol) {
255 QUILL_LOG_WARNING(
256 log,
257 "MMF converged/restored but mode drifted (alignment={:.3f} < {:.3f})",
258 alignment, cfg_.angle_tol);
259 return -1;
260 }
261 cached_mode_ = finalModeMatrix;
262 has_cached_mode_ = true;
263 return 0;
264 } else if (minModeStatus == MinModeSaddleSearch::STATUS_BAD_MAX_ITERATIONS) {
265 return 1;
266 } else {
267 QUILL_LOG_WARNING(log, "MMF failed. Mode-tangent alignment: {:.3f}",
268 alignment);
269 return -1;
270 }
271}
272
274 double newForce) {
275 current_threshold_ = newForce * (0.5 + 0.4 * (newForce / convForce));
276 double max_threshold = std::max(baseline_force_ * cfg_.trigger_factor,
277 2.0 * cfg_.force_tolerance);
278 current_threshold_ = std::min(current_threshold_, max_threshold);
279}
280
282 double alpha = std::clamp(alignment, 0.0, 1.0);
283 double penalty_factor = 0.5 + 0.5 * alpha;
284 current_threshold_ = baseline_force_ * cfg_.trigger_factor * penalty_factor;
285 // Lower bound on the MMF trigger threshold. Scaled by force_tolerance so
286 // the MMF gate never collapses to zero when the NEB is already near
287 // convergence, but also capped by the trigger_factor envelope so a
288 // loose force_tolerance cannot push min_threshold above the cap and
289 // starve MMF activation.
290 double min_threshold = 2.0 * cfg_.force_tolerance;
291 current_threshold_ = std::max(current_threshold_, min_threshold);
292}
293
294} // namespace eonc::neb
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
const neb_options_t & neb_options() const
static bool walkHelped(double walkedForce, double convForce, int mmfStatus)
bool shouldTrigger(double convForce, bool ci_active, long climbingImage, long numImages, int ciStabilityCounter) const
static Config fromParams(const Parameters &params)
void updateThresholdSuccess(double convForce, double newForce)
void updateStability(long climbingImage)
MMFResult run(eonc::NudgedElasticBand &neb, double convForce)
int runDimer(eonc::NudgedElasticBand &neb, double &alignment)
void initBaseline(double baseline_force)
static double forceMeasure(const AtomMatrix &freeForces, std::string_view metric)
Measure free-atom forces with the band's configured convergence metric.
void updateThresholdBackoff(double alignment)
static bool convergedClimb(double bandForce, double forceTolerance, int mmfStatus)
void resamplePathInPlace(std::span< std::shared_ptr< Matter > > path)
In-place path reparameterization for NEB shared_ptr paths.
quill::Logger * get() noexcept
Get or create the default "combi" logger.
Definition EonLogger.h:111
double maxFreeAtomForceNorm(const double *forces, const double *fixed, long nAtoms)
Max Euclidean norm over N x 3 row-major force rows.
struct eonc::neb_options_t::climbing_image_options_t::hybrid_dimer_t ocineb
struct eonc::neb_options_t::climbing_image_options_t climbing_image