Loading...
Searching...
No Matches
eonc::NudgedElasticBand Class Reference

#include <NudgedElasticBand.h>

Public Types

enum class  NEBStatus {
  GOOD = 0 , INIT = 1 , BAD_MAX_ITERATIONS = 2 , RUNNING ,
  MAX_UNCERTAINTY
}

Public Member Functions

 NudgedElasticBand (std::shared_ptr< Matter > initialPassed, std::shared_ptr< Matter > finalPassed, const Parameters &parametersPassed, std::shared_ptr< Potential > potPassed)
 NudgedElasticBand (std::vector< Matter > initPath, const Parameters &parametersPassed, std::shared_ptr< Potential > potPassed)
 ~NudgedElasticBand ()=default
NudgedElasticBand::NEBStatus compute (void)
NudgedElasticBand::NEBStatus getStatus ()
long lastIteration () const noexcept
 Iteration count from the last compute(). Zero before compute() runs.
bool solidState () const noexcept
double solidJacobian () const noexcept
const Matrix3d & cellForce (long image) const
void updateForces (bool ci_active)
void updateForces (void)
void setCIEnabled (bool enabled)
double convergenceForce (void)
void adoptSessionProjection (long ciIndex)
 Host bookkeeping for a band whose projected force came from the rgsaddle session: the highest interior image, the climbing image (ciIndex, or none when it is not an interior image) and the tangents, from the images' current energies and positions.
void findExtrema (void)
void printImageData (bool writeToFile=false, size_t idx=0)
std::vector< readcon::ConFrame > pathFrames (std::optional< size_t > bandIndex=std::nullopt)
 In-memory ConFrames with the same NEB stamps as writePathCon / neb.con.
long imageOwner (std::size_t i) const noexcept
 The identity band image i carries in a batch (forceBatchOwned): interior image i is i - 1, the reactant numImages and the product numImages + 1, so no image shares a key with an endpoint.

Public Attributes

std::vector< std::shared_ptr< EigenmodeStrategy > > eigenmode_solvers
int atoms {0}
long numImages {0}
long climbingImage {0}
long numExtrema {0}
double reactantEnergy {0.0}
std::vector< std::shared_ptr< Matter > > path
std::vector< std::shared_ptr< AtomMatrix > > tangent
std::vector< std::shared_ptr< AtomMatrix > > projectedForce
std::vector< double > extremumEnergy
std::vector< double > extremumPosition
std::vector< double > extremumCurvature
std::size_t maxEnergyImage {0}
bool movedAfterForceCall {false}
bool perImagePotentials_
 Whether per-image potential instances exist.
double ksp {0.0}
double k_u {0.0}
double k_l {0.0}
double E_ref

Private Member Functions

void prepareSolidState ()
void projectSolidState (bool ci_active)

Private Attributes

bool ci_enabled_ {false}
double baseline_force {-1.0}
Parameters params
std::shared_ptr< Potential > pot
NEBStatus status
long iteration_ {0}
eonc::log::Scoped log
neb::TangentStrategy tangentStrat_
neb::ProjectionStrategy projectionStrat_
bool solidState_ {false}
double solidJacobian_ {1.0}
std::vector< Matrix3d > projectedCellForce

Friends

class eonc::neb::OCINEBController

Detailed Description

Definition at line 38 of file NudgedElasticBand.h.

Member Enumeration Documentation

◆ NEBStatus

Enumerator
GOOD 
INIT 
BAD_MAX_ITERATIONS 
RUNNING 
MAX_UNCERTAINTY 

Definition at line 42 of file NudgedElasticBand.h.

42 {
43 GOOD = 0,
44 INIT = 1,
45 BAD_MAX_ITERATIONS = 2,
46 RUNNING,
47 MAX_UNCERTAINTY
48 };

Constructor & Destructor Documentation

◆ NudgedElasticBand() [1/2]

eonc::NudgedElasticBand::NudgedElasticBand ( std::shared_ptr< Matter > initialPassed,
std::shared_ptr< Matter > finalPassed,
const Parameters & parametersPassed,
std::shared_ptr< Potential > potPassed )

Definition at line 58 of file NudgedElasticBand.cpp.

63 [&]() {
64 auto &init_opt = parametersPassed.neb_options().initialization;
65 const size_t base_count =
66 parametersPassed.neb_options().image_count;
67 if (parametersPassed.neb_options().solid_state.enabled &&
68 init_opt.method != NEBInit::LINEAR &&
69 init_opt.method != NEBInit::FILE) {
70 throw std::invalid_argument(
71 "solid_state accepts initializer linear or file");
72 }
73 if (parametersPassed.neb_options().match_endpoints) {
75 *initialPassed, *finalPassed, 1.0);
76 auto *log = eonc::log::get();
77 if (aligned.error != 0) {
78 QUILL_LOG_WARNING(
79 log,
80 "match_endpoints: IRA align failed (error {}), "
81 "interpolating the input order",
82 aligned.error);
83 } else {
84 QUILL_LOG_INFO(log,
85 "match_endpoints: Hausdorff {:.4f} A after IRA "
86 "permute+rotate of the reactant",
87 aligned.hausdorffDistance);
88 }
89 }
90
91 // Apply oversampling factor if flag exists
92 const size_t relax_count =
93 init_opt.oversampling
94 ? base_count * init_opt.oversampling_factor
95 : base_count;
96
97 std::vector<Matter> path;
98 switch (init_opt.method) {
99 case NEBInit::FILE: {
100 std::vector<fs::path> file_paths =
101 eonc::helpers::neb_paths::readFilePaths(init_opt.input_path);
103 file_paths, *initialPassed, base_count);
104 // filePathInit reloads every frame, including ends the caller
105 // may already have minimized.
106 path.front() = Matter(*initialPassed);
107 path.back() = Matter(*finalPassed);
108 break;
109 }
110 case NEBInit::IDPP:
112 *initialPassed, *finalPassed, relax_count, parametersPassed);
113 break;
116 *initialPassed, *finalPassed, relax_count, parametersPassed);
117 break;
118 case NEBInit::SIDPP:
121 *initialPassed, *finalPassed, relax_count, parametersPassed,
122 (init_opt.method == NEBInit::SIDPP_ZBL));
123 break;
124 case NEBInit::LINEAR:
125 default:
127 *initialPassed, *finalPassed, base_count);
128 break;
129 }
130
131 // Decimate path back to the target count using the cubic spline
132 if (init_opt.oversampling && path.size() > (base_count + 2)) {
133 auto *log = eonc::log::get();
134 QUILL_LOG_INFO(log,
135 "Decimating oversampled path ({} images) to "
136 "{} images via cubic spline.",
137 path.size() - 2, base_count);
138
139 // Perform the Spline Resampling
141
142 // POST-DECIMATION RE-RELAXATION
143 // The spline might have placed atoms in high-energy positions.
144 QUILL_LOG_INFO(
145 log, "Relaxing decimated path to restore IDPP surface...");
146
147 // Collective IDPP objective for the new reduced path
148 std::shared_ptr<ObjectiveFunction> post_decim_objf =
149 std::make_shared<CollectiveIDPPObjectiveFunction>(
150 path, parametersPassed);
151
152 // Wrap with ZBL if the original method used ZBL options
153 bool use_zbl = (init_opt.method == NEBInit::SIDPP_ZBL);
154 if (use_zbl) {
156 post_decim_objf = std::make_shared<ZBLRepulsiveIDPPObjective>(
157 post_decim_objf, zbl_pot, path, parametersPassed, 1.0);
158 }
159
161 post_decim_objf, parametersPassed.neb_options().opt_method,
162 parametersPassed);
163
164 // Run a short optimization
165 optim->run(
166 parametersPassed.neb_options().initialization.max_iterations,
167 parametersPassed.neb_options().initialization.max_move);
168 }
169 if (parametersPassed.neb_options().solid_state.enabled &&
170 init_opt.method == NEBInit::LINEAR) {
171 if (init_opt.oversampling) {
172 throw std::invalid_argument(
173 "solid_state NEB does not oversample the initial path");
174 }
175 for (Matter &image : path) {
177 }
179 } else if (parametersPassed.neb_options().solid_state.enabled &&
180 init_opt.method == NEBInit::FILE) {
181 for (Matter &image : path) {
183 }
184 }
185 return path;
186 }(),
187 parametersPassed, potPassed) {}
const neb_options_t & neb_options() const
static MatchResult alignReactantToProduct(Matter &reactant, const Matter &product, double distThreshold)
Rigid-align + permute reactant onto product.
NudgedElasticBand(std::shared_ptr< Matter > initialPassed, std::shared_ptr< Matter > finalPassed, const Parameters &parametersPassed, std::shared_ptr< Potential > potPassed)
std::vector< std::shared_ptr< Matter > > path
std::unique_ptr< Optimizer > mkOptim(std::shared_ptr< ObjectiveFunction > a_objf, OptType a_otype, const Parameters &a_params)
Definition Optimizer.cpp:55
std::vector< Matter > resamplePath(const std::vector< Matter > &densePath, size_t targetCount)
std::vector< Matter > sidppPath(const Matter &initImg, const Matter &finalImg, size_t target_nimgs, const Parameters &params, bool use_zbl)
std::shared_ptr< Potential > createZBLPotential()
std::vector< Matter > linearPath(const Matter &initImg, const Matter &finalImg, const size_t nimgs)
std::vector< Matter > filePathInit(const std::vector< fs::path > &fsrcs, const Matter &refImg, const size_t nimgs)
std::vector< Matter > idppPath(const Matter &initImg, const Matter &finalImg, const size_t nimgs, const Parameters &params, bool use_zbl)
std::vector< Matter > idppCollectivePath(const Matter &initImg, const Matter &finalImg, size_t nimgs, const Parameters &params, bool use_zbl)
std::vector< fs::path > readFilePaths(const std::string &listFilePath)
Reads a file where each line contains a path to another file.
quill::Logger * get() noexcept
Get or create the default "combi" logger.
Definition EonLogger.h:111
void interpolateSolidStateLinear(std::vector< Matter > &images)
Replace interior images by a fractional linear interpolation of the oriented endpoints.
void orientSolidStateMatter(Matter &image)
struct eonc::neb_options_t::solid_state_options_t solid_state
bool match_endpoints
Permute+rotate the reactant onto the product before interpolation.
struct eonc::neb_options_t::path_initialization_t initialization

