Loading...
Searching...
No Matches
eonc::neb Namespace Reference

Namespaces

namespace  zoom

Classes

struct  CartesianStep
 One steepest step in Cartesian coordinates and the cell matrix. More...
struct  DNEB_Projection
 Trygubenko & Wales, JCP 120:2082, 2004. More...
struct  ExtremaResult
struct  GeometricSpring
 Cubic-potential spring. More...
struct  ImageForceData
 Data for a single image needed by projection strategies. More...
struct  ImprovedTangent
 Henkelman & Jonsson, JCP 113:9978, 2000. More...
struct  JointBlock
struct  NEB_Projection
 Jonsson, Mills, Jacobsen 1998 (World Scientific). More...
class  OCINEBController
 Goswami (in prep). More...
struct  OnsagerMachlupSpring
 Onsager-Machlup action-based springs (Mandelli & Parrinello 2021). More...
struct  PlainEB
 Mills, Jonsson, Schenter, Surf. More...
struct  SimpleTangent
 Mills, Jonsson, Schenter, Surf. More...
struct  SpringResult
 Result of spring force computation for a single image. More...
struct  UniformSpring
 Uniform spring constant for all images. More...
struct  WeightedSpring
 Energy-weighted spring constants (variable per segment). More...

Typedefs

using ProjectionStrategy
using SpringStrategy
using TangentStrategy = std::variant<SimpleTangent, ImprovedTangent>

Functions

AtomMatrix computeTangent (const AtomMatrix &posDiffNext, const AtomMatrix &posDiffPrev, double energy, double energyPrev, double energyNext, bool use_old_tangent)
 Compute the tangent vector at image i using the improved tangent scheme.
AtomMatrix forcePerp (const AtomMatrix &force, const AtomMatrix &tangent)
 Compute the perpendicular component of force relative to the tangent.
AtomMatrix climbingImageForce (const AtomMatrix &force, const AtomMatrix &tangent, const AtomMatrix &forceDNEB)
 Compute the climbing image projected force.
AtomMatrix computeDNEB (const AtomMatrix &forceSpring, const AtomMatrix &tangent, const AtomMatrix &forcePerp, bool useSwitching=true)
 Compute the doubly-nudged elastic band perpendicular spring force.
void zeroTranslation (AtomMatrix &projectedForce, int nFreeAtoms, int nAtoms)
 Zero net translational force for fully free systems.
ProjectionStrategy buildProjectionStrategy (const Parameters &params)
 Build the projection strategy from parameters.
AtomMatrix computeDNEBComponent (const AtomMatrix &forceSpring, const AtomMatrix &tangent, const AtomMatrix &forcePerp, bool useSwitching)
 Compute the DNEB force component for a given image.
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.
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.
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=std::numeric_limits< double >::quiet_NaN())
 Print NEB image data to log and optionally to file.
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=std::nullopt, double referenceEnergy=std::numeric_limits< double >::quiet_NaN(), const std::vector< double > *quantumFreeEnergy=nullptr, const eonc::tunneling::BandWalls *walls=nullptr)
 Build stamped ConFrames for a NEB band (same metadata as writePathCon).
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=std::nullopt, double referenceEnergy=std::numeric_limits< double >::quiet_NaN(), const std::vector< double > *quantumFreeEnergy=nullptr, const eonc::tunneling::BandWalls *walls=nullptr)
 Write a NEB band as a multi-frame .con via readcon ConFrameBuilder::clone().
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.
TangentStrategy buildTangentStrategy (const Parameters &params)
 Build the tangent strategy from parameters.
double solidStateJacobian (double meanVolume, int nAtoms, double weight)
 J = (V/N)^{1/3} * N^{1/2} * weight, with V the mean endpoint volume.
bool orientCellLowerTriangular (Matrix3d &cell, AtomMatrix &positions)
 Rotate the lab frame so the cell is lower triangular: the first lattice vector lies on x and the second lies in the xy plane.
