Loading...
Searching...
No Matches
AtomicDimer.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/*
6 * AtomicDimer.h
7 *
8 * Created on: 23 Oct 2020
9 * Author: Maxim Masterov
10 * Company: SURFSara
11 */
12
13#ifndef GPR_GPR_H_
14#define GPR_GPR_H_
15
16#include <Eigen/Dense>
17#include <algorithm>
18#include <chrono>
19#include <cmath>
20#include <cstddef>
21#include <cstdint>
22#include <exception>
23#include <functional>
24#include <iosfwd>
25#include <limits>
26#include <memory>
27#include <optional>
28#include <string>
29#include <utility>
30#include <vector>
31
32#include "../data_types/Field.h"
38#include "gpr/Enums.h"
39#include "gpr/PublicLayout.h"
43#include "ml/TrustRadius.h"
45#include "neb/RgSellaSaddle.h"
46#include "neb/RgsaddleClient.h"
53
54namespace readcon_db {
55class Corpus;
56}
57
58namespace gpr {
59namespace tests {
60class AtomicDimerTest;
61class MeasuredRefinementTerminalTest;
62class PolicyCacheTest;
63} // namespace tests
64} // namespace gpr
65
66namespace atmd {
67
68[[nodiscard]] bool shouldLogDimerFinalState(gpr::Index_t debug_level) noexcept;
69
72void writeDimerCampaignSummary(std::ostream& os, double energy, bool converged,
73 double energy_zero = 0.0);
74
79
83[[nodiscard]] Eigen::Index selectHssvdModeIndex(
84 const Eigen::VectorXd& eigenvalues, const Eigen::MatrixXd& eigenvectors,
85 const Eigen::VectorXd& reference, HssvdModeSelectionPolicy policy) noexcept;
86
89[[nodiscard]] const gpr::Coord& selectHssvdModeReference(
90 const gpr::Coord& initial_reference, const gpr::Coord& current_orientation,
91 HssvdModeSelectionPolicy policy, bool preserve_initial_reference) noexcept;
92
96[[nodiscard]] inline bool dimerPhaseBudgetAllows(gpr::Index_t phase,
97 gpr::Index_t limit) noexcept
98{
99 return limit <= 0 || phase < limit;
100}
101
107
108[[nodiscard]] inline bool dimerSearchStalled(
109 gpr::Index_t consecutive_degenerate_probes) noexcept
110{
111 return consecutive_degenerate_probes >= kMaxStalledDegenerateProbes;
112}
113
118enum class DimerRelaxationCycleKind : std::uint8_t {
119 None = 0,
122};
123
134
136[[nodiscard]] inline bool dimerGeometriesCoincide(const gpr::Coord& a,
137 const gpr::Coord& b) noexcept
138{
140}
141
147[[nodiscard]] inline bool refusalRepeatsIndexZeroExpansion(
148 const gpr::Coord& midpoint, const gpr::Coord& expansion_midpoint,
149 double curvature, double curvature_resolution, double separation) noexcept
150{
151 return midpoint.size() > 0 &&
152 expansion_midpoint.rows() == midpoint.rows() &&
153 expansion_midpoint.cols() == midpoint.cols() &&
154 std::isfinite(curvature) && std::isfinite(curvature_resolution) &&
155 curvature >= -std::abs(curvature_resolution) &&
156 std::isfinite(separation) && separation > 0.0 &&
157 (midpoint - expansion_midpoint).norm() < separation;
158}
159
165[[nodiscard]] inline DimerRelaxationCycleCertificate
167 const gpr::Coord& proposed,
168 const gpr::Coord* preceding, double force_current,
169 double force_preceding) noexcept
170{
172 if (dimerGeometriesCoincide(proposed, current)) {
173 cert.terminate = true;
175 cert.retain_current = true;
176 return cert;
177 }
178 if (preceding != nullptr && preceding->size() != 0 &&
179 dimerGeometriesCoincide(proposed, *preceding)) {
180 cert.terminate = true;
182 // Strict < keeps the current member on equal force (stable choice).
183 cert.retain_current = !(force_preceding < force_current);
184 return cert;
185 }
186 return cert;
187}
188
195[[nodiscard]] inline bool repeatedProjectedTrustStep(
196 const gpr::Coord& step, double curvature, const gpr::Coord& previous_step,
197 double previous_curvature) noexcept
198{
199 if (step.rows() != previous_step.rows() ||
200 step.cols() != previous_step.cols() || step.size() == 0 ||
201 !step.allFinite() || !previous_step.allFinite() ||
202 !std::isfinite(curvature) || !std::isfinite(previous_curvature))
203 return false;
204 const double step_norm = step.norm();
205 const double previous_norm = previous_step.norm();
206 if (!(step_norm > 0.0) || !(previous_norm > 0.0)) return false;
207 // The same cutoff the stable basis uses to separate singular values.
208 // A step inside it is not a new direction of that basis.
209 const double cutoff = std::sqrt(std::numeric_limits<double>::epsilon());
210 const double scale =
211 std::max({1.0, step_norm, previous_norm, std::abs(curvature),
212 std::abs(previous_curvature)});
213 return std::abs(curvature - previous_curvature) <= cutoff * scale &&
214 (step - previous_step).norm() <= cutoff * scale;
215}
216
222 double curvature, double current_residual,
223 double proposed_residual) noexcept
224{
225 if (!std::isfinite(current_residual) || !std::isfinite(proposed_residual)) {
226 return true;
227 }
228 return curvature < 0.0 && !(proposed_residual < current_residual);
229}
230
235 double curvature, double current_residual) noexcept
236{
237 return curvature < 0.0 && std::isfinite(current_residual);
238}
239
241 bool accepted = false;
243 double residual = std::numeric_limits<double>::infinity();
244 int evaluations = 0;
245};
246
252
258
262[[nodiscard]] inline double dimerPosteriorActionForceScale(
263 double current_residual, double force_tolerance) noexcept
264{
265 if (!(std::isfinite(current_residual) && current_residual >= 0.0) ||
266 !(std::isfinite(force_tolerance) && force_tolerance > 0.0)) {
267 return std::numeric_limits<double>::quiet_NaN();
268 }
269 return std::max(current_residual, force_tolerance);
270}
271
274[[nodiscard]] inline bool posteriorForceResolved(double proposed_force_variance,
275 double action_scale) noexcept
276{
277 if (!(std::isfinite(proposed_force_variance) &&
278 proposed_force_variance >= 0.0))
279 return false;
280 if (!(std::isfinite(action_scale) && action_scale > 0.0)) return false;
281 return proposed_force_variance < action_scale * action_scale;
282}
283
287[[nodiscard]] inline bool measuredRadiusClipRequestsOracle(
288 bool clipped, double proposed_force_variance, double action_scale) noexcept
289{
290 return clipped &&
291 !posteriorForceResolved(proposed_force_variance, action_scale);
292}
293
297[[nodiscard]] inline DimerResidualGlobalizationAction
299 double proposed_force_variance,
300 double action_scale) noexcept
301{
303 posteriorForceResolved(proposed_force_variance, action_scale))
305 return action;
306}
307
310[[nodiscard]] inline double posteriorResolvedStep(double force_sigma,
311 double curvature) noexcept
312{
313 if (!(std::isfinite(force_sigma) && force_sigma > 0.0)) return 0.0;
314 if (!(std::isfinite(curvature) && curvature != 0.0)) return 0.0;
315 return force_sigma / std::abs(curvature);
316}
317
333[[nodiscard]] inline double rejectedTrialRadius(
334 double shrunk, double displacement, double force_sigma, double curvature,
335 double prediction_error,
336 double force_increase = std::numeric_limits<double>::quiet_NaN(),
337 bool transverse_residual_exceeds_step = false) noexcept
338{
339 if (!(std::isfinite(shrunk) && shrunk >= 0.0)) return shrunk;
340 if (!(std::isfinite(displacement) && displacement > shrunk)) return shrunk;
341 if (!(std::isfinite(prediction_error) && prediction_error >= 0.0 &&
342 std::isfinite(force_sigma) && force_sigma > 0.0))
343 return shrunk;
344 const double resolved = posteriorResolvedStep(force_sigma, curvature);
345 if (resolved > displacement && !transverse_residual_exceeds_step &&
346 std::isfinite(force_increase) && force_increase >= 0.0 &&
347 force_increase <= force_sigma &&
348 std::abs(curvature) * displacement >= force_increase)
349 return displacement;
350 if (!(resolved > shrunk && resolved <= displacement)) return shrunk;
351 const double agreed = prediction_error > 0.0
352 ? std::min(1.0, force_sigma / prediction_error)
353 : 1.0;
354 return shrunk + (resolved - shrunk) * agreed;
355}
356
357[[nodiscard]] inline double modelAgreementTrustDistance(
358 double configured, double length_scale, double force_error,
359 double force_scale, double energy_error, double energy_scale) noexcept
360{
361 if (!(std::isfinite(configured) && configured > 0.0)) return configured;
362 if (!(std::isfinite(length_scale) && length_scale > 0.0)) return configured;
363 const auto within = [](double error, double scale) noexcept {
364 return std::isfinite(scale) && scale > 0.0 && std::isfinite(error) &&
365 error >= 0.0 && error <= scale;
366 };
367 if (!within(force_error, force_scale) ||
368 !within(energy_error, energy_scale))
369 return configured;
370 return std::max(configured, length_scale);
371}
372
377
404
408class OracleBudgetExhausted : public std::exception {
409public:
410 explicit OracleBudgetExhausted(std::string message)
411 : message_(std::move(message))
412 {
413 }
414 [[nodiscard]] const char* what() const noexcept override
415 {
416 return message_.c_str();
417 }
418
419private:
420 std::string message_;
421};
422
434
450
454 bool path_leashed_recovery, bool oracle_certified, double best_oracle_force,
455 double trial_oracle_force) noexcept;
456
461[[nodiscard]] inline bool dimerOracleTrialNeedsRefit(
462 double reference_force, double trial_force, double measured_change,
463 double prediction_error, double force_tolerance) noexcept
464{
465 if (!(std::isfinite(reference_force) && reference_force >= 0.0 &&
466 trial_force > reference_force))
467 return false;
468 if (!(std::isfinite(trial_force) && std::isfinite(measured_change) &&
469 measured_change >= 0.0 && std::isfinite(prediction_error) &&
470 prediction_error >= 0.0 && std::isfinite(force_tolerance) &&
471 force_tolerance > 0.0))
472 return true;
473 return prediction_error >
474 dimerPosteriorActionForceScale(reference_force, force_tolerance);
475}
476
479[[nodiscard]] inline DimerProposalGlobalizationAction
481 double curvature, double current_residual, double force_tolerance,
482 double proposed_force_variance,
483 double posterior_action_force_scale) noexcept
484{
485 if (!std::isfinite(curvature) || !std::isfinite(current_residual) ||
486 !(std::isfinite(force_tolerance) && force_tolerance > 0.0) ||
487 !(std::isfinite(proposed_force_variance) &&
488 proposed_force_variance >= 0.0) ||
489 !(std::isfinite(posterior_action_force_scale) &&
490 posterior_action_force_scale > 0.0)) {
492 }
493 const double proposed_force_std = std::sqrt(proposed_force_variance);
494 // Far from the force basin the GP walk is the point of the
495 // surrogate. Measure only when the residual is within a few
496 // tolerances of convergence, or the variance is non-finite.
497 const bool near_force_basin = current_residual <= 2.0 * force_tolerance;
498 if (!std::isfinite(proposed_force_std) ||
499 (near_force_basin &&
500 proposed_force_std >= posterior_action_force_scale)) {
502 }
503 if (curvature < 0.0 && current_residual <= force_tolerance) {
505 }
507}
508
509[[nodiscard]] inline DimerProposalGlobalizationAction
511 double current_residual,
512 double force_tolerance,
513 double proposed_force_variance) noexcept
514{
516 curvature, current_residual, force_tolerance, proposed_force_variance,
517 force_tolerance);
518}
519
523[[nodiscard]] inline DimerResidualGlobalizationAction
525 double current_residual,
526 bool backtrack_accepted) noexcept
527{
528 if (!std::isfinite(curvature) || !std::isfinite(current_residual)) {
530 }
531 if (curvature >= 0.0) {
533 }
534 return backtrack_accepted
537}
538
542[[nodiscard]] inline DimerResidualGlobalizationAction
544 DimerProposalGlobalizationAction proposal_action, double curvature,
545 double current_residual, bool backtrack_accepted) noexcept
546{
547 if (proposal_action ==
550 }
551 if (proposal_action ==
554 }
555 return selectDimerResidualGlobalizationAction(curvature, current_residual,
556 backtrack_accepted);
557}
558
562[[nodiscard]] inline DimerRelaxationBacktrackResult
564 const gpr::Coord& current, const gpr::Coord& proposed,
565 double current_residual,
566 const std::function<double(const gpr::Coord&)>& evaluate_residual)
567{
569 if (current.rows() != proposed.rows() ||
570 current.cols() != proposed.cols() || current.size() == 0 ||
571 !current.allFinite() || !proposed.allFinite() ||
572 !std::isfinite(current_residual) || !evaluate_residual) {
573 return result;
574 }
575
576 gpr::Coord candidate = proposed;
577 while (!dimerGeometriesCoincide(current, candidate)) {
578 result.residual = evaluate_residual(candidate);
579 ++result.evaluations;
580 if (std::isfinite(result.residual) &&
581 result.residual < current_residual) {
582 result.accepted = true;
583 result.positions = std::move(candidate);
584 return result;
585 }
586 candidate = current + 0.5 * (candidate - current);
587 }
588 return result;
589}
590
592 bool accepted = false;
593 std::size_t evaluations = 0;
595 double change = std::numeric_limits<double>::infinity();
596};
597
603 const gpr::Coord& current, const gpr::Coord& proposed,
604 const gpr::Coord& gradient, const gpr::Coord& orientation, double curvature,
605 const std::function<double(const gpr::Coord&)>& energy_change)
606{
608 if (current.rows() != 1 || proposed.rows() != 1 || gradient.rows() != 1 ||
609 orientation.rows() != 1 || current.cols() == 0 ||
610 proposed.cols() != current.cols() ||
611 gradient.cols() != current.cols() ||
612 orientation.cols() != current.cols() || !current.allFinite() ||
613 !proposed.allFinite() || !gradient.allFinite() ||
614 !orientation.allFinite() || !std::isfinite(curvature) ||
615 !(curvature < 0.0) || !energy_change)
616 return result;
617 const double norm = orientation.norm();
618 if (!(norm > 0.0) || !std::isfinite(norm)) return result;
619 const Eigen::RowVectorXd axis = orientation.row(0) / norm;
620 const double parallel_gradient = gradient.row(0).dot(axis);
621 const Eigen::RowVectorXd reflected_gradient =
622 gradient.row(0) - 2.0 * parallel_gradient * axis;
623 const double slope = reflected_gradient.dot((proposed - current).row(0));
624 if (!(slope < 0.0) || !std::isfinite(slope)) return result;
625
626 gpr::Coord candidate = proposed;
627 while (!dimerGeometriesCoincide(current, candidate)) {
628 const Eigen::RowVectorXd step = (candidate - current).row(0);
629 const double parallel_step = step.dot(axis);
630 result.change = energy_change(candidate) -
631 2.0 * parallel_gradient * parallel_step -
632 curvature * parallel_step * parallel_step;
633 ++result.evaluations;
634 // A quarter of the predicted linear decrease leaves a strict
635 // descent margin and admits a quadratic Newton step.
636 if (std::isfinite(result.change) &&
637 result.change <= 0.25 * reflected_gradient.dot(step)) {
638 result.accepted = true;
639 result.positions = std::move(candidate);
640 return result;
641 }
642 candidate = current + 0.5 * (candidate - current);
643 }
644 return result;
645}
646
651inline constexpr int kMaxConsecutiveOracleFailures = 8;
652
657public:
661 AtomicDimer();
662 virtual ~AtomicDimer();
663
664 friend class gpr::tests::AtomicDimerTest;
665 friend class gpr::tests::MeasuredRefinementTerminalTest;
666 friend class gpr::tests::PolicyCacheTest;
669
670 /* *********************************** */
671 /* *** Initializers and executers **** */
672 /* *********************************** */
683 void initialize(const gpr::InputParameters& parameters,
684 const gpr::Observation& initial_data,
685 const gpr::Observation& middle_point,
686 const gpr::Coord& initial_orientation,
687 const gpr::AtomsConfiguration& init_atom_config);
688
694 inline void setAtomsConfiguration(
695 const gpr::AtomsConfiguration& _atoms_config);
696
714 void execute(pot::PotentialWrapper& general_potential);
720 void setSecantOrientationSeed(bool enabled) noexcept
721 {
722 secant_orientation_seed_ = enabled;
723 }
725 const noexcept
726 {
727 return secant_hessian_;
728 }
732 const noexcept
733 {
734 return secant_counts_;
735 }
736
737 void setMaxWallSeconds(double seconds)
738 {
739 setWallClockLimit(seconds > 0.0 && std::isfinite(seconds)
740 ? std::make_shared<gpr::WallClockLimit>(seconds)
741 : nullptr);
742 }
743
744 void setWallClockLimit(std::shared_ptr<const gpr::WallClockLimit> limit)
745 {
746 wall_clock_limit_ = std::move(limit);
747 if (gpr_model != nullptr)
748 gpr_model->setWallClockLimit(wall_clock_limit_);
749 }
750
754 std::shared_ptr<const gpr::policy::TrainingPolicy> policy);
755 [[nodiscard]] bool wallClockLimitReached() const
756 {
757 return wall_clock_limit_ && wall_clock_limit_->reached();
758 }
759
767 bool certifyStoppedForce(pot::PotentialWrapper& potential, double step,
768 int& calls);
774 void setForceStopCertificateStep(double step) noexcept
775 {
776 force_stop_certificate_step_ = step;
777 }
778
782 {
783 vibrational_stencil_ = mode;
784 }
786 const noexcept
787 {
788 return vibrational_stencil_;
789 }
790 [[nodiscard]] double forceStopCertificateStep() const noexcept
791 {
792 return force_stop_certificate_step_;
793 }
794
795 [[nodiscard]] bool getForceStopCertified() const noexcept
796 {
797 return force_stop_certified_;
798 }
799
801 [[nodiscard]] int getForceStopCertificateCalls() const noexcept
802 {
803 return force_stop_certificate_calls_;
804 }
805
813 [[nodiscard]] bool hasValidAtomsConfiguration()
814 {
815 return isAtomsConfigurationCorrect();
816 }
817
818 /* *********************************** */
819 /* ************* Getters ************* */
820 /* *********************************** */
821
829 double getFinalRotationAngle() const noexcept
830 {
831 return final_rotation_omega_;
832 }
833
839 double getLatestModeCurvature() const noexcept
840 {
841 return latest_mode_curvature_;
842 }
843
845 const gpr::Observation& finalMidpoint() const noexcept
846 {
847 return middle_point_final;
848 }
849
857 bool isMinModeAngleCertified() const noexcept
858 {
859 return final_converged_ && measuredModeIsCertified();
860 }
861
865 double getFinalRotationResidual() const noexcept
866 {
867 return final_rotation_residual_;
868 }
869
872 bool measuredModeIsCertified() const noexcept;
876 bool terminalModeIsReady() const noexcept;
880 void refineMeasuredModeCurvature(const gpr::Observation& midpoint,
881 const gpr::Coord& orientation,
882 pot::PotentialWrapper& potential,
883 double surrogate_curvature);
884
890 [[nodiscard]] inline Eigen::VectorXd getFinalGradientAtMidPoint() const;
891
899 [[deprecated(
900 "returns the gradient; use "
901 "getFinalGradientAtMidPoint()")]] [[nodiscard]] inline Eigen::VectorXd
903
907 [[nodiscard]] inline double getFinalForceNormForConvergence() const;
908
912 [[nodiscard]] inline Eigen::VectorXd getFinalCoordOfMidPoint() const;
919 bool restartFromHigherOrderPoint(const Eigen::MatrixXd& cartesian_hessian,
920 const Eigen::VectorXd& kick,
921 const gpr::Observation& measured_rows,
922 pot::PotentialWrapper& potential);
963 const Eigen::MatrixXd& cartesian_hessian,
964 pot::PotentialWrapper& potential, double resolution = 0.0);
970 const Eigen::MatrixXd& cartesian_hessian,
971 pot::PotentialWrapper& potential, gpr::Observation* raw_candidate,
972 double resolution = 0.0, bool complete_stencil = false);
984 const gpr::Observation& raw_center,
985 const Eigen::MatrixXd& certified_cartesian_hessian,
986 const Eigen::MatrixXd& certified_mass_weighted_basis,
987 bool first_order_certificate);
991 [[nodiscard]] bool hasUnconditionedObservations() const noexcept
992 {
993 return curvature_requires_full_refit_ ||
994 !hasOptimizedCurrentObservedData();
995 }
996
1004 bool restartAlongWeakMode(const Eigen::VectorXd& direction, double length,
1005 const gpr::Observation& measured_rows,
1006 pot::PotentialWrapper& potential);
1007 bool restartAlongWeakMode(const Eigen::VectorXd& direction, double length,
1008 const gpr::Observation& measured_rows,
1009 pot::PotentialWrapper& potential,
1010 const Eigen::MatrixXd& cartesian_hessian);
1011
1015 [[nodiscard]] inline gpr::Index_t getTotalForceCalls() const;
1016
1024 bool measureCurvatureProbes(const gpr::Coord& positions,
1025 pot::PotentialWrapper& potential,
1026 gpr::Observation& raw);
1027
1031 [[nodiscard]] inline gpr::Index_t getTotalGPRForceCalls() const;
1032
1038 [[nodiscard]] inline gpr::Index_t getIterations() const;
1039
1043 [[nodiscard]] inline double getFinalEnergy() const;
1044
1048 [[nodiscard]] inline double getFinalCurvature() const;
1049
1053 [[nodiscard]] inline bool getConverged() const;
1055 [[nodiscard]] double getMaxStepLength() const
1056 {
1057 return transition_param.max_step_length;
1058 }
1059
1060 [[nodiscard]] double getConvergenceForce() const noexcept
1061 {
1062 return stop_citeria_dimer.force;
1063 }
1064
1065 void setConvergenceForce(double force)
1066 {
1067 if (!(std::isfinite(force) && force > 0.0)) return;
1068 configured_force_criterion_ = force;
1069 stop_citeria_dimer.force = force;
1070 }
1071
1072 [[nodiscard]] double convergenceForceNorm(
1073 const Eigen::Ref<const Eigen::RowVectorXd>& positions,
1074 const Eigen::Ref<const Eigen::RowVectorXd>& gradient) const
1075 {
1076 return forceNormForConvergence(positions, gradient);
1077 }
1078
1082 [[nodiscard]] inline const gpr::Coord& getFinalOrientation() const;
1083
1097 double energy = 0.0;
1098 double curvature = 0.0;
1099 double reference_alignment = std::numeric_limits<double>::quiet_NaN();
1102 bool oracle_certified = false;
1105 };
1106
1110 [[nodiscard]] const std::vector<DimerPhaseRecord>& getPhaseHistory()
1111 const noexcept
1112 {
1113 return phase_history_;
1114 }
1115
1118 {
1119 return relaxation_termination_reason_;
1120 }
1121
1125 [[nodiscard]] Eigen::MatrixXd getMeasuredIndexZeroHessian() const
1126 {
1127 if (relaxation_termination_reason_ !=
1129 return {};
1130 return measured_index_zero_hessian_;
1131 }
1132
1136 [[nodiscard]] double getMeasuredIndexZeroResolution() const
1137 {
1138 if (relaxation_termination_reason_ !=
1140 return 0.0;
1141 return measured_index_zero_resolution_;
1142 }
1143
1148 [[nodiscard]] Eigen::MatrixXd gpMeanHessianAtMidpoint();
1149
1154 const gpr::Observation& oracle_middle_point,
1155 const gpr::Coord& initial_orientation);
1156
1157 [[nodiscard]] const DimerSurrogateActionCertificate&
1159 {
1160 return first_surrogate_action_;
1161 }
1162
1167
1172
1177
1182
1184 void preserveSeedKernel() noexcept
1185 {
1186 preserve_seed_kernel_ = true;
1187 }
1188
1203 void attachExternalGP(gpr::GaussianProcessRegression* external_gp) noexcept;
1204
1215 [[nodiscard]] inline gpr::Index_t getNumNewObservations() const
1216 {
1217 const gpr::Index_t n_total =
1218 static_cast<gpr::Index_t>(all_obs.E.rows());
1219 return (n_total > N_obs_init) ? (n_total - N_obs_init) : 0;
1220 }
1221
1227 [[nodiscard]] inline gpr::Index_t getInitialObservationCount() const
1228 {
1229 return N_obs_init;
1230 }
1231
1243 [[nodiscard]] inline gpr::FieldMatrixd getEnergyZeroLevel() const
1244 {
1245 return E_zero_level;
1246 }
1247
1256 const gpr::vector3_reg (&cell_dimensions)[3],
1257 gpr::Observation& mid_point, pot::PotentialWrapper& potential);
1258
1271 bool isFinalConvergenceReached(const gpr::Observation& middle_point,
1272 const double stop_criteria);
1273
1281 bool isRotationalConvergenceReached(const gpr::Coord& orient,
1282 gpr::Observation& middle_point);
1283
1291 const gpr::Coord& orient, const gpr::Observation& approx_obs,
1292 const double stop_criteria);
1293
1297 bool rotateDimer(const double stop_criteria, gpr::Coord& orient,
1298 gpr::LBFGSInfo& rot_info, gpr::Observation& middle_point,
1299 gpr::Observation& approx_obs);
1300
1304 void translateDimer(const gpr::Observation& middle_point,
1305 const gpr::Coord& orient,
1306 const gpr::Observation& approx_obs,
1307 const double curvature, gpr::LBFGSInfo& trans_info,
1308 gpr::Coord& R_new);
1309
1310 // NOTE: public for eOn subproject access; make private when API stabilizes
1315 bool updateActiveFrozenAtoms(const gpr::Coord& R_new,
1316 gpr::LBFGSInfo& rot_info,
1317 gpr::LBFGSInfo& trans_info);
1318
1319 // NOTE: public for eOn subproject access; make private when API stabilizes
1324
1325private:
1327 bool recordMeasuredModeCertificate(const gpr::Observation& midpoint,
1328 const gpr::Coord& orientation,
1329 const gpr::Observation& endpoint);
1332 bool resolveAdditionalNegativeMode(const gpr::Observation& midpoint,
1333 const gpr::Coord& orientation,
1334 pot::PotentialWrapper& potential,
1335 gpr::Observation& recovery,
1336 gpr::Coord* measured_mode = nullptr,
1337 bool complete_stencil_follows = false);
1339 [[nodiscard]] bool image1CarriesOracleGradient() const;
1342 bool descendMeasuredNegativeMode(const gpr::Observation& midpoint,
1343 const Eigen::VectorXd& escape,
1344 double separation, double step,
1345 pot::PotentialWrapper& potential,
1346 gpr::Observation& recovery);
1349 std::vector<bool> hyperparameterRowPool();
1351 void updateVarianceSubsetFootprint(const std::vector<bool>& pool,
1352 bool preserve_support = false);
1357 bool retainFittedKernelForConsistentRows();
1360 double directionalCurvatureUncertainty(const gpr::Coord& R,
1361 const Eigen::VectorXd& direction);
1363 void prepareIndexOneProjection(const gpr::Coord& R);
1366 void applyIndexOneProjection(const Eigen::VectorXd& direction,
1367 Eigen::VectorXd& action) const;
1371 void resolveSurrogateNegativeModesBeforePhase(
1372 const gpr::Observation& midpoint, const gpr::Coord& orientation,
1373 pot::PotentialWrapper& potential);
1375 bool refineMeasuredMode(const gpr::Observation& midpoint,
1376 gpr::Coord& orientation,
1377 pot::PotentialWrapper& potential);
1378 void resetTranslationHistory(gpr::LBFGSInfo& history);
1379
1383 void clear();
1384
1385 bool isAtomsConfigurationCorrect();
1386
1390 void evaluateAccurateEnergyAndForceAtMidPoint(
1391 gpr::Observation& middle_point,
1392 pot::PotentialWrapper& general_potential);
1393
1416 bool evaluateAccurateEnergyAndForce(
1417 gpr::Observation& obs, pot::PotentialWrapper& general_potential,
1418 bool apply_emd_dedup = true);
1419
1420 struct AccurateObservationResult {
1421 bool measured;
1422 bool appended;
1423 };
1424
1427 bool evaluateAccurateProbe(gpr::Observation& obs,
1428 pot::PotentialWrapper& general_potential);
1429 bool evaluateAccurateProbe(gpr::Observation& obs,
1430 pot::PotentialWrapper& general_potential,
1431 gpr::Observation* raw_observation);
1432 bool acquireAccurateProbe(gpr::Observation& obs,
1433 pot::PotentialWrapper& general_potential,
1434 Eigen::Index batch_chunk, std::string& failure);
1435
1437 void retainStructuralObservation(const gpr::Observation& obs);
1438
1440 AccurateObservationResult evaluateAccurateObservation(
1441 gpr::Observation& obs, pot::PotentialWrapper& general_potential,
1442 bool apply_emd_dedup = true);
1443
1444 enum class DimerOracleProbeRole { Midpoint, StructuralImage1 };
1445
1453 bool maybeSkipAccurateViaVariance(
1454 gpr::Observation& obs,
1455 DimerOracleProbeRole role = DimerOracleProbeRole::Midpoint);
1456
1457 gpr::Coord lowestModeFromGradientJacobian(
1458 const gpr::FieldMatrixd& gradient_jacobian, const gpr::Coord& R) const;
1459 enum class SurrogateSpectrumRequest {
1460 ModeOnly,
1461 Spectrum,
1462 ContourProjection
1463 };
1464 std::pair<gpr::Coord, double> estimateLowestModeAndCurvatureFromGP(
1465 const gpr::Coord& R, const gpr::Coord* seed_orient = nullptr,
1466 SurrogateSpectrumRequest request =
1467 SurrogateSpectrumRequest::ContourProjection);
1468 gpr::Coord estimateLowestModeFromGP(
1469 const gpr::Coord& R, const gpr::Coord* seed_orient = nullptr);
1470
1471 void optimizeGPRModel();
1472 void refitGPRModel(bool reinitialize, const gpr::Observation& witness,
1473 const gpr::Coord& mode,
1474 bool measured_trial_rejected = false);
1477 void applyLikelihoodNoiseFloorAfterRefit();
1478 void refreshGPRModelFixedTheta();
1481 [[nodiscard]] bool contradictionRefitWouldBeFutile(
1482 double evidence_nats) const;
1485 void recordContradictionRefitOutcome(const Eigen::VectorXd& theta_before,
1486 double noise_before);
1487 bool refreshGPRModelFixedThetaIfObjectiveStationary();
1488 void calculateApproximatePotential(gpr::Observation& obs);
1489 void calculateApproximateVariance(gpr::Observation& obs);
1490 void logPhaseTimingSummary(double elapsed_seconds);
1491
1492 void updateLocation(const gpr::Coord orient, const gpr::Coord& middle_point,
1493 gpr::Coord& new_point);
1494
1501 bool limitTranslation(const gpr::Coord& R, gpr::LBFGSInfo& trans_info,
1502 gpr::Coord& R_new, bool* measured_boundary = nullptr);
1504 bool limitTranslationGeometry(const gpr::Coord& R,
1505 gpr::LBFGSInfo& trans_info,
1506 gpr::Coord& R_new);
1510 bool retractTranslation(const gpr::Coord& R, gpr::Coord& R_new,
1511 bool* measured_boundary = nullptr);
1513 bool retractTranslationGeometry(const gpr::Coord& R, gpr::Coord& R_new);
1514
1515 struct InterAtomicTrustDistance {
1516 double distance = std::numeric_limits<double>::infinity();
1517 double threshold = 0.0;
1518 };
1519
1520 [[nodiscard]] double shortestKernelLengthScale() const noexcept;
1521 void recordPredictedMeasuredAgreement(const gpr::Observation& predicted,
1522 const gpr::Observation& measured);
1523 [[nodiscard]] InterAtomicTrustDistance evaluateInterAtomicTrustDistance(
1524 const gpr::Coord& R_new, const gpr::Coord& R_all) const;
1525 [[nodiscard]] bool projectInterAtomicTrustBoundary(
1526 const gpr::Coord& R_current, const gpr::Coord& R_trial,
1527 const gpr::Coord& R_all, gpr::Coord& R_projected) const;
1528
1536 bool isInterAtomicDistanceTooBig(const gpr::Coord& R_new,
1537 const gpr::Coord& R_all,
1538 gpr::Index_t& num_es1);
1539
1543 gpr::Index_t getNumEvaluations();
1544
1551 void checkIfMaxIterReachedAndPrintWarning(const gpr::Index_t iter_counter,
1552 const gpr::Index_t iter_limit,
1553 const std::string& message);
1554
1563 bool checkRotationalConvergence(const gpr::Coord& orient,
1564 const gpr::Coord& orient_old,
1565 const double stop_criteria);
1566 [[nodiscard]] bool isRotationCurvatureInformative(
1567 double curvature) const noexcept;
1568 [[nodiscard]] double exactEmdDuplicateThreshold(
1569 const gpr::Coord& query) const noexcept;
1573 void defineStartPath(const gpr::Coord& R_latest_conv,
1574 const gpr::Coord& orient_latest_conv,
1575 const gpr::Coord& orient_init_gpr,
1576 const gpr::Index_t outer_iter_idx,
1577 gpr::Coord& R_previous, gpr::Coord& orient_previous,
1578 gpr::Observation& middle_point, gpr::Coord& orient);
1579
1588 void performInitialRotations(gpr::Observation& middle_point,
1589 gpr::Coord& orient,
1590 pot::PotentialWrapper& potential);
1591
1600 std::pair<double, gpr::Coord> performGPRIterations(
1601 gpr::Observation& middle_point, gpr::Coord& orient,
1602 pot::PotentialWrapper& potential);
1603
1604 // Returns curvature
1605 double performRotationAndTranslationWithGPR(
1606 const double stop_dimer_gp, gpr::Observation& middle_point,
1607 gpr::Coord& orient, gpr::Coord& R_latest_conv, gpr::Coord& R_previous,
1608 gpr::Coord& orient_latest_conv, gpr::Coord& orient_previous,
1609 gpr::Coord& R_new, gpr::Index_t& num_esmax, gpr::Index_t& num_es1,
1610 const size_t& outer_iter_idx, bool& require_midpoint_oracle,
1611 DimerSurrogateActionCertificate* first_action = nullptr,
1612 bool stop_after_first_action = false,
1613 const gpr::Observation* measured_reference = nullptr);
1614
1615 // Refreshes the mode at the fixed midpoint and returns its curvature.
1616 double performSurrogateRotation(gpr::Observation& middle_point,
1617 gpr::Observation& approx_obs,
1618 gpr::Coord& orient,
1619 gpr::LBFGSInfo& rot_info);
1620
1621 // Returns curvature
1622 double performRotationAndTranslationPure(gpr::Observation& middle_point,
1623 gpr::Observation& approx_obs,
1624 gpr::Coord& orient,
1625 gpr::Coord& R_new,
1626 gpr::LBFGSInfo& rot_info,
1627 gpr::LBFGSInfo& trans_info);
1628
1629 inline double calculateCurvature(
1630 const gpr::Coord& orient, const gpr::Observation& approx_obs,
1631 bool use_hssvd_analytic = false,
1632 double cached_hssvd_curvature =
1633 std::numeric_limits<double>::quiet_NaN());
1634
1635 inline void assignFinalResults(
1636 const gpr::Observation& middle_point,
1637 const std::pair<double, gpr::Coord>& eigen_data);
1638
1639 void writeLatticeData(gpr::Observation& middle_point);
1640
1641#ifdef WITH_HDF5
1642 void writeHDF5(const gpr::Observation& middle_point,
1643 const std::string& addl_group, const size_t& idx);
1644#endif
1645
1646 void markObservedDataChanged() noexcept
1647 {
1648 ++all_obs_revision_;
1649 optimized_all_obs_revision_ = kUnoptimizedObservationRevision;
1650 }
1651
1652 void synchronizeObservedData();
1653
1654 void reseedAttachedModelIfWarmStartInfeasible();
1658 [[nodiscard]] bool keepsAbsoluteEnergies() const noexcept;
1659 void markGPRModelOptimizedForObservedData() noexcept
1660 {
1661 optimized_all_obs_revision_ = all_obs_revision_;
1662 refit_oracle_batch_.clear();
1663 }
1664 [[nodiscard]] bool hasOptimizedCurrentObservedData() const noexcept
1665 {
1666 return optimized_all_obs_revision_ == all_obs_revision_;
1667 }
1668
1669private:
1670 static constexpr std::uint64_t kUnoptimizedObservationRevision =
1671 std::numeric_limits<std::uint64_t>::max();
1672
1676 gpr::vector3_reg cell_dimensions[3];
1677
1681 gpr::Coord orient_init;
1682
1686 gpr::Observation middle_point_init;
1687
1691 gpr::Observation image1;
1692
1696 gpr::Observation all_obs;
1698 gpr::Observation refit_oracle_batch_;
1701 bool curvature_requires_full_refit_ = false;
1706 double pending_contradiction_evidence_nats_ =
1707 std::numeric_limits<double>::quiet_NaN();
1713 double futile_refit_evidence_nats_ =
1714 std::numeric_limits<double>::quiet_NaN();
1716 double futile_refit_noise_variance_ =
1717 std::numeric_limits<double>::quiet_NaN();
1720 std::size_t last_escape_descent_calls_ = 0;
1723 std::size_t last_certificate_probe_calls_ = 0;
1727 double configured_force_criterion_ =
1728 std::numeric_limits<double>::quiet_NaN();
1731 double last_certificate_force_target_ =
1732 std::numeric_limits<double>::infinity();
1733 std::uint64_t all_obs_revision_ = 0;
1734 std::uint64_t optimized_all_obs_revision_ = kUnoptimizedObservationRevision;
1735 // Present in every build. A build without readcon-db leaves the corpus
1736 // empty; the pointer and string do not depend on USE_READCON_DB.
1737 gpr::neb::ObservationArchive* observation_archive_ = nullptr;
1738 std::unique_ptr<readcon_db::Corpus> trace_corpus_;
1739 std::string trace_con_path_;
1740
1744 gpr::Observation middle_point_final;
1745 double curvature_final;
1746 gpr::Coord orient_final;
1747 bool final_converged_ = false;
1748 double latest_mode_curvature_ = 0.0;
1751 double latest_mode_curvature_resolution_ = 0.0;
1752 // Rotational angle omega (radians) of the min-mode at the converged
1753 // midpoint, recorded alongside final_converged_. A small omega certifies
1754 // that the dimer axis is aligned with the true lowest-curvature eigenvector
1755 // (the saddle's reaction coordinate), so a flat saddle whose force sits in
1756 // the (conv_tol, 2 conv_tol) band can be accepted on the angle + negative
1757 // curvature instead of force alone. NaN until a converged phase records it.
1758 double final_rotation_omega_ = std::numeric_limits<double>::quiet_NaN();
1759 double final_rotation_residual_ = std::numeric_limits<double>::infinity();
1760 // Measured terminal rotation rounds at the current force-converged
1761 // midpoint; each expansion retains an independent physical direction.
1762 Eigen::Index measured_rotation_rounds_ = 0;
1763 // Forward Hessian actions share one midpoint, separation, and physical
1764 // space. Their Ritz vectors propose rotations; measured endpoints
1765 // supply the curvature and angle certificates.
1766 gpr::Observation measured_rotation_reference_;
1767 double measured_rotation_separation_ = 0.0;
1768 Eigen::MatrixXd measured_rotation_physical_;
1769 Eigen::MatrixXd measured_rotation_basis_;
1770 Eigen::MatrixXd measured_rotation_actions_;
1771 // The measured action has no component outside the retained subspace;
1772 // its best measured mode is passed to the independent index stencil.
1773 bool measured_rotation_stationary_ = false;
1774 // Last measured center handed to a refit; anchors the hyperparameter
1775 // subset pool of a handed-over archive.
1776 gpr::Coord hyperparameter_pool_reference_;
1777 double best_measured_rotation_residual_ =
1778 std::numeric_limits<double>::infinity();
1779 double best_measured_rotation_angle_ =
1780 std::numeric_limits<double>::quiet_NaN();
1781 double best_measured_rotation_curvature_ =
1782 std::numeric_limits<double>::quiet_NaN();
1783 gpr::Coord best_measured_orientation_;
1784 gpr::Observation best_measured_image1_;
1785
1789 gpr::Index_t N_obs_init = 0;
1790
1794 gpr::FieldMatrixd E_zero_level;
1795
1807 std::unique_ptr<gpr::GaussianProcessRegression> owned_gpr_model_;
1808 gpr::GaussianProcessRegression* gpr_model = nullptr;
1809 bool uses_external_gp_ = false;
1810 bool preserve_seed_kernel_ = false;
1811
1812 gpr::StopCriteriaForDimer stop_citeria_dimer;
1813 gpr::StopCriteriaForDimer stop_citeria_gpr;
1814 ConvergenceNormType convergence_force_norm = ConvergenceNormType::L2_NORM;
1815 bool project_rigid_modes_for_convergence_ = false;
1816 double divisor_stop_criteria_gpr;
1817
1822 double dimer_sep;
1823
1827 gpr::IterationsLimits max_iter_init_rot;
1828 bool use_gpr_initial_rotations_ = true;
1829
1830 gpr::IterationsLimits max_iter_new_pairs;
1831
1832 gpr::IterationsLimits max_iter_relax_rot;
1833
1834 bool assume_many_iterations;
1835 bool evaluate_image1_each_phase_;
1836
1842 double ratio_at_limit;
1843
1847 double actdist_fro;
1848
1853 gpr::Index_t num_bigiter_initparam;
1854
1859 gpr::Index_t num_bigiter_initloc;
1860
1864 uint8_t method_rot;
1865
1869 uint8_t method_trans;
1870
1874 struct early_stopping_t {
1879 DistanceMetricType _dist_metric;
1880
1885 double _threshold;
1886
1893 bool _use_adaptive_threshold;
1894
1904 double _adaptive_A;
1905
1915 double _adaptive_floor;
1916
1917 double _adaptive_t_min;
1918 double _adaptive_delta_explore;
1919 int _adaptive_half_life;
1920
1921 } early_params;
1922
1926 gpr::TransitionParameters transition_param;
1927
1933 gpr::Index_t start_prune_at;
1934 gpr::Index_t nprune_vals;
1935
1939 gpr::io::LogManager log_man;
1940
1944 gpr::Index_t totalIterations;
1945
1946 gpr::Index_t num_of_gen_potential_calls;
1947 // GPR surrogate call count is read from
1948 // gpr_model->getNumberOfPotentialCalls()
1949 Eigen::Index oracle_batch_chunk_ = 0;
1950
1951 bool profile_phase_timing_ = false;
1952 bool use_hssvd_analytic_curvature_ = false;
1955 bool inexact_curvature_logged_ = false;
1961 bool want_second_negative_mode_ = false;
1962 bool external_terminal_certificate_ = false;
1965 bool higher_order_restart_ = false;
1966 void retainMeasuredNegativeSubspace(const Eigen::MatrixXd& hessian,
1967 const gpr::Coord& position);
1971 bool escapeByOrderOneSaddleSession(const gpr::Observation& midpoint,
1972 pot::PotentialWrapper& potential,
1973 gpr::Observation& recovery);
1974 static rgsaddle_status_t orderOneSurface(
1975 void* user, gpr_rgsaddle_surface_request_t* request);
1978 Eigen::MatrixXd escape_hessian_;
1980 double index_frequency_resolution_ = 0.0;
1981 Eigen::Index last_negative_mode_count_ = -1;
1982 // Negative eigenpairs of the last surrogate spectrum other than the
1983 // selected mode: the rank-k correction of the nearest index-one matrix.
1984 std::vector<std::pair<double, Eigen::VectorXd>> index_one_clamped_modes_;
1989 struct SurrogateSpectrum {
1990 bool valid = false;
1991 gpr::Coord R;
1992 Eigen::VectorXd curvatures;
1993 Eigen::MatrixXd modes;
1994 Eigen::Index mode_index = -1;
1995 } surrogate_spectrum_;
2001 bool projectedTrustRegionStep(const gpr::Coord& R, const gpr::Coord& F,
2002 double radius, gpr::Coord& R_new);
2005 bool restartLocalTranslation(const gpr::Coord& R,
2006 const gpr::Coord& gradient,
2007 gpr::Coord& orientation, gpr::Coord& R_new,
2008 double& curvature);
2012 std::vector<std::pair<Eigen::VectorXd, double>>
2013 measured_negative_directions_;
2015 gpr::Coord measured_negative_reference_;
2019 Eigen::VectorXd pending_flat_direction_;
2020 double pending_flat_curvature_ = std::numeric_limits<double>::quiet_NaN();
2024 bool last_step_descends_measured_negative_ = false;
2029 void resolveFlatResidualDirection(const gpr::Observation& midpoint,
2030 const gpr::Coord& orientation,
2031 pot::PotentialWrapper& potential);
2032 // Transverse negative eigenvalues the posterior asserts beyond its own
2033 // curvature uncertainty; left in the surrogate for the index stencil.
2034 Eigen::Index last_asserted_negative_modes_ = 0;
2035 Eigen::VectorXd additional_mode_;
2038 Eigen::MatrixXd index_search_directions_;
2039 double additional_gp_curvature_ = std::numeric_limits<double>::quiet_NaN();
2045 double trial_variance_calibration_ = 1.0;
2048 std::optional<gpr::ScaleFreeTrustRegion> measured_trial_trust_;
2049 gpr::TrustRadius measured_trial_region_;
2050 gpr::Coord measured_trial_anchor_;
2051 bool limitMeasuredTrial(const gpr::Coord& current, gpr::Coord& proposed);
2052 void setMeasuredTrialAnchor(const gpr::Coord& measured);
2056 void shrinkMeasuredTrialTrust(double displacement,
2057 const gpr::Coord& accepted);
2059 int consecutive_oracle_failures_ = 0;
2062 void recordOracleTrialFailure(const std::string& what);
2066 gpr::Coord last_refused_midpoint_;
2071 gpr::Coord measured_index_zero_midpoint_;
2072 Eigen::MatrixXd measured_index_zero_hessian_;
2074 double measured_index_zero_resolution_ = 0.0;
2075 double last_trial_force_variance_ =
2076 std::numeric_limits<double>::quiet_NaN();
2077 double model_force_error_ = std::numeric_limits<double>::quiet_NaN();
2078 double model_force_scale_ = std::numeric_limits<double>::quiet_NaN();
2079 double model_energy_error_ = std::numeric_limits<double>::quiet_NaN();
2080 double model_energy_scale_ = std::numeric_limits<double>::quiet_NaN();
2085 bool uncertainty_aware_rotation_ = false;
2086 double kappa_dimer_beta_ = 0.0;
2087 bool kappa_dimer_refining_ = false;
2088 std::unique_ptr<gpr::neb::RgsaddleClient> kappa_dimer_client_;
2089 // Owned rgmin translation session. A pointer keeps the public layout
2090 // stable.
2091 std::unique_ptr<gpr::optim::RgminStep> rgmin_trans_;
2092 HssvdModeSelectionPolicy hssvd_mode_selection_policy_ =
2094 double accurate_potential_seconds_ = 0.0;
2095 double gp_optimize_seconds_ = 0.0;
2096 double gp_predict_seconds_ = 0.0;
2097 double gp_predict_mean_seconds_ = 0.0;
2098 double gp_predict_variance_seconds_ = 0.0;
2099 // Mode timing covers surrogate Hessian preparation and mode extraction.
2100 double gp_mode_seconds_ = 0.0;
2101 double gp_fixed_theta_refresh_seconds_ = 0.0;
2102 gpr::Index_t accurate_potential_calls_ = 0;
2103 gpr::Index_t gp_optimize_calls_ = 0;
2104 gpr::Index_t gp_predict_calls_ = 0;
2105 gpr::Index_t gp_predict_mean_calls_ = 0;
2106 gpr::Index_t gp_predict_variance_calls_ = 0;
2107 gpr::Index_t gp_mode_calls_ = 0;
2108
2109 // Active-frozen-set instrumentation (the CuH2-step failure-mode
2110 // demonstrator): how many times activateFrozenAtoms grew the active
2111 // frozen set (each growth forces a full GPR refresh + optimiser-history
2112 // reset -> the stale-history / bloat stressor) and the latest active
2113 // frozen-atom count. Logged in the phase-timing summary; zero-cost when
2114 // profile_phase_timing_ is off.
2115 gpr::Index_t active_set_change_count_ = 0;
2116 gpr::Index_t active_frozen_count_ = 0;
2117
2118 // Variance-gated acquisition: when GPR posterior variance at the
2119 // query point drops below `config_.accept_tau`, skip the accurate
2120 // potential evaluation and trust the GP prediction. A zero or
2121 // negative `accept_tau` disables the gate entirely (preserves the
2122 // MAP default behaviour). The LAPLACE path provides a calibrated
2123 // posterior variance that accounts for hyperparameter uncertainty;
2124 // MAP provides the point-estimate variance.
2125public:
2131 double accept_tau = 0.0;
2132
2144
2158
2167
2174 };
2175
2177 {
2178 variance_gate_ = cfg;
2179 }
2181 const noexcept
2182 {
2183 return variance_gate_;
2184 }
2185
2189 void setVarianceAcceptTau(double tau) noexcept
2190 {
2191 variance_gate_.accept_tau = tau;
2192 }
2193
2194#ifdef USE_READCON_DB
2200 void setObservationArchive(gpr::neb::ObservationArchive* archive) noexcept
2201 {
2202 observation_archive_ = archive;
2203 }
2204
2207 void setTraceCorpus(const std::string& db_path);
2208 [[nodiscard]] readcon_db::Corpus* traceCorpus() const noexcept
2209 {
2210 return trace_corpus_.get();
2211 }
2212#endif
2213
2218 void writeTraceFrame(const gpr::Observation& obs, const std::string& phase,
2219 size_t idx);
2220
2223 void archiveObservations(const gpr::Observation& obs) noexcept
2224 {
2225#ifdef USE_READCON_DB
2226 if (!observation_archive_) return;
2227 for (Eigen::Index row = 0; row < obs.R.rows(); ++row) {
2228 if (row >= obs.E.rows() || row >= obs.G.rows()) break;
2229 const Eigen::VectorXd positions = obs.R.row(row).transpose();
2230 const Eigen::VectorXd gradient = obs.G.row(row).transpose();
2231 (void)observation_archive_->append(positions, obs.E(row, 0),
2232 gradient);
2233 }
2234#else
2235 (void)obs;
2236#endif
2237 }
2238 [[nodiscard]] double getVarianceAcceptTau() const noexcept
2239 {
2240 return variance_gate_.accept_tau;
2241 }
2242
2248 void setVarianceAcceptTauRelative(double tau_relative) noexcept
2249 {
2250 variance_gate_.accept_tau_relative = tau_relative;
2251 }
2252 [[nodiscard]] double getVarianceAcceptTauRelative() const noexcept
2253 {
2254 return variance_gate_.accept_tau_relative;
2255 }
2256 [[nodiscard]] gpr::Index_t getVarianceSkippedAccurateCalls() const noexcept
2257 {
2258 return variance_skipped_accurate_calls_;
2259 }
2260 [[nodiscard]] gpr::Index_t getImspeSoftSkippedCalls() const noexcept
2261 {
2262 return imspe_soft_skipped_calls_;
2263 }
2264 [[nodiscard]] gpr::Index_t getImspeFixedThetaRefreshCalls() const noexcept
2265 {
2266 return fixed_theta_refresh_calls_;
2267 }
2268 [[nodiscard]] gpr::Index_t getFixedThetaRefreshCalls() const noexcept
2269 {
2270 return fixed_theta_refresh_calls_;
2271 }
2273 const noexcept
2274 {
2275 return imspe_admitted_near_duplicate_observations_;
2276 }
2277
2281 [[nodiscard]] gpr::Index_t getDedupRejectedObservations() const noexcept
2282 {
2283 return dedup_rejected_observations_;
2284 }
2285
2290 void setAlignmentAbortTol(double tol) noexcept
2291 {
2292 alignment_abort_tol_ = tol;
2293 }
2294
2301 void setAbortOnDegenerateProbes(bool enabled) noexcept
2302 {
2303 abort_on_degenerate_probes_ = enabled;
2304 }
2305
2309 void setMaxOracleCalls(gpr::Index_t calls) noexcept
2310 {
2311 max_oracle_calls_ = calls;
2312 }
2313 [[nodiscard]] gpr::Index_t maxOracleCalls() const noexcept
2314 {
2315 return max_oracle_calls_;
2316 }
2317
2322 void setIndexFrequencyResolution(double wavenumber) noexcept
2323 {
2324 index_frequency_resolution_ = wavenumber;
2325 }
2326 [[nodiscard]] double indexFrequencyResolution() const noexcept
2327 {
2328 return index_frequency_resolution_;
2329 }
2330
2332 {
2333 want_second_negative_mode_ = enabled;
2334 }
2335 [[nodiscard]] bool measuredIndexRecoveryEnabled() const noexcept
2336 {
2337 return want_second_negative_mode_ &&
2338 (!external_terminal_certificate_ || higher_order_restart_);
2339 }
2340
2343 void setExternalTerminalCertificate(bool enabled) noexcept
2344 {
2345 external_terminal_certificate_ = enabled;
2346 }
2347 [[nodiscard]] Eigen::Index lastNegativeModeCount() const noexcept
2348 {
2349 return last_negative_mode_count_;
2350 }
2351
2357 void setMeasuredEnergyCeiling(double ceiling) noexcept
2358 {
2359 measured_energy_ceiling_ = ceiling;
2360 }
2361
2365 void setSaddleEnergyFloor(double floor) noexcept
2366 {
2367 saddle_energy_floor_ = floor;
2368 }
2369
2371 [[nodiscard]] bool lastRefinementReachedIndexOne() const noexcept
2372 {
2373 return last_refinement_reached_index_one_;
2374 }
2375
2382 void setAbortOnInteratomicCollapse(bool enabled) noexcept
2383 {
2384 abort_on_interatomic_collapse_ = enabled;
2385 }
2386
2391 void setPreserveInitialAlignmentReference(bool enabled) noexcept
2392 {
2393 preserve_initial_alignment_reference_ = enabled;
2394 }
2395
2403 void setLikelihoodNoiseFloorSigma2(double floor_sigma2) noexcept
2404 {
2405 likelihood_noise_floor_sigma2_ = floor_sigma2;
2406 }
2407
2413 {
2414 self_owned_model_profile_ = profile;
2415 }
2416
2419 void setSelfOwnedUseZblPriorMean(bool use) noexcept
2420 {
2421 self_owned_use_zbl_prior_mean_ = use;
2422 }
2423 void setSelfOwnedUseFfPriorMean(bool use) noexcept
2424 {
2425 self_owned_use_ff_prior_mean_ = use;
2426 }
2427 [[nodiscard]] double getAlignmentAbortTol() const noexcept
2428 {
2429 return alignment_abort_tol_;
2430 }
2431
2440 void setLeashRelaxWhenClose(bool enabled) noexcept
2441 {
2442 leash_relax_when_close_ = enabled;
2443 }
2444 [[nodiscard]] bool getLeashRelaxWhenClose() const noexcept
2445 {
2446 return leash_relax_when_close_;
2447 }
2448 void setEvaluateImage1EachPhase(bool enabled) noexcept
2449 {
2450 evaluate_image1_each_phase_ = enabled;
2451 }
2452 [[nodiscard]] bool getEvaluateImage1EachPhase() const noexcept
2453 {
2454 return evaluate_image1_each_phase_;
2455 }
2456 void setConvergenceForceNorm(int norm_type) noexcept
2457 {
2458 convergence_force_norm = static_cast<ConvergenceNormType>(norm_type);
2459 }
2460 void setProjectRigidModesForConvergence(bool enabled) noexcept
2461 {
2462 project_rigid_modes_for_convergence_ = enabled;
2463 }
2464
2468 void setOracleBatchChunk(Eigen::Index chunk) noexcept
2469 {
2470 oracle_batch_chunk_ = chunk < 0 ? 0 : chunk;
2471 }
2472 [[nodiscard]] Eigen::Index getOracleBatchChunk() const noexcept
2473 {
2474 return oracle_batch_chunk_;
2475 }
2476
2477 void setProfilePhaseTiming(bool enabled) noexcept
2478 {
2479 profile_phase_timing_ = enabled;
2480 }
2481 [[nodiscard]] bool getProfilePhaseTiming() const noexcept
2482 {
2483 return profile_phase_timing_;
2484 }
2485 void setProfileDimerTimes(bool enabled) noexcept
2486 {
2487 setProfilePhaseTiming(enabled);
2488 }
2489 [[nodiscard]] bool getProfileDimerTimes() const noexcept
2490 {
2491 return getProfilePhaseTiming();
2492 }
2493 void setUseHssvdAnalyticCurvature(bool enabled) noexcept
2494 {
2495 use_hssvd_analytic_curvature_ = enabled;
2496 }
2497 [[nodiscard]] bool getUseHssvdAnalyticCurvature() const noexcept
2498 {
2499 return use_hssvd_analytic_curvature_;
2500 }
2502 {
2503 hssvd_mode_selection_policy_ = policy;
2504 }
2505 // Active-frozen-set instrumentation accessors (CuH2-step demonstrator).
2506 [[nodiscard]] gpr::Index_t activeSetChangeCount() const noexcept
2507 {
2508 return active_set_change_count_;
2509 }
2510 [[nodiscard]] gpr::Index_t activeFrozenCount() const noexcept
2511 {
2512 return active_frozen_count_;
2513 }
2514 void setHdf5TracePath(const std::string& path)
2515 {
2516 hdf5_trace_path_ = path;
2517 }
2518
2521 void setUncertaintyAwareRotation(bool enabled) noexcept
2522 {
2523 uncertainty_aware_rotation_ = enabled;
2524 }
2525
2529 void setProjectMeasuredRotations(bool enabled) noexcept
2530 {
2531 project_measured_rotations_ = enabled;
2532 }
2533
2536 void setKappaDimer(double beta);
2537 [[nodiscard]] double kappaDimerBeta() const noexcept
2538 {
2539 return kappa_dimer_beta_;
2540 }
2541
2542 [[nodiscard]] const std::string& getHdf5TracePath() const noexcept
2543 {
2544 return hdf5_trace_path_;
2545 }
2546 // The per-iteration dimer trace is a debug artifact; OFF by default so
2547 // benchmark/production runs never write a shared gpridge_out.h5 that
2548 // concurrent ranks or successive runs collide on. Setting a path via
2549 // the CLI enables it.
2550 void setHdf5TraceEnabled(bool enabled)
2551 {
2552 hdf5_trace_enabled_ = enabled;
2553 }
2554 [[nodiscard]] bool hdf5TraceEnabled() const noexcept
2555 {
2556 return hdf5_trace_enabled_;
2557 }
2558
2559private:
2560 struct LocalPotentialReference {
2561 const gpr::Observation* measured = nullptr;
2562 gpr::Observation prediction;
2563 std::uint64_t factor_epoch = std::numeric_limits<std::uint64_t>::max();
2564 };
2565 bool hdf5_trace_enabled_ = false;
2566 bool project_measured_rotations_ = true;
2567 std::string hdf5_trace_path_ = "gpridge_out.h5";
2568 VarianceGateConfig variance_gate_{};
2569 const gpr::policy::TrainingPolicy* training_policy_ = nullptr;
2570 std::shared_ptr<const gpr::policy::TrainingPolicy> training_policy_owner_;
2571 std::uint64_t policy_retained_all_obs_revision_ =
2572 kUnoptimizedObservationRevision;
2573 const gpr::policy::TrainingPolicy* policy_retained_owner_ = nullptr;
2574 bool policy_admission_passthrough_ = false;
2575 std::vector<DimerPhaseRecord> phase_history_;
2576 DimerSurrogateActionCertificate first_surrogate_action_;
2577 DimerRelaxationTerminationReason relaxation_termination_reason_ =
2579 double likelihood_noise_floor_sigma2_ =
2580 std::numeric_limits<double>::quiet_NaN();
2581 gpr::GPModelProfile self_owned_model_profile_ =
2583 bool self_owned_use_zbl_prior_mean_ = false;
2584 bool self_owned_use_ff_prior_mean_ = false;
2585 double alignment_abort_tol_ = 0.0;
2586 bool abort_on_degenerate_probes_ = false;
2587 gpr::Index_t max_oracle_calls_ = 0;
2588 std::shared_ptr<const gpr::WallClockLimit> wall_clock_limit_;
2589 double force_stop_certificate_step_ = gpr::optim::defaultStencilStep();
2590 gpr::optim::VibrationalStencil vibrational_stencil_ =
2592 bool force_stop_certified_ = false;
2593 int force_stop_certificate_calls_ = 0;
2594 gpr::Observation budget_stop_midpoint_;
2595 gpr::Coord budget_stop_orientation_;
2596 bool oracle_budget_unwinds_ = false;
2597 bool abort_on_interatomic_collapse_ = false;
2598 bool converged_above_energy_ceiling_ = false;
2599 double seed_min_interatomic_ = std::numeric_limits<double>::quiet_NaN();
2604 gpr::Coord contact_reference_geometries_;
2607 void recordContactReferences(const gpr::Observation& middle_point);
2610 [[nodiscard]] std::vector<int> contactDomainAtomicNumbers(
2611 Eigen::Index moving_count, Eigen::Index frozen_active_count) const;
2612 double measured_energy_ceiling_ = std::numeric_limits<double>::quiet_NaN();
2613 double saddle_energy_floor_ = std::numeric_limits<double>::quiet_NaN();
2614 bool last_refinement_reached_index_one_ = false;
2615 bool preserve_initial_alignment_reference_ = false;
2616 bool leash_relax_when_close_ = false;
2617 gpr::Index_t variance_skipped_accurate_calls_ = 0;
2618 gpr::Index_t imspe_soft_skipped_calls_ = 0;
2619 gpr::Index_t fixed_theta_refresh_calls_ = 0;
2620 gpr::Index_t imspe_admitted_near_duplicate_observations_ = 0;
2621 // EMD-filtered ring buffer of recent dimer GP-query points. The
2622 // IMSPE soft-skip predicate scores a candidate against this set:
2623 // a low score means oracling the candidate would not collapse
2624 // summed posterior variance over the dimer's recent novel
2625 // exploration neighborhood, so the dimer can fall back to the GP
2626 // mean without losing information.
2627 Eigen::MatrixXd imspe_query_history_;
2628 int imspe_query_history_count_ = 0;
2629 int imspe_query_history_head_ = 0;
2630 // Returns true if R_query should be soft-skipped. The candidate is
2631 // judged against the same local IMSPE stencil used by observation
2632 // admission, keeping oracle scheduling and training-set admission
2633 // coupled to the same information criterion.
2634 [[nodiscard]] bool maybeSoftSkipViaImspe(const gpr::Coord& R_query);
2635 void recordImspeQueryHistory(const gpr::Coord& R_query);
2636 [[nodiscard]] bool computeImspeAdmissionScore(const gpr::Coord& R_query,
2637 double& score,
2638 double& relative_gain,
2639 bool allow_hssvd_local);
2640 [[nodiscard]] bool shouldSkipOracleByImspeAdmission(
2641 const gpr::Coord& R_query);
2642 [[nodiscard]] bool shouldSkipMidpointOracleByEmdNear(
2643 const gpr::Observation& obs);
2644 [[nodiscard]] double forceNormForConvergence(
2645 const Eigen::Ref<const Eigen::RowVectorXd>& gradient) const;
2646 [[nodiscard]] double forceNormForConvergence(
2647 const Eigen::Ref<const Eigen::RowVectorXd>& positions,
2648 const Eigen::Ref<const Eigen::RowVectorXd>& gradient) const;
2649 [[nodiscard]] double forceNormForConvergence(
2650 const gpr::Observation& obs) const;
2651 [[nodiscard]] double surrogateForceTolerance(
2652 const gpr::Observation& oracle_middle_point) const;
2653 [[nodiscard]] double bestObservedForceNorm() const;
2654 // Reusable scratch observation for the variance probe inside
2655 // maybeSkipAccurateViaVariance. Keeping it as a member avoids
2656 // per-call heap allocations for the probe's R / E / G buffers on
2657 // the hot dimer path.
2658 gpr::Observation variance_probe_scratch_;
2659
2660 // EMD near-duplicate rejection at the all_obs entry point.
2661 //
2662 // A burst-phase oracle evaluation whose EMD distance
2663 // (aux::Distance::dist_emd, the same metric the early-stop trust
2664 // region uses) to its nearest existing observation is below
2665 // emd_dedup_threshold_ is NOT appended to all_obs: a near-coincident
2666 // row adds no conditioning information and drives the GP covariance
2667 // toward rank deficiency, which is what makes per-burst SCG
2668 // hyperparameter optimisation diverge.
2669 //
2670 // The threshold is the dimer finite-difference stencil diameter. A
2671 // midpoint query inside the stencil is a re-sampling of the local dimer
2672 // region rather than a distinct training location; the structural
2673 // image-1 companion bypasses this midpoint filter by construction.
2674 double emd_dedup_threshold_ = 0.0;
2681 [[nodiscard]] double effectiveEmdDedupThreshold() const;
2682 [[nodiscard]] double initialRotationStopCriterion() const;
2683 gpr::Index_t dedup_rejected_observations_ = 0;
2684 // Consecutive EMD-degenerate (deduped) burst probes. Reset to zero
2685 // whenever a probe contributes a distinct row. When it reaches
2686 // kMaxConsecutiveDegenerateProbes the burst is re-probing one region
2687 // without gathering new data ("GP uncertain / nothing to learn
2688 // here"); performGPRIterations then aborts the burst early and hands
2689 // control back to the NEB, alongside the alignment / positive-
2690 // curvature handback criteria.
2691 static constexpr gpr::Index_t kMaxConsecutiveDegenerateProbes = 3;
2692 gpr::Index_t consecutive_degenerate_probes_ = 0;
2700 Eigen::VectorXd last_nonterminal_certificate_r_;
2701 bool certificate_fixed_point_ = false;
2702
2703 // Consecutive burst phases whose GP-surrogate rotation ended without
2704 // a finite negative-curvature mode. The dimer rotation force is a finite
2705 // difference of the
2706 // GP gradient across the dimer separation; it vanishes on a flat or
2707 // over-smoothed surrogate, so the rotation "converges"
2708 // (omega < T_anglerot) onto whatever axis it started with without
2709 // ever rotating. A non-negative GP curvature is the signature of
2710 // that dead surrogate. Each such phase spends one true image-1
2711 // evaluation (the AtomicGPDimer interleave) to inject a real
2712 // curvature sample; the new off-axis gradient observation also
2713 // steers SCG away from the degenerate hyperparameters that produced
2714 // the flat surrogate. When the count reaches
2715 // kMaxUninformativeRotations the true samples have still failed to
2716 // expose a mode -- the dimer cannot resolve a saddle direction here;
2717 // the burst is handed back to the NEB alongside the degenerate-probe
2718 // and alignment criteria.
2719 static constexpr gpr::Index_t kMaxUninformativeRotations = 3;
2720 gpr::Index_t consecutive_uninformative_rotations_ = 0;
2721
2722 // Append `obs` to all_obs when it is EMD-distinct, or when the local
2723 // IMSPE stencil says an EMD-near row still reduces posterior
2724 // uncertainty by more than the observation-noise floor.
2725 bool appendObservationIfInformative(const gpr::Observation& obs);
2726 bool policySuppressesAccurateCall(const gpr::Observation& obs,
2727 DimerOracleProbeRole role);
2728 bool policyRetainObservations();
2729 bool coalesceObservationIntoNearestEmdRepresentative(
2730 const gpr::Observation& obs);
2731 // Append an accurate midpoint witness only when its true force is
2732 // terminal. A nonterminal EMD-near witness updates the nearest
2733 // dictionary representative in place, so the GP sees the certificate
2734 // residual without adding a rank-poor row.
2735 void appendConvergenceCertificateObservation(const gpr::Observation& obs);
2736
2737 [[nodiscard]] bool shouldAbortDegenerateProbeBurst() const noexcept
2738 {
2739 return (alignment_abort_tol_ > 0.0 || abort_on_degenerate_probes_) &&
2740 consecutive_degenerate_probes_ >=
2741 kMaxConsecutiveDegenerateProbes;
2742 }
2743 [[nodiscard]] bool searchStalledOnDegenerateProbes() const noexcept
2744 {
2745 return dimerSearchStalled(consecutive_degenerate_probes_);
2746 }
2747 [[nodiscard]] bool oracleBudgetSpent() noexcept
2748 {
2749 return max_oracle_calls_ > 0 &&
2750 getNumEvaluations() >= max_oracle_calls_;
2751 }
2756 bool requireOracleBudget(Eigen::Index rows);
2757 void requireWallClock() const
2758 {
2759 if (gpr::collectiveWallClockLimitReached(wall_clock_limit_))
2760 throw gpr::WallClockLimitReached{};
2761 }
2764 void certifyExecuteForceStop(pot::PotentialWrapper& potential);
2765 [[nodiscard]] bool shouldProbeImage1ForDegenerateMidpoint() const noexcept
2766 {
2767 return !evaluate_image1_each_phase_ &&
2768 consecutive_degenerate_probes_ >=
2769 kMaxConsecutiveDegenerateProbes;
2770 }
2771
2772 // Auxiliary counter
2773 gpr::Index_t file_counter = 0;
2774 gpr::EnergySurfaceOutputInfo debug_output_info;
2775 gpr::Index_t debug_level;
2779 Eigen::MatrixXd last_certificate_hessian_;
2781 gpr::Coord last_certificate_positions_;
2782 // A local affine correction matches the measured energy and gradient
2783 // while preserving the posterior Hessian and covariance.
2784 LocalPotentialReference* local_potential_reference_ = nullptr;
2785 gpr::optim::SecantHessianConfig secant_config_;
2786 gpr::optim::SecantHessian secant_hessian_;
2787 std::vector<gpr::optim::SecantForceSample> secant_force_samples_;
2788 gpr::optim::SecantCurvatureCounts secant_counts_;
2789 std::size_t secant_pairs_checked_ = 0;
2790 bool secant_probe_in_progress_ = false;
2791 bool secant_orientation_seed_ = true;
2792 void syncSecantQuadraticPrior();
2795 void recordTrueForceSecant(const gpr::Observation& observation,
2796 gpr::optim::SecantAccounting accounting =
2798 void rememberSecantForceSample(const Eigen::VectorXd& position,
2799 const Eigen::VectorXd& gradient,
2800 double energy);
2801 [[nodiscard]] Eigen::VectorXd secantQuadraticHessianAction(
2802 const Eigen::VectorXd& direction) const;
2803 void purchaseSecantConsistency(pot::PotentialWrapper& potential);
2804 void seedOrientationFromSecant(gpr::Coord& orient) const;
2805};
2806
2807} /* namespace atmd */
2808
2809#include "AtomicDimer.inl" // inline getters/setters only
2810
2811#endif /* GPR_GPR_H_ */
ConvergenceNormType
Definition Enums.h:48
DistanceMetricType
Definition Enums.h:46
Dimensionless, self-tuning trust region for GP-accelerated NEB.
Decisions a search asks before it calls the oracle, admits a row, refits hyperparameters,...
Trust radius for GP surrogate validity.
double getAlignmentAbortTol() const noexcept
void initialize(const gpr::InputParameters &parameters, const gpr::Observation &initial_data, const gpr::Observation &middle_point, const gpr::Coord &initial_orientation, const gpr::AtomsConfiguration &init_atom_config)
Initilalize with initial data.
void setVarianceGateConfig(const VarianceGateConfig &cfg) noexcept
gpr::optim::SecantCurvatureCounts secantCounts() const
bool lastRefinementReachedIndexOne() const noexcept
gpr::Index_t getImspeFixedThetaRefreshCalls() const noexcept
bool restartAlongWeakMode(const Eigen::VectorXd &direction, double length, const gpr::Observation &measured_rows, pot::PotentialWrapper &potential)
const DimerSurrogateActionCertificate & getFirstSurrogateActionCertificate() const noexcept
void setWallClockLimit(std::shared_ptr< const gpr::WallClockLimit > limit)
Share an enclosing deadline (used by OCI-NEB and deterministic tests).
bool isApproximateRotationalConvergenceReached(const gpr::Coord &orient, const gpr::Observation &approx_obs, const double stop_criteria)
GP-stencil rotational convergence test.
void setProjectMeasuredRotations(bool enabled) noexcept
const gpr::Observation & finalMidpoint() const noexcept
Midpoint recorded at the end of execute().
void translateDimer(const gpr::Observation &middle_point, const gpr::Coord &orient, const gpr::Observation &approx_obs, const double curvature, gpr::LBFGSInfo &trans_info, gpr::Coord &R_new)
Translate the dimer.
bool getEvaluateImage1EachPhase() const noexcept
void refineMeasuredModeCurvature(const gpr::Observation &midpoint, const gpr::Coord &orientation, pot::PotentialWrapper &potential, double surrogate_curvature)
double indexFrequencyResolution() const noexcept
const gpr::optim::SecantHessian & secantHessian() const noexcept
const std::string & getHdf5TracePath() const noexcept
const VarianceGateConfig & getVarianceGateConfig() const noexcept
gpr::GaussianProcessRegression * getGPRModel()
Get GPR model.
bool getUseHssvdAnalyticCurvature() const noexcept
void setExternalTerminalCertificate(bool enabled) noexcept
Eigen::Index lastNegativeModeCount() const noexcept
double getFinalRotationResidual() const noexcept
Eigen::VectorXd getFinalCoordOfMidPoint() const
Return final coordinates of the middle point.
void setAtomsConfiguration(const gpr::AtomsConfiguration &_atoms_config)
Set configuration of the atoms.
bool commitExternallyCertifiedRefinement(const gpr::Observation &raw_center, const Eigen::MatrixXd &certified_cartesian_hessian, const Eigen::MatrixXd &certified_mass_weighted_basis, bool first_order_certificate)
void archiveObservations(const gpr::Observation &obs) noexcept
bool measuredIndexRecoveryEnabled() const noexcept
bool rotateDimer(const double stop_criteria, gpr::Coord &orient, gpr::LBFGSInfo &rot_info, gpr::Observation &middle_point, gpr::Observation &approx_obs)
Rotate the dimer.
bool restartFromHigherOrderPoint(const Eigen::MatrixXd &cartesian_hessian, const Eigen::VectorXd &kick, const gpr::Observation &measured_rows, pot::PotentialWrapper &potential)
gpr::optim::SecantCurvatureCounts secantLedger() const noexcept
Pair, probe and rejection counts, without the GP's quadratic-mean uses.
bool hasUnconditionedObservations() const noexcept
bool wallClockLimitReached() const
bool hdf5TraceEnabled() const noexcept
bool isMinModeAngleCertified() const noexcept
True iff the converged min-mode is angle-certified: a converged phase recorded a finite rotation omeg...
gpr::Index_t getImspeAdmittedNearDuplicateObservations() const noexcept
gpr::Index_t activeSetChangeCount() const noexcept
void setProfilePhaseTiming(bool enabled) noexcept
Eigen::MatrixXd gpMeanHessianAtMidpoint()
void setForceStopCertificateStep(double step) noexcept
void setEvaluateImage1EachPhase(bool enabled) noexcept
gpr::Index_t getNumNewObservations() const
Number of accurate (general-potential) observations the dimer accumulated during ~execute~....
bool hasValidAtomsConfiguration()
Whether the atoms configuration holds the moving-atom set that execute() needs.
gpr::Coord & getGradientForAllObservationPointsRef()
Return gradients for all observed points.
void setAlignmentAbortTol(double tol) noexcept
gpr::Index_t getImspeSoftSkippedCalls() const noexcept
void setSecantOrientationSeed(bool enabled) noexcept
gpr::Index_t getTotalGPRForceCalls() const
Return the total number of force calls.
bool getLeashRelaxWhenClose() const noexcept
gpr::AtomsConfiguration atoms_config
void setOracleBatchChunk(Eigen::Index chunk) noexcept
gpr::Index_t getFixedThetaRefreshCalls() const noexcept
void setSelfOwnedUseFfPriorMean(bool use) noexcept
void setLikelihoodNoiseFloorSigma2(double floor_sigma2) noexcept
void writeTraceFrame(const gpr::Observation &obs, const std::string &phase, size_t idx)
bool terminalModeIsReady() const noexcept
gpr::FieldMatrixd & getEnergyForAllObservationPointsRef()
Return energies for all observed points.
void setUseHssvdAnalyticCurvature(bool enabled) noexcept
void setHdf5TraceEnabled(bool enabled)
void setConvergenceForceNorm(int norm_type) noexcept
double getMaxStepLength() const
The bound of one translation step in Cartesian length (Angstrom).
bool measureCurvatureProbes(const gpr::Coord &positions, pot::PotentialWrapper &potential, gpr::Observation &raw)
Eigen::VectorXd getFinalGradientAtMidPoint() const
Return the final gradient dE/dR at the middle point.
double getMeasuredIndexZeroResolution() const
void setUncertaintyAwareRotation(bool enabled) noexcept
double convergenceForceNorm(const Eigen::Ref< const Eigen::RowVectorXd > &positions, const Eigen::Ref< const Eigen::RowVectorXd > &gradient) const
gradient in the norm the convergence test applies at positions.
const gpr::Coord & getFinalOrientation() const
Return final orientation of the dimer.
void setPreserveInitialAlignmentReference(bool enabled) noexcept
gpr::Index_t getInitialObservationCount() const
Index of the first row in ~all_obs~ that the dimer appended during ~execute~. Pair with ~getNumNewObs...
void setKappaDimer(double beta)
void setHssvdModeSelectionPolicy(HssvdModeSelectionPolicy policy) noexcept
void setTrainingPolicy(const gpr::policy::TrainingPolicy *policy)
Not owned. The pointer must outlive execute(). Null is the engine.
gpr::FieldMatrixd getEnergyZeroLevel() const
Internal E_zero_level used by the dimer's cutOffEnergy bookkeeping. The energies returned by ~getEner...
void setVarianceAcceptTau(double tau) noexcept
void setHdf5TracePath(const std::string &path)
bool certifyStoppedForce(pot::PotentialWrapper &potential, double step, int &calls)
void setMaxOracleCalls(gpr::Index_t calls) noexcept
DimerSurrogateActionCertificate previewFirstSurrogateAction(const gpr::Observation &oracle_middle_point, const gpr::Coord &initial_orientation)
double getVarianceAcceptTauRelative() const noexcept
gpr::Index_t getTotalForceCalls() const
Return the total number of force calls.
void setConvergenceForce(double force)
Replace the configured true-PES force criterion and the live stop.
void setSelfOwnedUseZblPriorMean(bool use) noexcept
double getFinalForceNormForConvergence() const
Return final force in the configured convergence norm.
void attachExternalGP(gpr::GaussianProcessRegression *external_gp) noexcept
Attach an externally-owned GPR model. Must be called BEFORE ~initialize~. The dimer will use this GP ...
bool isFinalConvergenceReached(const gpr::Observation &middle_point, const double stop_criteria)
Final convergence test for force.
void setVarianceAcceptTauRelative(double tau_relative) noexcept
Eigen::Index getOracleBatchChunk() const noexcept
void setVibrationalStencil(gpr::optim::VibrationalStencil mode) noexcept
double getFinalEnergy() const
Return final energy.
void setMeasuredEnergyCeiling(double ceiling) noexcept
double kappaDimerBeta() const noexcept
gpr::optim::VibrationalStencil vibrationalStencil() const noexcept
bool getForceStopCertified() const noexcept
Whether the last execute() certified its force stop as index one.
Eigen::VectorXd getFinalForceAtMidPoint() const
Deprecated alias of getFinalGradientAtMidPoint().
gpr::Index_t maxOracleCalls() const noexcept
void callGeneralPotentialFromEON(const gpr::vector3_reg(&cell_dimensions)[3], gpr::Observation &mid_point, pot::PotentialWrapper &potential)
Call for a potential defined in a Matter object.
void setAbortOnDegenerateProbes(bool enabled) noexcept
void preserveSeedKernel() noexcept
Retain an imported kernel's parameters and absolute energy origin.
int getForceStopCertificateCalls() const noexcept
bool refineSaddleFromMeasuredHessian(const Eigen::MatrixXd &cartesian_hessian, pot::PotentialWrapper &potential, double resolution=0.0)
void setSecantHessianConfig(const gpr::optim::SecantHessianConfig &config)
Replace the true-force secant and drop its history.
void setRejectHigherIndexSurrogateConvergence(bool enabled) noexcept
See want_second_negative_mode_.
gpr::Index_t getVarianceSkippedAccurateCalls() const noexcept
DimerRelaxationTerminationReason getRelaxationTerminationReason() const noexcept
void setProjectRigidModesForConvergence(bool enabled) noexcept
void setIndexFrequencyResolution(double wavenumber) noexcept
double getFinalRotationAngle() const noexcept
Min-mode rotational angle omega (radians) at the converged midpoint, or NaN if no converged phase rec...
double getFinalCurvature() const
Return final curvature.
void setSelfOwnedModelProfile(gpr::GPModelProfile profile) noexcept
gpr::Index_t activeFrozenCount() const noexcept
bool getProfilePhaseTiming() const noexcept
double getVarianceAcceptTau() const noexcept
bool getConverged() const
Return true when the final force convergence criterion is met.
void setSaddleEnergyFloor(double floor) noexcept
AtomicDimer()
Default constructor.
gpr::Coord & getMidPointCoordForAllObservationPointsRef()
Return gpr::Coordinates of all observed points.
bool getProfileDimerTimes() const noexcept
const std::vector< DimerPhaseRecord > & getPhaseHistory() const noexcept
Return the per-phase dimer trajectory history.
void execute(pot::PotentialWrapper &general_potential)
This function uses the atomic GP-dimer method to converge to a saddle point, starting from somewhere ...
void setMaxWallSeconds(double seconds)
Set a wall-clock cap measured from this call. Non-positive disables.
bool measuredModeIsCertified() const noexcept
double getConvergenceForce() const noexcept
Force norm below which the dimer search is converged.
Eigen::MatrixXd getMeasuredIndexZeroHessian() const
void setProfileDimerTimes(bool enabled) noexcept
gpr::Index_t getIterations() const
Return the total number of cycles.
bool updateActiveFrozenAtoms(const gpr::Coord &R_new, gpr::LBFGSInfo &rot_info, gpr::LBFGSInfo &trans_info)
Update active frozen atoms.
gpr::Index_t getDedupRejectedObservations() const noexcept
void setLeashRelaxWhenClose(bool enabled) noexcept
void setAbortOnInteratomicCollapse(bool enabled) noexcept
double getLatestModeCurvature() const noexcept
Latest min-mode curvature from a dimer rotation. The force-stop stencil records the returned curvatur...
bool isRotationalConvergenceReached(const gpr::Coord &orient, gpr::Observation &middle_point)
Rotational convergence test.
double forceStopCertificateStep() const noexcept
OracleBudgetExhausted(std::string message)
const char * what() const noexcept override
Type-erased wrapper around any potential that provides a force() interface.
eon_relax_band_t eon_relax_surface_fn void * user
The atomic dimer search (class AtomicDimer) and its status types.
bool dimerSearchStalled(gpr::Index_t consecutive_degenerate_probes) noexcept
DimerRelaxationBacktrackResult backtrackDimerRelaxationForResidualDecrease(const gpr::Coord &current, const gpr::Coord &proposed, double current_residual, const std::function< double(const gpr::Coord &)> &evaluate_residual)
void writeDimerCampaignSummary(std::ostream &os, double energy, bool converged, double energy_zero)
bool posteriorForceResolved(double proposed_force_variance, double action_scale) noexcept
DimerOracleProgressAction selectDimerOracleProgressAction(bool path_leashed_recovery, bool oracle_certified, double best_oracle_force, double trial_oracle_force) noexcept
DimerProposalGlobalizationAction
constexpr int kMaxConsecutiveOracleFailures
double dimerPosteriorActionForceScale(double current_residual, double force_tolerance) noexcept
DimerRelaxationCycleKind
DimerResidualGlobalizationAction selectDimerResidualGlobalizationAction(double curvature, double current_residual, bool backtrack_accepted) noexcept
bool shouldTerminateDimerRelaxationForLostProgress(double curvature, double current_residual, double proposed_residual) noexcept
HssvdModeSelectionPolicy
Definition AtomicDimer.h:75
bool shouldLogDimerFinalState(const gpr::Index_t debug_level) noexcept
bool shouldBacktrackDimerRelaxationForResidualDecrease(double curvature, double current_residual) noexcept
bool repeatedProjectedTrustStep(const gpr::Coord &step, double curvature, const gpr::Coord &previous_step, double previous_curvature) noexcept
DimerResidualGlobalizationAction resolvedPointKeepsTheSurrogateWalk(DimerResidualGlobalizationAction action, double proposed_force_variance, double action_scale) noexcept
const gpr::Coord & selectHssvdModeReference(const gpr::Coord &initial_reference, const gpr::Coord &current_orientation, HssvdModeSelectionPolicy policy, bool preserve_initial_reference) noexcept
DimerResidualGlobalizationAction
DimerSurrogateActionTermination
bool dimerOracleTrialNeedsRefit(double reference_force, double trial_force, double measured_change, double prediction_error, double force_tolerance) noexcept
constexpr gpr::Index_t kMaxStalledDegenerateProbes
DimerOracleProgressAction
DimerProposalGlobalizationAction selectDimerProposalGlobalizationAction(double curvature, double current_residual, double force_tolerance, double proposed_force_variance, double posterior_action_force_scale) noexcept
DimerSaddleMeritBacktrackResult backtrackDimerSaddleMerit(const gpr::Coord &current, const gpr::Coord &proposed, const gpr::Coord &gradient, const gpr::Coord &orientation, double curvature, const std::function< double(const gpr::Coord &)> &energy_change)
DimerResidualGlobalizationAction selectDimerPosteriorResidualGlobalizationAction(DimerProposalGlobalizationAction proposal_action, double curvature, double current_residual, bool backtrack_accepted) noexcept
bool dimerGeometriesCoincide(const gpr::Coord &a, const gpr::Coord &b) noexcept
Numerical geometry identity for cycle detection and measured-force rescue.
bool measuredRadiusClipRequestsOracle(bool clipped, double proposed_force_variance, double action_scale) noexcept
bool dimerPhaseBudgetAllows(gpr::Index_t phase, gpr::Index_t limit) noexcept
Definition AtomicDimer.h:96
Eigen::Index selectHssvdModeIndex(const Eigen::VectorXd &eigenvalues, const Eigen::MatrixXd &eigenvectors, const Eigen::VectorXd &reference, HssvdModeSelectionPolicy policy) noexcept
DimerRelaxationCycleCertificate certifyDimerRelaxationCycle(const gpr::Coord &current, const gpr::Coord &proposed, const gpr::Coord *preceding, double force_current, double force_preceding) noexcept
double modelAgreementTrustDistance(double configured, double length_scale, double force_error, double force_scale, double energy_error, double energy_scale) noexcept
double posteriorResolvedStep(double force_sigma, double curvature) noexcept
DimerRelaxationTerminationReason
@ InvalidParameters
The search parameters cannot define a dimer (non-positive separation).
@ WallClockLimit
The shared monotonic wall-clock deadline was reached.
@ InvalidAtomsConfiguration
execute() rejected the atom configuration before any search step.
@ OracleBudget
The caller's oracle-call budget was spent.
double rejectedTrialRadius(double shrunk, double displacement, double force_sigma, double curvature, double prediction_error, double force_increase=std::numeric_limits< double >::quiet_NaN(), bool transverse_residual_exceeds_step=false) noexcept
bool refusalRepeatsIndexZeroExpansion(const gpr::Coord &midpoint, const gpr::Coord &expansion_midpoint, double curvature, double curvature_resolution, double separation) noexcept
constexpr double defaultStencilStep() noexcept
bool coordinatesCoincideAtRoundoff(const Eigen::MatrixBase< Left > &left, const Eigen::MatrixBase< Right > &right) noexcept
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
PublicLayoutBytes libraryPublicLayout()
Eigen::Vector3d vector3_reg
Definition Macros.h:36
PublicLayoutBytes consumerPublicLayout()
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
bool collectiveWallClockLimitReached(const std::shared_ptr< const WallClockLimit > &limit, const linalg::MpiContext &context)
Definition PhaseTimers.h:81
GPModelProfile
Definition Structures.h:201
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
Potential wrappers and the batched oracle interface.
STL namespace.
rgsaddle_surface_request_t gpr_rgsaddle_surface_request_t
One entry of the dimer trajectory history – the midpoint configuration and dimer curvature estimate a...
double energy
energy relative to E_zero_level
double curvature
dimer curvature estimate this phase
gpr::Coord position
midpoint coordinates (1 x D)
gpr::Coord gradient
midpoint gradient (1 x D)
bool measured_descent_certified
The true-PES force strictly improves the preceding accepted center.
DimerRelaxationCycleKind kind
DimerProposalGlobalizationAction proposal_action
DimerSurrogateActionTermination termination
DimerResidualGlobalizationAction residual_action
gpr::Coord trial_positions
Cartesian geometry retained or proposed by this action.
Stores configurations of all atoms in the system.
Definition Structures.h:832
Structure of the input parameters. All input parameters are pairs of string names and values.
Definition Structures.h:370
Structure with information for the LBFGS method.
Definition Structures.h:977
Observation data: energy, gradient and positions.