◆ NudgedElasticBand() [2/2]

eonc::NudgedElasticBand::NudgedElasticBand ( std::vector< Matter > initPath,
const Parameters & parametersPassed,
std::shared_ptr< Potential > potPassed )

Definition at line 190 of file NudgedElasticBand.cpp.

193 : ci_enabled_{parametersPassed.neb_options().climbing_image.enabled},
194 params{parametersPassed},
195 pot{potPassed},
196 E_ref{0.0} {
197
200 params.optimizer_options().convergence_metric, "[Nudged Elastic Band]");
201 this->status = NEBStatus::INIT;
202 numImages = params.neb_options().image_count;
203 if (initPath.empty()) {
204 throw std::invalid_argument("NEB: initPath is empty");
205 }
206 if (initPath.size() != static_cast<size_t>(numImages + 2)) {
207 throw std::invalid_argument("NEB: initPath.size() must be image_count + 2");
208 }
209 atoms = initPath.front().numberOfAtoms();
210 for (size_t i = 1; i < initPath.size(); ++i) {
212 initPath[i], "path images");
213 }
214
215 // Common initialization logic
216 path.resize(numImages + 2);
217 tangent.resize(numImages + 2);
218 projectedForce.resize(numImages + 2);
219 extremumPosition.resize(2 * (numImages + 1));
220 extremumEnergy.resize(2 * (numImages + 1));
221 extremumCurvature.resize(2 * (numImages + 1));
222 numExtrema = 0;
223
224 // A potential that keeps per-geometry state (a neighbour table, a
225 // working directory) gets one instance per interior image, threads or
226 // not: a shared instance would rebuild that state for every image of
227 // every step. [Main] parallel only decides whether the images run on
228 // the image pool.
229 perImagePotentials_ = pot->needsPerImageInstance();
231 QUILL_LOG_INFO(log, "NEB: one potential instance per image ({} images)",
232 numImages);
233 }
234
235 for (long i = 0; i <= numImages + 1; i++) {
236 path[i] = std::make_shared<Matter>(std::move(initPath[i]));
237
238 // Each interior image gets its own instance. The endpoints keep the
239 // shared one: they are evaluated once, before the band moves.
240 if (perImagePotentials_ && i > 0 && i <= numImages) {
242 }
243
244 tangent[i] = std::make_shared<AtomMatrix>();
245 tangent[i]->resize(atoms, 3);
246 tangent[i]->setZero();
247 projectedForce[i] = std::make_shared<AtomMatrix>();
248 projectedForce[i]->resize(atoms, 3);
249 projectedForce[i]->setZero();
250 }
251
252 // Common final setup
253 movedAfterForceCall = true;
255 // Name images before the endpoint evaluation. The host matches a
256 // system to a band index by the position pointer.
257 if (pot) {
258 pot->bindBand(path);
259 }
260 // Both endpoints in one call, so two calculator groups take one each.
261 {
262 Matter *const ends[] = {path[0].get(), path[numImages + 1].get()};
263 const long owners[] = {imageOwner(0), imageOwner(numImages + 1)};
264 eonc::evaluateTogether(*pot, ends, false, owners);
265 }
266 reactantEnergy = path[0]->getPotentialEnergy();
267 climbingImage = 0;
268
269 // Setup springs
270 k_u = params.neb_options().spring.weighting.k_max;
271 k_l = params.neb_options().spring.weighting.k_min;
272 if (params.neb_options().spring.weighting.enabled) {
273 ksp = k_l;
274 } else {
275 ksp = params.neb_options().spring.constant;
276 }
277
278 // Cache strategies that are constant across iterations
281
282 // Optional debugging setup
283 if (params.debug_options().estimate_neb_eigenvalues) {
284 eigenmode_solvers.resize(numImages + 2);
285 for (long i = 0; i <= numImages + 1; i++) {
287 eonc::buildEigenmodeStrategy(path[i], parametersPassed, pot);
288 }
289 }
290}
std::vector< double > extremumEnergy
std::vector< std::shared_ptr< AtomMatrix > > tangent
bool perImagePotentials_
Whether per-image potential instances exist.
std::vector< double > extremumPosition
std::vector< std::shared_ptr< EigenmodeStrategy > > eigenmode_solvers
neb::TangentStrategy tangentStrat_
std::vector< std::shared_ptr< AtomMatrix > > projectedForce
long imageOwner(std::size_t i) const noexcept
The identity band image i carries in a batch (forceBatchOwned): interior image i is i - 1,...
std::shared_ptr< Potential > pot
neb::ProjectionStrategy projectionStrat_
std::vector< double > extremumCurvature
void requireSameAtomCount(const Matter &a, const Matter &b, std::string_view what)
Abort before Eigen subtracts two position matrices of different size.
std::shared_ptr< Potential > makeImagePotential(const Potential &pot, const Parameters &params)
A separate instance of pot for one image of a band, dimer or pair of minimizations: a clone when the ...
void requireKnownConvergenceMetric(std::string_view metric, std::string_view context)
Throws std::invalid_argument naming context when metric is unrecognized.
TangentStrategy buildTangentStrategy(const Parameters &params)
Build the tangent strategy from parameters.
ProjectionStrategy buildProjectionStrategy(const Parameters &params)
Build the projection strategy from parameters.
std::shared_ptr< LowestEigenmode > buildEigenmodeStrategy(std::shared_ptr< Matter > matter, const Parameters &params, std::shared_ptr< Potential > pot)
void evaluateTogether(Potential &pot, std::span< Matter *const > systems, bool threads, std::span< const long > owners)
Evaluates every system that needs a force update.
Definition Matter.cpp:998
struct eonc::neb_options_t::climbing_image_options_t climbing_image

◆ ~NudgedElasticBand()

eonc::NudgedElasticBand::~NudgedElasticBand ( )
default

Member Function Documentation

◆ adoptSessionProjection()

void eonc::NudgedElasticBand::adoptSessionProjection ( long ciIndex)

Host bookkeeping for a band whose projected force came from the rgsaddle session: the highest interior image, the climbing image (ciIndex, or none when it is not an interior image) and the tangents, from the images' current energies and positions.