void orientSolidStateMatter (Matter &image)
void interpolateSolidStateLinear (std::vector< Matter > &images)
 Replace interior images by a fractional linear interpolation of the oriented endpoints.
JointBlock jointDisplacement (const Matter &from, const Matter &to, double jacobian)
 Displacement of to relative to from in the joint metric.
double jointNorm (const JointBlock &block)
Matrix3d cellNebForce (const Matrix3d &cauchy, double volume, double jacobian, const Matrix3d &externalStress)
 NEB force on the Jacobian-scaled strain.
Matrix3d finiteDifferenceCauchyStress (const Matter &image, double strainStep)
 Central difference of the potential energy on the six lower strain components.
std::vector< Matrix3d > finiteDifferenceCauchyStresses (std::span< const Matter *const > images, double strainStep)
 The same central difference for several images at once.
double solidStateEnthalpy (const Matter &image, const Matter &reference, double pressure)
 Potential energy plus P : (h0^{-1} (h-h0)) * V0.
CartesianStep solidStateCartesianStep (const Matter &image, const AtomMatrix &atomicForce, const Matrix3d &cellForce, double jacobian)

Typedef Documentation

◆ ProjectionStrategy

Initial value:
std::variant<PlainEB, NEB_Projection, DNEB_Projection>

Definition at line 50 of file NEBProjection.h.

◆ SpringStrategy

Initial value:
Cubic-potential spring.
Onsager-Machlup action-based springs (Mandelli & Parrinello 2021).
Uniform spring constant for all images.
Energy-weighted spring constants (variable per segment).

Definition at line 68 of file NEBSpringForce.h.

◆ TangentStrategy

Definition at line 38 of file NEBTangent.h.

Function Documentation

◆ buildProjectionStrategy()

ProjectionStrategy eonc::neb::buildProjectionStrategy ( const Parameters & params)

Build the projection strategy from parameters.

DNEB is incompatible with OM and weighted springs; falls back to NEB_Projection.

Definition at line 33 of file NEBProjection.cpp.

33 {
34 bool omActive = params.neb_options().spring.om.enabled;
35 bool weightedActive = params.neb_options().spring.weighting.enabled;
36 bool geometric = params.neb_options().spring.geometric;
37
38 if (params.neb_options().spring.use_elastic_band && !omActive &&
39 !weightedActive && !geometric) {
40 return PlainEB{};
41 }
42 if (params.neb_options().spring.doubly_nudged && !omActive &&
43 !weightedActive && !geometric) {
44 return DNEB_Projection{params.neb_options().spring.use_switching};
45 }
46 return NEB_Projection{};
47}
const neb_options_t & neb_options() const
Jonsson, Mills, Jacobsen 1998 (World Scientific).
Mills, Jonsson, Schenter, Surf.
struct eonc::neb_options_t::spring_options_t::energy_weighting_t weighting
bool geometric
Parallel force k (d_next^2 - d_prev^2).
struct eonc::neb_options_t::spring_options_t::onsager_machlup_t om
struct eonc::neb_options_t::spring_options_t spring

◆ buildSpringStrategy()

SpringStrategy eonc::neb::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.

Definition at line 83 of file NEBSpringForce.cpp.

