Loading...
Searching...
No Matches
PrfoRefine.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/PrfoRefine.h"
13
14#include "eon/EonLogger.h"
15
16#include <stdexcept>
17#include <string>
18#include <vector>
19
20#ifdef WITH_RGSADDLE
21#include <rgsaddle.h>
22#endif
23
24namespace eonc {
25
26double modeCurvature(const Matter &matter, const AtomMatrix &mode, double dr) {
27 const AtomMatrix free = matter.getFree();
28 const AtomMatrix t = mode.cwiseProduct(free);
29 const double norm = t.norm();
30 if (!(norm > 0.0) || !(dr > 0.0)) {
31 throw std::invalid_argument("modeCurvature: zero mode or step");
32 }
33 const AtomMatrix unit = t / norm;
34 Matter probe(matter);
35 probe.setPositions(matter.getPositions() + dr * unit);
36 return -(probe.getForces() - matter.getForces()).cwiseProduct(unit).sum() /
37 dr;
38}
39
40// Application binary interface (ABI) minor 15 adds
41// rgsaddle_sella_saddle_seed_mode.
42#if defined(WITH_RGSADDLE) && RGSADDLE_ABI_MINOR >= 15
43namespace {
44
45// The session's coordinates are unwrapped, and Matter wraps what it is
46// given, so the last evaluation is keyed on the session's own vector.
47struct RefineSurface {
48 Matter *matter;
49 VectorXd mask;
50 VectorXd start;
51 VectorXd x;
52 double energy;
53 VectorXd gradient;
54};
55
56rgsaddle_status_t refineCallback(void *user, rgsaddle_surface_request_t *req) {
57 auto *s = static_cast<RefineSurface *>(user);
58 if (s == nullptr || req == nullptr || req->positions == nullptr ||
59 req->energies == nullptr || req->gradients == nullptr ||
60 req->n_images != 1) {
61 return RGSADDLE_SURFACE_FAILED;
62 }
63 const auto dof = s->x.size();
64 if (3 * req->n_atoms != dof) {
65 return RGSADDLE_SHAPE;
66 }
67 try {
68 const Eigen::Map<const VectorXd> x(req->positions, dof);
69 if (x != s->x) {
70 // A fixed coordinate of a free atom keeps its starting value.
71 s->matter->setPositionsFreeV((s->mask.array() > 0.5).select(x, s->start));
72 s->x = x;
73 s->energy = s->matter->getPotentialEnergy();
74 s->gradient = -s->matter->getForcesFreeV();
75 }
76 req->energies[0] = s->energy;
77 Eigen::Map<VectorXd>(req->gradients, dof) = s->gradient;
78 return RGSADDLE_OK;
79 } catch (...) {
80 return RGSADDLE_SURFACE_FAILED;
81 }
82}
83
84void check(int rc, const char *what) {
85 if (rc != RGSADDLE_OK) {
86 throw std::runtime_error(
87 std::string(what) + ": " +
88 rgsaddle_status_name(static_cast<rgsaddle_status_t>(rc)));
89 }
90}
91
92void checkPrfoKeys(const Parameters &params) {
93 const auto &opt = params.saddle_search_options().prfo_refine;
94 if (!(opt.force > 0.0) || opt.max_iterations < 1) {
95 throw std::invalid_argument("prfo_refine_force must be positive and "
96 "prfo_refine_max_iterations at least 1");
97 }
98}
99
100// The header can be newer than the library loaded at run time.
101void checkPrfoLibrary() {
102 rgsaddle_version_t stamp{};
103 check(rgsaddle_abi_stamp(&stamp), "rgsaddle_abi_stamp");
104 if (stamp.major != RGSADDLE_ABI_MAJOR || stamp.minor < 15) {
105 throw std::runtime_error(
106 "prfo_refine needs rgsaddle ABI 1.15 or newer at run time (loaded " +
107 std::to_string(stamp.major) + "." + std::to_string(stamp.minor) + ")");
108 }
109}
110
111// The rows getPositionsFree() returns, in its order.
112std::vector<long> freeAtoms(const Matter &matter) {
113 const AtomMatrix free = matter.getFree();
114 std::vector<long> rows;
115 for (long i = 0; i < free.rows(); ++i) {
116 if (free.row(i).sum() > 0.5) {
117 rows.push_back(i);
118 }
119 }
120 return rows;
121}
122
123} // namespace
124
125void requirePrfoRefine(const Parameters &params) {
127 checkPrfoKeys(params);
128 checkPrfoLibrary();
129 }
130}
131
133 double curvature, const Parameters &params) {
134 const auto &opt = params.saddle_search_options().prfo_refine;
135 checkPrfoKeys(params);
136 checkPrfoLibrary();
137 const std::vector<long> rows = freeAtoms(matter);
138 const auto nFree = static_cast<long>(rows.size());
139 const long callsBefore = matter.getForceCalls();
140 const Matter start(matter);
141 const double startForce = matter.maxForce();
142 const AtomMatrix free = matter.getFree();
143 AtomMatrix freeMode(nFree, 3);
144 AtomMatrix freeMask(nFree, 3);
145 VectorXd masses(nFree);
146 for (long j = 0; j < nFree; ++j) {
147 freeMask.row(j) = free.row(rows[j]);
148 freeMode.row(j) = mode.row(rows[j]).cwiseProduct(free.row(rows[j]));
149 masses[j] = matter.getMass(rows[j]);
150 }
151
152 RefineSurface surf{&matter,
153 VectorXd::Map(freeMask.data(), 3 * nFree),
154 matter.getPositionsFreeV(),
155 matter.getPositionsFreeV(),
156 matter.getPotentialEnergy(),
157 -matter.getForcesFreeV()};
158
159 rgsaddle_sella_saddle_config_t config{};
160 config.version = RGSADDLE_VERSION_INIT;
161 config.force_tol = opt.force;
162 config.force_gate = RGSADDLE_FORCE_MAX_ATOM;
163 config.order = 1;
164 // An empty chart: the default rigid quotient would project rotations
165 // out of a periodic cell or a slab with fixed atoms.
166 rgsaddle_constraints_config_t chartConfig{};
167 chartConfig.version = RGSADDLE_VERSION_INIT;
168 RgsaddleConstraints *chart = rgsaddle_constraints_create(&chartConfig, nFree);
169 if (chart == nullptr) {
170 throw std::runtime_error("rgsaddle_constraints_create failed");
171 }
172 RgsaddleSellaSaddle *session = rgsaddle_sella_saddle_create_on(
173 &config, nFree, surf.start.data(), masses.data(), chart);
174 rgsaddle_constraints_free(chart);
175 if (session == nullptr) {
176 throw std::runtime_error("rgsaddle_sella_saddle_create_on failed");
177 }
178
179 PrfoRefineResult result;
180 try {
181 // TS-BFGS (1), the transition-state Broyden-Fletcher-Goldfarb-Shanno
182 // update. Plain BFGS (0) can stall at a saddle.
183 check(rgsaddle_sella_saddle_set_hess_update(session, 1),
184 "rgsaddle_sella_saddle_set_hess_update");
185 check(rgsaddle_sella_saddle_seed_mode(session, freeMode.data(), curvature),
186 "rgsaddle_sella_saddle_seed_mode");
187 rgsaddle_report_t report{};
188 while (!result.converged && result.steps < opt.max_iterations) {
189 check(rgsaddle_sella_saddle_step(session, refineCallback, &surf, &report),
190 "rgsaddle_sella_saddle_step");
191 ++result.steps;
192 result.converged = report.status == RGSADDLE_STATUS_CONVERGED;
193 }
194 VectorXd x(3 * nFree);
195 check(rgsaddle_sella_saddle_position(session, x.data()),
196 "rgsaddle_sella_saddle_position");
197 if (x != surf.x) {
198 matter.setPositionsFreeV((surf.mask.array() > 0.5).select(x, surf.start));
199 }
200 } catch (...) {
201 rgsaddle_sella_saddle_free(session);
202 throw;
203 }
204 rgsaddle_sella_saddle_free(session);
205
206 result.maxForce = matter.maxForce();
207 result.forceCalls = matter.getForceCalls() - callsBefore;
208 if (result.maxForce > startForce) {
209 matter.assignKeepingBias(start);
210 result.restored = true;
211 result.converged = false;
212 result.maxForce = startForce;
213 }
214 result.energy = matter.getPotentialEnergy();
215 EONC_LOG_INFO("[P-RFO] {} steps, {} force calls, max atom force {:.3e} -> "
216 "{:.3e} eV/A{}",
217 result.steps, result.forceCalls, startForce, result.maxForce,
218 result.restored ? ", kept the starting point" : "");
219 return result;
220}
221
222#else
223
224namespace {
225
226[[noreturn]] void missingSession() {
227 throw std::runtime_error("[Saddle Search] prfo_refine needs eOn built with "
228 "-Dwith_rgsaddle=true against rgsaddle ABI 1.15 or "
229 "newer");
230}
231
232} // namespace
233
234void requirePrfoRefine(const Parameters &params) {
236 missingSession();
237 }
238}
239
241 const Parameters &) {
242 missingSession();
243}
244
245#endif
246
247} // namespace eonc
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
#define EONC_LOG_INFO(...)
Definition EonLogger.h:316
VectorXd getForcesFreeV() const
Definition Matter.cpp:512
AtomMatrix getFree() const
Definition Matter.cpp:799
void setPositionsFreeV(const VectorXd &pos)
Definition Matter.cpp:451
long getForceCalls() const
Definition Matter.cpp:657
VectorXd getPositionsFreeV() const
Definition Matter.cpp:415
double getMass(long int atom) const
Definition Matter.cpp:548
double getPotentialEnergy() const
Definition Matter.cpp:624
void assignKeepingBias(const Matter &other)
Copy another structure in and keep this Matter's own bias potential.
Definition Matter.cpp:470
double maxForce(void) const
Definition Matter.cpp:780
const saddle_search_options_t & saddle_search_options() const
const AtomMatrix & getPositions() const
Definition Matter.cpp:378
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
AtomMatrix getFree() const
Definition Matter.cpp:799
const AtomMatrix & getForces() const
Definition Matter.cpp:482
const saddle_search_options_t & saddle_search_options() const
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...
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.
struct eonc::saddle_search_options_t::prfo_refine_t prfo_refine