The projected force stays as the session assembled it.

Definition at line 971 of file NudgedElasticBand.cpp.

971 {
972 long highest = 1;
973 for (long i = 2; i <= numImages; ++i) {
974 if (path[i]->getPotentialEnergy() > path[highest]->getPotentialEnergy()) {
975 highest = i;
976 }
977 }
978 maxEnergyImage = static_cast<size_t>(highest);
979 climbingImage = (ciIndex > 0 && ciIndex <= numImages) ? ciIndex : 0;
980 for (long i = 1; i <= numImages; ++i) {
981 const AtomMatrix &pos = path[i]->getPositions();
982 const AtomMatrix posDiffNext =
983 path[i]->pbc(path[i + 1]->getPositions() - pos);
984 const AtomMatrix posDiffPrev =
985 path[i]->pbc(pos - path[i - 1]->getPositions());
986 const double energy = path[i]->getPotentialEnergy();
987 const double energyPrev = path[i - 1]->getPotentialEnergy();
988 const double energyNext = path[i + 1]->getPotentialEnergy();
989 *tangent[i] = std::visit(
990 [&](auto &t) {
991 return t.compute(posDiffNext, posDiffPrev, energy, energyPrev,
992 energyNext);
993 },
995 }
996}
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37

◆ cellForce()

const Matrix3d & eonc::NudgedElasticBand::cellForce ( long image) const
inlinenodiscard

Definition at line 64 of file NudgedElasticBand.h.

64 {
65 return projectedCellForce.at(static_cast<size_t>(image));
66 }
std::vector< Matrix3d > projectedCellForce

◆ compute()

NudgedElasticBand::NEBStatus eonc::NudgedElasticBand::compute ( void )

Definition at line 292 of file NudgedElasticBand.cpp.

292 {
293 iteration_ = 0;
294 long &iteration = iteration_;
296
297 QUILL_LOG_DEBUG(log, "Nudged elastic band calculation started.");
298
299 // Higher endpoint: springs stay at k_min until an image exceeds it.
300 E_ref = std::max(path[0]->getPotentialEnergy(),
301 path[numImages + 1]->getPotentialEnergy());
302
303 updateForces();
304
305 auto objf = std::make_shared<NEBObjectiveFunction>(this, params);
306
307 bool switched{false};
308#ifdef WITH_RGSADDLE
309 std::unique_ptr<XtsciBand> rustBand;
310#endif
311 std::unique_ptr<Optimizer> optim;
312 std::unique_ptr<Optimizer> refine_optim;
313#ifdef WITH_RGSADDLE
314 const auto bandMethod = params.neb_options().opt_method;
315 if (!params.neb_options().spring.geometric &&
316 (bandMethod == OptType::XTSCI || bandMethod == OptType::LBFGS ||
317 bandMethod == OptType::FIRE)) {
318 rustBand = std::make_unique<XtsciBand>(*this, params);
319 } else
320#endif
321 {
322 const auto &band = params.neb_options().band;
323 if (band.precon != "none" || band.stepper != "auto") {
324 throw std::invalid_argument(
325 "band_precon and band_stepper act on the rgsaddle band: a build "
326 "with rgsaddle, opt_method lbfgs, fire or xtsci, and no "
327 "geometric_spring");
328 }
330 objf, params.neb_options().opt_method, params);
331 if (params.optimizer_options().refine.method != OptType::None) {
332 refine_optim = eonc::helpers::create::mkOptim(
333 objf, params.optimizer_options().refine.method, params);
334 }
335 }
336 // OCINEB controller
338 eonc::neb::OCINEBController ocineb(ocinebCfg);
339 bool zoomDone{false};
340 long zoomStable{0};
341 long zoomPrevCI{-1};
342 long zoomAt{-1};
343 // Activation uses the stepping projection; acceptance uses configured CI.
344 double activation_force{0.0};
345 // Conjugate gradient has no curvature history to damp a bad step.
346 // A jump in the band force shortens the next CG step, and a stall
347 // drops the search direction. LBFGS keeps the configured length:
348 // shortening it here left bands short of the cap.
349 const double moveBase = params.optimizer_options().max_move;
350 const bool adaptCg = params.neb_options().opt_method == OptType::CG;
351 double moveNow = moveBase;
352 double bestForce = std::numeric_limits<double>::infinity();
353 int stall = 0;
354
355 while (this->status != NEBStatus::GOOD) {
356 if (!path.empty()) {
357 path.front()->pollCancel("neb");
358 }
359 if (params.debug_options().write_movies &&
360 (iteration % params.debug_options().write_movies_interval == 0)) {
361 bool append = (iteration != 0);
364 params.debug_options().estimate_neb_eigenvalues,
365 std::format("neb_path_{:03d}.con", iteration), iteration,
366 reactantEnergy))) {
367 QUILL_LOG_ERROR(log, "Failed to write NEB path movie for iteration {}",
368 iteration);
369 }
370
371 AtomMatrix maxTang;
372 if (maxEnergyImage == 0) {
373 maxTang =
374 path[0]->pbc(path[1]->getPositions() - path[0]->getPositions());
375 } else if (maxEnergyImage == static_cast<size_t>(numImages + 1)) {
376 maxTang = path[numImages]->pbc(path[numImages + 1]->getPositions() -
377 path[numImages]->getPositions());
378 } else {
379 maxTang = *tangent[maxEnergyImage];
380 }
381 eonc::safemath::safe_normalize_inplace(maxTang);
382 auto maxImageMetadata = eonc::io::ConFrameMetadata{};
383 maxImageMetadata.frame_index = static_cast<uint64_t>(maxEnergyImage);
384 maxImageMetadata.energy = path[maxEnergyImage]->getPotentialEnergy();
385 maxImageMetadata.neb_bead = static_cast<uint64_t>(maxEnergyImage);
386 maxImageMetadata.neb_band = static_cast<uint64_t>(iteration);
387 maxImageMetadata.scalars.push_back(
388 {"relative_energy",
389 path[maxEnergyImage]->getPotentialEnergy() - reactantEnergy});
390 maxImageMetadata.scalars.push_back(
391 {"parallel_force",
392 matDot(path[maxEnergyImage]->getForces(), maxTang)});
393 maxImageMetadata.strings.push_back({"movie_kind", "neb_maximage"});
395 "neb_maximage.con", append, &maxImageMetadata))) {
396 EONC_LOG_WARNING("Failed to write neb_maximage.con");
397 }
398 printImageData(true, iteration);
399 }
400
401 VectorXd pos = objf->getPositions();
402 double convForce = convergenceForce();
403
404 ocineb.updateStability(climbingImage);
405
406 if (iteration == 0) {
407 baseline_force = convForce;
408 activation_force = convForce;
409 ocineb.initBaseline(convForce);
410
411 // Log configuration banner
412 auto &ci_opt = params.neb_options().climbing_image;
413 auto &mmf_opt = ci_opt.ocineb;
414 auto fmt_trigger = [](double val) -> std::string {
415 if (val > 1e100)
416 return "INF";
417 return std::format("{:.4f}", val);
418 };
419
420 QUILL_LOG_INFO(
421 log,
422 "===============================================================");
423 QUILL_LOG_INFO(log, " NEB Optimization Configuration");
424 QUILL_LOG_INFO(
425 log,
426 "===============================================================");
427 QUILL_LOG_INFO(log, " {:<25} : {:.4f}", "Baseline Force", baseline_force);
428
429 std::string ci_status = ci_opt.enabled ? "ENABLED" : "DISABLED";
430 QUILL_LOG_INFO(log, " {:<25} : {}", "Climbing Image (CI)", ci_status);
431 if (ci_opt.enabled) {
432 double ci_rel_val = baseline_force * ci_opt.trigger_factor;
433 QUILL_LOG_INFO(log, " - {:<21} : {} (Factor: {:.2f})",
434 "Relative Trigger", fmt_trigger(ci_rel_val),
435 ci_opt.trigger_factor);
436 QUILL_LOG_INFO(log, " - {:<21} : {}", "Absolute Trigger",
437 fmt_trigger(ci_opt.trigger_force));
438 QUILL_LOG_INFO(log, " - {:<21} : {}", "Converged Only",
439 ci_opt.converged_only);
440 }
441
442 std::string mmf_status =
443 (ci_opt.enabled && mmf_opt.use_mmf) ? "ENABLED" : "DISABLED";
444 QUILL_LOG_INFO(log, " {:<25} : {}", "Hybrid MMF (OCINEB)", mmf_status);
445 if (ci_opt.enabled && mmf_opt.use_mmf) {
446 QUILL_LOG_INFO(log, " - {:<21} : {:.4f} (Factor: {:.2f})",
447 "Initial Threshold", ocineb.threshold(),
448 mmf_opt.trigger_factor);
449 QUILL_LOG_INFO(log, " - {:<21} : {:.4f}", "Absolute Floor",
450 mmf_opt.trigger_force);
451 QUILL_LOG_INFO(log, " - {:<21} : {:.4f}", "Angle Tolerance",
452 mmf_opt.angle_tol);
453 }
454 QUILL_LOG_INFO(
455 log,
456 "---------------------------------------------------------------");
457
458 EONC_LOG_DEBUG("{:>10s} {:>12s} {:>14s} {:>11s} {:>12s}", "iteration",
459 "step size",
460 params.optimizer_options().convergence_metric_label,
461 "max image", "max energy");
462 QUILL_LOG_DEBUG(
464 "---------------------------------------------------------------\n");
465 }
466
467 // CI active when force drops below relative threshold
468 bool ci_active =
469 params.neb_options().climbing_image.enabled &&
470 (activation_force <
472 params.neb_options().climbing_image.trigger_factor ||
473 activation_force < params.neb_options().climbing_image.trigger_force);
474
475 bool zoomedThisStep = false;
476 if (iteration && !zoomDone && params.neb_options().zoom.enabled &&
477 climbingImage > 0 && climbingImage + 1 < path.size()) {
478 if (static_cast<long>(climbingImage) == zoomPrevCI) {
479 ++zoomStable;
480 } else {
481 zoomPrevCI = static_cast<long>(climbingImage);
482 zoomStable = 1;
483 }
484 const auto &zoom = params.neb_options().zoom;
485 const double zoomForce =
486 zoom.activation_threshold > 0.0
487 ? zoom.activation_threshold
488 : 10.0 * params.neb_options().force_tolerance;
489 if (zoomStable >= zoom.stability_count && convForce < zoomForce) {
490 std::vector<double> energy;
491 energy.reserve(path.size());
492 for (const auto &image : path) {
493 energy.push_back(image->getPotentialEnergy());
494 }
495 const auto window =
498 zoom.interpolation)) {
499 movedAfterForceCall = true;
501 objf, params.neb_options().opt_method, params);
502 zoomDone = true;
503 zoomedThisStep = true;
504 zoomAt = iteration;
505 QUILL_LOG_INFO(log, "Zoom-NEB: packed the band onto images [{}, {}]",
506 window.lo, window.hi);
507 }
508 }
509 }
510
511 if (iteration) {
512 // MMF refines the climbing image; the residual of another band
513 // image is independent of the force used by its activation rule.
514 double mmfForce = convForce;
515 if (climbingImage > 0 && climbingImage <= numImages) {
517 path[climbingImage]->getForcesFree(),
518 params.optimizer_options().convergence_metric);
519 }
520 // MMF triggering via controller. Skipped on the zoom step so the
521 // dimer sees the redistributed band, not the pre-zoom geometry.
522 if (!zoomedThisStep &&
523 ocineb.shouldTrigger(mmfForce, ci_active, climbingImage, numImages,
524 ocineb.stabilityCount())) {
525 auto result = ocineb.run(*this, convForce);
526
527 if (result.convergedAfterMMF) {
529 break;
530 }
531 // The controller redistributes a helpful MMF walk before the
532 // band optimizer is reset at the resulting geometry.
533 if (result.shouldResetOptimizer) {
534#ifdef WITH_RGSADDLE
535 if (rustBand) {
536 rustBand->syncFromPath();
537 rustBand->reset();
538 } else
539#endif
540 {
542 objf, params.neb_options().opt_method, params);
543 }
544 }
545 }
546
547 long iterLimit = params.neb_options().max_iterations;
548 if (zoomDone && params.neb_options().zoom.max_iterations > 0 &&
549 zoomAt >= 0) {
550 iterLimit = zoomAt + params.neb_options().zoom.max_iterations;
551 }
552 if (iteration >= iterLimit) {
554 break;
555 }
556
557 if (zoomedThisStep) {
558 activation_force = convergenceForce();
559 iteration++;
560 continue;
561 }
562
563 // Set CI state so updateForces() inside the optimizer step
564 // applies the correct force projection.
565 setCIEnabled(ci_active);
566
567#ifdef WITH_RGSADDLE
568 if (rustBand) {
569 rustBand->step(moveNow);
570 } else
571#endif
572 {
573 auto &activeOptim =
574 (refine_optim &&
575 convForce <= params.optimizer_options().refine.threshold)
576 ? refine_optim
577 : optim;
578 if (refine_optim &&
579 convForce <= params.optimizer_options().refine.threshold &&
580 !switched) {
581 switched = true;
582 EONC_LOG_DEBUG("Switched to {}",
583 magic_enum::enum_name<OptType>(
584 params.optimizer_options().refine.method));
585 }
586 activeOptim->step(moveNow);
587 }
588
589 activation_force = convergenceForce();
590 if (adaptCg && activation_force < bestForce * 0.98) {
591 bestForce = activation_force;
592 stall = 0;
593 if (moveNow < moveBase && convForce > 0.0 &&
594 activation_force < 0.8 * convForce) {
595 moveNow = std::min(moveBase, moveNow * 1.5);
596 }
597 } else if (adaptCg) {
598 ++stall;
599 if (convForce > 0.0 && activation_force > 2.0 * convForce) {
600 moveNow = std::max(moveNow * 0.5, moveBase * 0.2);
601 }
602 if (stall >= 12) {
603 moveNow = std::max(moveBase * 0.2, moveNow * 0.5);
604 stall = 0;
605#ifdef WITH_RGSADDLE
606 if (rustBand) {
607 rustBand->reset();
608 } else
609#endif
610 {
612 objf, params.neb_options().opt_method, params);
613 if (refine_optim) {
614 refine_optim = eonc::helpers::create::mkOptim(
615 objf, params.optimizer_options().refine.method, params);
616 }
617 }
618 QUILL_LOG_DEBUG(log, "Band stalled; reset optimizer, step {:.4e}",
619 moveNow);
620 }
621 }
622 setCIEnabled(params.neb_options().climbing_image.enabled);
623 }
624
625 iteration++;
626
627 double dE = path[maxEnergyImage]->getPotentialEnergy() - reactantEnergy;
628 double stepSize = 0.0;
629 if (solidState_) {
630 const VectorXd delta = objf->difference(objf->getPositions(), pos);
631 const long seg = 3L * atoms + 9L;
632 for (long image = 0; image < numImages; ++image) {
633 stepSize = std::max(
634 stepSize, delta.segment(image * seg, seg).cwiseAbs().maxCoeff());
635 }
636 } else {
638 path[0]->pbcV(objf->getPositions() - pos));
639 }
640 QUILL_LOG_DEBUG(log, "{:>10} {:>12.4e} {:>14.4e} {:>11} {:>12.4}",
641 iteration, stepSize, convergenceForce(), maxEnergyImage,
642 dE);
643
644 if (pot->getType() == PotType::CatLearn) {
645 if (objf->isUncertain()) {
646 QUILL_LOG_DEBUG(log, "NEB failed due to high uncertainty");
648 break;
649 } else if (objf->isConverged()) {
650 QUILL_LOG_DEBUG(log, "NEB converged\n");
652 break;
653 }
654 } else {
655 if (objf->isConverged()) {
656 QUILL_LOG_DEBUG(log, "NEB converged\n");
658 break;
659 }
660 }
661 }
662 return status;
663}
double matDot(const AtomMatrix &a, const AtomMatrix &b)
SIMD-optimized dot product for contiguous Eigen matrices.
Definition Eigen.h:50
#define EONC_LOG_DEBUG(...)
Definition EonLogger.h:310
#define EONC_LOG_WARNING(...)
Definition EonLogger.h:322
void printImageData(bool writeToFile=false, size_t idx=0)
void setCIEnabled(bool enabled)
friend class eonc::neb::OCINEBController
static Config fromParams(const Parameters &params)
static double forceMeasure(const AtomMatrix &freeForces, std::string_view metric)
Measure free-atom forces with the band's configured convergence metric.
double maxAtomMotionV(const VectorXd v1)
IoStatus matter2con(Matter &m, std::string filename, bool append, const ConFrameMetadata *metadata)
Append a frame to a .con, or truncate and write one frame.
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
Window selectWindow(const std::vector< double > &energy, std::size_t climbingImage, const neb_options_t::zoom_options_t &cfg)
Auto: contiguous images around the climbing image whose energy is above E_ref + alpha * barrier.
Definition NEBZoom.cpp:74
bool redistributePath(std::vector< std::shared_ptr< Matter > > &path, Window window, neb_options_t::zoom_options_t::Interpolation how)
Place every band image on the window by equal arc length.
Definition NEBZoom.cpp:118
eonc::io::IoStatus writePathCon(const std::vector< std::shared_ptr< Matter > > &path, const std::vector< std::shared_ptr< AtomMatrix > > &tangent, const std::vector< std::shared_ptr< EigenmodeStrategy > > &eigenmode_solvers, long numImages, bool estimateEigenvalues, std::string filename, std::optional< size_t > bandIndex, double referenceEnergy, const std::vector< double > *quantumFreeEnergy, const eonc::tunneling::BandWalls *walls)
Write a NEB band as a multi-frame .con via readcon ConFrameBuilder::clone().