85 {
86
87 if (params.neb_options().spring.geometric) {
89 }
90
91 if (params.neb_options().spring.om.enabled) {
92 double base_k = params.neb_options().spring.constant;
93
94 if (params.neb_options().spring.om.optimize_k) {
95 double avgPotForce = 0.0;
96 double avgPathCurvature = 0.0;
97 int count = 0;
98 for (long j = 1; j <= numImages; j++) {
99 avgPotForce += path[j]->getForces().norm();
100 AtomMatrix next = path[j + 1]->getPositions();
101 AtomMatrix prev = path[j - 1]->getPositions();
102 AtomMatrix curr = path[j]->getPositions();
103 AtomMatrix curvVec = path[j]->pbc(next + prev - 2.0 * curr);
104 avgPathCurvature += curvVec.norm();
105 count++;
106 }
107 if (count > 0 && avgPathCurvature > 1e-6) {
108 double scale = params.neb_options().spring.om.k_scale;
109 base_k = scale * (avgPotForce / avgPathCurvature);
110 base_k = std::max(base_k, params.neb_options().spring.om.k_min);
111 base_k = std::min(base_k, params.neb_options().spring.om.k_max);
112 }
113 }
114
115 // Pre-calculate L vectors for all images
116 std::vector<AtomMatrix> L_vecs(numImages + 2);
117 for (long j = 0; j <= numImages + 1; j++) {
118 L_vecs[j].resize(atoms, 3);
119 if (j == 0 || j == numImages + 1) {
120 L_vecs[j].setZero();
121 } else {
122 const AtomMatrix &forces = path[j]->getForces();
123 double alpha_k = eonc::safemath::safe_recip(2.0 * base_k, 0.0);
124 for (int k = 0; k < atoms; k++) {
125 L_vecs[j].row(k) = alpha_k * forces.row(k);
126 }
127 }
128 }
129
130 return OnsagerMachlupSpring{base_k, std::move(L_vecs)};
131
132 } else if (params.neb_options().spring.weighting.enabled) {
133 double k_l = params.neb_options().spring.weighting.k_min;
134 double k_u = params.neb_options().spring.weighting.k_max;
135 std::vector<double> springConstants(numImages + 2, k_l);
136
137 double energyRange = maxEnergy - E_ref;
138 if (energyRange < 1e-10) {
139 std::fill(springConstants.begin(), springConstants.end(), k_l);
140 } else {
141 for (int idx = 1; idx <= numImages + 1; idx++) {
142 double Ei = std::max(path[idx]->getPotentialEnergy(),
143 path[idx - 1]->getPotentialEnergy());
144 if (Ei > E_ref) {
145 double alpha_i = (maxEnergy - Ei) / energyRange;
146 alpha_i = std::max(0.0, std::min(1.0, alpha_i));
147 springConstants[idx - 1] = (1.0 - alpha_i) * k_u + alpha_i * k_l;
148 } else {
149 springConstants[idx - 1] = k_l;
150 }
151 }
152 }
153
154 return WeightedSpring{std::move(springConstants)};
155
156 } else {
157 return UniformSpring{params.neb_options().spring.constant};
158 }
159}
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
constexpr double safe_recip(double x, double fallback=0.0)
Definition SafeMath.h:29

◆ buildTangentStrategy()

TangentStrategy eonc::neb::buildTangentStrategy ( const Parameters & params)

Build the tangent strategy from parameters.

Definition at line 72 of file NEBTangent.cpp.

72 {
74 return SimpleTangent{};
75 }
76 return ImprovedTangent{};
77}
Mills, Jonsson, Schenter, Surf.
Definition NEBTangent.h:23
struct eonc::neb_options_t::climbing_image_options_t climbing_image

◆ cellNebForce()

Matrix3d eonc::neb::cellNebForce ( const Matrix3d & cauchy,
double volume,
double jacobian,
const Matrix3d & externalStress )

NEB force on the Jacobian-scaled strain.

Cauchy stress uses sigma = (1/V) dE/dε for h <- h (I+ε) at fixed fractional coordinates. External stress is added before the -V factor (positive hydrostatic pressure pushes the cell inward).

Definition at line 146 of file SolidStateNEB.cpp.

147 {
148 if (!(volume > 0.0) || !(jacobian > 0.0)) {
149 throw std::invalid_argument(
150 "solid-state cell force needs a positive volume and Jacobian");
151 }
152 Matrix3d force = -(volume / jacobian) * (cauchy + externalStress);
153 zeroUpper(force);
154 return force;
155}
Eigen::Matrix< double, 3, 3, eOnStorageOrder > Matrix3d
Definition Eigen.h:35

◆ climbingImageForce()

