Loading...
Searching...
No Matches
EndpointConnectivity.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#ifndef GPRIDGEIZATION_ENDPOINT_CONNECTIVITY_H_
6#define GPRIDGEIZATION_ENDPOINT_CONNECTIVITY_H_
7
8#include <Eigen/Dense>
9#include <algorithm>
10#include <chrono>
11#include <cmath>
12#include <cstdint>
13#include <cstring>
14#include <fstream>
15#include <functional>
16#include <iomanip>
17#include <limits>
18#include <sstream>
19#include <string>
20#include <unordered_map>
21#include <utility>
22#include <vector>
23
24#ifdef GPR_HAVE_OPENBLAS
25extern "C" void openblas_set_num_threads(int);
26#endif
27
28#include <rgmin.h>
29
33#include "../ml/RgminAbi.h"
35#include "StencilIndex.h"
36
37namespace gpr::optim {
38
42 Eigen::VectorXd position;
43 double energy = 0.0;
44 Eigen::VectorXd gradient;
45};
46
57 bool reported = false;
63 bool connected = false;
67 bool graph_connected = false;
69 bool graph_applicable = true;
73 bool ball_applicable = true;
76 bool ball_matched = false;
79 bool ambiguous = false;
82 bool unresolved = false;
84 bool skipped = false;
85 double separation = std::numeric_limits<double>::quiet_NaN();
86 double reactant_ball = std::numeric_limits<double>::quiet_NaN();
87 double product_ball = std::numeric_limits<double>::quiet_NaN();
88 double lambda_reactant = std::numeric_limits<double>::quiet_NaN();
89 double lambda_product = std::numeric_limits<double>::quiet_NaN();
90 double lowest_reactant = std::numeric_limits<double>::quiet_NaN();
91 double lowest_product = std::numeric_limits<double>::quiet_NaN();
92 double resolution_reactant = std::numeric_limits<double>::quiet_NaN();
93 double resolution_product = std::numeric_limits<double>::quiet_NaN();
97 double saddle_curvature = std::numeric_limits<double>::quiet_NaN();
104 double directional_curvature = std::numeric_limits<double>::quiet_NaN();
109 bool measured_index = false;
112 bool index_first_order = false;
113 bool index_higher_order = false;
114 double index_resolution = std::numeric_limits<double>::quiet_NaN();
115 int index_calls = 0;
116 double forward_reactant = std::numeric_limits<double>::quiet_NaN();
117 double forward_product = std::numeric_limits<double>::quiet_NaN();
118 double reverse_reactant = std::numeric_limits<double>::quiet_NaN();
119 double reverse_product = std::numeric_limits<double>::quiet_NaN();
121 std::numeric_limits<double>::quiet_NaN();
122 double deposited_forward_product = std::numeric_limits<double>::quiet_NaN();
124 std::numeric_limits<double>::quiet_NaN();
125 double deposited_reverse_product = std::numeric_limits<double>::quiet_NaN();
126 double forward_force = std::numeric_limits<double>::quiet_NaN();
127 double reverse_force = std::numeric_limits<double>::quiet_NaN();
135 int calls = 0;
151 double oracle_seconds = 0;
152 double match_seconds = 0;
153 double reactant_energy = std::numeric_limits<double>::quiet_NaN();
154 double product_energy = std::numeric_limits<double>::quiet_NaN();
155 double forward_energy = std::numeric_limits<double>::quiet_NaN();
156 double reverse_energy = std::numeric_limits<double>::quiet_NaN();
159 Eigen::VectorXd saddle_positions;
160 Eigen::VectorXd mode;
161 double kick = std::numeric_limits<double>::quiet_NaN();
162 Eigen::VectorXd forward_position;
163 Eigen::VectorXd reverse_position;
164 double walk_separation = std::numeric_limits<double>::quiet_NaN();
168 double comparison_tolerance = std::numeric_limits<double>::quiet_NaN();
170 std::string reactant_bonds;
171 std::string product_bonds;
172 std::string forward_bonds;
173 std::string reverse_bonds;
174};
175
179 Eigen::VectorXd deposited_reactant;
180 Eigen::VectorXd deposited_product;
181 std::vector<int> atomic_numbers;
182 double tolerance = std::numeric_limits<double>::quiet_NaN();
183 Eigen::VectorXd relaxed_reactant;
184 Eigen::VectorXd relaxed_product;
185 double lambda_reactant = std::numeric_limits<double>::quiet_NaN();
186 double lambda_product = std::numeric_limits<double>::quiet_NaN();
187 bool ready = false;
188};
189
190inline const char* endpointConnectivityLabel(
191 const EndpointConnectivityReport& report) noexcept
192{
193 if (report.skipped) return "skipped";
194 if (report.unresolved) return "unresolved";
195 if (!report.reported) return "unavailable";
196 if (report.ambiguous) return "ambiguous";
197 if (!report.graph_applicable && !report.ball_applicable)
198 return "not applicable";
199 return report.connected ? "connected" : "not connected";
200}
201
205inline double atomicMassAmu(int atomic_number) noexcept
206{
207 switch (atomic_number) {
208 case 1:
209 return 1.008;
210 case 6:
211 return 12.011;
212 case 7:
213 return 14.007;
214 case 8:
215 return 15.999;
216 case 9:
217 return 18.998;
218 case 12:
219 return 24.305;
220 case 14:
221 return 28.085;
222 case 15:
223 return 30.974;
224 case 16:
225 return 32.06;
226 case 17:
227 return 35.45;
228 case 35:
229 return 79.904;
230 default:
231 return 1.0;
232 }
233}
234
237inline double corderoRadius(int atomic_number) noexcept
238{
239 switch (atomic_number) {
240 case 1:
241 return 0.31;
242 case 6:
243 return 0.76;
244 case 7:
245 return 0.71;
246 case 8:
247 return 0.66;
248 case 9:
249 return 0.57;
250 case 14:
251 return 1.11;
252 case 15:
253 return 1.07;
254 case 16:
255 return 1.05;
256 case 17:
257 return 1.02;
258 case 35:
259 return 1.20;
260 default:
261 return 0.0;
262 }
263}
264
267inline std::string bondGraph(const Eigen::VectorXd& positions,
268 const std::vector<int>& atomic_numbers)
269{
270 std::vector<std::string> edges;
271 const int n = static_cast<int>(atomic_numbers.size());
272 if (positions.size() != 3 * n) return {};
273 for (int i = 0; i < n; ++i) {
274 const double ri =
275 corderoRadius(atomic_numbers[static_cast<std::size_t>(i)]);
276 if (!(ri > 0.0)) continue;
277 for (int j = i + 1; j < n; ++j) {
278 const double rj =
279 corderoRadius(atomic_numbers[static_cast<std::size_t>(j)]);
280 if (!(rj > 0.0)) continue;
281 const double cutoff = 1.2 * (ri + rj);
282 const double dx = positions(3 * i) - positions(3 * j);
283 const double dy = positions(3 * i + 1) - positions(3 * j + 1);
284 const double dz = positions(3 * i + 2) - positions(3 * j + 2);
285 if (dx * dx + dy * dy + dz * dz <= cutoff * cutoff)
286 edges.push_back(std::to_string(i) + "-" + std::to_string(j));
287 }
288 }
289 std::sort(edges.begin(), edges.end());
290 std::ostringstream out;
291 for (std::size_t i = 0; i < edges.size(); ++i) {
292 if (i != 0) out << ",";
293 out << edges[i];
294 }
295 return out.str();
296}
297
298inline Eigen::VectorXd massesFromAtomicNumbers(const std::vector<int>& numbers)
299{
300 Eigen::VectorXd masses(static_cast<Eigen::Index>(numbers.size()));
301 for (std::size_t i = 0; i < numbers.size(); ++i)
302 masses(static_cast<Eigen::Index>(i)) = atomicMassAmu(numbers[i]);
303 return masses;
304}
305
310inline double labelledRmsd(const Eigen::VectorXd& reference,
311 const Eigen::VectorXd& mobile,
312 const std::vector<int>& atomic_numbers)
313{
314 const Eigen::Index n = reference.size();
315 const int n_atoms = static_cast<int>(atomic_numbers.size());
316 if (n_atoms * 3 != static_cast<int>(n))
317 return std::numeric_limits<double>::quiet_NaN();
318 return aux::rigidAlignedRmsd(reference, mobile);
319}
320
328inline double permutationAwareRmsd(const Eigen::VectorXd& reference,
329 const Eigen::VectorXd& mobile_in,
330 const std::vector<int>& atomic_numbers)
331{
332 const Eigen::Index n = reference.size();
333 const int n_atoms = static_cast<int>(atomic_numbers.size());
334 if (n == 0 || n != mobile_in.size() || n % 3 != 0 ||
335 n_atoms * 3 != static_cast<int>(n) || !reference.allFinite() ||
336 !mobile_in.allFinite())
337 return std::numeric_limits<double>::quiet_NaN();
338 std::vector<int> elements = atomic_numbers;
339 std::sort(elements.begin(), elements.end());
340 elements.erase(std::unique(elements.begin(), elements.end()),
341 elements.end());
342 const auto signature = [&](const Eigen::VectorXd& geometry, int atom) {
343 std::vector<double> out;
344 const Eigen::Vector3d here = geometry.segment<3>(3 * atom);
345 for (const int element: elements) {
346 std::vector<double> distances;
347 for (int other = 0; other < n_atoms; ++other) {
348 if (other == atom) continue;
349 if (atomic_numbers[static_cast<std::size_t>(other)] != element)
350 continue;
351 distances.push_back(
352 (geometry.segment<3>(3 * other) - here).norm());
353 }
354 std::sort(distances.begin(), distances.end());
355 out.insert(out.end(), distances.begin(), distances.end());
356 }
357 return out;
358 };
359 const auto assign = [&](const Eigen::VectorXd& from, auto cost_of) {
360 double diameter2 = 0.0;
361 for (int i = 0; i < n_atoms; ++i)
362 for (int j = 0; j < n_atoms; ++j)
363 diameter2 = std::max(diameter2, (reference.segment<3>(3 * i) -
364 from.segment<3>(3 * j))
365 .squaredNorm());
366 const double blocked =
367 diameter2 * static_cast<double>(n_atoms) + diameter2;
368 Eigen::MatrixXd cost(n_atoms, n_atoms);
369 for (int i = 0; i < n_atoms; ++i) {
370 for (int j = 0; j < n_atoms; ++j) {
371 if (atomic_numbers[static_cast<std::size_t>(i)] !=
372 atomic_numbers[static_cast<std::size_t>(j)]) {
373 cost(i, j) = blocked;
374 continue;
375 }
376 cost(i, j) = cost_of(i, j);
377 }
378 }
380 };
381 const auto permute = [&](const Eigen::VectorXd& source,
382 const std::vector<int>& assignment) {
383 Eigen::VectorXd out(n);
384 for (int i = 0; i < n_atoms; ++i)
385 out.segment<3>(3 * i) =
386 source.segment<3>(3 * assignment[static_cast<std::size_t>(i)]);
387 return out;
388 };
389 std::vector<std::vector<double>> reference_signature(n_atoms);
390 std::vector<std::vector<double>> mobile_signature(n_atoms);
391 for (int atom = 0; atom < n_atoms; ++atom) {
392 reference_signature[static_cast<std::size_t>(atom)] =
393 signature(reference, atom);
394 mobile_signature[static_cast<std::size_t>(atom)] =
395 signature(mobile_in, atom);
396 }
397 const auto by_signature = assign(mobile_in, [&](int i, int j) {
398 const auto& left = reference_signature[static_cast<std::size_t>(i)];
399 const auto& right = mobile_signature[static_cast<std::size_t>(j)];
400 double sum = 0.0;
401 for (std::size_t k = 0; k < left.size() && k < right.size(); ++k) {
402 const double gap = left[k] - right[k];
403 sum += gap * gap;
404 }
405 return sum;
406 });
407 if (by_signature.size() != static_cast<std::size_t>(n_atoms))
408 return std::numeric_limits<double>::quiet_NaN();
409 const auto iterated = [&](Eigen::VectorXd mobile) {
410 double best = std::numeric_limits<double>::infinity();
411 for (int round = 0; round < n_atoms; ++round) {
412 const Eigen::VectorXd aligned =
413 aux::kabschAlignProductToReactant(reference, mobile);
414 if (aligned.size() != n || !aligned.allFinite())
415 return std::numeric_limits<double>::quiet_NaN();
416 const double rmsd = (aligned - reference).norm() /
417 std::sqrt(static_cast<double>(n_atoms));
418 if (!(rmsd < best)) break;
419 best = rmsd;
420 const auto assignment = assign(aligned, [&](int i, int j) {
421 return (reference.segment<3>(3 * i) - aligned.segment<3>(3 * j))
422 .squaredNorm();
423 });
424 if (assignment.size() != static_cast<std::size_t>(n_atoms))
425 return std::numeric_limits<double>::quiet_NaN();
426 bool identity = true;
427 for (int i = 0; i < n_atoms; ++i)
428 identity =
429 identity && assignment[static_cast<std::size_t>(i)] == i;
430 if (identity) break;
431 mobile = permute(mobile, assignment);
432 }
433 return best;
434 };
435 const double from_geometry = iterated(mobile_in);
436 const double from_signature = iterated(permute(mobile_in, by_signature));
437 if (!std::isfinite(from_geometry)) return from_signature;
438 if (!std::isfinite(from_signature)) return from_geometry;
439 return std::min(from_geometry, from_signature);
440}
441
442inline void appendIrcProfile(std::ostream& line,
443 const EndpointConnectivityReport& report)
444{
445 line << "\nIRC profile: deposit=" << report.calls_deposit
446 << " endpoint_check=" << report.calls_endpoint_check
447 << " saddle=" << report.calls_saddle
448 << " descent=" << report.calls_descent
449 << " polish=" << report.calls_polish
450 << " end_check=" << report.calls_end_check
451 << " energy=" << report.calls_energy
452 << " oracle_s=" << report.oracle_seconds
453 << " match_s=" << report.match_seconds;
454}
455
456inline std::string formatEndpointConnectivity(
457 const EndpointConnectivityReport& report)
458{
459 std::ostringstream line;
460 line << std::setprecision(8);
461 line << "Endpoint connectivity: " << endpointConnectivityLabel(report);
462 if (report.skipped) {
463 line << "\n ball=skipped graph=skipped";
464 return line.str();
465 }
466 if (!report.reported) {
467 appendIrcProfile(line, report);
468 return line.str();
469 }
470 line << "\n separation_A=" << report.separation
471 << " reactant_ball_A=" << report.reactant_ball
472 << " product_ball_A=" << report.product_ball
473 << " lambda_reactant=" << report.lambda_reactant
474 << " lambda_product=" << report.lambda_product
475 << " lowest_reactant=" << report.lowest_reactant
476 << " lowest_product=" << report.lowest_product
477 << " resolution_reactant=" << report.resolution_reactant
478 << " resolution_product=" << report.resolution_product;
479 if (report.saddle_index_measured) {
480 line << " saddle_curvature=" << report.saddle_curvature;
481 } else {
482 line
483 << " directional_curvature=" << report.directional_curvature
484 << "\nSaddle index: descent direction verified; index not measured";
485 }
486 line << "\n forward_reactant_A=" << report.forward_reactant
487 << " forward_product_A=" << report.forward_product
488 << " reverse_reactant_A=" << report.reverse_reactant
489 << " reverse_product_A=" << report.reverse_product
490 << "\n deposited_forward_reactant_A="
492 << " deposited_forward_product_A=" << report.deposited_forward_product
493 << " deposited_reverse_reactant_A="
495 << " deposited_reverse_product_A=" << report.deposited_reverse_product
496 << "\n forward_force=" << report.forward_force
497 << " reverse_force=" << report.reverse_force
498 << " forward_calls=" << report.forward_calls
499 << " reverse_calls=" << report.reverse_calls
500 << " forward_steps=" << report.forward_steps
501 << " reverse_steps=" << report.reverse_steps
502 << " walk_separation_A=" << report.walk_separation
503 << " comparison_force=" << report.comparison_tolerance
504 << " calls=" << report.calls
505 << " reactant_energy=" << report.reactant_energy
506 << " product_energy=" << report.product_energy
507 << " forward_energy=" << report.forward_energy
508 << " reverse_energy=" << report.reverse_energy << " ball="
509 << (report.unresolved ? "unresolved"
510 : (!report.ball_applicable
511 ? "na"
512 : (report.ball_matched ? "yes" : "no")))
513 << " graph="
514 << (report.unresolved
515 ? "unresolved"
516 : (!report.graph_applicable
517 ? "na"
518 : (report.graph_connected ? "yes" : "no")))
519 << "\n reactant_bonds=" << report.reactant_bonds
520 << "\n product_bonds=" << report.product_bonds
521 << "\n forward_bonds=" << report.forward_bonds
522 << "\n reverse_bonds=" << report.reverse_bonds;
523 appendIrcProfile(line, report);
524 return line.str();
525}
526
531inline Eigen::MatrixXd ircStencilDirections(
532 const Eigen::VectorXd& center, const Eigen::VectorXd& masses,
533 const Eigen::MatrixXd* held_directions,
535{
536 if (held_directions != nullptr &&
537 held_directions->rows() == center.size() &&
538 held_directions->cols() > 0 &&
539 held_directions->cols() <= center.size() &&
540 held_directions->allFinite())
541 return *held_directions;
542 return stencilDirectionsForMode(mode, center, masses, /*periodic=*/false,
543 /*anchored=*/false);
544}
545
553 Eigen::MatrixXd& columns, double& resolution, const Eigen::VectorXd& center,
554 double step, const Eigen::MatrixXd& directions,
555 const std::function<bool(const Eigen::VectorXd&, Eigen::VectorXd&)>&
556 gradient_at,
557 Eigen::MatrixXd* raw_columns = nullptr)
558{
559 const Eigen::Index dof = center.size();
560 if (!(step > 0.0) || dof == 0 || !center.allFinite() ||
561 directions.rows() != dof || directions.cols() == 0)
562 return false;
563 const Eigen::MatrixXd points =
564 centralDifferencePoints(center, step, directions);
565 Eigen::MatrixXd actions(dof, directions.cols());
566 for (Eigen::Index k = 0; k < directions.cols(); ++k) {
567 Eigen::VectorXd g_plus(dof);
568 Eigen::VectorXd g_minus(dof);
569 if (!gradient_at(points.col(2 * k), g_plus) ||
570 !gradient_at(points.col(2 * k + 1), g_minus))
571 return false;
572 actions.col(k) = (g_plus - g_minus) / (2.0 * step);
573 }
574 Eigen::VectorXd center_gradient;
575 if (directions.cols() < dof) {
576 center_gradient.resize(dof);
577 if (!gradient_at(center, center_gradient)) return false;
578 }
579 const Eigen::MatrixXd raw = hessianColumnsFromDirections(
580 center, center_gradient, directions, actions);
581 if (raw.rows() != dof || raw.cols() != dof) return false;
582 columns.resize(dof, dof);
583 const Eigen::MatrixXd full = 0.5 * (raw - raw.transpose());
584 const Eigen::MatrixXd antisym =
585 directions.cols() < dof
586 ? Eigen::MatrixXd(directions.transpose() * full * directions)
587 : full;
588 resolution =
589 antisym.size() == 0
590 ? 0.0
591 : Eigen::JacobiSVD<Eigen::MatrixXd>(antisym).singularValues()(0);
592 if (raw_columns != nullptr) *raw_columns = raw;
593 columns = 0.5 * (raw + raw.transpose());
594 return columns.allFinite() && std::isfinite(resolution);
595}
596
597inline Eigen::MatrixXd cartesianRigidMotions(const Eigen::VectorXd& positions)
598{
599 const Eigen::Index n = positions.size() / 3;
600 Eigen::Vector3d centre = Eigen::Vector3d::Zero();
601 for (Eigen::Index i = 0; i < n; ++i)
602 centre += positions.segment<3>(3 * i);
603 centre /= static_cast<double>(n);
604 Eigen::MatrixXd basis = Eigen::MatrixXd::Zero(positions.size(), 6);
605 for (Eigen::Index i = 0; i < n; ++i) {
606 const Eigen::Vector3d r = positions.segment<3>(3 * i) - centre;
607 for (int k = 0; k < 3; ++k) {
608 basis(3 * i + k, k) = 1.0;
609 Eigen::Vector3d axis = Eigen::Vector3d::Zero();
610 axis(k) = 1.0;
611 basis.block<3, 1>(3 * i, 3 + k) = r.cross(axis);
612 }
613 }
614 return basis;
615}
616
619inline Eigen::VectorXd projectOutRigidMotions(const Eigen::VectorXd& positions,
620 Eigen::VectorXd displacement)
621{
622 if (displacement.size() != positions.size() || positions.size() < 3 ||
623 !displacement.allFinite())
624 return displacement;
625 const Eigen::MatrixXd rigid = cartesianRigidMotions(positions);
626 const Eigen::JacobiSVD<Eigen::MatrixXd> svd(
627 rigid, Eigen::ComputeThinU | Eigen::ComputeThinV);
628 const Eigen::Index rank = svd.rank();
629 if (rank <= 0) return displacement;
630 const Eigen::MatrixXd span = svd.matrixU().leftCols(rank);
631 displacement -= span * (span.transpose() * displacement);
632 return displacement;
633}
634
638 bool ok = false;
639 double curvature = 0.0;
640 Eigen::VectorXd cartesian;
642 Eigen::VectorXd cartesian_lowest;
643 double lambda_min = std::numeric_limits<double>::quiet_NaN();
644 double lambda_max = std::numeric_limits<double>::quiet_NaN();
645 double lowest = std::numeric_limits<double>::quiet_NaN();
646 double resolution = 0.0;
650 Eigen::MatrixXd stiff;
651};
652
653inline EndpointSpectrum spectrumOfColumns(const Eigen::MatrixXd& hessian,
654 double resolution,
655 const Eigen::VectorXd& positions,
656 const Eigen::VectorXd& masses,
657 double stiff_floor)
658{
660 out.resolution = resolution;
661 if (hessian.rows() != positions.size() ||
662 hessian.cols() != positions.size() || !hessian.allFinite() ||
663 !std::isfinite(resolution))
664 return out;
665 const Eigen::Index dof = positions.size();
666 Eigen::VectorXd inv_root(dof);
667 for (Eigen::Index k = 0; k < dof; ++k)
668 inv_root(k) = 1.0 / std::sqrt(masses(k / 3));
669 const Eigen::MatrixXd weighted =
670 hessian.cwiseProduct(inv_root * inv_root.transpose());
671 const Eigen::MatrixXd vibrational =
672 vibrationalComplement(positions, masses);
673 if (vibrational.cols() == 0) return out;
674 const Eigen::MatrixXd reduced =
675 vibrational.transpose() * weighted * vibrational;
676 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(reduced);
677 if (solver.info() != Eigen::Success) return out;
678 const Eigen::VectorXd mass_weighted =
679 vibrational * solver.eigenvectors().col(0);
680 out.cartesian.resize(dof);
681 for (Eigen::Index k = 0; k < dof; ++k)
682 out.cartesian(k) = mass_weighted(k) * inv_root(k);
683 out.curvature = solver.eigenvalues()(0);
684 if (!(out.cartesian.norm() > 0.0) || !out.cartesian.allFinite() ||
685 !std::isfinite(out.curvature))
686 return out;
687
688 const Eigen::MatrixXd rigid = cartesianRigidMotions(positions);
689 const Eigen::JacobiSVD<Eigen::MatrixXd> svd(rigid, Eigen::ComputeFullU);
690 const Eigen::MatrixXd cartesian_vib =
691 svd.matrixU().rightCols(dof - svd.rank());
692 if (cartesian_vib.cols() == 0) return out;
693 const Eigen::MatrixXd cartesian_reduced =
694 cartesian_vib.transpose() * hessian * cartesian_vib;
695 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> cartesian_solver(
696 cartesian_reduced);
697 if (cartesian_solver.info() != Eigen::Success) return out;
698 if (cartesian_solver.eigenvalues().size() > 0) {
699 out.lowest = cartesian_solver.eigenvalues()(0);
700 out.cartesian_lowest =
701 cartesian_vib * cartesian_solver.eigenvectors().col(0);
702 const double norm = out.cartesian_lowest.norm();
703 if (norm > 0.0) out.cartesian_lowest /= norm;
704 }
705 const double floor = std::max(out.resolution, 0.0);
706 std::vector<Eigen::Index> stiff_cols;
707 for (Eigen::Index i = 0; i < cartesian_solver.eigenvalues().size(); ++i) {
708 const double value = cartesian_solver.eigenvalues()(i);
709 if (value > floor && !std::isfinite(out.lambda_min))
710 out.lambda_min = value;
711 if (std::isfinite(value)) out.lambda_max = value;
712 if (value > std::max(std::abs(out.curvature), stiff_floor))
713 stiff_cols.push_back(i);
714 }
715 if (!stiff_cols.empty()) {
716 out.stiff.resize(dof, static_cast<Eigen::Index>(stiff_cols.size()));
717 for (Eigen::Index c = 0; c < out.stiff.cols(); ++c)
718 out.stiff.col(c) =
719 cartesian_vib * cartesian_solver.eigenvectors().col(
720 stiff_cols[static_cast<std::size_t>(c)]);
721 }
722 out.ok = true;
723 return out;
724}
725
729 const Eigen::VectorXd& positions, const Eigen::VectorXd& masses,
730 double step,
731 const std::function<bool(const Eigen::VectorXd&, Eigen::VectorXd&)>&
732 gradient_at,
733 double stiff_floor = std::numeric_limits<double>::infinity(),
734 Eigen::MatrixXd* raw_columns = nullptr,
735 const Eigen::MatrixXd* held_directions = nullptr)
736{
738 Eigen::MatrixXd hessian;
739 if (positions.size() == 0 || positions.size() % 3 != 0 ||
740 masses.size() * 3 != positions.size())
741 return out;
743 hessian, out.resolution, positions, step,
744 ircStencilDirections(positions, masses, held_directions),
745 gradient_at, raw_columns))
746 return out;
747 return spectrumOfColumns(hessian, out.resolution, positions, masses,
748 stiff_floor);
749}
750
754 struct Key {
755 Eigen::VectorXd position;
756 bool operator==(const Key& other) const
757 {
758 return position.size() == other.position.size() &&
759 std::memcmp(position.data(), other.position.data(),
760 sizeof(double) * static_cast<std::size_t>(
761 position.size())) == 0;
762 }
763 };
764 struct Hash {
765 std::size_t operator()(const Key& key) const noexcept
766 {
767 const auto* bytes =
768 reinterpret_cast<const unsigned char*>(key.position.data());
769 const std::size_t n =
770 sizeof(double) * static_cast<std::size_t>(key.position.size());
771 std::size_t hash = 14695981039346656037ull;
772 for (std::size_t i = 0; i < n; ++i) {
773 hash ^= bytes[i];
774 hash *= 1099511628211ull;
775 }
776 return hash;
777 }
778 };
779 std::unordered_map<Key, EndpointSpectrum, Hash> spectra;
780
781 bool recall(const Eigen::VectorXd& position, EndpointSpectrum& out) const
782 {
783 const auto found = spectra.find(Key{position});
784 if (found == spectra.end()) return false;
785 out = found->second;
786 return out.ok;
787 }
788
789 void store(const Eigen::VectorXd& position,
790 const EndpointSpectrum& spectrum)
791 {
792 if (!spectrum.ok || position.size() == 0 || !position.allFinite())
793 return;
794 spectra.emplace(Key{position}, spectrum);
795 }
796};
797
813template <typename GradientAt>
815 const Eigen::VectorXd& positions, const Eigen::VectorXd& masses,
816 double step, const GradientAt& gradient_at,
817 double stiff_floor = std::numeric_limits<double>::infinity())
818{
820 const Eigen::Index dof = positions.size();
821 if (!(step > 0.0) || dof == 0 || dof % 3 != 0 || masses.size() * 3 != dof ||
822 !positions.allFinite() || !masses.allFinite() ||
823 (masses.array() <= 0.0).any())
824 return out;
825 const Eigen::MatrixXd rigid = cartesianRigidMotions(positions);
826 const Eigen::JacobiSVD<Eigen::MatrixXd> svd(rigid, Eigen::ComputeFullU);
827 const Eigen::Index rank = svd.rank();
828 if (rank < 0 || rank >= dof) return out;
829 const Eigen::MatrixXd basis = svd.matrixU().rightCols(dof - rank);
830 const Eigen::Index m = basis.cols();
831 if (m <= 0) return out;
832 const double roundoff = std::sqrt(std::numeric_limits<double>::epsilon()) *
833 std::sqrt(static_cast<double>(m));
834
835 const auto product = [&](const Eigen::VectorXd& reduced,
836 Eigen::VectorXd& action) {
837 const Eigen::VectorXd direction = basis * reduced;
838 if (!(direction.norm() > 0.0) || !direction.allFinite()) return false;
839 const Eigen::MatrixXd points =
840 centralDifferencePoints(positions, step, direction);
841 Eigen::VectorXd plus(dof);
842 Eigen::VectorXd minus(dof);
843 if (!gradient_at(points.col(0), plus) ||
844 !gradient_at(points.col(1), minus) || plus.size() != dof ||
845 minus.size() != dof || !plus.allFinite() || !minus.allFinite())
846 return false;
847 action = basis.transpose() * ((plus - minus) / (2.0 * step));
848 return action.size() == m && action.allFinite();
849 };
850 const auto orthogonalize = [&](Eigen::VectorXd& direction,
851 const Eigen::MatrixXd& span,
852 Eigen::Index columns) {
853 if (columns <= 0) return;
854 const Eigen::MatrixXd basis_now = span.leftCols(columns);
855 for (int pass = 0; pass < 2; ++pass)
856 direction -= basis_now * (basis_now.transpose() * direction);
857 };
858
859 Eigen::MatrixXd directions(m, m);
860 Eigen::MatrixXd actions(m, m);
861 Eigen::Index columns = 0;
862 while (columns < m) {
863 Eigen::VectorXd direction(m);
864 if (columns == 0) {
865 direction.setOnes();
866 } else {
867 const Eigen::MatrixXd projected =
868 directions.leftCols(columns).transpose() *
869 actions.leftCols(columns);
870 const Eigen::MatrixXd symmetric =
871 0.5 * (projected + projected.transpose());
872 const Eigen::MatrixXd antisymmetric =
873 0.5 * (projected - projected.transpose());
874 const double resolution =
875 antisymmetric.size() == 0
876 ? 0.0
877 : Eigen::JacobiSVD<Eigen::MatrixXd>(antisymmetric)
878 .singularValues()(0);
879 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(
880 symmetric);
881 if (spectrum.info() != Eigen::Success ||
882 !spectrum.eigenvalues().allFinite())
883 return {};
884 const Eigen::VectorXd coordinate = spectrum.eigenvectors().col(0);
885 const double theta = spectrum.eigenvalues()(0);
886 Eigen::VectorXd residual =
887 actions.leftCols(columns) * coordinate -
888 theta * (directions.leftCols(columns) * coordinate);
889 // Full residual, before the part inside the Krylov subspace is
890 // removed. That norm bounds the distance from theta to the
891 // spectrum.
892 const double residual_norm = residual.norm();
893 if (columns >= 2 && std::isfinite(theta) &&
894 std::isfinite(residual_norm) && std::isfinite(resolution)) {
895 const double next = spectrum.eigenvalues()(1);
896 const double gap = next - theta;
897 const double noise = std::max(resolution, roundoff);
898 // The interval (theta ± residual) contains an eigenvalue of
899 // the vibrational operator. Inside the gap, and inside the
900 // stencil's own asymmetry, the Ritz vector is that mode.
901 if (theta + residual_norm < -resolution &&
902 gap > residual_norm && residual_norm <= noise) {
903 out.resolution = resolution;
904 out.lowest = theta;
905 out.lambda_max = spectrum.eigenvalues()(columns - 1);
906 const double floor = std::max(resolution, 0.0);
907 for (Eigen::Index i = 0; i < columns; ++i) {
908 const double value = spectrum.eigenvalues()(i);
909 if (value > floor && !std::isfinite(out.lambda_min))
910 out.lambda_min = value;
911 }
912 Eigen::VectorXd cartesian =
913 basis * (directions.leftCols(columns) * coordinate);
914 const double norm = cartesian.norm();
915 if (!(norm > 0.0) || !cartesian.allFinite()) return {};
916 cartesian /= norm;
917 out.cartesian_lowest = cartesian;
918 out.cartesian = cartesian;
919 double mass_norm = 0.0;
920 for (Eigen::Index atom = 0; atom < masses.size(); ++atom)
921 mass_norm +=
922 masses(atom) *
923 cartesian.segment<3>(3 * atom).squaredNorm();
924 out.curvature = mass_norm > 0.0 ? theta / mass_norm : theta;
925 out.ok = std::isfinite(out.curvature);
926 return out;
927 }
928 }
929 orthogonalize(residual, directions, columns);
930 const double outside =
931 roundoff * (1.0 + actions.leftCols(columns).norm());
932 if (!(residual.norm() > outside)) {
933 Eigen::Index least = 0;
934 double smallest = std::numeric_limits<double>::infinity();
935 const Eigen::MatrixXd span = directions.leftCols(columns);
936 for (Eigen::Index i = 0; i < m; ++i) {
937 const double represented = span.row(i).norm();
938 if (represented < smallest) {
939 smallest = represented;
940 least = i;
941 }
942 }
943 residual = Eigen::VectorXd::Unit(m, least);
944 orthogonalize(residual, directions, columns);
945 }
946 direction = residual;
947 }
948 const double norm = direction.norm();
949 if (!(norm > roundoff) || !direction.allFinite()) return {};
950 direction /= norm;
951 Eigen::VectorXd action;
952 if (!product(direction, action)) return {};
953 directions.col(columns) = direction;
954 actions.col(columns) = action;
955 ++columns;
956 }
957
958 const Eigen::MatrixXd projected = directions.transpose() * actions;
959 const Eigen::MatrixXd symmetric = 0.5 * (projected + projected.transpose());
960 const Eigen::MatrixXd antisymmetric =
961 0.5 * (projected - projected.transpose());
962 const double resolution =
963 antisymmetric.size() == 0
964 ? 0.0
965 : Eigen::JacobiSVD<Eigen::MatrixXd>(antisymmetric)
966 .singularValues()(0);
967 if (!symmetric.allFinite() || !std::isfinite(resolution)) return {};
968 const Eigen::MatrixXd hessian =
969 basis * (directions * symmetric * directions.transpose()) *
970 basis.transpose();
971 return spectrumOfColumns(hessian, resolution, positions, masses,
972 stiff_floor);
973}
974
981template <typename GradientAt>
983 const Eigen::VectorXd& positions, const Eigen::VectorXd& masses,
984 double step, const GradientAt& gradient_at,
985 MinimumSpectrumCache* cache = nullptr,
986 double stiff_floor = std::numeric_limits<double>::infinity())
987{
988 if (cache != nullptr) {
989 EndpointSpectrum cached;
990 if (cache->recall(positions, cached)) return cached;
991 }
992 const EndpointSpectrum vibrational = probeVibrationalMinimum(
993 positions, masses, step, gradient_at, stiff_floor);
995 vibrational.ok
996 ? vibrational
997 : spectrumAt(positions, masses, step, gradient_at, stiff_floor);
998 if (cache != nullptr && out.ok) cache->store(positions, out);
999 return out;
1000}
1001
1004inline EndpointSpectrum spectrumOfModelHessian(const Eigen::MatrixXd& raw,
1005 const Eigen::VectorXd& positions,
1006 const Eigen::VectorXd& masses,
1007 double stiff_floor)
1008{
1009 if (raw.rows() != positions.size() || raw.cols() != positions.size() ||
1010 !raw.allFinite())
1011 return {};
1012 const Eigen::MatrixXd antisym = 0.5 * (raw - raw.transpose());
1013 const double resolution =
1014 antisym.size() == 0
1015 ? 0.0
1016 : Eigen::JacobiSVD<Eigen::MatrixXd>(antisym).singularValues()(0);
1017 return spectrumOfColumns(0.5 * (raw + raw.transpose()), resolution,
1018 positions, masses, stiff_floor);
1019}
1020
1032inline double endpointMatchBall(double tolerance, double lambda_min,
1033 double half_separation) noexcept
1034{
1035 double ball = std::numeric_limits<double>::infinity();
1036 if (lambda_min > 0.0 && std::isfinite(lambda_min) && tolerance > 0.0)
1037 ball = 2.0 * tolerance / lambda_min;
1038 if (half_separation > 0.0 && std::isfinite(half_separation))
1039 ball = std::min(ball, half_separation);
1040 return ball;
1041}
1042
1048inline bool labelledEndpointsResolve(double separation,
1049 double harmonic_reactant,
1050 double harmonic_product) noexcept
1051{
1052 if (!(separation > 0.0) || !std::isfinite(separation)) return false;
1053 const auto outside = [&](double harmonic) {
1054 if (!std::isfinite(harmonic) || !(harmonic > 0.0)) return true;
1055 return separation > harmonic;
1056 };
1057 return outside(harmonic_reactant) && outside(harmonic_product);
1058}
1059
1060inline bool insideEndpointBall(double to_this, double to_other,
1061 double ball) noexcept
1062{
1063 return std::isfinite(to_this) && std::isfinite(to_other) &&
1064 std::isfinite(ball) && ball > 0.0 && to_this < to_other &&
1065 to_this < ball;
1066}
1067
1068namespace endpoint_detail {
1069
1070struct MinimizerState {
1071 std::function<bool(const Eigen::VectorXd&, double&, Eigen::VectorXd&)>
1072 oracle;
1073 Eigen::Index n = 0;
1074 Eigen::VectorXd last_x;
1075 Eigen::VectorXd last_gradient;
1076 double last_energy = 0.0;
1077 bool have = false;
1078 bool failed = false;
1081 bool stopped = false;
1082 int calls = 0;
1083};
1084
1088struct OracleMemory {
1089 struct Key {
1090 Eigen::VectorXd position;
1091 bool operator==(const Key& other) const
1092 {
1093 return position.size() == other.position.size() &&
1094 std::memcmp(position.data(), other.position.data(),
1095 sizeof(double) * static_cast<std::size_t>(
1096 position.size())) == 0;
1097 }
1098 };
1099 struct KeyHash {
1100 std::size_t operator()(const Key& key) const noexcept
1101 {
1102 const auto* bytes =
1103 reinterpret_cast<const unsigned char*>(key.position.data());
1104 const std::size_t n =
1105 sizeof(double) * static_cast<std::size_t>(key.position.size());
1106 std::size_t hash = 14695981039346656037ull;
1107 for (std::size_t i = 0; i < n; ++i) {
1108 hash ^= bytes[i];
1109 hash *= 1099511628211ull;
1110 }
1111 return hash;
1112 }
1113 };
1114 struct Row {
1115 double energy = 0.0;
1116 Eigen::VectorXd gradient;
1117 };
1118 std::unordered_map<Key, Row, KeyHash> rows;
1119
1120 bool recall(const Eigen::VectorXd& position, double& energy,
1121 Eigen::VectorXd& gradient) const
1122 {
1123 const auto found = rows.find(Key{position});
1124 if (found == rows.end()) return false;
1125 energy = found->second.energy;
1126 gradient = found->second.gradient;
1127 return true;
1128 }
1129
1130 bool holds(const Eigen::VectorXd& position) const
1131 {
1132 return rows.find(Key{position}) != rows.end();
1133 }
1134
1135 void add(const Eigen::VectorXd& position, double energy,
1136 const Eigen::VectorXd& gradient)
1137 {
1138 if (position.size() == 0 || gradient.size() != position.size() ||
1139 !position.allFinite() || !gradient.allFinite() ||
1140 !std::isfinite(energy))
1141 return;
1142 rows.emplace(Key{position}, Row{energy, gradient});
1143 }
1144};
1145
1146inline rgmin_status_t minimizerValueGradient(void* user,
1147 const DLManagedTensorVersioned* x,
1148 double* value,
1149 DLManagedTensorVersioned* gradient)
1150{
1151 auto* state = static_cast<MinimizerState*>(user);
1152 if (state->failed || x == nullptr || x->dl_tensor.data == nullptr ||
1153 gradient == nullptr || gradient->dl_tensor.data == nullptr ||
1154 value == nullptr)
1155 return RGMIN_INTERNAL_ERROR;
1156 const double* coordinates = reinterpret_cast<const double*>(
1157 static_cast<const std::uint8_t*>(x->dl_tensor.data) +
1158 static_cast<std::size_t>(x->dl_tensor.byte_offset));
1159 Eigen::Map<const Eigen::VectorXd> position(coordinates, state->n);
1160 if (!(state->have && state->last_x.size() == state->n &&
1161 state->last_x == position)) {
1162 double energy = 0.0;
1163 Eigen::VectorXd force(state->n);
1164 if (!state->oracle(position, energy, force) || !std::isfinite(energy) ||
1165 force.size() != state->n || !force.allFinite()) {
1166 state->failed = true;
1167 return RGMIN_INTERNAL_ERROR;
1168 }
1169 state->last_x = position;
1170 state->last_energy = energy;
1171 state->last_gradient = std::move(force);
1172 state->have = true;
1173 }
1174 *value = state->last_energy;
1175 auto* destination = reinterpret_cast<double*>(
1176 static_cast<std::uint8_t*>(gradient->dl_tensor.data) +
1177 static_cast<std::size_t>(gradient->dl_tensor.byte_offset));
1178 Eigen::Map<Eigen::VectorXd> out(destination, state->n);
1179 out = state->last_gradient;
1180 return RGMIN_SUCCESS;
1181}
1182
1183struct RelaxedPoint {
1184 Eigen::VectorXd position;
1185 double max_force = std::numeric_limits<double>::infinity();
1186 bool converged = false;
1188 bool negative_remains = false;
1190 bool stopped = false;
1192 int steps = 0;
1193 double energy = std::numeric_limits<double>::quiet_NaN();
1194};
1195
1196inline RelaxedPoint relaxWithLbfgs(MinimizerState& state, Eigen::VectorXd x,
1197 double tolerance, int max_steps,
1198 double initial_step, double max_move,
1199 int memory,
1200 const std::function<bool()>* stop = nullptr)
1201{
1202 RelaxedPoint out;
1203 out.position = x;
1204 if (x.size() != state.n || !(tolerance > 0.0) || max_steps <= 0) return out;
1206 rgmin_control_t control{};
1207 control.gtol = 0.0;
1208 control.maxiter = 1;
1209 control.istep = initial_step > 0.0 ? initial_step : 1.0;
1210 control.memory = static_cast<std::size_t>(std::max(memory, 1));
1211 control.maxmove = max_move > 0.0 ? max_move : 0.0;
1212 rgmin_solver_t* solver = rgmin_solver_create(
1213 RGMIN_LBFGS, &control, static_cast<std::size_t>(state.n));
1214 if (solver == nullptr) return out;
1215 rgmin_solver_set_atom_maxmove(solver, 0.0);
1216 DLManagedTensorVersioned* tensor = rgmin_tensor_borrow_cpu_f64(
1217 x.data(), static_cast<std::size_t>(state.n));
1218 if (tensor == nullptr) {
1219 rgmin_solver_free(solver);
1220 return out;
1221 }
1222 double energy = 0.0;
1223 Eigen::VectorXd gradient(state.n);
1224 if (!state.oracle(x, energy, gradient)) {
1225 if (state.stopped)
1226 out.stopped = true;
1227 else
1228 state.failed = true;
1229 rgmin_tensor_free(tensor);
1230 rgmin_solver_free(solver);
1231 return out;
1232 }
1233 state.have = true;
1234 state.last_x = x;
1235 state.last_energy = energy;
1236 state.last_gradient = gradient;
1237 out.max_force =
1239 for (int step = 0; step < max_steps && !state.failed; ++step) {
1240 if (stop != nullptr && (*stop)()) {
1241 out.stopped = true;
1242 break;
1243 }
1244 if (out.max_force < tolerance) {
1245 out.converged = true;
1246 break;
1247 }
1248 const Eigen::VectorXd previous = x;
1249 rgmin_report_t outcome{};
1250 const rgmin_status_t status = rgmin_solver_step_fg(
1251 solver, minimizerValueGradient, &state, tensor, &outcome);
1252 if (status != RGMIN_SUCCESS) break;
1253 ++out.steps;
1254 if (!(state.have && state.last_x.size() == state.n)) break;
1255 x = state.last_x;
1256 gradient = state.last_gradient;
1257 out.max_force =
1259 if (x == previous && !(out.max_force < tolerance)) break;
1260 }
1261 out.position = x;
1262 out.energy = state.last_energy;
1263 out.converged = out.max_force < tolerance && x.allFinite();
1264 rgmin_tensor_free(tensor);
1265 rgmin_solver_free(solver);
1266 return out;
1267}
1268
1269} // namespace endpoint_detail
1270
1276template <typename Oracle>
1278 const Eigen::VectorXd& saddle, const Eigen::VectorXd& masses,
1279 double force_tolerance, const Eigen::VectorXd& reactant,
1280 const Eigen::VectorXd& product, const std::vector<int>& atomic_numbers,
1281 Oracle oracle, RelaxedEndpointCache* cache = nullptr,
1282 double hessian_step = defaultStencilStep(),
1283 const std::function<bool()>* stop = nullptr,
1284 const std::vector<KnownOracleRow>* known = nullptr,
1285 const Eigen::MatrixXd* model_hessian = nullptr,
1286 const Eigen::MatrixXd* held_directions = nullptr,
1288{
1290 const Eigen::Index dof = saddle.size();
1291 const Eigen::Index n_atoms = masses.size();
1292 if (dof == 0 || dof % 3 != 0 || n_atoms * 3 != dof ||
1293 reactant.size() != dof || product.size() != dof ||
1294 static_cast<Eigen::Index>(atomic_numbers.size()) != n_atoms ||
1295 !saddle.allFinite() || !masses.allFinite() ||
1296 (masses.array() <= 0.0).any() || !reactant.allFinite() ||
1297 !product.allFinite() || !(force_tolerance > 0.0) ||
1298 !std::isfinite(force_tolerance) || !(hessian_step > 0.0))
1299 return report;
1300
1301 // A replay from the saved saddle must not inherit the search's
1302 // BLAS thread count. A threaded GEMM changes the Hessian's
1303 // summation order, the imaginary mode moves by a few ulps, and
1304 // L-BFGS ends in the same basin at a different point. The mode
1305 // sign is fixed below, so the two directions do not swap. L-BFGS
1306 // is a new solver on each walk; it does not keep the search's pairs.
1307 Eigen::setNbThreads(1);
1308#ifdef GPR_HAVE_OPENBLAS
1309 openblas_set_num_threads(1);
1310#endif
1311
1312 endpoint_detail::MinimizerState state;
1313 state.n = dof;
1314 endpoint_detail::OracleMemory memory;
1315 if (known != nullptr) {
1316 for (const KnownOracleRow& row: *known)
1317 memory.add(row.position, row.energy, row.gradient);
1318 }
1319 int* call_bucket = &report.calls_deposit;
1320 state.oracle = [&](const Eigen::VectorXd& position, double& energy,
1321 Eigen::VectorXd& gradient) {
1322 if (stop != nullptr && (*stop)()) {
1323 state.stopped = true;
1324 return false;
1325 }
1326 if (memory.recall(position, energy, gradient)) return true;
1327 const auto started = std::chrono::steady_clock::now();
1328 const auto sample = oracle(position);
1329 report.oracle_seconds += std::chrono::duration<double>(
1330 std::chrono::steady_clock::now() - started)
1331 .count();
1332 energy = sample.first;
1333 gradient = sample.second;
1334 if (!(std::isfinite(energy) && gradient.size() == position.size() &&
1335 gradient.allFinite()))
1336 return false;
1337 memory.add(position, energy, gradient);
1338 ++state.calls;
1339 ++*call_bucket;
1340 return true;
1341 };
1342 const auto gradient_at = [&](const Eigen::VectorXd& position,
1343 Eigen::VectorXd& gradient) {
1344 double energy = 0.0;
1345 if (!state.oracle(position, energy, gradient)) {
1346 if (!state.stopped) state.failed = true;
1347 return false;
1348 }
1349 return true;
1350 };
1351 // Endpoint and walk-end minima. The saddle stencil below stays the
1352 // complete measurement. A vibrational product that cannot be taken
1353 // does not by itself fail the certificate: the complete stencil is
1354 // the measurement when the sign is unresolved. A wall stop is not
1355 // that stencil.
1356 MinimumSpectrumCache minimum_cache;
1357 const auto minimum_at = [&](const Eigen::VectorXd& position) {
1358 EndpointSpectrum cached;
1359 if (minimum_cache.recall(position, cached)) return cached;
1360 const auto sample = [&](const Eigen::VectorXd& queried,
1361 Eigen::VectorXd& gradient) {
1362 double energy = 0.0;
1363 return state.oracle(queried, energy, gradient);
1364 };
1365 const EndpointSpectrum vibrational =
1366 probeVibrationalMinimum(position, masses, hessian_step, sample);
1367 if (state.stopped) return EndpointSpectrum{};
1368 // An unresolved curvature is still this probe's spectrum. Building
1369 // the complete stencil as well repeats the minimum measurement.
1371 vibrational.ok
1372 ? vibrational
1373 : spectrumAt(position, masses, hessian_step, gradient_at);
1374 if (out.ok) minimum_cache.store(position, out);
1375 return out;
1376 };
1377
1378 const double reach =
1379 std::max((saddle - reactant).norm(), (saddle - product).norm());
1380 // The L-BFGS memory is one vibrational window. Filling it and then
1381 // walking it again is what puts the deposit under the force tolerance.
1382 // One window can leave the force above the tolerance, and the certificate
1383 // then has nothing to report. The force test stops earlier. The reach
1384 // bound is the distance the walk can be asked to travel, in the steps
1385 // that measured the curvature.
1386 const int vibrational = std::max(1, static_cast<int>(dof) - 6);
1387 const int max_steps =
1388 std::max(vibrational + vibrational,
1389 static_cast<int>(
1390 std::ceil(std::max(reach, hessian_step) / hessian_step)));
1391
1392 const bool cache_hit = cache != nullptr && cache->ready &&
1393 cache->tolerance == force_tolerance &&
1394 cache->atomic_numbers == atomic_numbers &&
1395 cache->deposited_reactant.size() == dof &&
1396 cache->deposited_product.size() == dof &&
1397 cache->deposited_reactant == reactant &&
1398 cache->deposited_product == product &&
1399 cache->relaxed_reactant.size() == dof &&
1400 cache->relaxed_product.size() == dof;
1401
1402 Eigen::VectorXd relaxed_reactant;
1403 Eigen::VectorXd relaxed_product;
1404 if (cache_hit) {
1405 relaxed_reactant = cache->relaxed_reactant;
1406 relaxed_product = cache->relaxed_product;
1407 report.lambda_reactant = cache->lambda_reactant;
1408 report.lambda_product = cache->lambda_product;
1409 } else {
1410 // A deposited endpoint can already be under the force tolerance
1411 // and still have a negative mode (CH3O's reactant). The same
1412 // L-BFGS then stops on the force and never enters the basin the
1413 // saddle walk finds. Leave each resolved negative mode before
1414 // the match.
1415 const auto settle = [&](const Eigen::VectorXd& start) {
1416 endpoint_detail::RelaxedPoint point =
1417 endpoint_detail::relaxWithLbfgs(
1418 state, start, force_tolerance, max_steps, hessian_step,
1419 std::max(reach, hessian_step), vibrational, stop);
1420 EndpointSpectrum spec;
1421 for (int pass = 0;
1422 pass < vibrational && point.converged && !state.failed;
1423 ++pass) {
1424 call_bucket = &report.calls_endpoint_check;
1425 spec = minimum_at(point.position);
1426 call_bucket = &report.calls_deposit;
1427 if (!spec.ok || !(spec.lowest < -spec.resolution)) break;
1428 Eigen::VectorXd direction = projectOutRigidMotions(
1429 point.position, spec.cartesian_lowest);
1430 if (!(direction.norm() > 0.0)) break;
1431 direction.normalize();
1432 const double alpha =
1433 force_tolerance /
1434 std::max(std::abs(spec.lowest), spec.resolution);
1435 const Eigen::VectorXd kick = alpha * direction;
1436 double energy_plus = 0.0;
1437 double energy_minus = 0.0;
1438 Eigen::VectorXd gradient(dof);
1439 const Eigen::VectorXd plus = point.position + kick;
1440 const Eigen::VectorXd minus = point.position - kick;
1441 if (!state.oracle(plus, energy_plus, gradient) ||
1442 !state.oracle(minus, energy_minus, gradient)) {
1443 if (state.stopped)
1444 point.stopped = true;
1445 else
1446 state.failed = true;
1447 break;
1448 }
1449 const double sign = energy_plus < energy_minus ? 1.0 : -1.0;
1450 Eigen::VectorXd walked = point.position + sign * kick;
1451 double energy =
1452 energy_plus < energy_minus ? energy_plus : energy_minus;
1453 const int push_cap = std::max(
1454 1, static_cast<int>(
1455 std::ceil(std::max(reach, kick.norm()) /
1456 std::max(kick.norm(), hessian_step))));
1457 for (int pushed = 1; pushed < push_cap && !state.failed;
1458 ++pushed) {
1459 const Eigen::VectorXd trial = walked + sign * kick;
1460 double trial_energy = 0.0;
1461 if (!state.oracle(trial, trial_energy, gradient)) {
1462 if (state.stopped)
1463 point.stopped = true;
1464 else
1465 state.failed = true;
1466 break;
1467 }
1468 if (!(trial_energy < energy)) break;
1469 const double travelled = permutationAwareRmsd(
1470 point.position, trial, atomic_numbers);
1471 walked = trial;
1472 energy = trial_energy;
1473 if (std::isfinite(travelled) && reach > 0.0 &&
1474 travelled > reach)
1475 break;
1476 if (gpr::forceNorm(gradient,
1478 force_tolerance)
1479 break;
1480 }
1481 point = endpoint_detail::relaxWithLbfgs(
1482 state, walked, force_tolerance, max_steps,
1483 kick.norm() > 0.0 ? kick.norm() : hessian_step,
1484 std::max(reach, kick.norm()), vibrational, stop);
1485 if (point.stopped) break;
1486 }
1487 if (point.converged && !state.failed && !spec.ok) {
1488 call_bucket = &report.calls_endpoint_check;
1489 spec = minimum_at(point.position);
1490 call_bucket = &report.calls_deposit;
1491 }
1492 return std::pair{point, spec};
1493 };
1494 const auto reactant_settled = settle(reactant);
1495 const auto product_settled = settle(product);
1496 const auto& reactant_min = reactant_settled.first;
1497 const auto& product_min = product_settled.first;
1498 const auto& reactant_spectrum = reactant_settled.second;
1499 const auto& product_spectrum = product_settled.second;
1500 if (reactant_min.stopped || product_min.stopped || state.stopped) {
1501 report.calls = state.calls;
1502 report.unresolved = true;
1503 report.reported = true;
1504 return report;
1505 }
1506 if (!reactant_min.converged || !product_min.converged || state.failed) {
1507 report.calls = state.calls;
1508 report.ambiguous = true;
1509 report.reported = false;
1510 return report;
1511 }
1512 relaxed_reactant = reactant_min.position;
1513 relaxed_product = product_min.position;
1514 if (!reactant_spectrum.ok || !product_spectrum.ok || state.failed) {
1515 report.calls = state.calls;
1516 return report;
1517 }
1518 report.lambda_reactant = reactant_spectrum.lambda_min;
1519 report.lambda_product = product_spectrum.lambda_min;
1520 report.lowest_reactant = reactant_spectrum.lowest;
1521 report.lowest_product = product_spectrum.lowest;
1522 report.resolution_reactant = reactant_spectrum.resolution;
1523 report.resolution_product = product_spectrum.resolution;
1524 if (cache != nullptr) {
1525 cache->deposited_reactant = reactant;
1526 cache->deposited_product = product;
1527 cache->atomic_numbers = atomic_numbers;
1528 cache->tolerance = force_tolerance;
1529 cache->relaxed_reactant = relaxed_reactant;
1530 cache->relaxed_product = relaxed_product;
1531 cache->lambda_reactant = report.lambda_reactant;
1532 cache->lambda_product = report.lambda_product;
1533 cache->ready = true;
1534 }
1535 }
1536
1537 report.separation =
1538 labelledRmsd(relaxed_reactant, relaxed_product, atomic_numbers);
1539 const double half_separation =
1540 report.separation > 0.0 ? 0.5 * report.separation : 0.0;
1541 const double harmonic_reactant =
1542 endpointMatchBall(force_tolerance, report.lambda_reactant,
1543 std::numeric_limits<double>::infinity());
1544 const double harmonic_product =
1545 endpointMatchBall(force_tolerance, report.lambda_product,
1546 std::numeric_limits<double>::infinity());
1548 report.separation, harmonic_reactant, harmonic_product);
1550 force_tolerance, report.lambda_reactant, half_separation);
1552 force_tolerance, report.lambda_product, half_separation);
1553
1554 // A mode is stiff when it is stiffer than the imaginary mode and a
1555 // stencil step along it already exceeds the force tolerance. The
1556 // first bound keeps a mode softer than the reaction coordinate in
1557 // the descent. The second is the bond stretch whose λ_max made
1558 // force/λ_max creep. Floppy modes stay.
1559 call_bucket = &report.calls_saddle;
1560 const double stiff_floor = force_tolerance / hessian_step;
1561 // The saddle is measured along the validation stencil's directions, so
1562 // the rows the search measured there are read again.
1563 const Eigen::MatrixXd saddle_directions =
1564 ircStencilDirections(saddle, masses, held_directions, stencil);
1565 const Eigen::MatrixXd saddle_points =
1566 centralDifferencePoints(saddle, hessian_step, saddle_directions);
1567 bool stencil_held = saddle_points.cols() > 0;
1568 for (Eigen::Index j = 0; j < saddle_points.cols() && stencil_held; ++j)
1569 stencil_held = memory.holds(saddle_points.col(j));
1570 // The vibrational index rule. A stored stencil was already judged by
1571 // the search, so only a Hessian this walk measures is reported here.
1572 const auto note_measured_index = [&](const Eigen::MatrixXd& raw) {
1573 if (stencil_held) return;
1574 const auto decision = decideMeasuredIndex(
1575 raw, saddle, masses, hessian_step,
1576 [&](const Eigen::MatrixXd& points) {
1577 Eigen::MatrixXd rows(points.cols(), points.rows());
1578 for (Eigen::Index i = 0; i < points.cols(); ++i) {
1579 double energy = 0.0;
1580 Eigen::VectorXd gradient(points.rows());
1581 if (!state.oracle(points.col(i), energy, gradient)) {
1582 rows.resize(0, 0);
1583 return rows;
1584 }
1585 rows.row(i) = gradient.transpose();
1586 }
1587 return rows;
1588 },
1589 &saddle_directions);
1590 if (!std::isfinite(decision.resolution)) return;
1591 report.measured_index = true;
1592 report.index_resolution = decision.resolution;
1593 report.index_calls = report.calls_saddle;
1594 report.index_negative = decision.negative;
1595 report.index_unresolved = decision.unresolved;
1596 report.index_first_order = decision.first_order;
1597 report.index_higher_order = decision.higher_order;
1598 };
1599 EndpointSpectrum saddle_spectrum;
1600 bool model_mode = false;
1601 Eigen::MatrixXd measured_columns;
1602 if (!stencil_held && model_hessian != nullptr) {
1603 saddle_spectrum =
1604 spectrumOfModelHessian(*model_hessian, saddle, masses, stiff_floor);
1605 model_mode = saddle_spectrum.ok &&
1606 saddle_spectrum.curvature < -saddle_spectrum.resolution;
1607 }
1608 if (!model_mode) {
1609 saddle_spectrum =
1610 spectrumAt(saddle, masses, hessian_step, gradient_at, stiff_floor,
1611 &measured_columns, &saddle_directions);
1612 if (saddle_spectrum.ok) note_measured_index(measured_columns);
1613 }
1614 call_bucket = &report.calls_descent;
1615 if (saddle_spectrum.ok) report.saddle_curvature = saddle_spectrum.curvature;
1616 // A negative eigenvalue inside the stencil resolution is not an
1617 // imaginary mode. Rigid translation and rotation are removed before
1618 // the step: a mass-weighted mode can still carry them in Cartesian,
1619 // and stepping along that part leaves the IRC.
1620 if (state.stopped) {
1621 report.calls = state.calls;
1622 report.unresolved = true;
1623 report.reported = true;
1624 return report;
1625 }
1626 if (!saddle_spectrum.ok ||
1627 !(saddle_spectrum.curvature < -saddle_spectrum.resolution) ||
1628 state.failed) {
1629 report.calls = state.calls;
1630 return report;
1631 }
1632 // The eigensolver's sign is arbitrary. Orient forward toward the
1633 // product along the Kabsch-aligned endpoint chord when that
1634 // projection resolves the sign; otherwise make the first component
1635 // within a relative 1e-3 of the maximum magnitude positive so a
1636 // symmetric saddle does not flip forward and reverse on 1e-5 noise.
1637 const Eigen::VectorXd aligned_reactant =
1638 aux::kabschAlignProductToReactant(saddle, relaxed_reactant);
1639 const Eigen::VectorXd aligned_product =
1640 aux::kabschAlignProductToReactant(saddle, relaxed_product);
1641 Eigen::VectorXd reaction_chord;
1642 if (aligned_reactant.size() == dof && aligned_product.size() == dof &&
1643 aligned_reactant.allFinite() && aligned_product.allFinite()) {
1644 reaction_chord =
1645 projectOutRigidMotions(saddle, aligned_product - aligned_reactant);
1646 const double chord_norm = reaction_chord.norm();
1647 if (chord_norm > 0.0)
1648 reaction_chord /= chord_norm;
1649 else
1650 reaction_chord.resize(0);
1651 }
1652 const auto signed_mode = [&](const EndpointSpectrum& spec) {
1653 Eigen::VectorXd direction =
1654 projectOutRigidMotions(saddle, spec.cartesian);
1655 if (!(direction.norm() > 0.0)) return direction;
1656 direction.normalize();
1657 constexpr double kRelativeTieTolerance = 1e-3;
1658 if (reaction_chord.size() == dof) {
1659 const double projection = direction.dot(reaction_chord);
1660 if (std::abs(projection) > kRelativeTieTolerance) {
1661 if (projection < 0.0) direction = -direction;
1662 return direction;
1663 }
1664 }
1665 const double biggest = direction.cwiseAbs().maxCoeff();
1666 const double tie_floor = (1.0 - kRelativeTieTolerance) * biggest;
1667 Eigen::Index pivot = 0;
1668 for (Eigen::Index i = 0; i < direction.size(); ++i) {
1669 if (std::abs(direction(i)) >= tie_floor) {
1670 pivot = i;
1671 break;
1672 }
1673 }
1674 if (direction(pivot) < 0.0) direction = -direction;
1675 return direction;
1676 };
1677 Eigen::VectorXd mode = signed_mode(saddle_spectrum);
1678 // A model Hessian is not the measured stencil. Keep it only when it
1679 // produced a direction and the true force confirms that direction is
1680 // imaginary: the central difference of the directional derivative is
1681 // negative. Otherwise the measured stencil decides, as it does when
1682 // no model is supplied.
1683 const auto measure_saddle = [&]() {
1684 if (state.stopped) return false;
1685 call_bucket = &report.calls_saddle;
1686 saddle_spectrum =
1687 spectrumAt(saddle, masses, hessian_step, gradient_at, stiff_floor,
1688 &measured_columns, &saddle_directions);
1689 call_bucket = &report.calls_descent;
1690 if (saddle_spectrum.ok) note_measured_index(measured_columns);
1691 if (!saddle_spectrum.ok ||
1692 !(saddle_spectrum.curvature < -saddle_spectrum.resolution) ||
1693 state.failed)
1694 return false;
1695 report.saddle_curvature = saddle_spectrum.curvature;
1696 mode = signed_mode(saddle_spectrum);
1697 return mode.norm() > 0.0;
1698 };
1699 if (model_mode && mode.norm() > 0.0) {
1700 call_bucket = &report.calls_saddle;
1701 Eigen::VectorXd slope_plus(dof);
1702 Eigen::VectorXd slope_minus(dof);
1703 const bool probed =
1704 gradient_at(saddle + hessian_step * mode, slope_plus) &&
1705 gradient_at(saddle - hessian_step * mode, slope_minus);
1706 call_bucket = &report.calls_descent;
1707 const double directional =
1708 probed ? (slope_plus - slope_minus).dot(mode) / (2.0 * hessian_step)
1709 : 0.0;
1710 const bool imaginary = probed && directional < 0.0;
1711 if (imaginary) {
1712 // The model eigenvalue is not a measured spectrum. The true
1713 // number is the curvature of this one direction, and it does
1714 // not say how many other directions are negative.
1715 report.saddle_index_measured = false;
1716 report.directional_curvature = directional;
1717 report.saddle_curvature = std::numeric_limits<double>::quiet_NaN();
1718 }
1719 if (!imaginary) {
1720 if (state.stopped) {
1721 report.calls = state.calls;
1722 report.unresolved = true;
1723 report.reported = true;
1724 return report;
1725 }
1726 if (!measure_saddle()) {
1727 report.calls = state.calls;
1728 return report;
1729 }
1730 }
1731 } else if (model_mode && !measure_saddle()) {
1732 report.calls = state.calls;
1733 return report;
1734 }
1735 if (!(mode.norm() > 0.0)) {
1736 report.calls = state.calls;
1737 return report;
1738 }
1739 report.saddle_positions = saddle;
1740 report.mode = mode;
1741 double alpha = force_tolerance / std::abs(saddle_spectrum.curvature);
1742 if (half_separation > 0.0) {
1743 const double kick_rmsd =
1744 (alpha * mode).norm() / std::sqrt(static_cast<double>(n_atoms));
1745 if (kick_rmsd > half_separation) alpha *= half_separation / kick_rmsd;
1746 }
1747 report.kick = alpha;
1748
1749 const auto irc = [&](double sign) {
1750 endpoint_detail::RelaxedPoint out;
1751 out.position = saddle + sign * alpha * mode;
1752 double energy = 0.0;
1753 Eigen::VectorXd gradient(dof);
1754 if (!state.oracle(out.position, energy, gradient)) {
1755 if (state.stopped)
1756 out.stopped = true;
1757 else
1758 state.failed = true;
1759 return out;
1760 }
1761 out.energy = energy;
1762 out.max_force =
1764 // λ_max is the stiffest vibrational mode. The descent direction
1765 // is -g_i/m_i with the saddle modes stiffer than
1766 // tolerance/stencil removed, and the length is the Newton step
1767 // of the curvature that direction meets,
1768 // E(s) = E - slope·s + ½ k s². force/λ_max is the Newton step
1769 // of a bond stretch, so it creeps when the force is soft and
1770 // the walk spends the reach/stencil cap. k above the stencil
1771 // resolution gives slope/k. k below it does not bound the step:
1772 // the probe is a descent, and the next length grows by the
1773 // ratio of the slopes at its ends, up to the endpoint reach.
1774 // A rise shortens the trial to slope/k. The descent stops when
1775 // a step no longer lowers the energy. That force is not the end.
1776 const double floor_curvature = saddle_spectrum.resolution;
1777 double carried_step = hessian_step;
1778 for (int step = 0; step < max_steps && !state.failed; ++step) {
1779 if (stop != nullptr && (*stop)()) {
1780 out.stopped = true;
1781 break;
1782 }
1783 if (out.max_force < force_tolerance) break;
1784 Eigen::VectorXd driving = gradient;
1785 if (saddle_spectrum.stiff.cols() > 0 &&
1786 saddle_spectrum.stiff.rows() == gradient.size()) {
1787 const Eigen::VectorXd coeff =
1788 saddle_spectrum.stiff.transpose() * gradient;
1789 const Eigen::VectorXd soft =
1790 gradient - saddle_spectrum.stiff * coeff;
1791 if (soft.norm() > 0.0) driving = soft;
1792 }
1793 Eigen::VectorXd direction(dof);
1794 for (Eigen::Index k = 0; k < dof; ++k)
1795 direction(k) = -driving(k) / masses(k / 3);
1796 if (!(direction.norm() > 0.0)) break;
1797 direction.normalize();
1798 const double slope = -gradient.dot(direction);
1799 if (!(slope > 0.0)) break;
1800 double step_length =
1801 carried_step > 0.0 ? carried_step : hessian_step;
1802 if (reach > 0.0) step_length = std::min(step_length, reach);
1803 bool accepted = false;
1804 bool extended = false;
1805 for (int trial_index = 0;
1806 trial_index < vibrational && step_length > 0.0;
1807 ++trial_index) {
1808 const Eigen::VectorXd trial =
1809 out.position + step_length * direction;
1810 double trial_energy = 0.0;
1811 Eigen::VectorXd trial_gradient(dof);
1812 if (!state.oracle(trial, trial_energy, trial_gradient)) {
1813 if (state.stopped)
1814 out.stopped = true;
1815 else
1816 state.failed = true;
1817 break;
1818 }
1819 const double curvature =
1820 2.0 * (trial_energy - energy + slope * step_length) /
1821 (step_length * step_length);
1822 const bool bounded =
1823 curvature > floor_curvature && std::isfinite(curvature);
1824 const bool descends = trial_energy < energy;
1825 if (bounded) {
1826 double newton = slope / curvature;
1827 if (!std::isfinite(newton) || !(newton > 0.0)) break;
1828 if (reach > 0.0) newton = std::min(newton, reach);
1829 if (descends && !extended && newton > step_length) {
1830 step_length = newton;
1831 extended = true;
1832 continue;
1833 }
1834 if (!descends && newton < step_length) {
1835 step_length = newton;
1836 continue;
1837 }
1838 } else if (!descends) {
1839 break;
1840 }
1841 if (!descends) break;
1842 out.position = trial;
1843 energy = trial_energy;
1844 out.energy = energy;
1845 const double slope_trial = -trial_gradient.dot(direction);
1846 gradient = std::move(trial_gradient);
1847 out.max_force = gpr::forceNorm(
1849 if (!bounded && slope_trial > slope) {
1850 carried_step = step_length * (slope_trial / slope);
1851 if (reach > 0.0)
1852 carried_step = std::min(carried_step, reach);
1853 } else {
1854 carried_step = step_length;
1855 }
1856 accepted = true;
1857 ++out.steps;
1858 break;
1859 }
1860 if (out.stopped || !accepted) break;
1861 }
1862 // The descent has slowed. Finish on the true surface with
1863 // rgmin's L-BFGS, then leave a negative mode the force test
1864 // would have kept.
1865 if (!out.stopped) {
1866 const int descended = out.steps;
1867 call_bucket = &report.calls_polish;
1868 out = endpoint_detail::relaxWithLbfgs(
1869 state, out.position, force_tolerance, max_steps, carried_step,
1870 std::max(reach, carried_step), vibrational, stop);
1871 out.steps += descended;
1872 if (stop != nullptr && (*stop)()) out.stopped = true;
1873 }
1874 call_bucket = &report.calls_end_check;
1875 // The L-BFGS geometry is the end. A negative mode is stepped off
1876 // and relaxed again. Ambiguous means that mode is still there.
1877 EndpointSpectrum spec;
1878 for (int pass = 0; pass < vibrational && !state.failed && !out.stopped;
1879 ++pass) {
1880 if (stop != nullptr && (*stop)()) {
1881 out.stopped = true;
1882 break;
1883 }
1884 spec = minimum_at(out.position);
1885 if (!spec.ok || !(spec.lowest < -spec.resolution)) break;
1886 Eigen::VectorXd direction =
1888 if (!(direction.norm() > 0.0)) break;
1889 direction.normalize();
1890 const double leave =
1891 force_tolerance /
1892 std::max(std::abs(spec.lowest), spec.resolution);
1893 double energy_plus = 0.0;
1894 double energy_minus = 0.0;
1895 Eigen::VectorXd probe(dof);
1896 if (!state.oracle(out.position + leave * direction, energy_plus,
1897 probe) ||
1898 !state.oracle(out.position - leave * direction, energy_minus,
1899 probe)) {
1900 if (state.stopped)
1901 out.stopped = true;
1902 else
1903 state.failed = true;
1904 break;
1905 }
1906 const double side = energy_plus < energy_minus ? 1.0 : -1.0;
1907 const int before_leave = out.steps;
1908 out = endpoint_detail::relaxWithLbfgs(
1909 state, out.position + side * leave * direction, force_tolerance,
1910 max_steps, leave, std::max(reach, leave), vibrational, stop);
1911 out.steps += before_leave;
1912 if (out.stopped) break;
1913 spec = EndpointSpectrum{};
1914 }
1915 if (!spec.ok && !state.failed) spec = minimum_at(out.position);
1916 out.negative_remains = spec.ok && spec.lowest < -spec.resolution;
1917 return out;
1918 };
1919
1920 const int forward_before = state.calls;
1921 const auto forward = irc(1.0);
1922 report.forward_calls = state.calls - forward_before;
1923 const int reverse_before = state.calls;
1924 const auto reverse = irc(-1.0);
1925 report.reverse_calls = state.calls - reverse_before;
1926 report.calls = state.calls;
1927 report.unresolved = forward.stopped || reverse.stopped || state.stopped;
1928 if (state.failed || !forward.position.allFinite() ||
1929 !reverse.position.allFinite() || forward.position.size() != dof ||
1930 reverse.position.size() != dof) {
1931 if (report.unresolved) report.reported = true;
1932 return report;
1933 }
1934
1935 report.forward_force = forward.max_force;
1936 report.reverse_force = reverse.max_force;
1937 report.forward_steps = forward.steps;
1938 report.reverse_steps = reverse.steps;
1939 report.forward_position = forward.position;
1940 report.reverse_position = reverse.position;
1941 report.forward_energy = forward.energy;
1942 report.reverse_energy = reverse.energy;
1943 const auto match_started = std::chrono::steady_clock::now();
1944 report.forward_reactant =
1945 labelledRmsd(relaxed_reactant, forward.position, atomic_numbers);
1946 report.forward_product =
1947 labelledRmsd(relaxed_product, forward.position, atomic_numbers);
1948 report.reverse_reactant =
1949 labelledRmsd(relaxed_reactant, reverse.position, atomic_numbers);
1950 report.reverse_product =
1951 labelledRmsd(relaxed_product, reverse.position, atomic_numbers);
1953 permutationAwareRmsd(reactant, forward.position, atomic_numbers);
1955 permutationAwareRmsd(product, forward.position, atomic_numbers);
1957 permutationAwareRmsd(reactant, reverse.position, atomic_numbers);
1959 permutationAwareRmsd(product, reverse.position, atomic_numbers);
1961 forward.position, reverse.position, atomic_numbers);
1962 report.comparison_tolerance = force_tolerance;
1963 report.reported = true;
1964 report.ambiguous = forward.negative_remains || reverse.negative_remains;
1965 report.reactant_bonds = bondGraph(relaxed_reactant, atomic_numbers);
1966 report.product_bonds = bondGraph(relaxed_product, atomic_numbers);
1967 report.forward_bonds = bondGraph(forward.position, atomic_numbers);
1968 report.reverse_bonds = bondGraph(reverse.position, atomic_numbers);
1969 report.match_seconds = std::chrono::duration<double>(
1970 std::chrono::steady_clock::now() - match_started)
1971 .count();
1972 const bool forward_reactant_graph =
1973 report.forward_bonds == report.reactant_bonds &&
1974 report.forward_bonds != report.product_bonds;
1975 const bool forward_product_graph =
1976 report.forward_bonds == report.product_bonds &&
1977 report.forward_bonds != report.reactant_bonds;
1978 const bool reverse_reactant_graph =
1979 report.reverse_bonds == report.reactant_bonds &&
1980 report.reverse_bonds != report.product_bonds;
1981 const bool reverse_product_graph =
1982 report.reverse_bonds == report.product_bonds &&
1983 report.reverse_bonds != report.reactant_bonds;
1984 if (report.reactant_bonds == report.product_bonds) {
1985 report.graph_applicable = false;
1986 } else {
1987 report.graph_connected =
1988 !report.unresolved &&
1989 forward_reactant_graph != forward_product_graph &&
1990 reverse_reactant_graph != reverse_product_graph &&
1991 forward_reactant_graph != reverse_reactant_graph;
1992 }
1993 const auto matched = [&](const EndpointConnectivityReport& current) {
1994 const bool forward_reactant =
1995 insideEndpointBall(current.forward_reactant,
1996 current.forward_product, current.reactant_ball);
1997 const bool forward_product =
1998 insideEndpointBall(current.forward_product,
1999 current.forward_reactant, current.product_ball);
2000 const bool reverse_reactant =
2001 insideEndpointBall(current.reverse_reactant,
2002 current.reverse_product, current.reactant_ball);
2003 const bool reverse_product =
2004 insideEndpointBall(current.reverse_product,
2005 current.reverse_reactant, current.product_ball);
2006 const bool forward_one = forward_reactant != forward_product;
2007 const bool reverse_one = reverse_reactant != reverse_product;
2008 return forward_one && reverse_one &&
2009 forward_reactant != reverse_reactant;
2010 };
2011 report.ball_matched =
2012 !report.unresolved && report.ball_applicable && matched(report);
2013 // A conformer is another minimum of the same bond graph. The
2014 // half-separation ball rejects it. When the graphs differ, the
2015 // end is the endpoint's if it is a minimum and carries that graph.
2016 // Energy and the fixed-label distances above stay diagnostics.
2017 // Identical graphs cannot be assigned that way, so the balls decide.
2018 const bool minima = report.forward_force < force_tolerance &&
2019 report.reverse_force < force_tolerance;
2020 if (!report.graph_applicable) {
2021 report.connected = !report.unresolved && !report.ambiguous &&
2022 report.ball_matched && minima;
2023 } else {
2024 report.connected = !report.unresolved && !report.ambiguous && minima &&
2025 report.graph_connected;
2026 }
2027 call_bucket = &report.calls_energy;
2028 const auto energy_of = [&](const Eigen::VectorXd& position) {
2029 double energy = 0.0;
2030 Eigen::VectorXd gradient(dof);
2031 if (!state.oracle(position, energy, gradient))
2032 return std::numeric_limits<double>::quiet_NaN();
2033 return energy;
2034 };
2035 // Fill only energies the walk did not already take at that
2036 // geometry. A later oracle call can be refused by the wall, and
2037 // must not wipe an energy the accepted step recorded.
2038 if (!std::isfinite(report.reactant_energy))
2039 report.reactant_energy = energy_of(relaxed_reactant);
2040 if (!std::isfinite(report.product_energy))
2041 report.product_energy = energy_of(relaxed_product);
2042 if (!std::isfinite(report.forward_energy))
2043 report.forward_energy = energy_of(forward.position);
2044 if (!std::isfinite(report.reverse_energy))
2045 report.reverse_energy = energy_of(reverse.position);
2046 report.calls = state.calls;
2047 return report;
2048}
2049
2053inline bool writeIrcCertificate(const std::string& path,
2054 const EndpointConnectivityReport& report,
2055 const std::vector<int>& atomic_numbers)
2056{
2057 if (!report.reported || report.saddle_positions.size() == 0 ||
2058 report.saddle_positions.size() != report.mode.size() ||
2059 report.forward_position.size() != report.saddle_positions.size() ||
2060 report.reverse_position.size() != report.saddle_positions.size() ||
2061 static_cast<Eigen::Index>(atomic_numbers.size()) * 3 !=
2062 report.saddle_positions.size())
2063 return false;
2064 std::ofstream out(path);
2065 if (!out) return false;
2066 // max_digits10 round-trips a double through extraction. Hex floats
2067 // do not: operator>> reads the leading 0 and stops.
2068 out << std::setprecision(std::numeric_limits<double>::max_digits10);
2069 out << "irc-certificate 1\n";
2070 out << "n_atoms " << atomic_numbers.size() << "\n";
2071 out << "atomic_numbers";
2072 for (const int z: atomic_numbers)
2073 out << ' ' << z;
2074 out << "\nkick " << report.kick << "\n";
2075 out << "forward_energy " << report.forward_energy << "\n";
2076 out << "forward_force " << report.forward_force << "\n";
2077 out << "forward_steps " << report.forward_steps << "\n";
2078 out << "forward_calls " << report.forward_calls << "\n";
2079 out << "reverse_energy " << report.reverse_energy << "\n";
2080 out << "reverse_force " << report.reverse_force << "\n";
2081 out << "reverse_steps " << report.reverse_steps << "\n";
2082 out << "reverse_calls " << report.reverse_calls << "\n";
2083 out << "reactant_energy " << report.reactant_energy << "\n";
2084 out << "product_energy " << report.product_energy << "\n";
2085 const auto row = [&](const char* name, const Eigen::VectorXd& values) {
2086 out << name;
2087 for (Eigen::Index i = 0; i < values.size(); ++i)
2088 out << ' ' << values(i);
2089 out << '\n';
2090 };
2091 row("saddle", report.saddle_positions);
2092 row("mode", report.mode);
2093 row("forward", report.forward_position);
2094 row("reverse", report.reverse_position);
2095 if (!report.saddle_index_measured)
2096 out << "descent direction verified; index not measured\n";
2097 return static_cast<bool>(out);
2098}
2099
2101 std::vector<int> atomic_numbers;
2102 double kick = std::numeric_limits<double>::quiet_NaN();
2103 double forward_energy = std::numeric_limits<double>::quiet_NaN();
2104 double forward_force = std::numeric_limits<double>::quiet_NaN();
2107 double reverse_energy = std::numeric_limits<double>::quiet_NaN();
2108 double reverse_force = std::numeric_limits<double>::quiet_NaN();
2111 double reactant_energy = std::numeric_limits<double>::quiet_NaN();
2112 double product_energy = std::numeric_limits<double>::quiet_NaN();
2113 Eigen::VectorXd saddle;
2114 Eigen::VectorXd mode;
2115 Eigen::VectorXd forward;
2116 Eigen::VectorXd reverse;
2117};
2118
2119inline bool readIrcCertificate(const std::string& path,
2120 IrcCertificateRecord& record)
2121{
2122 std::ifstream in(path);
2123 if (!in) return false;
2124 std::string label;
2125 int version = 0;
2126 if (!(in >> label >> version) || label != "irc-certificate" || version != 1)
2127 return false;
2128 std::size_t n_atoms = 0;
2129 if (!(in >> label >> n_atoms) || label != "n_atoms") return false;
2130 if (!(in >> label) || label != "atomic_numbers") return false;
2131 record.atomic_numbers.resize(n_atoms);
2132 for (std::size_t i = 0; i < n_atoms; ++i) {
2133 if (!(in >> record.atomic_numbers[i])) return false;
2134 }
2135 const auto scalar = [&](const char* name, double& value) {
2136 std::string got;
2137 return static_cast<bool>(in >> got >> value) && got == name;
2138 };
2139 const auto integer = [&](const char* name, int& value) {
2140 std::string got;
2141 return static_cast<bool>(in >> got >> value) && got == name;
2142 };
2143 if (!scalar("kick", record.kick) ||
2144 !scalar("forward_energy", record.forward_energy) ||
2145 !scalar("forward_force", record.forward_force) ||
2146 !integer("forward_steps", record.forward_steps) ||
2147 !integer("forward_calls", record.forward_calls) ||
2148 !scalar("reverse_energy", record.reverse_energy) ||
2149 !scalar("reverse_force", record.reverse_force) ||
2150 !integer("reverse_steps", record.reverse_steps) ||
2151 !integer("reverse_calls", record.reverse_calls) ||
2152 !scalar("reactant_energy", record.reactant_energy) ||
2153 !scalar("product_energy", record.product_energy))
2154 return false;
2155 const auto vector = [&](const char* name, Eigen::VectorXd& values) {
2156 std::string got;
2157 if (!(in >> got) || got != name) return false;
2158 values.resize(static_cast<Eigen::Index>(3 * n_atoms));
2159 for (Eigen::Index i = 0; i < values.size(); ++i) {
2160 if (!(in >> values(i))) return false;
2161 }
2162 return true;
2163 };
2164 return vector("saddle", record.saddle) && vector("mode", record.mode) &&
2165 vector("forward", record.forward) &&
2166 vector("reverse", record.reverse);
2167}
2168
2169} // namespace gpr::optim
2170
2171#endif // GPRIDGEIZATION_ENDPOINT_CONNECTIVITY_H_
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
eon_relax_band_t eon_relax_surface_fn void * user
Eigen::VectorXd kabschAlignProductToReactant(const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions)
std::vector< int > solve_assignment_indices(const Eigen::MatrixXd &cost_matrix)
Like solve_assignment_problem, but returns the optimal assignment.
Definition Distance.cpp:193
double rigidAlignedRmsd(const Eigen::VectorXd &reference, const Eigen::VectorXd &mobile)
Intrinsic reaction coordinate drivers in mass-weighted coordinates.
Definition IRCDriver.cpp:20
double labelledRmsd(const Eigen::VectorXd &reference, const Eigen::VectorXd &mobile, const std::vector< int > &atomic_numbers)
EndpointConnectivityReport reportEndpointConnectivity(const Eigen::VectorXd &saddle, const Eigen::VectorXd &masses, double force_tolerance, const Eigen::VectorXd &reactant, const Eigen::VectorXd &product, const std::vector< int > &atomic_numbers, Oracle oracle, RelaxedEndpointCache *cache=nullptr, double hessian_step=defaultStencilStep(), const std::function< bool()> *stop=nullptr, const std::vector< KnownOracleRow > *known=nullptr, const Eigen::MatrixXd *model_hessian=nullptr, const Eigen::MatrixXd *held_directions=nullptr, VibrationalStencil stencil=VibrationalStencil::Full)
void appendIrcProfile(std::ostream &line, const EndpointConnectivityReport &report)
double permutationAwareRmsd(const Eigen::VectorXd &reference, const Eigen::VectorXd &mobile_in, const std::vector< int > &atomic_numbers)
Eigen::MatrixXd hessianColumnsFromDirections(const Eigen::VectorXd &center, const Eigen::VectorXd &center_gradient, const Eigen::MatrixXd &directions, const Eigen::MatrixXd &actions)
EndpointSpectrum probeVibrationalMinimum(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const GradientAt &gradient_at, double stiff_floor=std::numeric_limits< double >::infinity())
Eigen::MatrixXd ircStencilDirections(const Eigen::VectorXd &center, const Eigen::VectorXd &masses, const Eigen::MatrixXd *held_directions, VibrationalStencil mode=VibrationalStencil::Full)
MeasuredIndexDecision decideMeasuredIndex(const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const Gradients &gradients, const Eigen::MatrixXd *measured=nullptr)
measured is analyzeStencilIndex's.
bool labelledEndpointsResolve(double separation, double harmonic_reactant, double harmonic_product) noexcept
Eigen::VectorXd massesFromAtomicNumbers(const std::vector< int > &numbers)
bool writeIrcCertificate(const std::string &path, const EndpointConnectivityReport &report, const std::vector< int > &atomic_numbers)
EndpointSpectrum spectrumOfModelHessian(const Eigen::MatrixXd &raw, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double stiff_floor)
double corderoRadius(int atomic_number) noexcept
bool cartesianHessianColumns(Eigen::MatrixXd &columns, double &resolution, const Eigen::VectorXd &center, double step, const Eigen::MatrixXd &directions, const std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> &gradient_at, Eigen::MatrixXd *raw_columns=nullptr)
EndpointSpectrum spectrumAt(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> &gradient_at, double stiff_floor=std::numeric_limits< double >::infinity(), Eigen::MatrixXd *raw_columns=nullptr, const Eigen::MatrixXd *held_directions=nullptr)
bool readIrcCertificate(const std::string &path, IrcCertificateRecord &record)
Eigen::MatrixXd vibrationalComplement(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses)
constexpr double defaultStencilStep() noexcept
double endpointMatchBall(double tolerance, double lambda_min, double half_separation) noexcept
Eigen::MatrixXd stencilDirectionsForMode(VibrationalStencil mode, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, bool periodic, bool anchored, const Eigen::VectorXi *frozen=nullptr)
EndpointSpectrum spectrumForMinimumCheck(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const GradientAt &gradient_at, MinimumSpectrumCache *cache=nullptr, double stiff_floor=std::numeric_limits< double >::infinity())
Eigen::MatrixXd cartesianRigidMotions(const Eigen::VectorXd &positions)
Eigen::VectorXd projectOutRigidMotions(const Eigen::VectorXd &positions, Eigen::VectorXd displacement)
EndpointSpectrum spectrumOfColumns(const Eigen::MatrixXd &hessian, double resolution, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double stiff_floor)
bool insideEndpointBall(double to_this, double to_other, double ball) noexcept
std::string formatEndpointConnectivity(const EndpointConnectivityReport &report)
Eigen::MatrixXd centralDifferencePoints(const Eigen::VectorXd &center, double step, const Eigen::MatrixXd &directions)
std::string bondGraph(const Eigen::VectorXd &positions, const std::vector< int > &atomic_numbers)
double atomicMassAmu(int atomic_number) noexcept
const char * endpointConnectivityLabel(const EndpointConnectivityReport &report) noexcept
void requireCompatibleLibrary()
Definition RgminAbi.h:90
double forceNorm(const Eigen::MatrixBase< Derived > &force, ConvergenceNormType norm)
Definition ForceNorm.h:45
int forward_steps
Steepest-descent steps plus L-BFGS steps on that side.
bool graph_applicable
False when the relaxed endpoints have one bond graph.
bool skipped
--irc-certificate off. The walk is not run.
std::string reactant_bonds
Bond graphs: sorted "i-j" pairs inside 1.2 times the Cordero radii.
Eigen::VectorXd cartesian_lowest
Unit Cartesian direction of the lowest Cartesian vibrational eigenvalue.
std::size_t operator()(const Key &key) const noexcept
bool operator==(const Key &other) const
std::unordered_map< Key, EndpointSpectrum, Hash > spectra
void store(const Eigen::VectorXd &position, const EndpointSpectrum &spectrum)
bool recall(const Eigen::VectorXd &position, EndpointSpectrum &out) const