Loading...
Searching...
No Matches
NEBSplineExtrema.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/ConFileIO.h"
14#include "eon/Tunneling.h"
15#include <algorithm>
16#include <cmath>
17#include <format>
18#include <fstream>
19#include <limits>
20
21namespace fs = std::filesystem;
22
23namespace eonc::neb {
24
25namespace {
26
27void normalizeOrZero(AtomMatrix &v) {
28 const double n = v.norm();
29 if (n > 1e-10) {
30 v /= n;
31 }
32}
33
34// Stored endpoint tangents are left at zero. The band direction there is the
35// normalized minimum-image step to the neighboring image.
37storedOrEndpointTangent(const std::vector<std::shared_ptr<Matter>> &path,
38 const std::vector<std::shared_ptr<AtomMatrix>> &tangent,
39 long numImages, long imageIndex) {
40 AtomMatrix tang;
41 if (imageIndex == 0) {
42 tang = path[0]->pbc(path[1]->getPositions() - path[0]->getPositions());
43 normalizeOrZero(tang);
44 return tang;
45 }
46 if (imageIndex == numImages + 1) {
47 tang = path[numImages]->pbc(path[numImages + 1]->getPositions() -
48 path[numImages]->getPositions());
49 normalizeOrZero(tang);
50 return tang;
51 }
52 return *tangent[static_cast<size_t>(imageIndex)];
53}
54
55// NaN means path[0]; see pathToConFrames.
56double referenceOrFirst(const std::vector<std::shared_ptr<Matter>> &path,
57 double referenceEnergy) {
58 return std::isnan(referenceEnergy) ? path[0]->getPotentialEnergy()
59 : referenceEnergy;
60}
61
62eonc::io::ConFrameMetadata neb_frame_metadata(
63 const std::vector<std::shared_ptr<Matter>> &path,
64 const std::vector<std::shared_ptr<AtomMatrix>> &tangent,
65 const std::vector<std::shared_ptr<EigenmodeStrategy>> &eigenmode_solvers,
66 long numImages, bool estimateEigenvalues, long imageIndex,
67 double reactionCoordinate, std::optional<size_t> bandIndex,
68 double referenceEnergy) {
69 AtomMatrix tang;
70 if (imageIndex == 0) {
71 tang = path[0]->pbc(path[1]->getPositions() - path[0]->getPositions());
72 } else if (imageIndex == numImages + 1) {
73 tang = path[numImages]->pbc(path[numImages + 1]->getPositions() -
74 path[numImages]->getPositions());
75 } else {
76 tang = *tangent[imageIndex];
77 }
78 normalizeOrZero(tang);
79
80 const double reference_energy = referenceOrFirst(path, referenceEnergy);
81 const double absolute_energy = path[imageIndex]->getPotentialEnergy();
82 const double relative_energy = absolute_energy - reference_energy;
83 const double parallel_force = matDot(path[imageIndex]->getForces(), tang);
84
85 eonc::io::ConFrameMetadata metadata;
86 metadata.frame_index = static_cast<uint64_t>(imageIndex);
87 metadata.energy = absolute_energy;
88 metadata.neb_bead = static_cast<uint64_t>(imageIndex);
89 if (bandIndex) {
90 metadata.neb_band = static_cast<uint64_t>(*bandIndex);
91 }
92 metadata.scalars.push_back({"reaction_coordinate", reactionCoordinate});
93 metadata.scalars.push_back({"relative_energy", relative_energy});
94 metadata.scalars.push_back({"parallel_force", parallel_force});
95
96 if (estimateEigenvalues && imageIndex >= 0 &&
97 imageIndex < static_cast<long>(eigenmode_solvers.size()) &&
98 eigenmode_solvers[imageIndex]) {
99 eonc::eigenmodeCompute(*eigenmode_solvers[imageIndex], path[imageIndex],
100 tang);
101 metadata.scalars.push_back(
102 {"lowest_eigenvalue",
103 eonc::eigenmodeGetEigenvalue(*eigenmode_solvers[imageIndex])});
104 }
105
106 return metadata;
107}
108
109} // namespace
110
112findSplineExtrema(const std::vector<std::shared_ptr<Matter>> &path,
113 const std::vector<std::shared_ptr<AtomMatrix>> &tangent,
114 long numImages) {
115
116 auto *log = eonc::log::get();
117
118 // Calculate cubic parameters for each interval
119 AtomMatrix tangentEndpoint;
120 std::vector<double> a(numImages + 1), b(numImages + 1), c(numImages + 1),
121 d(numImages + 1);
122 double F1, F2, U1, U2, dist;
123
124 for (long i = 0; i <= numImages; i++) {
125 dist = path[i]->distanceTo(*path[i + 1]);
126 if (i == 0) {
127 tangentEndpoint =
128 path[i]->pbc(path[1]->getPositions() - path[0]->getPositions());
129 normalizeOrZero(tangentEndpoint);
130 F1 = matDot(path[i]->getForces(), tangentEndpoint) * dist;
131 } else {
132 F1 = matDot(path[i]->getForces(), *tangent[i]) * dist;
133 }
134 if (i == numImages) {
135 tangentEndpoint = path[i + 1]->pbc(path[numImages + 1]->getPositions() -
136 path[numImages]->getPositions());
137 normalizeOrZero(tangentEndpoint);
138 F2 = matDot(path[i + 1]->getForces(), tangentEndpoint) * dist;
139 } else {
140 F2 = matDot(path[i + 1]->getForces(), *tangent[i + 1]) * dist;
141 }
142 U1 = path[i]->getPotentialEnergy();
143 U2 = path[i + 1]->getPotentialEnergy();
144 a[i] = U1;
145 b[i] = -F1;
146 c[i] = 3. * (U2 - U1) + 2. * F1 + F2;
147 d[i] = -2. * (U2 - U1) - (F1 + F2);
148 }
149
150 ExtremaResult result;
151 result.positions.resize(2 * (numImages + 1));
152 result.energies.resize(2 * (numImages + 1));
153 result.curvatures.resize(2 * (numImages + 1));
154
155 double discriminant, f;
156
157 for (long i = 0; i <= numImages; i++) {
158 discriminant = c[i] * c[i] - 3.0 * b[i] * d[i];
159 if (discriminant >= 0) {
160 f = -1;
161
162 // Quadratic case
163 if ((d[i] == 0) && (c[i] != 0)) {
164 f = (-b[i] / (2. * c[i]));
165 }
166 // Cubic case 1
167 else if (d[i] != 0) {
168 f = -(c[i] + std::sqrt(discriminant)) / (3. * d[i]);
169 }
170 if ((f >= 0) && (f <= 1)) {
171 result.positions[result.numExtrema] = i + f;
172 result.energies[result.numExtrema] =
173 ((d[i] * f + c[i]) * f + b[i]) * f + a[i]; // Horner's method
174 result.curvatures[result.numExtrema] = 6.0 * d[i] * f + 2 * c[i];
175 result.numExtrema++;
176 }
177 // Cubic case 2. A zero cubic coefficient leaves f at the quadratic
178 // root, and a zero discriminant is that same cubic root. Storing
179 // either again doubles one stationary point.
180 if (d[i] != 0 && discriminant != 0.0) {
181 f = -(c[i] - std::sqrt(discriminant)) / (3. * d[i]);
182 } else {
183 f = -1;
184 }
185 if ((f >= 0) && (f <= 1)) {
186 result.positions[result.numExtrema] = i + f;
187 result.energies[result.numExtrema] =
188 ((d[i] * f + c[i]) * f + b[i]) * f + a[i]; // Horner's method
189 result.curvatures[result.numExtrema] = 6 * d[i] * f + 2 * c[i];
190 result.numExtrema++;
191 }
192 }
193 }
194
195 QUILL_LOG_DEBUG(log, "Found {} extrema", result.numExtrema);
196 QUILL_LOG_DEBUG(log, "Energy reference: {}", path[0]->getPotentialEnergy());
197 for (long i = 0; i < result.numExtrema; i++) {
198 QUILL_LOG_DEBUG(
199 log, "extrema #{} at image position {} with energy {} and curvature {}",
200 i + 1, result.positions[i],
201 result.energies[i] - path[0]->getPotentialEnergy(),
202 result.curvatures[i]);
203 }
204
205 return result;
206}
207
209interpolatedPeakMode(const std::vector<std::shared_ptr<Matter>> &path,
210 const std::vector<std::shared_ptr<AtomMatrix>> &tangent,
211 long numImages, double posFraction) {
212 const int nat = path.empty() ? 0 : path[0]->numberOfAtoms();
213 const auto leftIdx = static_cast<long>(std::floor(posFraction));
214 if (path.size() < 2 || leftIdx < 0 || leftIdx >= numImages + 1 ||
215 leftIdx + 1 >= static_cast<long>(path.size())) {
216 return AtomMatrix::Zero(nat, 3);
217 }
218 const double f = posFraction - static_cast<double>(leftIdx);
219 AtomMatrix mode =
220 (1.0 - f) * storedOrEndpointTangent(path, tangent, numImages, leftIdx) +
221 f * storedOrEndpointTangent(path, tangent, numImages, leftIdx + 1);
222 normalizeOrZero(mode);
223 return mode;
224}
225
227 const std::vector<std::shared_ptr<Matter>> &path,
228 const std::vector<std::shared_ptr<AtomMatrix>> &tangent,
229 const std::vector<std::shared_ptr<EigenmodeStrategy>> &eigenmode_solvers,
230 long numImages, bool estimateEigenvalues, bool writeToFile, size_t idx,
231 eonc::log::Scoped log, double referenceEnergy) {
232
233 double dist, distTotal = 0;
234 AtomMatrix tangentStart =
235 path[0]->pbc(path[1]->getPositions() - path[0]->getPositions());
236 AtomMatrix tangentEnd = path[numImages]->pbc(
237 path[numImages + 1]->getPositions() - path[numImages]->getPositions());
238 AtomMatrix tang;
239 std::string header;
240 if (estimateEigenvalues) {
241 header = std::format("{:>3s} {:>12s} {:>12s} {:>12s} {:>12s}", "img",
242 "rxn_coord", "energy", "f_para", "eigval");
243 } else {
244 header = std::format("{:>3s} {:>12s} {:>12s} {:>12s}", "img", "rxn_coord",
245 "energy", "f_para");
246 }
247
248 normalizeOrZero(tangentStart);
249 normalizeOrZero(tangentEnd);
250
251 std::ofstream fileLogger;
252 if (writeToFile) {
253 std::string neb_dat_fs;
254 if (idx == std::numeric_limits<size_t>::max()) {
255 neb_dat_fs = "neb.dat";
256 } else {
257 neb_dat_fs = std::format("neb_{:03}.dat", idx);
258 }
259 if (fs::exists(neb_dat_fs)) {
260 fs::remove(neb_dat_fs);
261 }
262 fileLogger.open(neb_dat_fs);
263 if (fileLogger.is_open()) {
264 fileLogger << header << "\n";
265 }
266 }
267 const double energy_reactant = referenceOrFirst(path, referenceEnergy);
268
269 for (long i = 0; i <= numImages + 1; i++) {
270 if (i == 0) {
271 tang = tangentStart;
272 } else if (i == numImages + 1) {
273 tang = tangentEnd;
274 } else {
275 tang = *tangent[i];
276 }
277
278 if (i > 0) {
279 dist = path[i]->distanceTo(*path[i - 1]);
280 distTotal += dist;
281 }
282
283 double relative_energy = path[i]->getPotentialEnergy() - energy_reactant;
284 double parallel_force = matDot(path[i]->getForces(), tang);
285
286 if (estimateEigenvalues) {
287 eonc::eigenmodeCompute(*eigenmode_solvers[i], path[i], tang);
288 double lowest_eigenvalue =
289 eonc::eigenmodeGetEigenvalue(*eigenmode_solvers[i]);
290 if (fileLogger.is_open()) {
291 fileLogger << std::format(
292 "{:>3} {:>12.6f} {:>12.6f} {:>12.6f} {:>12.6f}\n", i, distTotal,
293 relative_energy, parallel_force, lowest_eigenvalue);
294 } else {
295 QUILL_LOG_DEBUG(log, "{:>3} {:>12.6f} {:>12.6f} {:>12.6f} {:>12.6f}", i,
296 distTotal, relative_energy, parallel_force,
297 lowest_eigenvalue);
298 }
299 } else {
300 if (fileLogger.is_open()) {
301 fileLogger << std::format("{:>3} {:>12.6f} {:>12.6f} {:>12.6f}\n", i,
302 distTotal, relative_energy, parallel_force);
303 } else {
304 QUILL_LOG_DEBUG(log, "{:>3} {:>12.6f} {:>12.6f} {:>12.6f}", i,
305 distTotal, relative_energy, parallel_force);
306 }
307 }
308 }
309}
310
311std::vector<readcon::ConFrame> pathToConFrames(
312 const std::vector<std::shared_ptr<Matter>> &path,
313 const std::vector<std::shared_ptr<AtomMatrix>> &tangent,
314 const std::vector<std::shared_ptr<EigenmodeStrategy>> &eigenmode_solvers,
315 long numImages, bool estimateEigenvalues, std::optional<size_t> bandIndex,
316 double referenceEnergy, const std::vector<double> *quantumFreeEnergy,
317 const eonc::tunneling::BandWalls *walls) {
318 const size_t nframes = static_cast<size_t>(numImages) + 2;
319 if (path.size() < nframes) {
320 return {};
321 }
322
323 double distTotal = 0.0;
324 std::vector<eonc::io::ConFrameMetadata> metas;
325 metas.reserve(nframes);
326
327 // The mass-weighted arc length rides beside the Cartesian one: it is the
328 // coordinate a tunnelling integral along the band runs over. A structure
329 // without masses leaves it out rather than failing the write.
330 double distMw = 0.0;
331 bool haveMw = true;
332 for (long i = 0; i <= numImages + 1; i++) {
333 if (i > 0) {
334 distTotal += path[i]->distanceTo(*path[i - 1]);
335 if (haveMw) {
336 try {
337 distMw +=
338 eonc::tunneling::massWeightedDistance(*path[i - 1], *path[i]);
339 } catch (const std::invalid_argument &) {
340 haveMw = false;
341 }
342 }
343 }
344 metas.push_back(neb_frame_metadata(path, tangent, eigenmode_solvers,
345 numImages, estimateEigenvalues, i,
346 distTotal, bandIndex, referenceEnergy));
347 if (haveMw) {
348 metas.back().scalars.push_back({"reaction_coordinate_mw", distMw});
349 }
350 }
351 // The band's one-dimensional tunnelling estimate goes on its first frame:
352 // the well frequencies, the WKB action and the splitting a two-level-system
353 // screen reads. Left out when an image has no mass or an end well is flat.
354 if (haveMw && !metas.empty()) {
355 try {
356 std::vector<std::shared_ptr<Matter>> ends(
357 path.begin(), path.begin() + static_cast<std::ptrdiff_t>(nframes));
358 const auto split = eonc::tunneling::bandSplitting(
359 ends, referenceOrFirst(path, referenceEnergy));
360 auto &head = metas.front().scalars;
361 head.push_back({"hbar_omega_reactant", split.hwReactant});
362 head.push_back({"hbar_omega_product", split.hwProduct});
363 head.push_back({"tunnel_action", split.action});
364 head.push_back({"tunnel_splitting", split.delta0});
365 head.push_back({"tunnel_asymmetry_zpe", split.asymmetry()});
366 head.push_back({"tls_energy", split.tlsEnergy()});
367 head.push_back({"tunnel_deep_wells", split.deepWells ? 1.0 : 0.0});
368 // The same band solved exactly in one dimension: the energy of the
369 // two-level system and its two parts.
370 const auto profile = eonc::tunneling::bandProfile(
371 ends, referenceOrFirst(path, referenceEnergy));
372 const auto levels = eonc::tunneling::bandLevels(profile, walls);
373 head.push_back({"tls_energy_dvr", levels.gap});
374 head.push_back({"tunnel_asymmetry_dvr", levels.asymmetry});
375 head.push_back({"tunnel_splitting_dvr", levels.delta0});
376 head.push_back({"tunnel_wall_sampled", walls != nullptr ? 1.0 : 0.0});
377 head.push_back({"tunnel_double_well",
378 eonc::tunneling::singleBarrier(profile) ? 1.0 : 0.0});
379 } catch (const std::invalid_argument &) {
380 }
381 }
382 if (quantumFreeEnergy != nullptr && quantumFreeEnergy->size() == nframes) {
383 const double reactant = quantumFreeEnergy->front();
384 const double barrier = *std::max_element(quantumFreeEnergy->begin(),
385 quantumFreeEnergy->end()) -
386 reactant;
387 for (size_t i = 0; i < nframes; ++i) {
388 metas[i].scalars.push_back(
389 {"quantum_free_energy", (*quantumFreeEnergy)[i]});
390 metas[i].scalars.push_back({"zpe_corrected_barrier", barrier});
391 }
392 }
393
394 std::vector<std::shared_ptr<Matter>> band(
395 path.begin(), path.begin() + static_cast<std::ptrdiff_t>(nframes));
396 return eonc::io::buildNebPathFrames(band, metas);
397}
398
400 const std::vector<std::shared_ptr<Matter>> &path,
401 const std::vector<std::shared_ptr<AtomMatrix>> &tangent,
402 const std::vector<std::shared_ptr<EigenmodeStrategy>> &eigenmode_solvers,
403 long numImages, bool estimateEigenvalues, std::string filename,
404 std::optional<size_t> bandIndex, double referenceEnergy,
405 const std::vector<double> *quantumFreeEnergy,
406 const eonc::tunneling::BandWalls *walls) {
407 auto frames = pathToConFrames(path, tangent, eigenmode_solvers, numImages,
408 estimateEigenvalues, bandIndex, referenceEnergy,
409 quantumFreeEnergy, walls);
410 if (frames.empty()) {
412 }
413 return eonc::io::writeConFrames(std::move(filename), frames);
414}
415
416} // namespace eonc::neb
double matDot(const AtomMatrix &a, const AtomMatrix &b)
SIMD-optimized dot product for contiguous Eigen matrices.
Definition Eigen.h:50
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
IoStatus writeConFrames(std::string filename, const std::vector< readcon::ConFrame > &frames)
Write already-built ConFrames to a multi-frame .con (temp or durable).
std::vector< readcon::ConFrame > buildNebPathFrames(const std::vector< std::shared_ptr< Matter > > &path, const std::vector< ConFrameMetadata > &metadata_per_image)
Build NEB band ConFrames without writing (clone builder path of writeNebPath).
IoStatus
Structured I/O result for the client surface (nanobind-friendly).
Definition ConFileIO.h:29
quill::Logger * get() noexcept
Get or create the default "combi" logger.
Definition EonLogger.h:111
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).
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().
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.
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.
Splitting bandSplitting(const std::vector< std::shared_ptr< Matter > > &band, double referenceEnergy)
The splitting of a converged band, with the well frequencies from the band's curvature at each end.
bool singleBarrier(const Profile &p)
Whether a profile is one double well: its images rise to exactly one maximum between the two ends.
double massWeightedDistance(const Matter &a, const Matter &b)
sqrt(sum_i m_i |b_i - a_i|^2) under the minimum image of a's cell.
Definition Tunneling.cpp:61
Levels bandLevels(const Profile &p, const BandWalls *walls)
dvrLevels on a band: the profile between the images, and past each end the well's fit a s^2 + b s^3 c...
Profile bandProfile(const std::vector< std::shared_ptr< Matter > > &band, double referenceEnergy)
The energy of a band against its mass-weighted arc length, measured from referenceEnergy.
void eigenmodeCompute(LowestEigenmode &s, std::shared_ptr< Matter > matter, AtomMatrix direction)
double eigenmodeGetEigenvalue(LowestEigenmode &s)
std::optional< uint64_t > frame_index
Definition ConFileIO.h:72
std::optional< uint64_t > neb_band
Definition ConFileIO.h:77
std::vector< ConMetadataValue > scalars
Definition ConFileIO.h:79
std::optional< double > energy
Definition ConFileIO.h:73
std::optional< uint64_t > neb_bead
Definition ConFileIO.h:76
RAII helper for class-scoped logging.
Definition EonLogger.h:238
std::vector< double > energies
std::vector< double > curvatures
std::vector< double > positions