AtomMatrix eonc::neb::climbingImageForce ( const AtomMatrix & force,
const AtomMatrix & tangent,
const AtomMatrix & forceDNEB )

Compute the climbing image projected force.

F_CI = F - 2*(F.t)*t + forceDNEB

Definition at line 73 of file NEBForceProjection.cpp.

75 {
76 return force - 2.0 * matDot(force, tangent) * tangent + forceDNEB;
77}
double matDot(const AtomMatrix &a, const AtomMatrix &b)
SIMD-optimized dot product for contiguous Eigen matrices.
Definition Eigen.h:50

◆ computeDNEB()

AtomMatrix eonc::neb::computeDNEB ( const AtomMatrix & forceSpring,
const AtomMatrix & tangent,
const AtomMatrix & forcePerp,
bool useSwitching = true )

Compute the doubly-nudged elastic band perpendicular spring force.

useSwitching multiplies the remainder by (2/pi)*atan(|F_perp|^2 / |F_spring_perp|^2).

Definition at line 79 of file NEBForceProjection.cpp.

80 {
81 AtomMatrix forceSpringPerp =
82 forceSpring - matDot(forceSpring, tangent) * tangent;
83
84 const double forceSpringPerpNorm = forceSpringPerp.norm();
85 const double forcePerpNorm = fPerp.norm();
86
87 if (forceSpringPerpNorm > 1e-10 && forcePerpNorm > 1e-10) {
88 AtomMatrix forcePerpNormalized = fPerp / forcePerpNorm;
89 AtomMatrix dneb =
90 forceSpringPerp -
91 matDot(forceSpringPerp, forcePerpNormalized) * forcePerpNormalized;
92
93 if (useSwitching) {
94 double switching = 2.0 / eonc::helpers::pi *
95 std::atan(forcePerpNorm * forcePerpNorm /
96 (forceSpringPerpNorm * forceSpringPerpNorm));
97 dneb *= switching;
98 }
99 return dneb;
100 }
101
102 return AtomMatrix::Zero(tangent.rows(), tangent.cols());
103}
constexpr double pi

◆ computeDNEBComponent()

AtomMatrix eonc::neb::computeDNEBComponent ( const AtomMatrix & forceSpring,
const AtomMatrix & tangent,
const AtomMatrix & forcePerp,
bool useSwitching )

Compute the DNEB force component for a given image.

Returned separately so it can be added to the CI force when DNEB is active. useSwitching applies the (2/pi)*atan scale. Otherwise the perpendicular spring remainder is unscaled.

Definition at line 49 of file NEBProjection.cpp.

51 {
52 return eonc::neb::computeDNEB(forceSpring, tangent, fPerp, useSwitching);
53}
AtomMatrix computeDNEB(const AtomMatrix &forceSpring, const AtomMatrix &tangent, const AtomMatrix &fPerp, bool useSwitching)
Compute the doubly-nudged elastic band perpendicular spring force.

◆ computeTangent()

AtomMatrix eonc::neb::computeTangent ( const AtomMatrix & posDiffNext,
const AtomMatrix & posDiffPrev,
double energy,
double energyPrev,
double energyNext,
bool use_old_tangent )

Compute the tangent vector at image i using the improved tangent scheme.

Returns a normalized tangent vector.

Definition at line 22 of file NEBForceProjection.cpp.

