Loading...
Searching...
No Matches
SaddleSearchJob.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*/
12#include "eon/SaddleSearchJob.h"
13#ifdef WITH_ARTN
15#endif
16#include "eon/EonLogger.h"
17#include "eon/EpiCenters.h"
18#include "eon/HelperFunctions.h"
19#include "eon/Potential.h"
20#include "eon/PrfoRefine.h"
21#include "eon/XtsciIrc.h"
22
23#include <filesystem>
24#include <format>
25#include <fstream>
26#include <stdexcept>
27#include <string>
28
29namespace eonc {
30
31std::vector<std::string> SaddleSearchJob::run() {
32 if (params.saddle_search_options().method == "min_mode") {
34 }
35 std::string reactantFilename = eonc::helpers::getRelevantFile("pos.con");
36 std::string displacementFilename("displacement.con");
37 std::string modeFilename("direction.dat");
38
39 if (params.main_options().checkpoint) {
40 if (std::filesystem::exists("displacement_cp.con") &&
41 std::filesystem::exists("mode_cp.dat")) {
42 displacementFilename = "displacement_cp.con";
43 modeFilename = "mode_cp.dat";
44 QUILL_LOG_DEBUG(log, "Resuming from checkpoint");
45 } else {
46 QUILL_LOG_DEBUG(log, "No checkpoint files found");
47 }
48 }
49
50 initial = std::make_shared<Matter>(pot, params);
51 displacement = std::make_shared<Matter>(pot, params);
52 saddle = std::make_shared<Matter>(pot, params);
53
54 if (!eonc::io::io_ok(initial->con2matter(reactantFilename))) {
55 EONC_LOG_CRITICAL("Failed to load {}", reactantFilename);
56 throw std::runtime_error("failed to load " + reactantFilename);
57 }
58
59 const bool standaloneARTn = params.saddle_search_options().method == "artn";
60
61 AtomMatrix mode = AtomMatrix::Zero(initial->numberOfAtoms(), 3);
62 if (!standaloneARTn && params.saddle_search_options().displace_type ==
64 // Load displacement.con, or synthesize from pos.con + direction.dat (#79).
66 *saddle, *initial, displacementFilename, modeFilename,
67 params.saddle_search_options().displace_magnitude)) {
68 EONC_LOG_CRITICAL("Failed to load {} (and no usable {})",
69 displacementFilename, modeFilename);
70 throw std::runtime_error("missing displacement.con and direction.dat");
71 }
72 if (std::filesystem::exists(modeFilename)) {
73 mode = eonc::helpers::loadMode(modeFilename, initial->numberOfAtoms());
74 }
75 } else if (!standaloneARTn && eonc::helpers::applyClientDisplacement(
76 *saddle, *initial, params, &mode)) {
77 // listed_atoms / random / last_atom / least_coordinated / not_fcc_hcp
78 } else {
79 *saddle = *initial;
80 }
81
82 if (standaloneARTn && std::filesystem::exists(modeFilename)) {
83 mode = eonc::helpers::loadMode(modeFilename, initial->numberOfAtoms());
84 }
85
86 static_cast<void>(runPrepared(mode));
87 return returnFiles;
88}
89
90std::shared_ptr<Matter>
91SaddleSearchJob::runFromMatter(std::shared_ptr<Matter> seed) {
92 if (!seed) {
93 throw std::runtime_error("SaddleSearchJob::runFromMatter: null Matter");
94 }
95 initial = seed;
96 initial->setPotential(pot);
97 displacement = std::make_shared<Matter>(pot, params);
98 saddle = std::make_shared<Matter>(pot, params);
99 AtomMatrix mode = AtomMatrix::Zero(initial->numberOfAtoms(), 3);
101 &mode)) {
102 *saddle = *initial;
103 }
105 return runPrepared(mode);
106}
107
108std::shared_ptr<Matter> SaddleSearchJob::runPrepared(const AtomMatrix &mode) {
109 const auto &ircOpts = params.saddle_search_options().irc;
110 if (ircOpts.after) {
111 if (!ircAvailable()) {
112 throw std::runtime_error("[Saddle Search] irc_after needs eOn built with "
113 "-Dwith_rgsaddle=true against rgsaddle C ABI "
114 "minor 14 or newer");
115 }
116 if (!(ircOpts.step_size > 0.0) || !(ircOpts.converged_force > 0.0) ||
117 ircOpts.max_steps < 1) {
118 throw std::invalid_argument("[Saddle Search] irc_step_size and "
119 "irc_converged_force must be positive and "
120 "irc_max_steps at least 1");
121 }
122 }
123 const bool useStandaloneARTn =
124 params.saddle_search_options().method == "artn";
125 const bool useARTnAsMinMode =
126 params.saddle_search_options().method == "min_mode" &&
127 params.saddle_search_options().minmode_method == "artn";
128
129#ifdef WITH_ARTN
130 if (useStandaloneARTn || useARTnAsMinMode) {
132 std::make_unique<ARTnSaddleSearch>(saddle, pot, mode, params);
133 } else
134#endif
135 {
136#ifndef WITH_ARTN
137 if (useStandaloneARTn) {
138 throw std::runtime_error(
139 "saddle_search.method=artn requires a build with ARTn support");
140 }
141 if (useARTnAsMinMode) {
142 throw std::runtime_error(
143 "saddle_search.minmode_method=artn requires a build with ARTn "
144 "support");
145 }
146#endif
147 saddleSearch = std::make_unique<MinModeSaddleSearch>(
148 saddle, mode, initial->getPotentialEnergy(), params, pot);
149 }
150
151 int status = doSaddleSearch();
152 printEndState(status);
153 if (ircOpts.after && status == MinModeSaddleSearch::STATUS_GOOD) {
154 if (saddleSearch->getEigenvalue() < 0.0) {
155 runIrc();
156 } else {
157 QUILL_LOG_WARNING(log,
158 "[Saddle Search] IRC skipped: lowest eigenvalue "
159 "{:f} is not negative",
160 saddleSearch->getEigenvalue());
161 }
162 }
163 saveData(status);
164
165 return saddle;
166}
167
169 long status;
170 const size_t registryBefore = potRegistryForceCalls();
171 const size_t potBefore = this->pot->forceCallCounter;
172 try {
173 status = saddleSearch->run();
174 } catch (int e) {
175 if (e == 100) {
177 } else {
178 QUILL_LOG_ERROR(log, "unknown exception: {}", e);
179 throw e;
180 }
181 } catch (const std::exception &e) {
182 QUILL_LOG_ERROR(log, "Saddle search potential failed: {}", e.what());
184 }
185
186 if (params.saddle_search_options().method == "min_mode" &&
187 params.saddle_search_options().minmode_method ==
189 fCallsSaddle = saddleSearch->getForceCalls();
190 } else if (params.saddle_search_options().method == "artn") {
191 fCallsSaddle = saddleSearch->getForceCalls();
192 } else {
193 const size_t calls = potRegistryForceCalls() - registryBefore;
194 fCallsImages = calls - (this->pot->forceCallCounter - potBefore);
195 fCallsSaddle += static_cast<int>(calls);
196 }
197
198 return status;
199}
200
202 std::string resultsFilename("results.dat");
203 returnFiles.push_back(resultsFilename);
204
205 std::ofstream out(resultsFilename, std::ios::binary);
206 if (out) {
207 out << std::format("{} termination_reason\n", status);
208 out << std::format("{} termination_reason_text\n",
209 saddleSearch->describeStatus(status));
210 out << "saddle_search job_type\n";
211 out << std::format("{} random_seed\n", params.main_options().randomSeed);
212 out << std::format(
213 "{} potential_type\n",
214 magic_enum::enum_name<PotType>(params.potential_options().potential));
215 out << std::format("{} total_force_calls\n",
216 this->pot->forceCallCounter.load() + fCallsImages);
217 out << std::format("{} force_calls_saddle\n", fCallsSaddle);
218 out << std::format("{} iterations\n", saddleSearch->getIterationCount());
220 out << std::format("{:f} potential_energy_saddle\n",
221 saddle->getPotentialEnergy());
222 out << std::format("{:f} final_eigenvalue\n",
223 saddleSearch->getEigenvalue());
224 }
225 out << std::format("{:f} potential_energy_reactant\n",
226 initial->getPotentialEnergy());
227 if (irc.ran) {
228 out << std::format("{} irc_branches_at_minimum\n", irc.branchesAtMinimum);
229 out << std::format("{} irc_ends_relaxed\n", int{irc.endsRelaxed});
230 out << std::format("{} irc_connects_reactant\n",
231 int{irc.connectsReactant});
232 out << std::format("{} force_calls_irc\n", irc.forceCalls);
233 out << std::format("{} force_calls_irc_minimization\n",
234 irc.forceCallsMin);
235 out << std::format("{:f} potential_energy_irc_min1\n", irc.energies[0]);
236 out << std::format("{:f} potential_energy_irc_min2\n", irc.energies[1]);
237 }
238 }
239
240 std::string modeFilename("mode.dat");
241 returnFiles.push_back(modeFilename);
242 eonc::helpers::saveMode(modeFilename, saddle, saddleSearch->getEigenvector());
243
244 std::string saddleFilename("saddle.con");
245 returnFiles.push_back(saddleFilename);
246 if (!eonc::io::io_ok(saddle->matter2con(saddleFilename))) {
247 QUILL_LOG_ERROR(log, "Failed to write {}", saddleFilename);
248 }
249}
250
252 irc.ran = true;
253 const size_t before = pot->forceCallCounter;
254 IrcPath path;
255 try {
256 path = followIrc(*saddle, saddleSearch->getEigenvector(), params);
257 } catch (const std::exception &e) {
258 irc.forceCalls = pot->forceCallCounter - before;
259 QUILL_LOG_ERROR(log, "[Saddle Search] IRC failed: {}", e.what());
260 return;
261 }
262 irc.forceCalls = pot->forceCallCounter - before;
263 irc.branchesAtMinimum =
264 int{path.minus.reachedMinimum} + int{path.plus.reachedMinimum};
265
266 // irc.con runs from the minus end through the saddle to the plus end.
267 // irc.dat follows the neb.dat layout, with max_force in the last column.
268 // rxn_coord and energy are taken from the saddle.
269 struct Point {
270 const AtomMatrix *pos;
271 double energy;
272 double maxForce;
273 };
274 std::vector<Point> points;
275 for (size_t i = path.minus.positions.size(); i-- > 0;) {
276 points.push_back({&path.minus.positions[i], path.minus.energies[i],
277 path.minus.maxForces[i]});
278 }
279 const size_t saddleIndex = points.size();
280 const AtomMatrix saddlePos = saddle->getPositions();
281 const double saddleEnergy = saddle->getPotentialEnergy();
282 points.push_back({&saddlePos, saddleEnergy, saddle->maxForce()});
283 for (size_t i = 0; i < path.plus.positions.size(); ++i) {
284 points.push_back({&path.plus.positions[i], path.plus.energies[i],
285 path.plus.maxForces[i]});
286 }
287 std::vector<double> arc(points.size(), 0.0);
288 for (size_t i = 1; i < points.size(); ++i) {
289 arc[i] =
290 arc[i - 1] + saddle->pbc(*points[i].pos - *points[i - 1].pos).norm();
291 }
292 Matter frame(*saddle);
293 std::ofstream dat("irc.dat", std::ios::binary);
294 dat << std::format("{:>3s} {:>12s} {:>12s} {:>12s}\n", "img", "rxn_coord",
295 "energy", "max_force");
296 for (size_t i = 0; i < points.size(); ++i) {
297 frame.setPositions(*points[i].pos);
299 meta.energy = points[i].energy;
300 if (!eonc::io::io_ok(frame.matter2con("irc.con", i > 0, &meta))) {
301 QUILL_LOG_ERROR(log, "Failed to write irc.con");
302 }
303 dat << std::format("{:>3} {:>12.6f} {:>12.6f} {:>12.6f}\n", i,
304 arc[i] - arc[saddleIndex],
305 points[i].energy - saddleEnergy, points[i].maxForce);
306 }
307 returnFiles.push_back("irc.con");
308 returnFiles.push_back("irc.dat");
309
310 const size_t minBefore = pot->forceCallCounter;
311 irc.endsRelaxed = true;
312 const IrcBranch *branches[2] = {&path.minus, &path.plus};
313 for (int k = 0; k < 2; ++k) {
314 Matter end(*saddle);
315 if (!branches[k]->positions.empty()) {
316 end.setPositions(branches[k]->positions.back());
317 }
318 irc.endsRelaxed = end.relax(true) && irc.endsRelaxed;
319 irc.energies[k] = end.getPotentialEnergy();
320 Matter reactant(*initial);
321 irc.connectsReactant = irc.connectsReactant || reactant.compare(end);
322 const std::string name = std::format("irc_min{}.con", k + 1);
323 returnFiles.push_back(name);
324 if (!eonc::io::io_ok(end.matter2con(name))) {
325 QUILL_LOG_ERROR(log, "Failed to write {}", name);
326 }
327 }
328 irc.forceCallsMin = pot->forceCallCounter - minBefore;
329 QUILL_LOG_INFO(log,
330 "[Saddle Search] IRC: {} of 2 branches at a minimum, {} force "
331 "calls, {} more to relax the ends",
332 irc.branchesAtMinimum, irc.forceCalls, irc.forceCallsMin);
333}
334
336 auto msg = saddleSearch->describeStatus(status);
337 if (status == MinModeSaddleSearch::STATUS_GOOD) {
338 QUILL_LOG_DEBUG(log, "[Saddle Search] {}", msg);
339 } else {
340 QUILL_LOG_WARNING(log, "[Saddle Search] {}", msg);
341 }
342}
343
344} // namespace eonc
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
#define EONC_LOG_CRITICAL(...)
Definition EonLogger.h:334
Finds transition states by finding saddle points on the potential energy surface.
size_t potRegistryForceCalls() const noexcept
Force calls charged to pot's registry.
Definition Job.cpp:44
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
static const char MINMODE_GPRDIMER[]
bool relax(bool quiet=false, bool writeMovie=false, bool checkpoint=false, std::string prefixMovie=std::string(), std::string prefixCheckpoint=std::string(), bool retainMovieFrames=false)
Definition Matter.cpp:404
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
double getPotentialEnergy() const
Definition Matter.cpp:624
io::IoStatus matter2con(std::string filename, bool append=false, const io::ConFrameMetadata *metadata=nullptr)
Definition Matter.h:293
std::unique_ptr< SaddleSearchMethod > saddleSearch
Initializes a ref SaddleSearchMethod (base class for polymorphism).
std::vector< std::string > returnFiles
Container for the results of the run.
std::shared_ptr< Matter > runFromMatter(std::shared_ptr< Matter > seed)
In-process entry: seed reactant Matter, no pos.con.
std::shared_ptr< Matter > saddle
Configuration used during the saddle point search.
eonc::log::Scoped log
std::vector< std::string > run(void) override
Kicks off the Saddle Search.
int doSaddleSearch()
Runs the correct saddle search; also checks if the run was successful.
int fCallsSaddle
Force calls to find the saddle.
struct eonc::SaddleSearchJob::IrcSummary irc
std::shared_ptr< Matter > displacement
Configuration used during the saddle point search.
void saveData(int status)
Writes the results from the run to file.
void printEndState(int status)
Logs the run status and makes sure the run was successful.
std::shared_ptr< Matter > initial
Initial configuration.
std::shared_ptr< Matter > runPrepared(const AtomMatrix &mode)
const char DISP_LOAD[]
Definition EpiCenters.h:20
bool applyClientDisplacement(Matter &target, const Matter &initial, const Parameters &params, AtomMatrix *modeOut)
std::string getRelevantFile(std::string filename)
bool loadOrSynthesizeDisplacement(Matter &target, const Matter &initial, const std::string &displacementPath, const std::string &modePath, double scale)
AtomMatrix loadMode(FILE *modeFile, int nAtoms)
void saveMode(FILE *modeFile, std::shared_ptr< Matter > matter, AtomMatrix mode)
Write a mode; constrained axes are emitted as 0.
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
RAII resource manager for the ARTn C library with global synchronization.
IrcPath followIrc(const Matter &saddle, const AtomMatrix &mode, const Parameters &params)
Follows the rgsaddle IRC from a converged saddle along both signs of its lowest mode.
Definition XtsciIrc.cpp:138
bool ircAvailable()
True when this build can run followIrc: linked to rgsaddle at C ABI minor 14 or newer,...
Definition XtsciIrc.cpp:128
void requirePrfoRefine(const Parameters &params)
Does nothing unless [Saddle Search] prfo_refine is on.
Accepted points of one branch of the intrinsic reaction coordinate (IRC), in order away from the sadd...
Definition XtsciIrc.h:23
std::vector< AtomMatrix > positions
Definition XtsciIrc.h:24
std::vector< double > maxForces
Definition XtsciIrc.h:26
std::vector< double > energies
Definition XtsciIrc.h:25
bool reachedMinimum
Definition XtsciIrc.h:30
Both branches of the IRC.
Definition XtsciIrc.h:35
IrcBranch minus
Definition XtsciIrc.h:36
IrcBranch plus
Definition XtsciIrc.h:37
std::optional< double > energy
Definition ConFileIO.h:73