◆ convergenceForce()

double eonc::NudgedElasticBand::convergenceForce ( void )

Definition at line 666 of file NudgedElasticBand.cpp.

666 {
668 updateForces();
669
670 auto imageForce = [&](long i) -> double {
671 const double cellNorm =
672 solidState_ ? projectedCellForce[static_cast<size_t>(i)].norm() : 0.0;
673 if (params.optimizer_options().convergence_metric == "norm") {
674 return std::hypot(projectedForce[i]->norm(), cellNorm);
675 }
676 if (params.optimizer_options().convergence_metric == "max_atom") {
677 // Every image shares the reactant constraint mask.
678 return std::max(path[0]->maxFreeAtomForce(*projectedForce[i]), cellNorm);
679 }
680 if (params.optimizer_options().convergence_metric == "max_component") {
681 double component = projectedForce[i]->cwiseAbs().maxCoeff();
682 if (solidState_) {
683 component = std::max(
684 component,
685 projectedCellForce[static_cast<size_t>(i)].cwiseAbs().maxCoeff());
686 }
687 return component;
688 }
690 QUILL_LOG_CRITICAL(
691 log, "[Nudged Elastic Band] unknown opt_convergence_metric: {}",
692 params.optimizer_options().convergence_metric);
693 throw std::invalid_argument(
694 std::format("[Nudged Elastic Band] unknown convergence_metric: {}",
695 params.optimizer_options().convergence_metric));
696 };
697
698 double bandMax = 0;
699 for (long i = 1; i <= numImages; ++i) {
700 bandMax = std::max(bandMax, imageForce(i));
701 }
702
703 const bool ciOnly = params.neb_options().climbing_image.converged_only &&
705 if (!ciOnly) {
706 return bandMax;
707 }
708
709 const double ciForce = imageForce(climbingImage);
710 const double slack = params.neb_options().climbing_image.band_slack;
711 const double tol = params.neb_options().force_tolerance;
712 if (slack > 0.0 && bandMax > slack * tol) {
713 return bandMax;
714 }
715 return ciForce;
716}
double norm(const Eigen::MatrixBase< A > &x)
sqrt of the correctly rounded squared norm; IEEE sqrt is itself correctly rounded,...
quill::Logger * traceback() noexcept
Get or create the "_traceback" logger for traceback logging.
Definition EonLogger.h:155