25 {
26 AtomMatrix tang;
27
28 if (use_old_tangent) {
29 tang = posDiffNext;
30 } else {
31 // Improved tangent scheme
32 if (energyNext > energy && energy > energyPrev) {
33 tang = posDiffNext;
34 } else if (energy > energyNext && energyPrev > energy) {
35 tang = posDiffPrev;
36 } else {
37 // Extremum: energy-weighted combination
38 double energyDiffPrev = energyPrev - energy;
39 double energyDiffNext = energyNext - energy;
40 double minDiffEnergy =
41 std::min(std::abs(energyDiffPrev), std::abs(energyDiffNext));
42 double maxDiffEnergy =
43 std::max(std::abs(energyDiffPrev), std::abs(energyDiffNext));
44
45 if (energyDiffPrev > energyDiffNext) {
46 tang = posDiffNext * minDiffEnergy + posDiffPrev * maxDiffEnergy;
47 } else {
48 tang = posDiffNext * maxDiffEnergy + posDiffPrev * minDiffEnergy;
49 }
50 }
51 }
52
53 // Normalize with safety check
54 double norm = tang.norm();
55 if (norm > 1e-10) {
56 tang /= norm;
57 } else {
58 // Fallback: use direction to next image
59 tang = posDiffNext;
60 norm = tang.norm();
61 if (norm > 1e-10) {
62 tang /= norm;
63 }
64 }
65
66 return tang;
67}
double norm(const Eigen::MatrixBase< A > &x)
sqrt of the correctly rounded squared norm; IEEE sqrt is itself correctly rounded,...

◆ findSplineExtrema()

ExtremaResult eonc::neb::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.

Definition at line 112 of file NEBSplineExtrema.cpp.

114 {
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}
quill::Logger * get() noexcept
Get or create the default "combi" logger.
Definition EonLogger.h:111
std::vector< double > positions

◆ finiteDifferenceCauchyStress()

Matrix3d eonc::neb::finiteDifferenceCauchyStress ( const Matter & image,
double strainStep )

Central difference of the potential energy on the six lower strain components.

Upper-triangle components stay zero.

Definition at line 157 of file SolidStateNEB.cpp.

157 {
158 const Matter *const one[] = {&image};
159 return finiteDifferenceCauchyStresses(one, strainStep).front();
160}
std::vector< Matrix3d > finiteDifferenceCauchyStresses(std::span< const Matter *const > images, double strainStep)
The same central difference for several images at once.

◆ finiteDifferenceCauchyStresses()

std::vector< Matrix3d > eonc::neb::finiteDifferenceCauchyStresses ( std::span< const Matter *const > images,
double strainStep )

The same central difference for several images at once.

The 12 strained copies of every image go to the potential as one batch, so calculator groups or a batched model take them together.

Definition at line 163 of file SolidStateNEB.cpp.

164 {
165 if (!(strainStep > 0.0)) {
166 throw std::invalid_argument(
167 "stress finite difference needs a positive step");
168 }
169 const int rows[6] = {0, 1, 1, 2, 2, 2};
170 const int cols[6] = {0, 0, 1, 0, 1, 2};
171 // Per image: raised then lowered copy for each of the six components.
172 std::vector<Matter> strained;
173 strained.reserve(12 * images.size());
174 std::vector<double> volumes;
175 volumes.reserve(images.size());
176 for (const Matter *image : images) {
177 const Matrix3d cell = image->getCell();
178 const AtomMatrix positions = image->getPositions();
179 const double volume = std::abs(cell.determinant());
180 if (!(volume > 0.0)) {
181 throw std::invalid_argument(
182 "stress finite difference needs a nonzero cell");
183 }
184 volumes.push_back(volume);
185 for (int comp = 0; comp < 6; ++comp) {
186 Matrix3d strain = Matrix3d::Zero();
187 strain(rows[comp], cols[comp]) = strainStep;
188 for (const Matrix3d &deformation :
189 {Matrix3d(Matrix3d::Identity() + strain),
190 Matrix3d(Matrix3d::Identity() - strain)}) {
191 Matter &copy = strained.emplace_back(*image);
192 copy.setCell(cell * deformation);
193 copy.setPositions(positions * deformation);
194 }
195 }
196 }
197 std::vector<Matter *> batch;
198 batch.reserve(strained.size());
199 for (Matter &m : strained) {
200 batch.push_back(&m);
201 }
202 if (!batch.empty()) {
203 eonc::evaluateTogether(*batch.front()->getPotential(), batch);
204 }
205 std::vector<Matrix3d> sigma(images.size(), Matrix3d::Zero());
206 for (size_t k = 0; k < images.size(); ++k) {
207 for (int comp = 0; comp < 6; ++comp) {
208 const Matter &raised = strained[12 * k + 2 * comp];
209 const Matter &lowered = strained[12 * k + 2 * comp + 1];
210 const double derivative =
211 (raised.getPotentialEnergy() - lowered.getPotentialEnergy()) /
212 (2.0 * strainStep);
213 sigma[k](rows[comp], cols[comp]) = derivative / volumes[k];
214 }
215 }
216 return sigma;
217}
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
void setCell(const Matrix3d &newCell)
Definition Matter.cpp:347
double getPotentialEnergy() const
Definition Matter.cpp:624
constexpr long derivative
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

