Loading...
Searching...
No Matches
NudgedElasticBandJob.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/BaseStructures.h"
15#include "eon/EonLogger.h"
16#include "eon/JobResult.h"
19#include "eon/PotRegistry.h"
20#include "eon/Potential.h"
22#include "eon/Tunneling.h"
23
24#include <filesystem>
25#include <format>
26#include <fstream>
27#include <stdexcept>
28
29namespace eonc {
30
31std::vector<std::string> NudgedElasticBandJob::run() {
33 size_t f1;
35
36 std::string reactantFilename = eonc::helpers::getRelevantFile("reactant.con");
37 std::string productFilename = eonc::helpers::getRelevantFile("product.con");
38
39 // TS interpolation: only when initializer is FILE (explicit path loading).
40 // Previously, any ts.con in CWD would silently override SIDPP/IDPP paths.
41 bool tsInterpolate = false;
42 std::shared_ptr<Matter> transitionState = nullptr;
43 if (params.neb_options().initialization.method == NEBInit::FILE &&
44 std::filesystem::exists("ts.con")) {
45 std::string transitionStateFilename =
47 transitionState = std::make_shared<Matter>(pot, params);
48 tsInterpolate = true;
49 if (!eonc::io::io_ok(
50 transitionState->con2matter(transitionStateFilename))) {
51 EONC_LOG_CRITICAL("Failed to load {}", transitionStateFilename);
52 throw std::runtime_error("failed to load " + transitionStateFilename);
53 }
54 }
55
56 auto initial = std::make_shared<Matter>(pot, params);
57 auto final_state = std::make_shared<Matter>(pot, params);
58
59 // When initializer=file and initial_path_in is set, endpoints are the first
60 // and last frames of that list — do not require reactant.con / product.con
61 // (issue #278; buggy endpoint files were still loaded and could crash).
62 const bool usePathEndpoints =
63 params.neb_options().initialization.method == NEBInit::FILE &&
64 !params.neb_options().initialization.input_path.empty();
65
66 if (usePathEndpoints) {
67 const auto file_paths = eonc::helpers::neb_paths::readFilePaths(
68 params.neb_options().initialization.input_path);
69 if (file_paths.size() < 2) {
70 throw std::runtime_error(
71 "NEB initial_path_in must list at least two frames "
72 "(reactant and product endpoints)");
73 }
74 if (!eonc::io::io_ok(initial->con2matter(file_paths.front().string()))) {
75 EONC_LOG_CRITICAL("Failed to load NEB path reactant frame {}",
76 file_paths.front().string());
77 throw std::runtime_error("failed to load NEB path reactant frame");
78 }
79 if (!eonc::io::io_ok(final_state->con2matter(file_paths.back().string()))) {
80 EONC_LOG_CRITICAL("Failed to load NEB path product frame {}",
81 file_paths.back().string());
82 throw std::runtime_error("failed to load NEB path product frame");
83 }
84 QUILL_LOG_INFO(m_log,
85 "NEB endpoints from initial path list (skipped {} / {})",
86 reactantFilename, productFilename);
87 } else {
88 if (!eonc::io::io_ok(initial->con2matter(reactantFilename))) {
89 EONC_LOG_CRITICAL("Failed to load {}", reactantFilename);
90 throw std::runtime_error("failed to load reactant.con");
91 }
92 if (!eonc::io::io_ok(final_state->con2matter(productFilename))) {
93 EONC_LOG_CRITICAL("Failed to load {}", productFilename);
94 throw std::runtime_error("failed to load product.con");
95 }
96 }
97
99 "reactant and product");
100 if (tsInterpolate) {
101 eonc::helpers::neb_paths::requireSameAtomCount(*initial, *transitionState,
102 "reactant and ts.con");
103 }
104
105 // Endpoint minimization logic:
106 // - If params.neb_options().endpoints.minimize is false: never minimize
107 // endpoints.
108 // - If params.neb_options().endpoints.minimize is true and
109 // params.neb_options().initialization.input_path is empty: minimize
110 // endpoints.
111 // - If params.nebMinimEP is true and params.nebIpath is NOT empty:
112 // -> minimize endpoints only if params.nebMinimEPIpath is true.
113 // Log what decision was made so users can see behavior.
114 bool shouldMinimizeEndpoints = false;
115 if (!params.neb_options().endpoints.minimize) {
116 QUILL_LOG_DEBUG(m_log,
117 "minimize_endpoints == false: not minimizing endpoints.");
118 shouldMinimizeEndpoints = false;
119 } else {
120 if (params.neb_options().initialization.input_path.empty()) {
121 QUILL_LOG_DEBUG(m_log, "minimize_endpoints == true and nebIpath "
122 "empty: minimizing endpoints.");
123 shouldMinimizeEndpoints = true;
124 } else {
125 // nebIpath provided: only minimize if neb_options.endpoints.use_path_file
126 // explicitly allowed.
127 if (params.neb_options().endpoints.use_path_file) {
128 QUILL_LOG_DEBUG(
129 m_log,
130 "minimize_endpoints == true and nebIpath provided, but "
131 "minimize_endpoints_for_ipath == true: minimizing endpoints.");
132 shouldMinimizeEndpoints = true;
133 } else {
134 QUILL_LOG_DEBUG(
135 m_log,
136 "minimize_endpoints == true but nebIpath provided and "
137 "minimize_endpoints_for_ipath == false: not minimizing endpoints.");
138 shouldMinimizeEndpoints = false;
139 }
140 }
141 }
142
143 if (shouldMinimizeEndpoints) {
144 QUILL_LOG_DEBUG(m_log, "Minimizing reactant");
145 initial->relax(false, params.debug_options().write_movies,
146 params.main_options().checkpoint, "react_neb", "react_neb");
147 QUILL_LOG_DEBUG(m_log, "Minimized reactant");
148 QUILL_LOG_DEBUG(m_log, "Minimizing product");
149 final_state->relax(false, params.debug_options().write_movies,
150 params.main_options().checkpoint, "prod_neb",
151 "prod_neb");
152 }
153
154 auto neb =
155 std::make_unique<NudgedElasticBand>(initial, final_state, params, pot);
156
157 if (tsInterpolate) {
158 AtomMatrix reactantToTS = transitionState->pbc(
159 transitionState->getPositions() - initial->getPositions());
160 AtomMatrix TSToProduct = transitionState->pbc(
161 final_state->getPositions() - transitionState->getPositions());
162 for (int image = 1; image <= neb->numImages; image++) {
163 int mid = neb->numImages / 2 + 1;
164 if (image < mid) {
165 double frac = static_cast<double>(image) / static_cast<double>(mid);
166 neb->path[image]->setPositions(initial->getPositions() +
167 frac * reactantToTS);
168 } else if (image > mid) {
169 double frac = static_cast<double>(image - mid) /
170 static_cast<double>(neb->numImages - mid + 1);
171 neb->path[image]->setPositions(transitionState->getPositions() +
172 frac * TSToProduct);
173 } else if (image == mid) {
174 neb->path[image]->setPositions(transitionState->getPositions());
175 }
176 }
177 }
178
179 f1 = pots().total_force_calls();
180 status = neb->compute();
181 fCallsNEB += pots().total_force_calls() - f1;
182
184 neb->printImageData();
185 neb->findExtrema();
186 if (params.saddle_search_options().prfo_refine.enabled) {
188 }
189 }
190
191 printEndState(status);
192 saveData(status, neb.get());
193
194 return returnFiles;
195}
196
197// The band is left as it converged; the refined saddle is a separate file.
199 if (neb.climbingImage <= 0) {
200 QUILL_LOG_WARNING(m_log, "prfo_refine: the band has no climbing image");
201 return;
202 }
203 const size_t before = pots().total_force_calls();
204 const auto ci = static_cast<size_t>(neb.climbingImage);
205 Matter saddle(*neb.path[ci]);
206 const AtomMatrix &tangent = *neb.tangent[ci];
207 const double curvature = eonc::modeCurvature(
208 saddle, tangent, params.main_options().finiteDifference);
209 if (curvature < 0.0) {
210 refined_ = eonc::prfoRefineSaddle(saddle, tangent, curvature, params);
211 const std::string refinedFilename("sp_refined.con");
212 if (eonc::io::io_ok(saddle.matter2con(refinedFilename))) {
213 returnFiles.push_back(refinedFilename);
214 } else {
215 QUILL_LOG_ERROR(m_log, "Failed to write {}", refinedFilename);
216 }
217 } else {
218 QUILL_LOG_WARNING(m_log,
219 "prfo_refine: curvature {:.4f} along the climbing "
220 "image tangent is not negative, no refinement",
221 curvature);
222 }
223 fCallsRefine_ = pots().total_force_calls() - before;
224}
225
228 std::string resultsFilename("results.dat");
229 returnFiles.push_back(resultsFilename);
230 // The outer walls of both wells, for the one-dimensional tunnelling
231 // levels written beside the band; sampled first, so the force calls they
232 // take are in results.dat.
233 std::optional<eonc::tunneling::BandWalls> walls;
234 if (const long points = params.neb_options().tunnel_wall_points;
235 points > 0 && status == NudgedElasticBand::NEBStatus::GOOD) {
236 try {
237 const std::vector<std::shared_ptr<Matter>> band(
238 neb->path.begin(),
239 neb->path.begin() + static_cast<std::ptrdiff_t>(neb->numImages + 2));
240 walls = eonc::tunneling::bandWalls(band, neb->reactantEnergy, points);
241 } catch (const std::invalid_argument &ex) {
242 QUILL_LOG_WARNING(m_log, "No tunnelling walls for this band: {}",
243 ex.what());
244 }
245 }
246
247 {
252 params.potential_options().potential, pots().total_force_calls(), true,
253 neb->reactantEnergy);
254 env.provenance = provenanceForJob(params);
255 env.job_type = "neb";
256 env.extras.emplace_back("force_calls_neb", static_cast<double>(fCallsNEB));
257 env.extras.emplace_back("energy_reference", neb->reactantEnergy);
258 env.extras.emplace_back("number_of_images",
259 static_cast<double>(neb->numImages));
260 if (params.saddle_search_options().prfo_refine.enabled) {
261 env.extras.emplace_back("force_calls_prfo_refine",
262 static_cast<double>(fCallsRefine_));
263 }
264 if (refined_) {
265 env.extras.emplace_back("prfo_refine_converged",
266 refined_->converged ? 1.0 : 0.0);
267 env.extras.emplace_back("prfo_refine_max_force", refined_->maxForce);
268 env.extras.emplace_back("prfo_refine_energy",
269 refined_->energy - neb->reactantEnergy);
270 }
271 env.writeResultsDat(resultsFilename);
272 std::ofstream out(resultsFilename, std::ios::binary | std::ios::app);
273 if (!out) {
274 QUILL_LOG_ERROR(m_log, "Failed to reopen {} for image keys",
275 resultsFilename);
276 return;
277 }
278
279 for (long i = 0; i <= neb->numImages + 1; i++) {
280 out << std::format(
281 "{:f} image{}_energy\n",
282 neb->path[i]->getPotentialEnergy() - neb->reactantEnergy, i);
283 out << std::format("{:f} image{}_force\n",
284 neb->path[i]->getForces().norm(), i);
285 double proj_norm = (i >= 1 && i <= neb->numImages)
286 ? neb->projectedForce[i]->norm()
287 : 0.0;
288 out << std::format("{:f} image{}_projected_force\n", proj_norm, i);
289 }
290
291 long safeNumExtrema = std::min(
292 neb->numExtrema, static_cast<long>(neb->extremumPosition.size()));
293 out << std::format("{} number_of_extrema\n", safeNumExtrema);
294 for (long i = 0; i < safeNumExtrema; i++) {
295 out << std::format("{:f} extremum{}_position\n", neb->extremumPosition[i],
296 i);
297 out << std::format("{:f} extremum{}_energy\n", neb->extremumEnergy[i], i);
298 }
299 }
300
301 // Save the Full NEB Path
302 std::string nebFilename("neb.con");
303 returnFiles.push_back(nebFilename);
304 std::vector<double> quantumFreeEnergy;
305 const double quantumTemperature = params.neb_options().quantum_temperature;
306 const std::vector<double> *quantumPtr = nullptr;
307 if (quantumTemperature > 0.0) {
308 quantumFreeEnergy = eonc::quantumFreeEnergies(neb->path, neb->tangent,
309 quantumTemperature, params);
310 quantumPtr = &quantumFreeEnergy;
311 }
313 neb->path, neb->tangent, neb->eigenmode_solvers, neb->numImages,
314 params.debug_options().estimate_neb_eigenvalues, nebFilename,
315 std::nullopt, neb->reactantEnergy, quantumPtr,
316 walls ? &*walls : nullptr))) {
317 QUILL_LOG_ERROR(m_log, "Failed to write {}", nebFilename);
318 }
319
320 // Save Discrete Saddle Point (Highest Energy Image)
321 std::string spFilename("sp.con");
322 if (!eonc::io::io_ok(
323 neb->path[neb->maxEnergyImage]->matter2con(spFilename))) {
324 QUILL_LOG_ERROR(m_log, "Failed to write {}", spFilename);
325 }
326 returnFiles.push_back(spFilename);
327
328 // Setup Dimer Configurations for Each Spline Peak
329 if (params.neb_options().mmf_peaks.enabled && neb->numExtrema > 0) {
330 int peakCount = 0;
331 for (long i = 0; i < neb->numExtrema; i++) {
332 // Filter 1: Only look at maxima (negative curvature)
333 // Filter 2: Energy threshold (e.g., peak must be > 0.05 eV above
334 // reactant)
335 double relativeEnergy = neb->extremumEnergy[i] - neb->reactantEnergy;
336
337 if (neb->extremumCurvature[i] < 0 &&
338 relativeEnergy > params.neb_options().mmf_peaks.tolerance) {
339 double posFraction = neb->extremumPosition[i];
340 int leftIdx = static_cast<int>(std::floor(posFraction));
341 double f = posFraction - leftIdx;
342
343 if (leftIdx < 0 || leftIdx >= neb->numImages + 1)
344 continue;
345
346 // 1. Write Interpolated Position (.con)
348 *neb->path[leftIdx], *neb->path[leftIdx + 1], f);
349 std::string peakPosFile = std::format("peak{:02d}_pos.con", peakCount);
350 if (!eonc::io::io_ok(peakPos.matter2con(peakPosFile))) {
351 QUILL_LOG_ERROR(m_log, "Failed to write {}", peakPosFile);
352 }
353 returnFiles.push_back(peakPosFile);
354
355 // 2. Write Interpolated Tangent as standard mode.dat
357 neb->path, neb->tangent, neb->numImages, posFraction);
358
359 std::string peakModeFile =
360 std::format("peak{:02d}_mode.dat", peakCount);
361 {
362 std::ofstream modeOut(peakModeFile);
363 if (modeOut) {
364 for (long row = 0; row < peakMode.rows(); ++row) {
365 modeOut << std::format("{:.17g} {:.17g} {:.17g}\n",
366 peakMode(row, 0), peakMode(row, 1),
367 peakMode(row, 2));
368 }
369 returnFiles.push_back(peakModeFile);
370 }
371 }
372
373 QUILL_LOG_INFO(
374 m_log,
375 "Generated MMF peak {:02d} at position {:.3f} (Energy: {:.3f} eV)",
376 peakCount, posFraction, relativeEnergy);
377 peakCount++;
378 }
379 }
380 }
381
382 returnFiles.push_back("neb.dat");
383 neb->printImageData(true, std::numeric_limits<size_t>::max());
384}
385
387 QUILL_LOG_DEBUG(m_log, "Final state: ");
389 QUILL_LOG_DEBUG(m_log, "Nudged elastic band, successful.");
391 QUILL_LOG_DEBUG(m_log, "Nudged elastic band, too many iterations.");
392 else
393 QUILL_LOG_WARNING(m_log, "Unknown status: {}!", static_cast<int>(status));
394 return;
395}
396
397} // namespace eonc
Direct optimization for energy minimization.
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
#define EONC_LOG_CRITICAL(...)
Definition EonLogger.h:334
PotRegistry & pots() noexcept
Definition Job.h:109
std::shared_ptr< Potential > pot
Set when one Potential is shared across Matters, images, or a caller.
Definition Job.h:66
Parameters params
Definition Job.h:58
io::IoStatus matter2con(std::string filename, bool append=false, const io::ConFrameMetadata *metadata=nullptr)
Definition Matter.h:293
std::vector< std::string > run(void)
Virtual run; used solely for dynamic dispatch.
void printEndState(NudgedElasticBand::NEBStatus status)
std::vector< std::string > returnFiles
void saveData(NudgedElasticBand::NEBStatus status, NudgedElasticBand *neb)
std::optional< PrfoRefineResult > refined_
void refineClimbingImage(NudgedElasticBand &neb)
size_t total_force_calls() const noexcept
Matter interpolateImage(const Matter &A, const Matter &B, double fraction)
void requireSameAtomCount(const Matter &a, const Matter &b, std::string_view what)
Abort before Eigen subtracts two position matrices of different size.
std::vector< fs::path > readFilePaths(const std::string &listFilePath)
Reads a file where each line contains a path to another file.
std::string getRelevantFile(std::string filename)
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
AtomMatrix interpolatedPeakMode(const std::vector< std::shared_ptr< Matter > > &path, const std::vector< std::shared_ptr< AtomMatrix > > &tangent, long numImages, double posFraction)
Unit tangent at a fractional image index.
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().
BandWalls bandWalls(const std::vector< std::shared_ptr< Matter > > &band, double referenceEnergy, long points)
The walls of both ends of a band, after Khomenko et al.
RAII resource manager for the ARTn C library with global synchronization.
PrfoRefineResult prfoRefineSaddle(Matter &, const AtomMatrix &, double, const Parameters &)
Partitioned rational function optimization (P-RFO) of a first-order saddle in the rgsaddle Sella orde...
JobResultProvenance provenanceForJob(const Parameters &params)
Optimizer backend, engine identity, rgpot pin, and xts ABI from a job.
std::vector< double > quantumFreeEnergies(const std::vector< std::shared_ptr< Matter > > &path, const std::vector< std::shared_ptr< AtomMatrix > > &tangent, double temperature, const Parameters &params)
F(s) = V(s) + the harmonic free energy of the vibrations, one entry per image.
void requirePrfoRefine(const Parameters &params)
Does nothing unless [Saddle Search] prfo_refine is on.
double modeCurvature(const Matter &matter, const AtomMatrix &mode, double dr)
Curvature along mode from one forward difference of the forces over dr Angstrom.
static JobResultEnvelope fromMinimization(RunStatus status, PotType pot, std::uint64_t fcalls, bool hasE, double energy)
Definition JobResult.h:251