◆ findExtrema()

void eonc::NudgedElasticBand::findExtrema ( void )

Definition at line 1006 of file NudgedElasticBand.cpp.

1006 {
1008 numExtrema = result.numExtrema;
1009 extremumPosition = std::move(result.positions);
1010 extremumEnergy = std::move(result.energies);
1011 extremumCurvature = std::move(result.curvatures);
1012}
ExtremaResult findSplineExtrema(const std::vector< std::shared_ptr< Matter > > &path, const std::vector< std::shared_ptr< AtomMatrix > > &tangent, long numImages)
Find extrema along the MEP using cubic spline interpolation.

◆ getStatus()

NudgedElasticBand::NEBStatus eonc::NudgedElasticBand::getStatus ( )
inline

Definition at line 59 of file NudgedElasticBand.h.

59{ return this->status; };

◆ imageOwner()

long eonc::NudgedElasticBand::imageOwner ( std::size_t i) const
inlinenodiscardnoexcept

The identity band image i carries in a batch (forceBatchOwned): interior image i is i - 1, the reactant numImages and the product numImages + 1, so no image shares a key with an endpoint.

Definition at line 97 of file NudgedElasticBand.h.

97 {
98 const auto idx = static_cast<long>(i);
99 if (idx == 0)
100 return numImages;
101 return idx == numImages + 1 ? numImages + 1 : idx - 1;
102 }

◆ lastIteration()

long eonc::NudgedElasticBand::lastIteration ( ) const
inlinenodiscardnoexcept

Iteration count from the last compute(). Zero before compute() runs.

Definition at line 61 of file NudgedElasticBand.h.

61{ return iteration_; }

◆ pathFrames()

std::vector< readcon::ConFrame > eonc::NudgedElasticBand::pathFrames ( std::optional< size_t > bandIndex = std::nullopt)
nodiscard

In-memory ConFrames with the same NEB stamps as writePathCon / neb.con.

Empty if path is incomplete. Does not write to disk.

Definition at line 1015 of file NudgedElasticBand.cpp.

1015 {
1018 params.debug_options().estimate_neb_eigenvalues, bandIndex,
1020}
std::vector< readcon::ConFrame > pathToConFrames(const std::vector< std::shared_ptr< Matter > > &path, const std::vector< std::shared_ptr< AtomMatrix > > &tangent, const std::vector< std::shared_ptr< EigenmodeStrategy > > &eigenmode_solvers, long numImages, bool estimateEigenvalues, std::optional< size_t > bandIndex, double referenceEnergy, const std::vector< double > *quantumFreeEnergy, const eonc::tunneling::BandWalls *walls)
Build stamped ConFrames for a NEB band (same metadata as writePathCon).

◆ prepareSolidState()

void eonc::NudgedElasticBand::prepareSolidState ( )
private

Definition at line 1086 of file NudgedElasticBand.cpp.

1086 {
1087 if (!params.neb_options().solid_state.enabled) {
1088 return;
1089 }
1090 refuseSolidStateCombination(params);
1091 for (const auto &image : path) {
1092 if (!image->getPeriodic()) {
1093 throw std::invalid_argument(
1094 "solid_state NEB requires periodic boundaries on every image");
1095 }
1097 }
1098 const double volume0 = std::abs(path.front()->getCell().determinant());
1099 const double volume1 = std::abs(path.back()->getCell().determinant());
1101 eonc::neb::solidStateJacobian(0.5 * (volume0 + volume1), atoms,
1102 params.neb_options().solid_state.weight);
1103 projectedCellForce.assign(static_cast<size_t>(numImages + 2),
1104 Matrix3d::Zero());
1105 solidState_ = true;
1106 QUILL_LOG_INFO(log, "Solid-state NEB Jacobian {:.6f} Angstrom",
1108}
double solidStateJacobian(double meanVolume, int nAtoms, double weight)
J = (V/N)^{1/3} * N^{1/2} * weight, with V the mean endpoint volume.

◆ printImageData()

void eonc::NudgedElasticBand::printImageData ( bool writeToFile = false,
size_t idx = 0 )

Definition at line 1000 of file NudgedElasticBand.cpp.

1000 {
1002 params.debug_options().estimate_neb_eigenvalues,
1003 writeToFile, idx, log, reactantEnergy);
1004}
void printImageData(const std::vector< std::shared_ptr< Matter > > &path, const std::vector< std::shared_ptr< AtomMatrix > > &tangent, const std::vector< std::shared_ptr< EigenmodeStrategy > > &eigenmode_solvers, long numImages, bool estimateEigenvalues, bool writeToFile, size_t idx, eonc::log::Scoped log, double referenceEnergy)
Print NEB image data to log and optionally to file.