◆ forcePerp()

AtomMatrix eonc::neb::forcePerp ( const AtomMatrix & force,
const AtomMatrix & tangent )

Compute the perpendicular component of force relative to the tangent.

Definition at line 69 of file NEBForceProjection.cpp.

69 {
70 return force - matDot(force, tangent) * tangent;
71}

◆ interpolatedPeakMode()

AtomMatrix eonc::neb::interpolatedPeakMode ( const std::vector< std::shared_ptr< Matter > > & path,
const std::vector< std::shared_ptr< AtomMatrix > > & tangent,
long numImages,
double posFraction )
nodiscard

Unit tangent at a fractional image index.

End intervals use the geometric endpoint displacement because stored endpoint tangents stay zero.

Definition at line 209 of file NEBSplineExtrema.cpp.

211 {
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}

◆ interpolateSolidStateLinear()

void eonc::neb::interpolateSolidStateLinear ( std::vector< Matter > & images)

Replace interior images by a fractional linear interpolation of the oriented endpoints.

images includes the endpoints.

Definition at line 93 of file SolidStateNEB.cpp.

93 {
94 const auto n = static_cast<long>(images.size());
95 if (n < 3) {
96 throw std::invalid_argument(
97 "solid_state interpolation needs two endpoints and one image");
98 }
99 const Matrix3d h0 = images.front().getCell();
100 const Matrix3d h1 = images.back().getCell();
101 const AtomMatrix s0 = fractionalCoordinates(images.front());
102 AtomMatrix ds = fractionalCoordinates(images.back()) - s0;
103 for (int atom = 0; atom < ds.rows(); ++atom) {
104 for (int axis = 0; axis < 3; ++axis) {
105 ds(atom, axis) = wrapFrac(ds(atom, axis));
106 }
107 }
108 const double denom = static_cast<double>(n - 1);
109 for (long i = 1; i < n - 1; ++i) {
110 const double t = static_cast<double>(i) / denom;
111 Matrix3d h = (1.0 - t) * h0 + t * h1;
112 zeroUpper(h);
113 const AtomMatrix fractional = s0 + t * ds;
114 images[static_cast<size_t>(i)].setCell(h);
115 images[static_cast<size_t>(i)].setPositions(fractional * h);
116 }
117}

◆ jointDisplacement()

JointBlock eonc::neb::jointDisplacement ( const Matter & from,
const Matter & to,
double jacobian )

Displacement of to relative to from in the joint metric.

Atomic rows are fractional minimum-image displacements mapped through the average cell. The cell block is the averaged right strain of the Jacobian-scaled cell difference.

Definition at line 119 of file SolidStateNEB.cpp.

120 {
121 if (!(jacobian > 0.0)) {
122 throw std::invalid_argument(
123 "solid-state displacement needs a positive Jacobian");
124 }
125 const Matrix3d hFrom = from.getCell();
126 const Matrix3d hTo = to.getCell();
127 AtomMatrix frac = fractionalCoordinates(to) - fractionalCoordinates(from);
128 for (int atom = 0; atom < frac.rows(); ++atom) {
129 for (int axis = 0; axis < 3; ++axis) {
130 frac(atom, axis) = wrapFrac(frac(atom, axis));
131 }
132 }
133 const Matrix3d average = 0.5 * (hFrom + hTo);
134 JointBlock out;
135 out.atomic = frac * average;
136 const Matrix3d dh = jacobian * (hTo - hFrom);
137 out.cell = 0.5 * (hFrom.inverse() * dh + hTo.inverse() * dh);
138 zeroUpper(out.cell);
139 return out;
140}
Matrix3d getCell() const
Definition Matter.cpp:345

