27 Eigen::Index ndof = 0;
29 bool captured =
false;
30 Eigen::VectorXd position;
31 Eigen::VectorXd gradient_value;
33 bool saw_last =
false;
34 Eigen::VectorXd last_position;
35 Eigen::VectorXd last_gradient;
36 double last_energy = 0.0;
39extern "C" rgsaddle_status_t ircSurface(
void*
user,
40 rgsaddle_surface_request_t* req)
43 if (
surface ==
nullptr ||
surface->gradient ==
nullptr || req ==
nullptr ||
44 req->positions ==
nullptr || req->energies ==
nullptr ||
45 req->gradients ==
nullptr || req->n_images != 1 ||
46 req->n_atoms * 3 !=
surface->ndof) {
47 return RGSADDLE_SHAPE;
50 Eigen::VectorXd position(
surface->ndof);
51 for (Eigen::Index i = 0; i <
surface->ndof; ++i)
52 position(i) = req->positions[i];
53 const auto evaluated = (*
surface->gradient)(position);
54 if (evaluated.second.size() !=
surface->ndof)
return RGSADDLE_SHAPE;
55 req->energies[0] = evaluated.first;
56 for (Eigen::Index i = 0; i <
surface->ndof; ++i)
57 req->gradients[i] = evaluated.second(i);
64 surface->gradient_value = evaluated.second;
65 surface->energy = evaluated.first;
68 surface->last_position = std::move(position);
69 surface->last_gradient = evaluated.second;
70 surface->last_energy = evaluated.first;
74 return RGSADDLE_SURFACE_FAILED;
79Eigen::VectorXd buildSqrtMasses(
const Eigen::VectorXd& masses)
81 const Eigen::Index n = masses.size();
82 Eigen::VectorXd s(3 * n);
83 for (Eigen::Index a = 0; a < n; ++a) {
84 const double sm = std::sqrt(masses(a));
85 for (
int k = 0; k < 3; ++k)
91Eigen::MatrixXd hessianToMassWeighted(
const Eigen::MatrixXd& h_plain,
92 const Eigen::VectorXd& sqrt_masses)
94 const Eigen::VectorXd inv_s = sqrt_masses.cwiseInverse();
95 return inv_s.asDiagonal() * h_plain * inv_s.asDiagonal();
101int32_t rgsaddleDirection(
bool along_positive_mode,
const Eigen::VectorXd& v_mw)
103 bool flipped =
false;
104 for (Eigen::Index i = 0; i < v_mw.size(); ++i) {
105 if (std::abs(v_mw(i)) > 1e-16) {
106 flipped = v_mw(i) < 0.0;
110 const bool library_reverse = (along_positive_mode == flipped);
111 return library_reverse ? RGSADDLE_IRC_REVERSE : RGSADDLE_IRC_FORWARD;
117 rgsaddle_irc_config_t cfg{};
118 cfg.version.major = client.
abiMajor();
119 cfg.version.minor = client.
abiMinor();
122 cfg.force_gate = RGSADDLE_FORCE_MW_L2;
124 cfg.kind = RGSADDLE_IRC_MOROKUMA;
125 cfg.direction = direction;
127 ? RGSADDLE_IRC_ADAPTIVE
138uint64_t splitmix64(uint64_t& state)
140 state += 0x9E3779B97F4A7C15ULL;
142 z = (
z ^ (
z >> 30)) * 0xBF58476D1CE4E5B9ULL;
143 z = (
z ^ (
z >> 27)) * 0x94D049BB133111EBULL;
144 return z ^ (
z >> 31);
149Eigen::VectorXd gaussianSketch(uint64_t sketch_seed, Eigen::Index ndof)
151 uint64_t state = sketch_seed != 0 ? sketch_seed : 1ULL;
152 const double pi = std::acos(-1.0);
153 Eigen::VectorXd draw(ndof);
154 for (Eigen::Index i = 0; i < ndof; ++i) {
155 const uint64_t z1 = splitmix64(state);
157 static_cast<double>(z1 & 0xFFFFFFFFULL) / 4294967296.0 + 1e-12;
158 const uint64_t z2 = splitmix64(state);
159 const double u2 =
static_cast<double>(z2 >> 32) / 4294967296.0;
160 draw(i) = std::sqrt(-2.0 * std::log(u1)) * std::cos(2.0 * pi * u2);
165void projectOut(Eigen::VectorXd& vector,
const Eigen::MatrixXd& directions)
167 if (directions.cols() == 0 || vector.size() != directions.rows())
return;
168 const Eigen::JacobiSVD<Eigen::MatrixXd> svd(directions,
169 Eigen::ComputeThinU);
170 const auto& values = svd.singularValues();
172 values.size() > 0 ? values(0) : std::numeric_limits<double>::min();
174 1e-10 * std::max(scale, std::numeric_limits<double>::min());
175 Eigen::Index rank = 0;
176 for (Eigen::Index k = 0; k < values.size(); ++k)
177 if (values(k) > cut) ++rank;
178 if (rank == 0)
return;
179 const Eigen::MatrixXd span = svd.matrixU().leftCols(rank);
180 vector -= span * (span.transpose() * vector);
187Eigen::VectorXd surfaceLaunchSeed(uint64_t sketch_seed,
188 const Eigen::VectorXd& positions,
189 const Eigen::VectorXd& masses,
190 const Eigen::VectorXd& sqrt_masses)
192 Eigen::VectorXd weighted = gaussianSketch(sketch_seed, sqrt_masses.size())
193 .cwiseProduct(sqrt_masses);
194 Eigen::MatrixXd rigid =
196 if (masses.size() < 3) rigid.conservativeResize(rigid.rows(), 3);
197 projectOut(weighted, rigid);
198 const double floor = 64.0 * std::numeric_limits<double>::epsilon() *
199 std::max(1.0,
static_cast<double>(weighted.size()));
200 if (!(weighted.norm() > floor)) {
201 const Eigen::MatrixXd vibrational =
203 if (vibrational.cols() > 0) weighted = vibrational.col(0);
205 return weighted.cwiseQuotient(sqrt_masses);
210double massWeightedCurvature(
const Eigen::VectorXd& saddle,
211 const Eigen::VectorXd& kick,
212 const Eigen::VectorXd& sqrt_masses,
double eps,
215 const double scale = kick.norm();
216 if (!(scale > 0.0) || !kick.allFinite())
return 0.0;
217 const Eigen::VectorXd dir = kick / scale;
218 const auto plus = gradient(saddle + eps * dir);
219 const auto minus = gradient(saddle - eps * dir);
220 if (plus.second.size() != dir.size() || minus.second.size() != dir.size()) {
221 throw std::invalid_argument(
222 "IRCDriver::run: gradient length differs from the positions");
224 const double directional =
225 dir.dot(plus.second - minus.second) / (2.0 * eps);
226 const double mass_norm = dir.cwiseProduct(sqrt_masses).squaredNorm();
227 if (!(mass_norm > 0.0))
return 0.0;
228 return directional / mass_norm;
233 if (!client.
load()) {
234 throw std::runtime_error(
235 "IRCDriver: rgsaddle is required and is not available (" +
237 "). IRC does not fall back to a local stepper.");
240 throw std::runtime_error(
241 "IRCDriver: the linked librgsaddle has no IRC entry points "
242 "(rgsaddle_irc_create, rgsaddle_irc_step, "
243 "rgsaddle_irc_set_direction). IRC does not fall back to a "
247 throw std::runtime_error(
248 "IRCDriver: the linked librgsaddle has no "
249 "rgsaddle_irc_set_lengths. IRC needs the carried rgsaddle "
250 "controls (adaptive Morokuma length, a kick length, and the "
251 "mass-weighted force gate). IRC does not fall back to a "
256class IrcSessionGuard {
260 : client_(&client), session_(session)
265 if (client_ !=
nullptr) client_->ircFree(session_);
267 IrcSessionGuard(
const IrcSessionGuard&) =
delete;
268 IrcSessionGuard& operator=(
const IrcSessionGuard&) =
delete;
283 : gradient_fn_(
std::move(gradient_fn)),
284 masses_(
std::move(masses)),
288 throw std::invalid_argument(
289 "IRCDriver: gradient functor must not be null");
291 if (masses_.size() < 1) {
292 throw std::invalid_argument(
293 "IRCDriver: masses vector must have at least one atom");
295 for (Eigen::Index a = 0; a < masses_.size(); ++a) {
296 if (!(masses_(a) > 0.0) || !std::isfinite(masses_(a))) {
297 throw std::invalid_argument(
298 "IRCDriver: each mass must be finite and positive");
301 sqrt_masses_ = buildSqrtMasses(masses_);
305 const Eigen::MatrixXd& saddle_hessian)
307 const Eigen::Index ndof = 3 * masses_.size();
308 if (saddle_positions.size() != ndof) {
309 throw std::invalid_argument(
310 "IRCDriver::run: positions size mismatch with masses");
312 if (saddle_hessian.rows() != ndof || saddle_hessian.cols() != ndof) {
313 throw std::invalid_argument(
314 "IRCDriver::run: hessian shape mismatch with positions");
318 throw std::invalid_argument(
"IRCDriver::run: unknown IRC method");
322 requireRgsaddle(client);
329 Eigen::VectorXd mode = Eigen::VectorXd::Zero(ndof);
330 bool compensate_sign =
false;
331 if (options_.hessian_sketch_rank > 0) {
332 if (options_.mode_to_follow != 1) {
333 throw std::runtime_error(
334 "IRCDriver::run: rgsaddle_irc_create_from_surface returns "
335 "only the lowest mode");
338 throw std::runtime_error(
339 "IRCDriver::run: the linked librgsaddle has no "
340 "rgsaddle_irc_create_from_surface");
343 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(
344 hessianToMassWeighted(saddle_hessian, sqrt_masses_));
345 if (es.info() != Eigen::Success) {
346 throw std::runtime_error(
347 "IRCDriver::run: eigendecomposition of saddle Hessian failed");
349 const int k = std::max(1, options_.mode_to_follow) - 1;
350 if (k >= es.eigenvalues().size()) {
351 throw std::invalid_argument(
352 "IRCDriver::run: mode_to_follow exceeds available "
355 if (es.eigenvalues()(k) >= 0.0) {
356 throw std::runtime_error(
357 "IRCDriver::run: requested mode is not imaginary "
358 "(eigenvalue >= 0); not a saddle along this coordinate");
360 const Eigen::VectorXd v_mw = es.eigenvectors().col(k);
361 mode = v_mw.cwiseQuotient(sqrt_masses_);
362 compensate_sign =
true;
367 surface.gradient = &gradient_fn_;
371 auto direction_code = [&](
bool forward) -> int32_t {
372 if (!compensate_sign)
373 return forward ? RGSADDLE_IRC_FORWARD : RGSADDLE_IRC_REVERSE;
374 return rgsaddleDirection(forward, mode.cwiseProduct(sqrt_masses_));
377 const bool first_is_forward = want_forward || !want_reverse;
378 const int32_t first_direction = direction_code(first_is_forward);
379 const rgsaddle_irc_config_t cfg =
380 ircConfig(client, options_, first_direction);
382 if (options_.hessian_sketch_rank > 0) {
383 const Eigen::VectorXd seed = surfaceLaunchSeed(
384 options_.sketch_seed, saddle_positions, masses_, sqrt_masses_);
386 &cfg,
static_cast<int64_t
>(masses_.size()), saddle_positions.data(),
387 masses_.data(), seed.data(), ircSurface, &
surface);
389 raw = client.
ircCreate(&cfg,
static_cast<int64_t
>(masses_.size()),
390 saddle_positions.data(), masses_.data(),
393 if (raw ==
nullptr) {
394 throw std::runtime_error(
395 options_.hessian_sketch_rank > 0
396 ?
"IRCDriver::run: rgsaddle_irc_create_from_surface returned "
398 :
"IRCDriver::run: rgsaddle_irc_create returned null");
400 IrcSessionGuard session(client, raw);
402 session.get(), options_.initial_displacement, options_.max_step,
405 if (lengths != RGSADDLE_OK) {
406 throw std::runtime_error(
407 "IRCDriver::run: rgsaddle_irc_set_lengths failed with status " +
408 std::to_string(lengths));
410 if (options_.hessian_sketch_rank > 0) {
416 rgsaddle_report_t launch{};
419 if (stepped != RGSADDLE_OK) {
420 throw std::runtime_error(
421 "IRCDriver::run: rgsaddle_irc_step failed with status " +
422 std::to_string(stepped));
425 throw std::runtime_error(
426 "IRCDriver::run: rgsaddle_irc_step did not evaluate "
429 const Eigen::VectorXd kick =
surface.position - saddle_positions;
432 if (restored != RGSADDLE_OK) {
433 throw std::runtime_error(
434 "IRCDriver::run: rgsaddle_irc_set_direction failed "
436 std::to_string(restored));
439 options_.hv_eps > 0.0 && std::isfinite(options_.hv_eps)
442 const double curvature = massWeightedCurvature(
443 saddle_positions, kick, sqrt_masses_, eps, gradient_fn_);
444 if (curvature >= 0.0) {
445 throw std::runtime_error(
446 "IRCDriver::run: requested mode is not imaginary "
447 "(eigenvalue >= 0); not a saddle along this coordinate");
454 static_cast<std::size_t
>(std::max(options_.max_steps, 0)) + 1);
455 const int evals_before = evals;
457 saddle_step.
positions = saddle_positions;
458 if (options_.record_energy) {
459 const auto evaluated = gradient_fn_(saddle_positions);
461 if (evaluated.second.size() != ndof) {
462 throw std::invalid_argument(
463 "IRCDriver::run: gradient length differs from the "
466 saddle_step.
energy = evaluated.first;
467 saddle_step.
gradient = evaluated.second;
469 evaluated.second.cwiseQuotient(sqrt_masses_).norm();
471 branch.
path.push_back(std::move(saddle_step));
473 Eigen::VectorXd previous = saddle_positions;
475 for (
int step = 0; step < options_.max_steps; ++step) {
479 rgsaddle_report_t report{};
482 if (rc != RGSADDLE_OK) {
483 throw std::runtime_error(
484 "IRCDriver::run: rgsaddle_irc_step failed with status " +
488 throw std::runtime_error(
489 "IRCDriver::run: rgsaddle_irc_step did not evaluate "
497 surface.gradient_value.cwiseQuotient(sqrt_masses_).norm();
499 (
surface.position - previous).cwiseProduct(sqrt_masses_).norm();
502 const bool small_gradient = sample.
g_norm <= options_.conv_tol;
503 branch.
path.push_back(std::move(sample));
509 const bool library_done =
510 report.status == RGSADDLE_STATUS_CONVERGED;
511 if (small_gradient && library_done) {
518 if (report.status == RGSADDLE_STATUS_CONVERGED) {
519 Eigen::VectorXd accepted(ndof);
520 if (client.
ircPosition(session.get(), accepted.data()) !=
522 throw std::runtime_error(
523 "IRCDriver::run: rgsaddle_irc_position failed");
525 if ((accepted - branch.
path.back().positions).norm() > 1e-12) {
527 const bool last_is_accepted =
529 (
surface.last_position - accepted).norm() <= 1e-12;
530 if (last_is_accepted) {
535 const auto evaluated = gradient_fn_(accepted);
537 if (evaluated.second.size() != ndof) {
538 throw std::invalid_argument(
539 "IRCDriver::run: gradient length differs "
540 "from the positions");
543 arrived.
energy = evaluated.first;
544 arrived.
gradient = evaluated.second;
547 arrived.
gradient.cwiseQuotient(sqrt_masses_).norm();
548 if (arrived.
g_norm <= options_.conv_tol) {
550 .cwiseProduct(sqrt_masses_)
554 branch.
path.push_back(std::move(arrived));
563 branch.
path.empty() ? 0.0 : branch.
path.back().energy;
568 if (want_forward)
out.forward = trace();
573 if (rc != RGSADDLE_OK) {
574 throw std::runtime_error(
575 "IRCDriver::run: rgsaddle_irc_set_direction failed "
580 out.reverse = trace();