◆ projectSolidState()

void eonc::NudgedElasticBand::projectSolidState ( bool ci_active)
private

Definition at line 1110 of file NudgedElasticBand.cpp.

1110 {
1111 // Each image keeps one cell. The band does not store a cell on each bead.
1112 const double pressure = params.neb_options().solid_state.pressure;
1113 const Matrix3d external = Matrix3d::Identity() * pressure;
1114 std::vector<double> enthalpy(static_cast<size_t>(numImages + 2));
1115 for (long i = 0; i <= numImages + 1; ++i) {
1116 enthalpy[static_cast<size_t>(i)] =
1117 eonc::neb::solidStateEnthalpy(*path[i], *path[0], pressure);
1118 }
1119
1120 long highest = 1;
1121 for (long i = 2; i <= numImages; ++i) {
1122 if (enthalpy[static_cast<size_t>(i)] >
1123 enthalpy[static_cast<size_t>(highest)]) {
1124 highest = i;
1125 }
1126 }
1127 maxEnergyImage = static_cast<size_t>(highest);
1128 const double endpointEnthalpy = std::max(enthalpy.front(), enthalpy.back());
1129 const bool climb =
1130 ci_active && enthalpy[static_cast<size_t>(highest)] > endpointEnthalpy;
1131 climbingImage = 0;
1132
1133 if (params.neb_options().spring.weighting.enabled) {
1134 E_ref = std::max(path[0]->getPotentialEnergy(),
1135 path[numImages + 1]->getPotentialEnergy());
1136 }
1137 const double maxEnergy = path[highest]->getPotentialEnergy();
1139 maxEnergy, E_ref);
1140 if (const auto *uniform = std::get_if<eonc::neb::UniformSpring>(&spring)) {
1141 ksp = uniform->ksp;
1142 }
1143
1144 if (!pot->computesStress()) {
1145 throw std::invalid_argument(
1146 "solid_state NEB requires a potential that reports the Cauchy stress");
1147 }
1148
1149 for (long i = 1; i <= numImages; ++i) {
1150 const double volume = std::abs(path[i]->getCell().determinant());
1151 Matrix3d stress = path[i]->cauchyStress();
1152 Matrix3d cellTrue =
1153 eonc::neb::cellNebForce(stress, volume, solidJacobian_, external);
1154 AtomMatrix atomicTrue = path[i]->getForces();
1155 for (long atom = 0; atom < atoms; ++atom) {
1156 if (path[i]->getFixed(atom)) {
1157 atomicTrue.row(atom).setZero();
1158 }
1159 }
1160
1161 const eonc::neb::JointBlock toNext =
1163 const eonc::neb::JointBlock toPrev =
1165 const AtomMatrix packedNext = packJoint(toNext.atomic, toNext.cell);
1166 const AtomMatrix packedPrev = packJoint(toPrev.atomic, toPrev.cell);
1167 const double energy = enthalpy[static_cast<size_t>(i)];
1168 const double energyPrev = enthalpy[static_cast<size_t>(i - 1)];
1169 const double energyNext = enthalpy[static_cast<size_t>(i + 1)];
1170 const AtomMatrix packedTangent = std::visit(
1171 [&](auto &tangentStrategy) {
1172 return tangentStrategy.compute(packedNext, packedPrev, energy,
1173 energyPrev, energyNext);
1174 },
1176 *tangent[i] = packedTangent.topRows(atoms);
1177
1178 AtomMatrix packedForce = packJoint(atomicTrue, cellTrue);
1179 AtomMatrix total;
1180 if (climb && i == highest) {
1181 climbingImage = static_cast<size_t>(highest);
1182 const double parallel = matDot(packedForce, packedTangent);
1183 total = packedForce - 2.0 * parallel * packedTangent;
1184 } else {
1185 const double parallel = matDot(packedForce, packedTangent);
1186 const AtomMatrix perpendicular = packedForce - parallel * packedTangent;
1187 const double scale = springScale(spring, i, eonc::neb::jointNorm(toNext),
1188 eonc::neb::jointNorm(toPrev));
1189 total = perpendicular + scale * packedTangent;
1190 }
1191 *projectedForce[i] = total.topRows(atoms);
1192 projectedCellForce[static_cast<size_t>(i)] = total.bottomRows(3);
1193 projectedCellForce[static_cast<size_t>(i)](0, 1) = 0.0;
1194 projectedCellForce[static_cast<size_t>(i)](0, 2) = 0.0;
1195 projectedCellForce[static_cast<size_t>(i)](1, 2) = 0.0;
1196 for (long atom = 0; atom < atoms; ++atom) {
1197 if (path[i]->getFixed(atom)) {
1198 projectedForce[i]->row(atom).setZero();
1199 }
1200 }
1201 eonc::neb::zeroTranslation(*projectedForce[i], path[i]->numberOfFreeAtoms(),
1202 path[i]->numberOfAtoms());
1203 }
1204}
Eigen::Matrix< double, 3, 3, eOnStorageOrder > Matrix3d
Definition Eigen.h:35
void zeroTranslation(AtomMatrix &projectedForce, int nFreeAtoms, int nAtoms)
Zero net translational force for fully free systems.
SpringStrategy buildSpringStrategy(const Parameters &params, const std::vector< std::shared_ptr< Matter > > &path, long numImages, int atoms, double maxEnergy, double E_ref)
Build the appropriate spring strategy from parameters and current path state.
double jointNorm(const JointBlock &block)
JointBlock jointDisplacement(const Matter &from, const Matter &to, double jacobian)
Displacement of to relative to from in the joint metric.
double solidStateEnthalpy(const Matter &image, const Matter &reference, double pressure)
Potential energy plus P : (h0^{-1} (h-h0)) * V0.
Matrix3d cellNebForce(const Matrix3d &cauchy, double volume, double jacobian, const Matrix3d &externalStress)
NEB force on the Jacobian-scaled strain.

◆ setCIEnabled()

void eonc::NudgedElasticBand::setCIEnabled ( bool enabled)
inline

Definition at line 70 of file NudgedElasticBand.h.

70 {
71 if (ci_enabled_ != enabled) {
72 ci_enabled_ = enabled;
73 // CI changes the projection while physical force caches remain valid.
75 }
76 }

◆ solidJacobian()

double eonc::NudgedElasticBand::solidJacobian ( ) const
inlinenodiscardnoexcept

Definition at line 63 of file NudgedElasticBand.h.

63{ return solidJacobian_; }

◆ solidState()

bool eonc::NudgedElasticBand::solidState ( ) const
inlinenodiscardnoexcept

Definition at line 62 of file NudgedElasticBand.h.

62{ return solidState_; }

◆ updateForces() [1/2]

void eonc::NudgedElasticBand::updateForces ( bool ci_active)

Definition at line 719 of file NudgedElasticBand.cpp.