◆ jointNorm()

double eonc::neb::jointNorm ( const JointBlock & block)

Definition at line 142 of file SolidStateNEB.cpp.

142 {
143 return std::hypot(block.atomic.norm(), block.cell.norm());
144}

◆ orientCellLowerTriangular()

bool eonc::neb::orientCellLowerTriangular ( Matrix3d & cell,
AtomMatrix & positions )

Rotate the lab frame so the cell is lower triangular: the first lattice vector lies on x and the second lies in the xy plane.

Fractional coordinates and the sign of the volume are unchanged. Returns false when the cell is singular or two lattice vectors are parallel.

Definition at line 49 of file SolidStateNEB.cpp.

49 {
50 const Vector3d a = cell.row(0);
51 const Vector3d b = cell.row(1);
52 const double na = a.norm();
53 if (!(na > 1e-12)) {
54 return false;
55 }
56 const Vector3d e1 = a / na;
57 const Vector3d bPerp = b - b.dot(e1) * e1;
58 const double nb = bPerp.norm();
59 if (!(nb > 1e-12)) {
60 return false;
61 }
62 const Vector3d e2 = bPerp / nb;
63 const Vector3d e3 = e1.cross(e2);
64 Matrix3d rotation;
65 rotation.col(0) = e1;
66 rotation.col(1) = e2;
67 rotation.col(2) = e3;
68 Matrix3d oriented = cell * rotation;
69 zeroUpper(oriented);
70 if (positions.rows() > 0) {
71 positions = positions * rotation;
72 }
73 if (!(std::abs(oriented.determinant()) > 1e-18)) {
74 return false;
75 }
76 cell = oriented;
77 return true;
78}

◆ orientSolidStateMatter()

void eonc::neb::orientSolidStateMatter ( Matter & image)

Definition at line 80 of file SolidStateNEB.cpp.

80 {
81 Matrix3d cell = image.getCell();
82 AtomMatrix positions = image.getPositions();
83 if (!orientCellLowerTriangular(cell, positions)) {
84 throw std::invalid_argument(
85 "solid_state NEB could not put the cell in lower-triangular form");
86 }
87 image.setCell(cell);
88 if (positions.rows() > 0) {
89 image.setPositions(positions);
90 }
91}
const AtomMatrix & getPositions() const
Definition Matter.cpp:378
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
void setCell(const Matrix3d &newCell)
Definition Matter.cpp:347
bool orientCellLowerTriangular(Matrix3d &cell, AtomMatrix &positions)
Rotate the lab frame so the cell is lower triangular: the first lattice vector lies on x and the seco...

◆ pathToConFrames()

std::vector< readcon::ConFrame > eonc::neb::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 = std::nullopt,
double referenceEnergy = std::numeric_limits< double >::quiet_NaN(),
const std::vector< double > * quantumFreeEnergy = nullptr,
const eonc::tunneling::BandWalls * walls = nullptr )
nodiscard

Build stamped ConFrames for a NEB band (same metadata as writePathCon).

Empty on invalid path size. Does not write to disk. referenceEnergy is the energy relative energies are measured from; NaN means path[0]. A zoomed band passes its original reactant energy, since zoom moves path[0] to the start of its window. walls are the outer walls tunneling::bandWalls sampled past both minima; without them the one-dimensional levels continue each well by its fit.

Definition at line 311 of file NEBSplineExtrema.cpp.

317 {
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}
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).
constexpr long reactant
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.

◆ printImageData()

void eonc::neb::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.

Definition at line 226 of file NEBSplineExtrema.cpp.

231 {
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}
void eigenmodeCompute(LowestEigenmode &s, std::shared_ptr< Matter > matter, AtomMatrix direction)
double eigenmodeGetEigenvalue(LowestEigenmode &s)

◆ solidStateCartesianStep()

CartesianStep eonc::neb::solidStateCartesianStep ( const Matter & image,
const AtomMatrix & atomicForce,
const Matrix3d & cellForce,
double jacobian )

Definition at line 231 of file SolidStateNEB.cpp.

234 {
235 if (!(jacobian > 0.0)) {
236 throw std::invalid_argument("solid-state step needs a positive Jacobian");
237 }
238 if (atomicForce.rows() != image.numberOfAtoms()) {
239 throw std::invalid_argument("solid-state step force row count mismatch");
240 }
241 const Matrix3d cell = image.getCell();
242 Matrix3d strain = cellForce / jacobian;
243 zeroUpper(strain);
244 CartesianStep step;
245 step.cell = cell * strain;
246 zeroUpper(step.cell);
247 step.positions = atomicForce + image.getPositions() * strain;
248 for (long atom = 0; atom < image.numberOfAtoms(); ++atom) {
249 if (image.getFixed(atom)) {
250 step.positions.row(atom).setZero();
251 }
252 }
253 return step;
254}
long int numberOfAtoms() const
Definition Matter.cpp:343
int getFixed(long int atom) const
1 if every Cartesian axis of the atom is fixed, else 0.
Definition Matter.cpp:575

◆ solidStateEnthalpy()

double eonc::neb::solidStateEnthalpy ( const Matter & image,
const Matter & reference,
double pressure )

Potential energy plus P : (h0^{-1} (h-h0)) * V0.

Pressure is hydrostatic, in eV/Angstrom^3. A zero pressure returns the potential energy.

Definition at line 219 of file SolidStateNEB.cpp.

220 {
221 const double energy = image.getPotentialEnergy();
222 if (pressure == 0.0) {
223 return energy;
224 }
225 const Matrix3d h0 = reference.getCell();
226 const Matrix3d strain = h0.inverse() * (image.getCell() - h0);
227 const double volume = std::abs(h0.determinant());
228 return energy + pressure * strain.trace() * volume;
229}
double getPotentialEnergy() const
Definition Matter.cpp:624

◆ solidStateJacobian()

double eonc::neb::solidStateJacobian ( double meanVolume,
int nAtoms,
double weight )

J = (V/N)^{1/3} * N^{1/2} * weight, with V the mean endpoint volume.

doi:10.1063/1.3684549

Definition at line 40 of file SolidStateNEB.cpp.

40 {
41 if (!(meanVolume > 0.0) || nAtoms < 1 || !(weight > 0.0)) {
42 throw std::invalid_argument(
43 "solid-state Jacobian needs a positive volume, atom count, and weight");
44 }
45 const double n = static_cast<double>(nAtoms);
46 return std::cbrt(meanVolume / n) * std::sqrt(n) * weight;
47}

◆ writePathCon()

eonc::io::IoStatus eonc::neb::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 )
nodiscard

Write a NEB band as a multi-frame .con via readcon ConFrameBuilder::clone().

Definition at line 399 of file NEBSplineExtrema.cpp.

406 {
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}
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 > 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).

◆ zeroTranslation()

void eonc::neb::zeroTranslation ( AtomMatrix & projectedForce,
int nFreeAtoms,
int nAtoms )

Zero net translational force for fully free systems.

Definition at line 105 of file NEBForceProjection.cpp.

105 {
106 if (nFreeAtoms == nAtoms) {
107 for (int j = 0; j <= 2; j++) {
108 double translationMag = projectedForce.col(j).sum();
109 int natoms = projectedForce.col(j).size();
110 projectedForce.col(j).array() -=
111 translationMag / static_cast<double>(natoms);
112 }
113 }
114}