719 {
720 // Update forces for all intermediate images. Prefer batched evaluation
721 // (single model.forward() over all dirty images, e.g. MetatomicPotential
722 // on GPU). Else fall back to per-image evaluation, which is itself
723 // thread-parallel when (a) the potential is thread-safe on the same
724 // instance, or (b) per-image instances were created (separate models).
725 if (pot->supportsBatchEvaluation() && numImages > 1) {
726 // Collect only images that need recomputation (positions changed).
727 // Materialize atomic numbers and cells first, then build the raw-pointer
728 // arrays after storage is stable. Otherwise vector growth can invalidate
729 // earlier .data() pointers and hand garbage cells/types to forceBatch().
730 std::vector<long> dirty; // indices into path[] (1-based)
731 dirty.reserve(numImages);
732 for (long i = 1; i <= numImages; i++) {
733 if (path[i]->needsForceUpdate()) {
734 dirty.push_back(i);
735 }
736 }
737
738 if (!dirty.empty()) {
739 if (!path.empty()) {
740 path.front()->pollCancel("neb");
741 }
742 auto nDirty = static_cast<long>(dirty.size());
743 std::vector<VectorXi> nrsStore;
744 std::vector<Matrix3d> boxStore;
745 std::vector<const double *> posVec, boxVec;
746 std::vector<const int *> nrsVec;
747 std::vector<double *> frcVec;
748 nrsStore.reserve(static_cast<size_t>(nDirty));
749 boxStore.reserve(static_cast<size_t>(nDirty));
750 posVec.reserve(static_cast<size_t>(nDirty));
751 boxVec.reserve(static_cast<size_t>(nDirty));
752 nrsVec.reserve(static_cast<size_t>(nDirty));
753 frcVec.reserve(static_cast<size_t>(nDirty));
754
755 for (long idx : dirty) {
756 nrsStore.push_back(path[idx]->getAtomicNrs());
757 // Isolated molecules still store a box for I/O. Pots that infer
758 // PBC from a non-zero cell must see a zero box, as
759 // Matter::computePotential does on the endpoints.
760 boxStore.push_back(
761 (path[idx]->getPeriodic() || pot->forwardsStoredCell())
762 ? path[idx]->getCell()
763 : Matrix3d::Zero());
764 }
765 for (long j = 0; j < nDirty; j++) {
766 auto idx = dirty[static_cast<size_t>(j)];
767 posVec.push_back(path[idx]->getPositions().data());
768 nrsVec.push_back(nrsStore[static_cast<size_t>(j)].data());
769 frcVec.push_back(path[idx]->forcesData());
770 boxVec.push_back(boxStore[static_cast<size_t>(j)].data());
771 }
772
773 std::vector<double> energies(nDirty), variances(nDirty);
774 // Image i is system i - 1 to the potential's router (imageOwner),
775 // whether or not the images before it are dirty.
776 std::vector<long> owners(static_cast<size_t>(nDirty));
777 for (long j = 0; j < nDirty; j++) {
778 owners[static_cast<size_t>(j)] =
779 imageOwner(static_cast<size_t>(dirty[static_cast<size_t>(j)]));
780 }
781 pot->forceBatchOwned(nDirty, atoms, posVec.data(), nrsVec.data(),
782 frcVec.data(), energies.data(), variances.data(),
783 boxVec.data(), owners.data());
784 for (long j = 0; j < nDirty; j++) {
785 path[dirty[j]]->setComputedPotential(energies[j], variances[j]);
786 }
787 }
788 } else {
789 // Per-image evaluation (sequential or parallel threads)
790 bool canParallel =
792 if (numImages > 1 && params.main_options().parallel && canParallel) {
793#ifdef EON_PARALLEL_NEB
794 // nvc++ -stdpar=multicore|gpu (meson -Dstdpar=cpu|gpu).
795 std::vector<long> beads(static_cast<size_t>(numImages));
796 std::iota(beads.begin(), beads.end(), 1);
797 std::exception_ptr neb_cancel;
798 std::mutex neb_cancel_mu;
799 std::for_each(std::execution::par, beads.begin(), beads.end(),
800 [this, &neb_cancel, &neb_cancel_mu](long i) {
801 try {
802 path[i]->getForcesRaw();
803 } catch (const JobCancelled &) {
804 std::lock_guard<std::mutex> lock(neb_cancel_mu);
805 if (!neb_cancel) {
806 neb_cancel = std::current_exception();
807 }
808 }
809 });
810 if (neb_cancel) {
811 std::rethrow_exception(neb_cancel);
812 }
813#else
815 [this](long i) { path[i]->getForcesRaw(); });
816#endif
817 } else {
818 for (long i = 1; i <= numImages; i++) {
819 path[i]->getForcesRaw();
820 }
821 }
822 }
823
824 if (solidState_) {
825 projectSolidState(ci_active);
826 movedAfterForceCall = ci_active != ci_enabled_;
827 return;
828 }
829
830 // Find the highest energy non-endpoint image
831 auto first = path.begin() + 1;
832 auto last = path.begin() + numImages + 1;
833 auto it = std::max_element(
834 first, last,
835 [](const std::shared_ptr<Matter> &a, const std::shared_ptr<Matter> &b) {
836 return a->getPotentialEnergy() < b->getPotentialEnergy();
837 });
838 maxEnergyImage = std::distance(path.begin(), it);
839 double maxEnergy = (*it)->getPotentialEnergy();
840
841 // Update E_ref for energy weighting. The higher endpoint keeps the
842 // soft spring on the side below that minimum.
843 if (params.neb_options().spring.weighting.enabled) {
844 E_ref = std::max(path[0]->getPotentialEnergy(),
845 path[numImages + 1]->getPotentialEnergy());
846 }
847
848 // Climbing requires an interior peak above both fixed endpoints.
849 // A monotonic path retains the spring force on every interior image.
850 const double endpointEnergy = std::max(path.front()->getPotentialEnergy(),
851 path.back()->getPotentialEnergy());
852 const bool climb = ci_active && maxEnergy > endpointEnergy;
853 const long previousCI = static_cast<long>(climbingImage);
854 climbingImage = 0;
855
856 // Spring strategy must be rebuilt each iteration (depends on maxEnergy,
857 // E_ref). Tangent and projection strategies are cached as members.
859 maxEnergy, E_ref);
860
861 if (const auto *uniform = std::get_if<eonc::neb::UniformSpring>(&spring)) {
862 ksp = uniform->ksp;
863 }
864 // The climbing image, chosen before the per-image work so that work
865 // writes nothing outside its own image.
866 // Re-picking the highest image every call hops the climber onto a
867 // shoulder, so the current one stays while it is a strict interior
868 // local maximum.
869 long ciTarget = static_cast<long>(maxEnergyImage);
870 if (climb && previousCI > 0 && previousCI <= numImages) {
871 const double eCI = path[previousCI]->getPotentialEnergy();
872 if (eCI > path[previousCI - 1]->getPotentialEnergy() &&
873 eCI > path[previousCI + 1]->getPotentialEnergy()) {
874 ciTarget = previousCI;
875 }
876 }
877 if (climb) {
878 climbingImage = static_cast<size_t>(ciTarget);
879 }
880
881 // Each image reads its neighbours' positions and energies and writes
882 // only its own tangent and projected force, so with [Main] parallel the
883 // images are projected on the image pool like their forces.
884 auto projectImage = [&](long i) {
885 AtomMatrix posDiffNext(atoms, 3), posDiffPrev(atoms, 3);
886 const AtomMatrix &force = path[i]->getForces();
887 const AtomMatrix &pos = path[i]->getPositions();
888 const AtomMatrix &posPrev = path[i - 1]->getPositions();
889 const AtomMatrix &posNext = path[i + 1]->getPositions();
890 double energy = path[i]->getPotentialEnergy();
891 double energyPrev = path[i - 1]->getPotentialEnergy();
892 double energyNext = path[i + 1]->getPotentialEnergy();
893 posDiffNext.noalias() = posNext - pos;
894 posDiffNext = path[i]->pbc(posDiffNext);
895 posDiffPrev.noalias() = pos - posPrev;
896 posDiffPrev = path[i]->pbc(posDiffPrev);
897 double distNext = posDiffNext.norm();
898 double distPrev = posDiffPrev.norm();
899
900 // Tangent via strategy dispatch
901 *tangent[i] = std::visit(
902 [&](auto &t) {
903 return t.compute(posDiffNext, posDiffPrev, energy, energyPrev,
904 energyNext);
905 },
907
908 // Spring forces via strategy dispatch
909 eonc::neb::SpringResult springResult = std::visit(
910 [&](auto &s) -> eonc::neb::SpringResult {
911 using T = std::decay_t<decltype(s)>;
912 if constexpr (std::is_same_v<T, eonc::neb::UniformSpring>) {
913 return s.compute(i, *tangent[i], distNext, distPrev, posDiffNext,
914 posDiffPrev, path[i]);
915 } else if constexpr (std::is_same_v<T, eonc::neb::WeightedSpring>) {
916 return s.compute(i, *tangent[i], distNext, distPrev);
917 } else if constexpr (std::is_same_v<T, eonc::neb::GeometricSpring>) {
918 return s.compute(i, *tangent[i], distNext, distPrev);
919 } else {
920 return s.compute(i, *tangent[i], posNext, posPrev, pos, path[i]);
921 }
922 },
923 spring);
924
925 // Climbing image or projected force
926 if (climb && i == ciTarget) {
927 // CI force: F - 2*(F.t)*t, plus DNEB correction if active
928 AtomMatrix forceDNEB = AtomMatrix::Zero(atoms, 3);
929 if (const auto *dnebProj =
930 std::get_if<eonc::neb::DNEB_Projection>(&projectionStrat_)) {
931 AtomMatrix fPerp = eonc::neb::forcePerp(force, *tangent[i]);
932 forceDNEB = eonc::neb::computeDNEBComponent(springResult.forceSpring,
933 *tangent[i], fPerp,
934 dnebProj->use_switching);
935 }
936 *projectedForce[i] =
937 eonc::neb::climbingImageForce(force, *tangent[i], forceDNEB);
938 } else {
939 eonc::neb::ImageForceData data{force, *tangent[i], springResult,
940 path[i]->numberOfFreeAtoms(),
941 path[i]->numberOfAtoms()};
942 *projectedForce[i] = std::visit([&](auto &p) { return p.project(data); },
944 }
945
946 // The spring force acts along the tangent, which has a component on a
947 // fixed atom whenever the endpoints place it differently; a fixed atom
948 // carries no force on the band.
949 if (path[i]->numberOfFreeAtoms() < path[i]->numberOfAtoms()) {
950 for (long j = 0; j < atoms; j++) {
951 if (path[i]->getFixed(j)) {
952 projectedForce[i]->row(j).setZero();
953 }
954 }
955 }
956
957 eonc::neb::zeroTranslation(*projectedForce[i], path[i]->numberOfFreeAtoms(),
958 path[i]->numberOfAtoms());
959 };
960 if (numImages > 1 && params.main_options().parallel) {
961 eonc::forEachImage(numImages, projectImage);
962 } else {
963 for (long i = 1; i <= numImages; i++) {
964 projectImage(i);
965 }
966 }
967
968 movedAfterForceCall = ci_active != ci_enabled_;
969}
void projectSolidState(bool ci_active)
AtomMatrix computeDNEBComponent(const AtomMatrix &forceSpring, const AtomMatrix &tangent, const AtomMatrix &fPerp, bool useSwitching)
Compute the DNEB force component for a given image.
AtomMatrix climbingImageForce(const AtomMatrix &force, const AtomMatrix &tangent, const AtomMatrix &forceDNEB)
Compute the climbing image projected force.
AtomMatrix forcePerp(const AtomMatrix &force, const AtomMatrix &tangent)
Compute the perpendicular component of force relative to the tangent.
bool potAllowsSharedInstance(const P &p) noexcept
void forEachImage(long n, Work &&work)

◆ updateForces() [2/2]

void eonc::NudgedElasticBand::updateForces ( void )
inline

Definition at line 69 of file NudgedElasticBand.h.

◆ eonc::neb::OCINEBController

friend class eonc::neb::OCINEBController
friend

Definition at line 39 of file NudgedElasticBand.h.

Member Data Documentation

◆ atoms

int eonc::NudgedElasticBand::atoms {0}

Definition at line 104 of file NudgedElasticBand.h.

104{0};

◆ baseline_force

double eonc::NudgedElasticBand::baseline_force {-1.0}
private

Definition at line 129 of file NudgedElasticBand.h.

129{-1.0};

◆ ci_enabled_

bool eonc::NudgedElasticBand::ci_enabled_ {false}
private

Definition at line 128 of file NudgedElasticBand.h.

128{false}; // runtime CI state, set by compute()

◆ climbingImage

long eonc::NudgedElasticBand::climbingImage {0}

Definition at line 105 of file NudgedElasticBand.h.

105{0}, climbingImage{0}, numExtrema{0};

◆ E_ref

double eonc::NudgedElasticBand::E_ref

Definition at line 124 of file NudgedElasticBand.h.

◆ eigenmode_solvers

std::vector<std::shared_ptr<EigenmodeStrategy> > eonc::NudgedElasticBand::eigenmode_solvers

Definition at line 92 of file NudgedElasticBand.h.

◆ extremumCurvature

std::vector<double> eonc::NudgedElasticBand::extremumCurvature

Definition at line 114 of file NudgedElasticBand.h.

◆ extremumEnergy

std::vector<double> eonc::NudgedElasticBand::extremumEnergy

Definition at line 112 of file NudgedElasticBand.h.

◆ extremumPosition

std::vector<double> eonc::NudgedElasticBand::extremumPosition

Definition at line 113 of file NudgedElasticBand.h.

◆ iteration_

long eonc::NudgedElasticBand::iteration_ {0}
private

Definition at line 133 of file NudgedElasticBand.h.

133{0};

◆ k_l

double eonc::NudgedElasticBand::k_l {0.0}

Definition at line 123 of file NudgedElasticBand.h.

123{0.0}; // Lower-bound value for the spring constant

◆ k_u

double eonc::NudgedElasticBand::k_u {0.0}

Definition at line 122 of file NudgedElasticBand.h.

122{0.0}; // Upper-bound value for the spring constant

◆ ksp

double eonc::NudgedElasticBand::ksp {0.0}

Definition at line 121 of file NudgedElasticBand.h.

121{0.0};

◆ log

eonc::log::Scoped eonc::NudgedElasticBand::log
private

Definition at line 134 of file NudgedElasticBand.h.

◆ maxEnergyImage

std::size_t eonc::NudgedElasticBand::maxEnergyImage {0}

Definition at line 116 of file NudgedElasticBand.h.

116{0};

◆ movedAfterForceCall

bool eonc::NudgedElasticBand::movedAfterForceCall {false}

Definition at line 118 of file NudgedElasticBand.h.

118{false};

◆ numExtrema

long eonc::NudgedElasticBand::numExtrema {0}

Definition at line 105 of file NudgedElasticBand.h.

105{0}, climbingImage{0}, numExtrema{0};

◆ numImages

long eonc::NudgedElasticBand::numImages {0}

Definition at line 105 of file NudgedElasticBand.h.

105{0}, climbingImage{0}, numExtrema{0};

◆ params

Parameters eonc::NudgedElasticBand::params
private

Definition at line 130 of file NudgedElasticBand.h.

◆ path

std::vector<std::shared_ptr<Matter> > eonc::NudgedElasticBand::path

Definition at line 109 of file NudgedElasticBand.h.

◆ perImagePotentials_

bool eonc::NudgedElasticBand::perImagePotentials_
Initial value:
{
false}

Whether per-image potential instances exist.

Definition at line 119 of file NudgedElasticBand.h.

119 {
120 false};

◆ pot

std::shared_ptr<Potential> eonc::NudgedElasticBand::pot
private

Definition at line 131 of file NudgedElasticBand.h.

◆ projectedCellForce

std::vector<Matrix3d> eonc::NudgedElasticBand::projectedCellForce
private

Definition at line 141 of file NudgedElasticBand.h.

◆ projectedForce

std::vector<std::shared_ptr<AtomMatrix> > eonc::NudgedElasticBand::projectedForce

Definition at line 111 of file NudgedElasticBand.h.

◆ projectionStrat_

neb::ProjectionStrategy eonc::NudgedElasticBand::projectionStrat_
private

Definition at line 138 of file NudgedElasticBand.h.

◆ reactantEnergy

double eonc::NudgedElasticBand::reactantEnergy {0.0}

Definition at line 108 of file NudgedElasticBand.h.

108{0.0};

◆ solidJacobian_

double eonc::NudgedElasticBand::solidJacobian_ {1.0}
private

Definition at line 140 of file NudgedElasticBand.h.

140{1.0};

◆ solidState_

bool eonc::NudgedElasticBand::solidState_ {false}
private

Definition at line 139 of file NudgedElasticBand.h.

139{false};

◆ status

NEBStatus eonc::NudgedElasticBand::status
private

Definition at line 132 of file NudgedElasticBand.h.

◆ tangent

std::vector<std::shared_ptr<AtomMatrix> > eonc::NudgedElasticBand::tangent

Definition at line 110 of file NudgedElasticBand.h.

◆ tangentStrat_

neb::TangentStrategy eonc::NudgedElasticBand::tangentStrat_
private

Definition at line 137 of file NudgedElasticBand.h.


The documentation for this class was generated from the following files: