Loading...
Searching...
No Matches
atmd::AtomicDimer Class Reference

Atomic dimer. More...

#include <gpr/AtomicDimer.h>

Classes

struct  DimerPhaseRecord
 One entry of the dimer trajectory history – the midpoint configuration and dimer curvature estimate at the end of one relaxation phase. More...
struct  VarianceGateConfig

Public Member Functions

 AtomicDimer ()
 Default constructor.
virtual ~AtomicDimer ()
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 setAtomsConfiguration (const gpr::AtomsConfiguration &_atoms_config)
 Set configuration of the atoms.
void execute (pot::PotentialWrapper &general_potential)
 This function uses the atomic GP-dimer method to converge to a saddle point, starting from somewhere inside the convergence area.
void setSecantHessianConfig (const gpr::optim::SecantHessianConfig &config)
 Replace the true-force secant and drop its history.
void setSecantOrientationSeed (bool enabled) noexcept
const gpr::optim::SecantHessian & secantHessian () const noexcept
gpr::optim::SecantCurvatureCounts secantCounts () const
gpr::optim::SecantCurvatureCounts secantLedger () const noexcept
 Pair, probe and rejection counts, without the GP's quadratic-mean uses.
void setMaxWallSeconds (double seconds)
 Set a wall-clock cap measured from this call. Non-positive disables.
void setWallClockLimit (std::shared_ptr< const gpr::WallClockLimit > limit)
 Share an enclosing deadline (used by OCI-NEB and deterministic tests).
void setTrainingPolicy (const gpr::policy::TrainingPolicy *policy)
 Not owned. The pointer must outlive execute(). Null is the engine.
void setTrainingPolicy (std::shared_ptr< const gpr::policy::TrainingPolicy > policy)
 Keeps a Python adapter alive for execute(), which releases the GIL.
bool wallClockLimitReached () const
void stopForWallClockLimit ()
bool certifyStoppedForce (pot::PotentialWrapper &potential, double step, int &calls)
void setForceStopCertificateStep (double step) noexcept
void setVibrationalStencil (gpr::optim::VibrationalStencil mode) noexcept
gpr::optim::VibrationalStencil vibrationalStencil () const noexcept
double forceStopCertificateStep () const noexcept
bool getForceStopCertified () const noexcept
 Whether the last execute() certified its force stop as index one.
int getForceStopCertificateCalls () const noexcept
bool hasValidAtomsConfiguration ()
 Whether the atoms configuration holds the moving-atom set that execute() needs.
double getFinalRotationAngle () const noexcept
 Min-mode rotational angle omega (radians) at the converged midpoint, or NaN if no converged phase recorded it. A small omega means the dimer axis is aligned with the true lowest-curvature eigenvector, so the caller can certify a flat saddle on angle + negative curvature rather than force alone.
double getLatestModeCurvature () const noexcept
 Latest min-mode curvature from a dimer rotation. The force-stop stencil records the returned curvature separately in getFinalCurvature().
const gpr::Observation & finalMidpoint () const noexcept
 Midpoint recorded at the end of execute().
bool isMinModeAngleCertified () const noexcept
 True iff the converged min-mode is angle-certified: a converged phase recorded a finite rotation omega within the dimer's own true-PES rotation tolerance (stop_citeria_dimer.angle_rotation) AND the converged curvature is negative (a real saddle direction). Uses the tolerance the dimer already rotated to – no new constant.
double getFinalRotationResidual () const noexcept
bool measuredModeIsCertified () const noexcept
bool terminalModeIsReady () const noexcept
void refineMeasuredModeCurvature (const gpr::Observation &midpoint, const gpr::Coord &orientation, pot::PotentialWrapper &potential, double surrogate_curvature)
Eigen::VectorXd getFinalGradientAtMidPoint () const
 Return the final gradient dE/dR at the middle point.
Eigen::VectorXd getFinalForceAtMidPoint () const
 Deprecated alias of getFinalGradientAtMidPoint().
double getFinalForceNormForConvergence () const
 Return final force in the configured convergence norm.
Eigen::VectorXd getFinalCoordOfMidPoint () const
 Return final coordinates of the middle point.
bool restartFromHigherOrderPoint (const Eigen::MatrixXd &cartesian_hessian, const Eigen::VectorXd &kick, const gpr::Observation &measured_rows, pot::PotentialWrapper &potential)
bool refineSaddleFromMeasuredHessian (const Eigen::MatrixXd &cartesian_hessian, pot::PotentialWrapper &potential, double resolution=0.0)
bool refineSaddleFromMeasuredHessian (const Eigen::MatrixXd &cartesian_hessian, pot::PotentialWrapper &potential, gpr::Observation *raw_candidate, double resolution=0.0, bool complete_stencil=false)
bool commitExternallyCertifiedRefinement (const gpr::Observation &raw_center, const Eigen::MatrixXd &certified_cartesian_hessian, const Eigen::MatrixXd &certified_mass_weighted_basis, bool first_order_certificate)
bool hasUnconditionedObservations () const noexcept
bool restartAlongWeakMode (const Eigen::VectorXd &direction, double length, const gpr::Observation &measured_rows, pot::PotentialWrapper &potential)
bool restartAlongWeakMode (const Eigen::VectorXd &direction, double length, const gpr::Observation &measured_rows, pot::PotentialWrapper &potential, const Eigen::MatrixXd &cartesian_hessian)
gpr::Index_t getTotalForceCalls () const
 Return the total number of force calls.
bool measureCurvatureProbes (const gpr::Coord &positions, pot::PotentialWrapper &potential, gpr::Observation &raw)
gpr::Index_t getTotalGPRForceCalls () const
 Return the total number of force calls.
gpr::Index_t getIterations () const
 Return the total number of cycles.
double getFinalEnergy () const
 Return final energy.
double getFinalCurvature () const
 Return final curvature.
bool getConverged () const
 Return true when the final force convergence criterion is met.
double getMaxStepLength () const
 The bound of one translation step in Cartesian length (Angstrom).
double getConvergenceForce () const noexcept
 Force norm below which the dimer search is converged.
void setConvergenceForce (double force)
 Replace the configured true-PES force criterion and the live stop.
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.
const std::vector< DimerPhaseRecord > & getPhaseHistory () const noexcept
 Return the per-phase dimer trajectory history.
DimerRelaxationTerminationReason getRelaxationTerminationReason () const noexcept
Eigen::MatrixXd getMeasuredIndexZeroHessian () const
double getMeasuredIndexZeroResolution () const
Eigen::MatrixXd gpMeanHessianAtMidpoint ()
DimerSurrogateActionCertificate previewFirstSurrogateAction (const gpr::Observation &oracle_middle_point, const gpr::Coord &initial_orientation)
const DimerSurrogateActionCertificate & getFirstSurrogateActionCertificate () const noexcept
gpr::Coord & getMidPointCoordForAllObservationPointsRef ()
 Return gpr::Coordinates of all observed points.
gpr::FieldMatrixd & getEnergyForAllObservationPointsRef ()
 Return energies for all observed points.
gpr::Coord & getGradientForAllObservationPointsRef ()
 Return gradients for all observed points.
gpr::GaussianProcessRegression * getGPRModel ()
 Get GPR model.
void preserveSeedKernel () noexcept
 Retain an imported kernel's parameters and absolute energy origin.
void attachExternalGP (gpr::GaussianProcessRegression *external_gp) noexcept
 Attach an externally-owned GPR model. Must be called BEFORE ~initialize~. The dimer will use this GP for all predict, refit, Cholesky and variance calls, and will NOT call its ~initialize(parameters, atoms_config)~ entry (the external owner has already done that). The dimer takes no ownership: the GP is not deleted in the destructor. Use case: ~OCINEBController~ shares the long-lived ~ActiveLearningSession::gp~ across NEB outer iters and MMF bursts so the singleton ~DistributedState~ distributed factor stays coherent across phases.
gpr::Index_t getNumNewObservations () const
 Number of accurate (general-potential) observations the dimer accumulated during ~execute~. Equals ~all_obs.E.rows() - N_obs_init~. The caller can pair this with ~getMidPointCoordForAllObservationPointsRef~ / ~getEnergyForAllObservationPointsRef~ / ~getGradientForAllObservationPointsRef~ to harvest the new rows back into a shared ~session.training_obs~ buffer. Energies are relative to ~getEnergyZeroLevel()~ as documented above.
gpr::Index_t getInitialObservationCount () const
 Index of the first row in ~all_obs~ that the dimer appended during ~execute~. Pair with ~getNumNewObservations~ for harvest bookkeeping.
gpr::FieldMatrixd getEnergyZeroLevel () const
 Internal E_zero_level used by the dimer's cutOffEnergy bookkeeping. The energies returned by ~getEnergyForAllObservationPointsRef~ and ~getFinalEnergy~ are relative to this value, not absolute PES energies. Add E_zero_level back to recover the absolute energy.
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.
bool isFinalConvergenceReached (const gpr::Observation &middle_point, const double stop_criteria)
 Final convergence test for force.
bool isRotationalConvergenceReached (const gpr::Coord &orient, gpr::Observation &middle_point)
 Rotational convergence test.
bool isApproximateRotationalConvergenceReached (const gpr::Coord &orient, const gpr::Observation &approx_obs, const double stop_criteria)
 GP-stencil rotational convergence test.
bool rotateDimer (const double stop_criteria, gpr::Coord &orient, gpr::LBFGSInfo &rot_info, gpr::Observation &middle_point, gpr::Observation &approx_obs)
 Rotate the dimer.
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 updateActiveFrozenAtoms (const gpr::Coord &R_new, gpr::LBFGSInfo &rot_info, gpr::LBFGSInfo &trans_info)
 Update active frozen atoms.
void setVarianceGateConfig (const VarianceGateConfig &cfg) noexcept
const VarianceGateConfig & getVarianceGateConfig () const noexcept
void setVarianceAcceptTau (double tau) noexcept
void writeTraceFrame (const gpr::Observation &obs, const std::string &phase, size_t idx)
void archiveObservations (const gpr::Observation &obs) noexcept
double getVarianceAcceptTau () const noexcept
void setVarianceAcceptTauRelative (double tau_relative) noexcept
double getVarianceAcceptTauRelative () const noexcept
gpr::Index_t getVarianceSkippedAccurateCalls () const noexcept
gpr::Index_t getImspeSoftSkippedCalls () const noexcept
gpr::Index_t getImspeFixedThetaRefreshCalls () const noexcept
gpr::Index_t getFixedThetaRefreshCalls () const noexcept
gpr::Index_t getImspeAdmittedNearDuplicateObservations () const noexcept
gpr::Index_t getDedupRejectedObservations () const noexcept
void setAlignmentAbortTol (double tol) noexcept
void setAbortOnDegenerateProbes (bool enabled) noexcept
void setMaxOracleCalls (gpr::Index_t calls) noexcept
gpr::Index_t maxOracleCalls () const noexcept
void setIndexFrequencyResolution (double wavenumber) noexcept
double indexFrequencyResolution () const noexcept
void setRejectHigherIndexSurrogateConvergence (bool enabled) noexcept
 See want_second_negative_mode_.
bool measuredIndexRecoveryEnabled () const noexcept
void setExternalTerminalCertificate (bool enabled) noexcept
Eigen::Index lastNegativeModeCount () const noexcept
void setMeasuredEnergyCeiling (double ceiling) noexcept
void setSaddleEnergyFloor (double floor) noexcept
bool lastRefinementReachedIndexOne () const noexcept
void setAbortOnInteratomicCollapse (bool enabled) noexcept
void setPreserveInitialAlignmentReference (bool enabled) noexcept
void setLikelihoodNoiseFloorSigma2 (double floor_sigma2) noexcept
void setSelfOwnedModelProfile (gpr::GPModelProfile profile) noexcept
void setSelfOwnedUseZblPriorMean (bool use) noexcept
void setSelfOwnedUseFfPriorMean (bool use) noexcept
double getAlignmentAbortTol () const noexcept
void setLeashRelaxWhenClose (bool enabled) noexcept
bool getLeashRelaxWhenClose () const noexcept
void setEvaluateImage1EachPhase (bool enabled) noexcept
bool getEvaluateImage1EachPhase () const noexcept
void setConvergenceForceNorm (int norm_type) noexcept
void setProjectRigidModesForConvergence (bool enabled) noexcept
void setOracleBatchChunk (Eigen::Index chunk) noexcept
Eigen::Index getOracleBatchChunk () const noexcept
void setProfilePhaseTiming (bool enabled) noexcept
bool getProfilePhaseTiming () const noexcept
void setProfileDimerTimes (bool enabled) noexcept
bool getProfileDimerTimes () const noexcept
void setUseHssvdAnalyticCurvature (bool enabled) noexcept
bool getUseHssvdAnalyticCurvature () const noexcept
void setHssvdModeSelectionPolicy (HssvdModeSelectionPolicy policy) noexcept
gpr::Index_t activeSetChangeCount () const noexcept
gpr::Index_t activeFrozenCount () const noexcept
void setHdf5TracePath (const std::string &path)
void setUncertaintyAwareRotation (bool enabled) noexcept
void setProjectMeasuredRotations (bool enabled) noexcept
void setKappaDimer (double beta)
double kappaDimerBeta () const noexcept
const std::string & getHdf5TracePath () const noexcept
void setHdf5TraceEnabled (bool enabled)
bool hdf5TraceEnabled () const noexcept

Public Attributes

gpr::AtomsConfiguration atoms_config

Friends

gpr::PublicLayoutBytes gpr::libraryPublicLayout ()
gpr::PublicLayoutBytes gpr::consumerPublicLayout ()

Detailed Description

Atomic dimer.

Definition at line 656 of file AtomicDimer.h.

Constructor & Destructor Documentation

◆ AtomicDimer()

atmd::AtomicDimer::AtomicDimer ( )

Default constructor.

Definition at line 560 of file AtomicDimer.cpp.

561{
562 clear();
563
564 // Planted CuH2 fixture cell: orthorhombic 15.35 x 21.70 x 100.
565 cell_dimensions[0] = {15.3455999999999992, 0., 0.};
566 cell_dimensions[1] = {0., 21.7020000000000017, 0.};
567 cell_dimensions[2] = {0., 0., 100.0000000000000000};
568
569 // Self-owned path. ~attachExternalGP~ repoints ~gpr_model~ at a
570 // caller-owned GP and releases this allocation. Eager allocation
571 // keeps default construction usable without a separate attach step.
572 owned_gpr_model_ = std::make_unique<gpr::GaussianProcessRegression>();
573 gpr_model = owned_gpr_model_.get();
574 uses_external_gp_ = false;
575 preserve_seed_kernel_ = false;
576
577 num_of_gen_potential_calls = 0;
578 profile_phase_timing_ = false;
579 early_params._threshold = 0.4;
580 early_params._use_adaptive_threshold = false;
581 early_params._adaptive_A = 1.3;
582 early_params._adaptive_floor = 0.25;
583 early_params._adaptive_t_min = 0.15;
584 early_params._adaptive_delta_explore = 0.35;
585 early_params._adaptive_half_life = 50;
586 early_params._dist_metric = DistanceMetricType::EMD;
587 rgmin_trans_ = std::make_unique<gpr::optim::RgminStep>();
588}

◆ ~AtomicDimer()

atmd::AtomicDimer::~AtomicDimer ( )
virtual

Definition at line 590 of file AtomicDimer.cpp.

591{
592 // ~clear~ drops the borrowed pointer; the unique_ptr destructor
593 // releases the owned GP (if any). External GPs are not touched.
594 clear();
595}

Member Function Documentation

◆ activeFrozenCount()

gpr::Index_t atmd::AtomicDimer::activeFrozenCount ( ) const
inlinenodiscardnoexcept

Definition at line 2510 of file AtomicDimer.h.

2511 {
2512 return active_frozen_count_;
2513 }

◆ activeSetChangeCount()

gpr::Index_t atmd::AtomicDimer::activeSetChangeCount ( ) const
inlinenodiscardnoexcept

Definition at line 2506 of file AtomicDimer.h.

2507 {
2508 return active_set_change_count_;
2509 }

◆ archiveObservations()

void atmd::AtomicDimer::archiveObservations ( const gpr::Observation & obs)
inlinenoexcept

Persist every row of obs to the observation archive when one is attached; a no-op otherwise. Never gates the science path.

Definition at line 2223 of file AtomicDimer.h.

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 }
FieldMatrixd E

◆ attachExternalGP()

void atmd::AtomicDimer::attachExternalGP ( gpr::GaussianProcessRegression * external_gp)
noexcept

Attach an externally-owned GPR model. Must be called BEFORE ~initialize~. The dimer will use this GP for all predict, refit, Cholesky and variance calls, and will NOT call its ~initialize(parameters, atoms_config)~ entry (the external owner has already done that). The dimer takes no ownership: the GP is not deleted in the destructor. Use case: ~OCINEBController~ shares the long-lived ~ActiveLearningSession::gp~ across NEB outer iters and MMF bursts so the singleton ~DistributedState~ distributed factor stays coherent across phases.

Idempotent: passing nullptr restores the legacy self-owned path (which ~initialize~ will then lazily allocate).

Definition at line 597 of file AtomicDimer.cpp.

599{
600 if (external_gp != nullptr) {
601 // Borrow: release any self-owned GP and point the access alias at
602 // the caller's instance. ~initialize~ uses the borrowed GP when
603 // ~owned_gpr_model_~ is empty.
604 owned_gpr_model_.reset();
605 gpr_model = external_gp;
606 uses_external_gp_ = true;
607 } else {
608 // Self-owned path. ~initialize~ allocates and configures the GP.
609 owned_gpr_model_ = std::make_unique<gpr::GaussianProcessRegression>();
610 gpr_model = owned_gpr_model_.get();
611 uses_external_gp_ = false;
612 }
613 if (wall_clock_limit_) gpr_model->setWallClockLimit(wall_clock_limit_);
614}

◆ callGeneralPotentialFromEON()

void atmd::AtomicDimer::callGeneralPotentialFromEON ( const gpr::vector3_reg(&) cell_dimensions[3],
gpr::Observation & mid_point,
pot::PotentialWrapper & potential )

Call for a potential defined in a Matter object.

Parameters
cell_dimensionsDimensions of the cell in EON 9 element format
mid_pointThe point on which to obtain the potential
potentialThe potential wrapper used for the evaluation

Definition at line 6448 of file AtomicDimer.cpp.

6451{
6452 long N;
6453 const double* R;
6454 const int* atomicNrs;
6455 double* F;
6456 double* U;
6457 const double box[9] = {
6458 cell_dimensions[0](0), cell_dimensions[0](1), cell_dimensions[0](2),
6459 cell_dimensions[1](0), cell_dimensions[1](1), cell_dimensions[1](2),
6460 cell_dimensions[2](0), cell_dimensions[2](1), cell_dimensions[2](2)};
6461
6462 // One energy per configuration, gradient same shape as coordinates
6463 mid_point.E.resize(mid_point.R.rows(), 1);
6464 mid_point.G.resize(mid_point.R.rows(), mid_point.R.cols());
6465
6466 // Total number of moving atoms
6467 N = gpr::coord::numPoints(mid_point.R);
6468
6469 // Position at middle point
6470 R = mid_point.R.data();
6471
6472 // Force at middle point
6473 F = mid_point.G.data();
6474
6475 // Energy at middle point
6476 U = mid_point.E.data();
6477
6478 // eOn and rgpot pass one species per coordinate atom, the moving set.
6479 // A loaded configuration stores frozen atoms first, so the full
6480 // atomicNrs pointer would compare those species with the moving ones.
6481 std::vector<int> moving_species;
6482 const Eigen::Index species_n = atoms_config.atomicNrs.size();
6483 if (species_n > 0 && atoms_config.is_frozen.size() == species_n) {
6484 moving_species.reserve(static_cast<std::size_t>(species_n));
6485 for (Eigen::Index atom = 0; atom < species_n; ++atom) {
6486 if (atoms_config.is_frozen(0, atom) != MOVING_ATOM) continue;
6487 moving_species.push_back(atoms_config.atomicNrs(0, atom));
6488 }
6489 atomicNrs = moving_species.data();
6490 } else {
6491 atomicNrs = atoms_config.atomicNrs.data();
6492 }
6493
6494 // Call for the potential calculations
6495 gpr::requireWallClock(wall_clock_limit_);
6496 {
6497 gpr::ScopedPhaseTimer oracle_timer(gpr::PhaseTimers::oracle_seconds);
6498 potential.force(N, R, atomicNrs, F, U, nullptr /*variance*/, box);
6499 }
6500}
@ MOVING_ATOM
Definition Enums.h:35
gpr::AtomsConfiguration atoms_config
void force(long N, const double *R, const int *atomicNrs, double *F, double *U, double *energy_noise_rms, const double *box)
Invoke the wrapped potential.
Index_t numPoints(const FieldMatrixd &mat)
void requireWallClock(const std::shared_ptr< const WallClockLimit > &limit)
Definition PhaseTimers.h:73
static double oracle_seconds

◆ certifyStoppedForce()

bool atmd::AtomicDimer::certifyStoppedForce ( pot::PotentialWrapper & potential,
double step,
int & calls )

One Cartesian stencil after the force loop has stopped, then a min-mode escape when that stencil is higher-order. calls counts those evaluations, which go through the search's counted and budgeted oracle path. True only when a measured stencil certifies a first-order saddle; an unmeasured stop is uncertified.

Definition at line 6502 of file AtomicDimer.cpp.

6504{
6505 calls = 0;
6506 if (!(step > 0.0) || !std::isfinite(step)) return false;
6507 const Eigen::VectorXd origin = getFinalCoordOfMidPoint();
6508 const Eigen::Index dof = origin.size();
6509 if (dof == 0 || dof % 3 != 0 || !origin.allFinite()) return false;
6510 const Eigen::Index n_atoms = dof / 3;
6511 Eigen::VectorXd masses = Eigen::VectorXd::Ones(n_atoms);
6512 if (atoms_config.atomic_masses.size() == n_atoms)
6513 masses = atoms_config.atomic_masses;
6514 // Rigid motions are zero modes only of a free system. Frozen atoms, or
6515 // a single atom with no internal coordinate, anchor every direction.
6516 const bool anchored = is_subsystem(atoms_config) || n_atoms == 1;
6517 const auto counted = [&](const auto& evaluate) {
6518 const gpr::Index_t before = getNumEvaluations();
6519 const bool ok = evaluate();
6520 calls += static_cast<int>(getNumEvaluations() - before);
6521 return ok;
6522 };
6523 const bool periodic = gpr::geometry::cellIsMicLattice(atoms_config.cell);
6524 gpr::neb::VibrationalIndexMeasurement latest;
6525 double measured_curvature = curvature_final;
6526 const auto measure = [&]() {
6527 gpr::optim::ForceStopMeasurement measured;
6528 const Eigen::VectorXd center = getFinalCoordOfMidPoint();
6529 const Eigen::MatrixXd directions = gpr::optim::stencilDirectionsForMode(
6530 vibrational_stencil_, center, masses, periodic, anchored);
6531 const Eigen::Index count = directions.cols();
6532 // The removed rigid columns are rebuilt about the center gradient.
6533 // The midpoint already holds it unless it was never evaluated.
6534 const bool center_held =
6535 count == dof || (middle_point_final.G.rows() == 1 &&
6536 middle_point_final.G.cols() == dof &&
6537 middle_point_final.G.allFinite());
6538 gpr::Observation probes;
6539 probes.R.resize(2 * count + (center_held ? 0 : 1), dof);
6540 probes.R.topRows(2 * count) =
6541 gpr::optim::centralDifferencePoints(center, step, directions)
6542 .transpose();
6543 if (!center_held) probes.R.row(2 * count) = center.transpose();
6544 const gpr::Index_t before = getNumEvaluations();
6545 std::string failure;
6546 const bool ok = acquireAccurateProbe(probes, potential,
6547 oracle_batch_chunk_, failure);
6548 measured.calls = static_cast<int>(getNumEvaluations() - before);
6549 calls += measured.calls;
6550 if (!ok) {
6551 log_man << "Force-stop certificate: stencil failed: " << failure
6552 << "\n";
6553 return measured;
6554 }
6555 broadcastObservation(probes);
6556 Eigen::MatrixXd actions(dof, count);
6557 for (Eigen::Index k = 0; k < count; ++k)
6558 actions.col(k) =
6559 (probes.G.row(2 * k) - probes.G.row(2 * k + 1)).transpose() /
6560 (2.0 * step);
6561 const Eigen::VectorXd center_gradient =
6562 center_held && count < dof
6563 ? Eigen::VectorXd(middle_point_final.G.row(0).transpose())
6564 : (center_held
6565 ? Eigen::VectorXd()
6566 : Eigen::VectorXd(probes.G.row(2 * count).transpose()));
6567 const Eigen::MatrixXd columns =
6568 gpr::optim::hessianColumnsFromDirections(center, center_gradient,
6569 directions, actions);
6570 if (columns.rows() != dof) {
6571 log_man << "Force-stop certificate: Hessian columns cannot be "
6572 "formed\n";
6573 return measured;
6574 }
6575 latest = gpr::neb::indexFromCartesianColumns(columns, center, masses,
6576 step, nullptr, nullptr,
6577 anchored, &directions);
6578 if (latest.pass && orient_final.rows() == 1 &&
6579 orient_final.cols() == dof) {
6580 const Eigen::VectorXd direction = orient_final.row(0).transpose();
6581 const double norm_squared = direction.squaredNorm();
6582 if (norm_squared > 0.0 && std::isfinite(norm_squared))
6583 measured_curvature =
6584 direction.dot(columns * direction) / norm_squared;
6585 }
6586 log_man << "Force-stop certificate: " << latest.negative
6587 << " negative, " << latest.unresolved << " unresolved, "
6588 << latest.positive << " positive modes (resolution "
6589 << latest.resolution << ")\n";
6590 measured.measured = latest.measured;
6591 measured.first_order = latest.pass;
6592 measured.higher_order = latest.negative > 1;
6593 return measured;
6594 };
6595 const auto move_to = [&](const Eigen::VectorXd& point) {
6596 gpr::Observation moved;
6597 moved.R = point.transpose();
6598 if (!counted([&]() { return evaluateAccurateProbe(moved, potential); }))
6599 return false;
6600 broadcastObservation(moved);
6601 middle_point_final = moved;
6602 middle_point_init = moved;
6603 return true;
6604 };
6605 const gpr::optim::ForceStopStencilPlan plan =
6607 /*requested=*/true);
6609 measure,
6610 [&]() {
6611 if (latest.step.size() != dof) return -1;
6612 return move_to(getFinalCoordOfMidPoint() + latest.step) ? 1 : -1;
6613 },
6614 plan);
6615 if (outcome.needs_min_mode_escape && latest.step.size() == dof &&
6616 latest.step.norm() > 0.0) {
6617 // Same escape the band and the gprd force stop take: leave the
6618 // higher-order point along the extra negative mode and certify
6619 // the geometry that is reached.
6620 double length = latest.step.norm();
6621 Eigen::VectorXd direction = latest.step / length;
6622 for (int escape = 0; outcome.needs_min_mode_escape &&
6624 ++escape) {
6625 length *= 2.0;
6626 if (!move_to(getFinalCoordOfMidPoint() + length * direction)) break;
6628 measure, [&]() { return -1; }, plan);
6629 if (latest.step.size() == dof && latest.step.norm() > 0.0)
6630 direction = latest.step / latest.step.norm();
6631 }
6632 }
6633 const bool certified =
6634 outcome.certified &&
6635 forceNormForConvergence(middle_point_final) < stop_citeria_dimer.force;
6636 if (certified) curvature_final = measured_curvature;
6637 return certified;
6638}
Eigen::VectorXd getFinalCoordOfMidPoint() const
Return final coordinates of the middle point.
bool is_subsystem(const gpr::AtomsConfiguration &atoms_config)
bool cellIsMicLattice(const double cell[9]) noexcept
Nonzero ASE 3x3 that is not the 25 A vacuum convention.
Definition MinImage.h:56
Half measured(const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &options)
Full central difference of the oracle gradient: 2 d calls.
VibrationalIndexMeasurement indexFromCartesianColumns(const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double move, const Eigen::VectorXd *center_gradient=nullptr, const Eigen::VectorXi *frozen=nullptr, bool anchored=false, const Eigen::MatrixXd *measured=nullptr)
Eigen::MatrixXd hessianColumnsFromDirections(const Eigen::VectorXd &center, const Eigen::VectorXd &center_gradient, const Eigen::MatrixXd &directions, const Eigen::MatrixXd &actions)
Eigen::MatrixXd stencilDirectionsForMode(VibrationalStencil mode, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, bool periodic, bool anchored, const Eigen::VectorXi *frozen=nullptr)
ForceStopStencilPlan planForceStopStencil(ForceStopStencilQuery query)
constexpr int forceStopMinModeEscapes() noexcept
Min-mode escapes after a higher-order certificate, for every search.
Eigen::MatrixXd centralDifferencePoints(const Eigen::VectorXd &center, double step, const Eigen::MatrixXd &directions)
ForceStopCertificateResult runForceStopCertificate(Measure measure, Refine refine, ForceStopStencilPlan plan, const ForceStopMeasurement *prior=nullptr)
VecchiaResult evaluate(const Eigen::MatrixXd &points, const Eigen::VectorXd &y, double lengthscale, double noise, int max_neighbours)
uint32_t Index_t
Definition Macros.h:17
std::vector< int > measured
1 for a mode at least 99% inside the measured directions.

◆ commitExternallyCertifiedRefinement()

bool atmd::AtomicDimer::commitExternallyCertifiedRefinement ( const gpr::Observation & raw_center,
const Eigen::MatrixXd & certified_cartesian_hessian,
const Eigen::MatrixXd & certified_mass_weighted_basis,
bool first_order_certificate )

Commit the same endpoint under the caller's complete first-order certificate and mass-weighted physical frame. The caller establishes matching oracle, cell, atom order and complete allowed coordinate space. The frame may be nonorthonormal; its mass-weighted Gram matrix selects the mode, which is reported as a Cartesian unit direction and Rayleigh curvature. This performs no evaluation, archive write, training admission or posterior fit. Raw energies are absolute and must roundtrip exactly through the retained energy gauge; the retained endpoint remains unconditioned in the GP. With initialized MPI this is collective: one rank's refusal prevents every rank's commit.

Definition at line 3470 of file AtomicDimer.cpp.

3475{
3476 gpr::Observation relative_center;
3477 gpr::Coord orientation;
3478 Eigen::MatrixXd symmetric;
3479 double curvature = std::numeric_limits<double>::quiet_NaN();
3480 double resolution = std::numeric_limits<double>::infinity();
3481 const auto prepare = [&]() {
3482 const Eigen::Index dimension = raw_center.R.cols();
3483 const Eigen::Index physical_dimension =
3484 certified_mass_weighted_basis.cols();
3485 if (!external_terminal_certificate_ || !first_order_certificate ||
3486 !last_refinement_reached_index_one_ || gpr_model == nullptr ||
3487 !curvature_requires_full_refit_ ||
3488 hasOptimizedCurrentObservedData() || dimension < 6 ||
3489 dimension % 3 != 0 || raw_center.R.rows() != 1 ||
3490 !raw_center.R.allFinite() || raw_center.E.rows() != 1 ||
3491 raw_center.E.cols() != 1 || !raw_center.E.allFinite() ||
3492 raw_center.G.rows() != 1 || raw_center.G.cols() != dimension ||
3493 !raw_center.G.allFinite() || E_zero_level.rows() != 1 ||
3494 E_zero_level.cols() != 1 || !E_zero_level.allFinite() ||
3495 middle_point_init.R.rows() != 1 ||
3496 middle_point_init.R.cols() != dimension ||
3497 middle_point_init.E.rows() != 1 ||
3498 middle_point_init.E.cols() != 1 ||
3499 middle_point_init.G.rows() != 1 ||
3500 middle_point_init.G.cols() != dimension ||
3501 !(raw_center.R.array() == middle_point_init.R.array()).all() ||
3502 !(raw_center.G.array() == middle_point_init.G.array()).all() ||
3503 certified_cartesian_hessian.rows() != dimension ||
3504 certified_cartesian_hessian.cols() != dimension ||
3505 !certified_cartesian_hessian.allFinite() ||
3506 certified_mass_weighted_basis.rows() != dimension ||
3507 physical_dimension < 2 || physical_dimension > dimension ||
3508 !certified_mass_weighted_basis.allFinite())
3509 return false;
3510
3511 relative_center = raw_center;
3512 aux::ProblemSetUp setup;
3513 setup.cutOffEnergy(E_zero_level, relative_center.E);
3514 if (!relative_center.E.allFinite() ||
3515 !std::isfinite(relative_center.E(0, 0) + E_zero_level(0, 0)) ||
3516 relative_center.E(0, 0) + E_zero_level(0, 0) !=
3517 raw_center.E(0, 0) ||
3518 !(relative_center.E.array() == middle_point_init.E.array()).all() ||
3519 !(forceNormForConvergence(relative_center) <
3520 stop_citeria_dimer.force) ||
3521 (std::isfinite(saddle_energy_floor_) &&
3522 raw_center.E(0, 0) < saddle_energy_floor_) ||
3523 (std::isfinite(measured_energy_ceiling_) &&
3524 raw_center.E(0, 0) > measured_energy_ceiling_))
3525 return false;
3526
3527 Eigen::VectorXd masses;
3528 try {
3529 masses =
3531 } catch (const std::invalid_argument&) {
3532 return false;
3533 }
3534 Eigen::MatrixXd cartesian_basis = certified_mass_weighted_basis;
3535 for (Eigen::Index atom = 0; atom < masses.size(); ++atom)
3536 cartesian_basis.middleRows(3 * atom, 3) /= std::sqrt(masses(atom));
3537 if (!cartesian_basis.allFinite()) return false;
3538 const Eigen::ColPivHouseholderQR<Eigen::MatrixXd> frame_qr(
3539 certified_mass_weighted_basis);
3540 if (frame_qr.rank() != physical_dimension) return false;
3541 const Eigen::MatrixXd gram = certified_mass_weighted_basis.transpose() *
3542 certified_mass_weighted_basis;
3543 if (!gram.allFinite()) return false;
3544 const Eigen::LLT<Eigen::MatrixXd> gram_factor(gram);
3545 if (gram_factor.info() != Eigen::Success) return false;
3546 symmetric = 0.5 * certified_cartesian_hessian +
3547 0.5 * certified_cartesian_hessian.transpose();
3548 const Eigen::MatrixXd reduced =
3549 cartesian_basis.transpose() * symmetric * cartesian_basis;
3550 if (!reduced.allFinite()) return false;
3551 // The supplied chart spans the certifier's complete physical space.
3552 // Its mass-weighted Gram matrix keeps the selected mode independent
3553 // of normalization and mixing of the supplied chart columns.
3554 const Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd>
3555 spectrum(0.5 * (reduced + reduced.transpose()), gram);
3556 if (spectrum.info() != Eigen::Success ||
3557 !spectrum.eigenvalues().allFinite())
3558 return false;
3559 Eigen::MatrixXd physical =
3560 frame_qr.householderQ() *
3561 Eigen::MatrixXd::Identity(dimension, physical_dimension);
3562 for (Eigen::Index atom = 0; atom < masses.size(); ++atom)
3563 physical.middleRows(3 * atom, 3) /= std::sqrt(masses(atom));
3564 const Eigen::MatrixXd measured =
3565 physical.transpose() * certified_cartesian_hessian * physical;
3566 if (!measured.allFinite()) return false;
3567 const Eigen::MatrixXd skew = 0.5 * (measured - measured.transpose());
3568 const Eigen::JacobiSVD<Eigen::MatrixXd> error_spectrum(skew);
3569 if (!error_spectrum.singularValues().allFinite()) return false;
3570 const double weighted_resolution =
3571 std::max(error_spectrum.singularValues().maxCoeff(),
3572 std::numeric_limits<double>::epsilon() *
3573 static_cast<double>(physical_dimension) *
3574 spectrum.eigenvalues().cwiseAbs().maxCoeff());
3575 if (!(spectrum.eigenvalues()(0) < -weighted_resolution) ||
3576 !(spectrum.eigenvalues()(1) > weighted_resolution))
3577 return false;
3578 Eigen::VectorXd mode = cartesian_basis * spectrum.eigenvectors().col(0);
3579 const double norm = mode.stableNorm();
3580 if (!(norm > 0.0) || !std::isfinite(norm)) return false;
3581 mode /= norm;
3582 if (orient_init.rows() == 1 && orient_init.cols() == dimension &&
3583 orient_init.allFinite() && orient_init.row(0).dot(mode) < 0.0)
3584 mode = -mode;
3585 curvature = mode.dot(symmetric * mode);
3586 resolution = masses.maxCoeff() * weighted_resolution;
3587 if (!mode.allFinite() || !std::isfinite(curvature) ||
3588 !std::isfinite(resolution) || !(curvature < -resolution))
3589 return false;
3590 orientation.resize(1, dimension);
3591 orientation.row(0) = mode.transpose();
3592
3593 return true;
3594 };
3595 int accepted = prepare() ? 1 : 0;
3596#if defined(GPR_LINALG_SCALAPACK) || defined(GPR_HAVE_MPI)
3597 int mpi_active = 0;
3598 MPI_Initialized(&mpi_active);
3599 if (mpi_active && MPI_Allreduce(MPI_IN_PLACE, &accepted, 1, MPI_INT,
3600 MPI_MIN, MPI_COMM_WORLD) != MPI_SUCCESS)
3601 accepted = 0;
3602#endif
3603 if (accepted == 0) return false;
3604
3605 // A full-Hessian certificate commits measured state without claiming
3606 // that the retained endpoint has conditioned the surrogate posterior.
3607 assignFinalResults(relative_center, {curvature, orientation});
3608 latest_mode_curvature_resolution_ = resolution;
3609 final_converged_ = true;
3610 last_negative_mode_count_ = 1;
3611 converged_above_energy_ceiling_ = false;
3612 relaxation_termination_reason_ =
3614 final_rotation_omega_ = std::numeric_limits<double>::quiet_NaN();
3615 final_rotation_residual_ = std::numeric_limits<double>::infinity();
3616 measured_rotation_stationary_ = false;
3617 measured_rotation_rounds_ = 0;
3618 measured_rotation_reference_ = gpr::Observation();
3619 measured_rotation_separation_ = 0.0;
3620 measured_rotation_physical_.resize(0, 0);
3621 measured_rotation_basis_.resize(0, 0);
3622 measured_rotation_actions_.resize(0, 0);
3623 best_measured_rotation_residual_ = std::numeric_limits<double>::infinity();
3624 best_measured_rotation_angle_ = std::numeric_limits<double>::quiet_NaN();
3625 best_measured_rotation_curvature_ =
3626 std::numeric_limits<double>::quiet_NaN();
3627 best_measured_orientation_.resize(0, 0);
3628 best_measured_image1_ = gpr::Observation();
3629 measured_index_zero_midpoint_.resize(0, 0);
3630 measured_index_zero_hessian_.resize(0, 0);
3631 last_certificate_hessian_ = symmetric;
3632 last_certificate_positions_ = relative_center.R;
3633 return true;
3634}
void cutOffEnergy(const gpr::FieldMatrixd &E_reference, gpr::FieldMatrixd &E_R)
Subtract reference energy value from E_R.
Eigen::VectorXd movingAtomicMasses(const gpr::AtomsConfiguration &config, Eigen::Index n_moving)
FieldMatrixd Coord
Definition Macros.h:35

◆ convergenceForceNorm()

double atmd::AtomicDimer::convergenceForceNorm ( const Eigen::Ref< const Eigen::RowVectorXd > & positions,
const Eigen::Ref< const Eigen::RowVectorXd > & gradient ) const
inlinenodiscard

gradient in the norm the convergence test applies at positions.

Definition at line 1072 of file AtomicDimer.h.

1075 {
1076 return forceNormForConvergence(positions, gradient);
1077 }

◆ execute()

void atmd::AtomicDimer::execute ( pot::PotentialWrapper & general_potential)

This function uses the atomic GP-dimer method to converge to a saddle point, starting from somewhere inside the convergence area.

The relaxation of the dimer on the approximated energy surface is done according to a dimer method, where a rotation step rotates the dimer (a pair of images) towards its minimum energy orientation to find the lowest curvature mode of the potential energy and translation step moves the dimer towards the saddle point by inverting the force component in the direction of the dimer. After each relaxation phase, the energy and gradient are acquired at the middle point of the dimer, and the GP hyperparameters are reoptimized.

Parameters
general_potentialReference to a class of general potential or to the object of Matter class (in a case of coupling with EON)

Definition at line 8950 of file AtomicDimer.cpp.

8951{
8952 struct RequireImprovingFallback {
8953 gpr::GaussianProcessRegression* model = nullptr;
8954 bool prior = false;
8955 explicit RequireImprovingFallback(gpr::GaussianProcessRegression* gp)
8956 : model(gp)
8957 {
8958 if (model == nullptr) return;
8959 prior = model->requiresScgFallbackImprovement();
8961 }
8962 ~RequireImprovingFallback()
8963 {
8964 if (model != nullptr)
8966 }
8967 RequireImprovingFallback(const RequireImprovingFallback&) = delete;
8968 RequireImprovingFallback& operator=(const RequireImprovingFallback&) =
8969 delete;
8970 } require_improving_fallback(gpr_model);
8971
8972 gpr::Observation middle_point;
8973
8974 gpr::FieldMatrixd E_gp;
8975 gpr::Coord orient;
8976 gpr::Coord orient_old;
8977 std::chrono::duration<double> elp_time;
8978 auto start = std::chrono::steady_clock::now();
8979 std::pair<double, gpr::Coord> eigen_data;
8980
8981 if (!isAtomsConfigurationCorrect()) {
8982 final_converged_ = false;
8983 relaxation_termination_reason_ =
8985 log_man
8986 << "Error! The structure of atoms configuration is incorrect!\n";
8987 return;
8988 }
8989 // Curvature priors belong to one search. A higher-order restart carries
8990 // its negative subspace as a proposal for fresh measurements.
8991 last_certificate_hessian_.resize(0, 0);
8992 last_certificate_positions_.resize(0, 0);
8993 if (!higher_order_restart_) index_search_directions_.resize(0, 0);
8994 measured_negative_directions_.clear();
8995 measured_negative_reference_.resize(0, 0);
8996 // Restore the configured tolerance when a certificate tightened it.
8997 if (std::isfinite(last_certificate_force_target_))
8998 stop_citeria_dimer.force = configured_force_criterion_;
8999 last_certificate_force_target_ = std::numeric_limits<double>::infinity();
9000 final_converged_ = false;
9001 final_rotation_omega_ = std::numeric_limits<double>::quiet_NaN();
9002 final_rotation_residual_ = std::numeric_limits<double>::infinity();
9003 measured_rotation_rounds_ = 0;
9004 measured_rotation_basis_.resize(0, 0);
9005 measured_index_zero_midpoint_.resize(0, 0);
9006 measured_index_zero_hessian_.resize(0, 0);
9007 measured_rotation_stationary_ = false;
9008 best_measured_rotation_residual_ = std::numeric_limits<double>::infinity();
9009 best_measured_orientation_.resize(0, 0);
9010 latest_mode_curvature_ = 0.0;
9011 inexact_curvature_logged_ = false;
9012 phase_history_.clear();
9013 dedup_rejected_observations_ = 0;
9014 consecutive_degenerate_probes_ = 0;
9015 consecutive_uninformative_rotations_ = 0;
9016
9017 gpr::coord::normalizeRow(orient_init, 0);
9018 middle_point.R = middle_point_init.R;
9019 orient = orient_init;
9020
9021 force_stop_certified_ = false;
9022 force_stop_certificate_calls_ = 0;
9023 budget_stop_midpoint_ = gpr::Observation();
9024 budget_stop_orientation_.resize(0, 0);
9025 struct BudgetUnwinds {
9026 bool& flag;
9027 explicit BudgetUnwinds(bool& f) : flag(f)
9028 {
9029 flag = true;
9030 }
9031 ~BudgetUnwinds()
9032 {
9033 flag = false;
9034 }
9035 } budget_unwinds(oracle_budget_unwinds_);
9036 try {
9037 // 1) Evaluate accurate energy E0 and force F0 at the middle point R0
9038 evaluateAccurateEnergyAndForceAtMidPoint(middle_point,
9039 general_potential);
9040
9041 // A midpoint already under the final tolerance needs no search; the
9042 // force-stop certificate below decides whether it is a saddle.
9043 const bool force_converged_at_start =
9044 isFinalConvergenceReached(middle_point, stop_citeria_dimer.force);
9045 if (force_converged_at_start) {
9046 final_converged_ = true;
9047 relaxation_termination_reason_ =
9049 log_man << "Force below tolerance at the start ("
9050 << getNumEvaluations()
9051 << " image evaluations); certifying the measured "
9052 "geometry.\n";
9053 eigen_data.first = latest_mode_curvature_;
9054 eigen_data.second = orient;
9055 } else {
9056 if (max_iter_init_rot.outer > 0) {
9057 // 3) Evaluate energy E1 and force F1 at R1
9058 updateLocation(orient, middle_point.R, image1.R);
9059 // Structural image-1 companion for the initial GP model:
9060 // never EMD-deduped.
9061 evaluateAccurateEnergyAndForce(image1, general_potential,
9062 /*apply_emd_dedup=*/false);
9063
9064 // 5) Repeat initial rotations until rotational convergence
9065 performInitialRotations(middle_point, orient,
9066 general_potential);
9067 }
9068
9069 if (max_iter_init_rot.outer == 0 &&
9070 (evaluate_image1_each_phase_ || all_obs.R.rows() < 2)) {
9071 updateLocation(orient, middle_point.R, image1.R);
9072 // Structural image-1 companion for the initial GP model:
9073 // never EMD-deduped.
9074 evaluateAccurateEnergyAndForce(image1, general_potential,
9075 /*apply_emd_dedup=*/false);
9076 log_man << "Evaluated image 1 of the dimer for the initial GP "
9077 "model.\n";
9078 }
9079
9080 eigen_data =
9081 performGPRIterations(middle_point, orient, general_potential);
9082 }
9083 } catch (const gpr::WallClockLimitReached&) {
9084 // Every completed accurate measurement updates this witness. A
9085 // deadline inside surrogate work or immediately before the next
9086 // oracle therefore returns measured state, never a partial trial.
9087 if (budget_stop_midpoint_.R.size() > 0) {
9088 middle_point = budget_stop_midpoint_;
9089 orient = budget_stop_orientation_;
9090 }
9091 final_converged_ = false;
9092 relaxation_termination_reason_ =
9094 log_man << "wall-clock limit reached; returning the best measured "
9095 "state; not converged.\n";
9096 eigen_data.first = latest_mode_curvature_;
9097 eigen_data.second = orient;
9098 if (middle_point.E.size() != 1 ||
9099 middle_point.G.cols() != middle_point.R.cols()) {
9100 middle_point.E = gpr::FieldMatrixd::Constant(
9101 1, 1, std::numeric_limits<double>::quiet_NaN());
9102 middle_point.G =
9103 gpr::Coord::Constant(1, middle_point.R.cols(),
9104 std::numeric_limits<double>::quiet_NaN());
9105 }
9106 } catch (const OracleBudgetExhausted& stop) {
9107 // Report the best measured midpoint of the relaxation; before it
9108 // starts, the midpoint is still the measured start.
9109 if (budget_stop_midpoint_.R.size() > 0) {
9110 middle_point = budget_stop_midpoint_;
9111 orient = budget_stop_orientation_;
9112 }
9113 final_converged_ = false;
9114 relaxation_termination_reason_ =
9116 log_man << "Stopped the search: " << stop.what()
9117 << "; not converged.\n";
9118 eigen_data.first = latest_mode_curvature_;
9119 eigen_data.second = orient;
9120 if (middle_point.E.size() != 1 ||
9121 middle_point.G.cols() != middle_point.R.cols()) {
9122 // No measurement at all: report none rather than a stale value.
9123 middle_point.E = gpr::FieldMatrixd::Constant(
9124 1, 1, std::numeric_limits<double>::quiet_NaN());
9125 middle_point.G =
9126 gpr::Coord::Constant(1, middle_point.R.cols(),
9127 std::numeric_limits<double>::quiet_NaN());
9128 }
9129 }
9130
9131 assignFinalResults(middle_point, eigen_data);
9132 certifyExecuteForceStop(general_potential);
9133
9134 if (debug_level == DEBUG_L1) {
9135 log_man << "\n";
9136 log_man << "Call statistics:\n";
9137 log_man << " General potential: " << getTotalForceCalls() << "\n";
9138 log_man << " GPR potential: " << getTotalGPRForceCalls() << "\n";
9139 log_man << "\n";
9140 }
9141
9142 elp_time = std::chrono::steady_clock::now() - start;
9143 log_man << "Elapsed time: " << elp_time.count() << "s\n";
9144 logPhaseTimingSummary(elp_time.count());
9145 if (middle_point_final.E.size() > 0) {
9146 std::ostringstream summary;
9147 const double energy_zero =
9148 (E_zero_level.size() > 0) ? E_zero_level(0, 0) : 0.0;
9149 double energy = getFinalEnergy() + energy_zero;
9150 writeDimerCampaignSummary(summary, energy, getConverged(), energy_zero);
9151 log_man << summary.str();
9152 }
9153
9154 if (shouldLogDimerFinalState(debug_level)) {
9155 log_man << "Final midpoint positions:\n"
9156 << middle_point_final.R << '\n';
9157 log_man << "Final midpoint energy:\n" << middle_point_final.E << '\n';
9158 log_man << "Final midpoint gradient:\n" << middle_point_final.G << '\n';
9159 }
9160}
@ DEBUG_L1
Definition Enums.h:41
gpr::Index_t getTotalGPRForceCalls() const
Return the total number of force calls.
gpr::Index_t getTotalForceCalls() const
Return the total number of force calls.
bool isFinalConvergenceReached(const gpr::Observation &middle_point, const double stop_criteria)
Final convergence test for force.
double getFinalEnergy() const
Return final energy.
bool getConverged() const
Return true when the final force convergence criterion is met.
bool requiresScgFallbackImprovement() const noexcept
void setRequireScgFallbackImprovement(bool enabled) noexcept
void writeDimerCampaignSummary(std::ostream &os, double energy, bool converged, double energy_zero)
bool shouldLogDimerFinalState(const gpr::Index_t debug_level) noexcept
@ 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.
void normalizeRow(FieldMatrixd &mat, Index_t i)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25

◆ finalMidpoint()

const gpr::Observation & atmd::AtomicDimer::finalMidpoint ( ) const
inlinenoexcept

Midpoint recorded at the end of execute().

Definition at line 845 of file AtomicDimer.h.

846 {
847 return middle_point_final;
848 }

◆ forceStopCertificateStep()

double atmd::AtomicDimer::forceStopCertificateStep ( ) const
inlinenodiscardnoexcept

Definition at line 790 of file AtomicDimer.h.

791 {
792 return force_stop_certificate_step_;
793 }

◆ getAlignmentAbortTol()

double atmd::AtomicDimer::getAlignmentAbortTol ( ) const
inlinenodiscardnoexcept

Definition at line 2427 of file AtomicDimer.h.

2428 {
2429 return alignment_abort_tol_;
2430 }

◆ getConverged()

bool atmd::AtomicDimer::getConverged ( ) const
inlinenodiscard

Return true when the final force convergence criterion is met.

Definition at line 136 of file AtomicDimer.inl.

137{
138 return final_converged_;
139}

◆ getConvergenceForce()

double atmd::AtomicDimer::getConvergenceForce ( ) const
inlinenodiscardnoexcept

Force norm below which the dimer search is converged.

Definition at line 1060 of file AtomicDimer.h.

1061 {
1062 return stop_citeria_dimer.force;
1063 }

◆ getDedupRejectedObservations()

gpr::Index_t atmd::AtomicDimer::getDedupRejectedObservations ( ) const
inlinenodiscardnoexcept

Number of freshly oracled rows the dimer rejected as EMD near-duplicates of an existing observation during ~execute~. A degenerate probe carries no conditioning information; a run of them is what the early-handback criterion watches.

Definition at line 2281 of file AtomicDimer.h.

2282 {
2283 return dedup_rejected_observations_;
2284 }

◆ getEnergyForAllObservationPointsRef()

gpr::FieldMatrixd & atmd::AtomicDimer::getEnergyForAllObservationPointsRef ( )
inline

Return energies for all observed points.

Return energies for all observation points.

Definition at line 155 of file AtomicDimer.inl.

156{
157 markObservedDataChanged();
158 return all_obs.E;
159}

◆ getEnergyZeroLevel()

gpr::FieldMatrixd atmd::AtomicDimer::getEnergyZeroLevel ( ) const
inlinenodiscard

Internal E_zero_level used by the dimer's cutOffEnergy bookkeeping. The energies returned by ~getEnergyForAllObservationPointsRef~ and ~getFinalEnergy~ are relative to this value, not absolute PES energies. Add E_zero_level back to recover the absolute energy.

Required by the OCINEB controller when harvesting the dimer's all_obs into a shared training_obs that the NEB expects to hold absolute PES energies.

Definition at line 1243 of file AtomicDimer.h.

1244 {
1245 return E_zero_level;
1246 }

◆ getEvaluateImage1EachPhase()

bool atmd::AtomicDimer::getEvaluateImage1EachPhase ( ) const
inlinenodiscardnoexcept

Definition at line 2452 of file AtomicDimer.h.

2453 {
2454 return evaluate_image1_each_phase_;
2455 }

◆ getFinalCoordOfMidPoint()

Eigen::VectorXd atmd::AtomicDimer::getFinalCoordOfMidPoint ( ) const
inlinenodiscard

Return final coordinates of the middle point.

Definition at line 98 of file AtomicDimer.inl.

99{
100 Eigen::VectorXd coord(middle_point_final.R.cols());
101
102 for (gpr::Index_t n = 0; n < coord.rows(); ++n)
103 coord(n) = middle_point_final.R(0, n);
104
105 return coord;
106}

◆ getFinalCurvature()

double atmd::AtomicDimer::getFinalCurvature ( ) const
inlinenodiscard

Return final curvature.

Definition at line 131 of file AtomicDimer.inl.

132{
133 return curvature_final;
134}

◆ getFinalEnergy()

double atmd::AtomicDimer::getFinalEnergy ( ) const
inlinenodiscard

Return final energy.

Definition at line 126 of file AtomicDimer.inl.

127{
128 return middle_point_final.E(0, 0);
129}

◆ getFinalForceAtMidPoint()

Eigen::VectorXd atmd::AtomicDimer::getFinalForceAtMidPoint ( ) const
inlinenodiscard

Deprecated alias of getFinalGradientAtMidPoint().

Despite the name it returns the gradient, not the force. Kept so existing callers keep their values; use the gradient name, or negate the result for the force.

Definition at line 88 of file AtomicDimer.inl.

89{
91}
Eigen::VectorXd getFinalGradientAtMidPoint() const
Return the final gradient dE/dR at the middle point.

◆ getFinalForceNormForConvergence()

double atmd::AtomicDimer::getFinalForceNormForConvergence ( ) const
inlinenodiscard

Return final force in the configured convergence norm.

Definition at line 93 of file AtomicDimer.inl.

94{
95 return forceNormForConvergence(middle_point_final);
96}

◆ getFinalGradientAtMidPoint()

Eigen::VectorXd atmd::AtomicDimer::getFinalGradientAtMidPoint ( ) const
inlinenodiscard

Return the final gradient dE/dR at the middle point.

The dimer stores gradients, so this is the negative of the force.

Definition at line 78 of file AtomicDimer.inl.

79{
80 Eigen::VectorXd gradient(middle_point_final.G.cols());
81
82 for (gpr::Index_t n = 0; n < gradient.rows(); ++n)
83 gradient(n) = middle_point_final.G(0, n);
84
85 return gradient;
86}

◆ getFinalOrientation()

const gpr::Coord & atmd::AtomicDimer::getFinalOrientation ( ) const
inlinenodiscard

Return final orientation of the dimer.

Definition at line 141 of file AtomicDimer.inl.

142{
143 return orient_final;
144}

◆ getFinalRotationAngle()

double atmd::AtomicDimer::getFinalRotationAngle ( ) const
inlinenoexcept

Min-mode rotational angle omega (radians) at the converged midpoint, or NaN if no converged phase recorded it. A small omega means the dimer axis is aligned with the true lowest-curvature eigenvector, so the caller can certify a flat saddle on angle + negative curvature rather than force alone.

Definition at line 829 of file AtomicDimer.h.

830 {
831 return final_rotation_omega_;
832 }

◆ getFinalRotationResidual()

double atmd::AtomicDimer::getFinalRotationResidual ( ) const
inlinenoexcept

Measured eigen-residual of the terminal mode in the convergence force norm: the gradient difference across the dimer after removing its component along the mode. Infinite until a converged phase records it.

Definition at line 865 of file AtomicDimer.h.

866 {
867 return final_rotation_residual_;
868 }

◆ getFirstSurrogateActionCertificate()

const DimerSurrogateActionCertificate & atmd::AtomicDimer::getFirstSurrogateActionCertificate ( ) const
inlinenodiscardnoexcept

Definition at line 1158 of file AtomicDimer.h.

1159 {
1160 return first_surrogate_action_;
1161 }

◆ getFixedThetaRefreshCalls()

gpr::Index_t atmd::AtomicDimer::getFixedThetaRefreshCalls ( ) const
inlinenodiscardnoexcept

Definition at line 2268 of file AtomicDimer.h.

2269 {
2270 return fixed_theta_refresh_calls_;
2271 }

◆ getForceStopCertificateCalls()

int atmd::AtomicDimer::getForceStopCertificateCalls ( ) const
inlinenodiscardnoexcept

Oracle evaluations the last execute() spent on its force-stop certificate, including escapes. They are part of getNumEvaluations().

Definition at line 801 of file AtomicDimer.h.

802 {
803 return force_stop_certificate_calls_;
804 }

◆ getForceStopCertified()

bool atmd::AtomicDimer::getForceStopCertified ( ) const
inlinenodiscardnoexcept

Whether the last execute() certified its force stop as index one.

Definition at line 795 of file AtomicDimer.h.

796 {
797 return force_stop_certified_;
798 }

◆ getGPRModel()

gpr::GaussianProcessRegression * atmd::AtomicDimer::getGPRModel ( )
inline

Get GPR model.

Definition at line 173 of file AtomicDimer.inl.

174{
175 return gpr_model;
176}

◆ getGradientForAllObservationPointsRef()

gpr::Coord & atmd::AtomicDimer::getGradientForAllObservationPointsRef ( )
inline

Return gradients for all observed points.

Return gradients for all observation points.

Definition at line 164 of file AtomicDimer.inl.

165{
166 markObservedDataChanged();
167 return all_obs.G;
168}

◆ getHdf5TracePath()

const std::string & atmd::AtomicDimer::getHdf5TracePath ( ) const
inlinenodiscardnoexcept

Definition at line 2542 of file AtomicDimer.h.

2543 {
2544 return hdf5_trace_path_;
2545 }

◆ getImspeAdmittedNearDuplicateObservations()

gpr::Index_t atmd::AtomicDimer::getImspeAdmittedNearDuplicateObservations ( ) const
inlinenodiscardnoexcept

Definition at line 2272 of file AtomicDimer.h.

2274 {
2275 return imspe_admitted_near_duplicate_observations_;
2276 }

◆ getImspeFixedThetaRefreshCalls()

gpr::Index_t atmd::AtomicDimer::getImspeFixedThetaRefreshCalls ( ) const
inlinenodiscardnoexcept

Definition at line 2264 of file AtomicDimer.h.

2265 {
2266 return fixed_theta_refresh_calls_;
2267 }

◆ getImspeSoftSkippedCalls()

gpr::Index_t atmd::AtomicDimer::getImspeSoftSkippedCalls ( ) const
inlinenodiscardnoexcept

Definition at line 2260 of file AtomicDimer.h.

2261 {
2262 return imspe_soft_skipped_calls_;
2263 }

◆ getInitialObservationCount()

gpr::Index_t atmd::AtomicDimer::getInitialObservationCount ( ) const
inlinenodiscard

Index of the first row in ~all_obs~ that the dimer appended during ~execute~. Pair with ~getNumNewObservations~ for harvest bookkeeping.

Definition at line 1227 of file AtomicDimer.h.

1228 {
1229 return N_obs_init;
1230 }

◆ getIterations()

gpr::Index_t atmd::AtomicDimer::getIterations ( ) const
inlinenodiscard

Return the total number of cycles.

This is essentially the number of relaxation phases

Definition at line 121 of file AtomicDimer.inl.

122{
123 return totalIterations;
124}

◆ getLatestModeCurvature()

double atmd::AtomicDimer::getLatestModeCurvature ( ) const
inlinenoexcept

Latest min-mode curvature from a dimer rotation. The force-stop stencil records the returned curvature separately in getFinalCurvature().

Definition at line 839 of file AtomicDimer.h.

840 {
841 return latest_mode_curvature_;
842 }

◆ getLeashRelaxWhenClose()

bool atmd::AtomicDimer::getLeashRelaxWhenClose ( ) const
inlinenodiscardnoexcept

Definition at line 2444 of file AtomicDimer.h.

2445 {
2446 return leash_relax_when_close_;
2447 }

◆ getMaxStepLength()

double atmd::AtomicDimer::getMaxStepLength ( ) const
inlinenodiscard

The bound of one translation step in Cartesian length (Angstrom).

Definition at line 1055 of file AtomicDimer.h.

1056 {
1057 return transition_param.max_step_length;
1058 }

◆ getMeasuredIndexZeroHessian()

Eigen::MatrixXd atmd::AtomicDimer::getMeasuredIndexZeroHessian ( ) const
inlinenodiscard

Cartesian Hessian of the complete measured expansion at the midpoint a MeasuredIndexZero relaxation stopped on, rigid directions zero. Empty after any other termination.

Definition at line 1125 of file AtomicDimer.h.

1126 {
1127 if (relaxation_termination_reason_ !=
1129 return {};
1130 return measured_index_zero_hessian_;
1131 }

◆ getMeasuredIndexZeroResolution()

double atmd::AtomicDimer::getMeasuredIndexZeroResolution ( ) const
inlinenodiscard

Empirical resolution in the mass-weighted physical space of the walk (eV/(A^2 amu)); zero after any other termination.

Definition at line 1136 of file AtomicDimer.h.

1137 {
1138 if (relaxation_termination_reason_ !=
1140 return 0.0;
1141 return measured_index_zero_resolution_;
1142 }

◆ getMidPointCoordForAllObservationPointsRef()

gpr::Coord & atmd::AtomicDimer::getMidPointCoordForAllObservationPointsRef ( )
inline

Return gpr::Coordinates of all observed points.

Definition at line 146 of file AtomicDimer.inl.

147{
148 markObservedDataChanged();
149 return all_obs.R;
150}

◆ getNumNewObservations()

gpr::Index_t atmd::AtomicDimer::getNumNewObservations ( ) const
inlinenodiscard

Number of accurate (general-potential) observations the dimer accumulated during ~execute~. Equals ~all_obs.E.rows() - N_obs_init~. The caller can pair this with ~getMidPointCoordForAllObservationPointsRef~ / ~getEnergyForAllObservationPointsRef~ / ~getGradientForAllObservationPointsRef~ to harvest the new rows back into a shared ~session.training_obs~ buffer. Energies are relative to ~getEnergyZeroLevel()~ as documented above.

Definition at line 1215 of file AtomicDimer.h.

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 }

◆ getOracleBatchChunk()

Eigen::Index atmd::AtomicDimer::getOracleBatchChunk ( ) const
inlinenodiscardnoexcept

Definition at line 2472 of file AtomicDimer.h.

2473 {
2474 return oracle_batch_chunk_;
2475 }

◆ getPhaseHistory()

const std::vector< DimerPhaseRecord > & atmd::AtomicDimer::getPhaseHistory ( ) const
inlinenodiscardnoexcept

Return the per-phase dimer trajectory history.

Definition at line 1110 of file AtomicDimer.h.

1112 {
1113 return phase_history_;
1114 }

◆ getProfileDimerTimes()

bool atmd::AtomicDimer::getProfileDimerTimes ( ) const
inlinenodiscardnoexcept

Definition at line 2489 of file AtomicDimer.h.

2490 {
2491 return getProfilePhaseTiming();
2492 }
bool getProfilePhaseTiming() const noexcept

◆ getProfilePhaseTiming()

bool atmd::AtomicDimer::getProfilePhaseTiming ( ) const
inlinenodiscardnoexcept

Definition at line 2481 of file AtomicDimer.h.

2482 {
2483 return profile_phase_timing_;
2484 }

◆ getRelaxationTerminationReason()

DimerRelaxationTerminationReason atmd::AtomicDimer::getRelaxationTerminationReason ( ) const
inlinenodiscardnoexcept

Definition at line 1117 of file AtomicDimer.h.

1118 {
1119 return relaxation_termination_reason_;
1120 }

◆ getTotalForceCalls()

gpr::Index_t atmd::AtomicDimer::getTotalForceCalls ( ) const
inlinenodiscard

Return the total number of force calls.

Definition at line 108 of file AtomicDimer.inl.

109{
110 return num_of_gen_potential_calls;
111}

◆ getTotalGPRForceCalls()

gpr::Index_t atmd::AtomicDimer::getTotalGPRForceCalls ( ) const
inlinenodiscard

Return the total number of force calls.

Definition at line 113 of file AtomicDimer.inl.

114{
115 if (gpr_model != nullptr) {
116 return gpr_model->getNumberOfPotentialCalls();
117 }
118 return 0;
119}

◆ getUseHssvdAnalyticCurvature()

bool atmd::AtomicDimer::getUseHssvdAnalyticCurvature ( ) const
inlinenodiscardnoexcept

Definition at line 2497 of file AtomicDimer.h.

2498 {
2499 return use_hssvd_analytic_curvature_;
2500 }

◆ getVarianceAcceptTau()

double atmd::AtomicDimer::getVarianceAcceptTau ( ) const
inlinenodiscardnoexcept

Definition at line 2238 of file AtomicDimer.h.

2239 {
2240 return variance_gate_.accept_tau;
2241 }

◆ getVarianceAcceptTauRelative()

double atmd::AtomicDimer::getVarianceAcceptTauRelative ( ) const
inlinenodiscardnoexcept

Definition at line 2252 of file AtomicDimer.h.

2253 {
2254 return variance_gate_.accept_tau_relative;
2255 }

◆ getVarianceGateConfig()

const VarianceGateConfig & atmd::AtomicDimer::getVarianceGateConfig ( ) const
inlinenodiscardnoexcept

Definition at line 2180 of file AtomicDimer.h.

2182 {
2183 return variance_gate_;
2184 }

◆ getVarianceSkippedAccurateCalls()

gpr::Index_t atmd::AtomicDimer::getVarianceSkippedAccurateCalls ( ) const
inlinenodiscardnoexcept

Definition at line 2256 of file AtomicDimer.h.

2257 {
2258 return variance_skipped_accurate_calls_;
2259 }

◆ gpMeanHessianAtMidpoint()

Eigen::MatrixXd atmd::AtomicDimer::gpMeanHessianAtMidpoint ( )
nodiscard

Hessian of the fitted posterior mean at the final midpoint, on all 3N Cartesian coordinates (eV/A^2), symmetrized; empty without a fitted model or a midpoint. No oracle call: the surrogate's own curvature, which proposes where a measurement should look.

Definition at line 2927 of file AtomicDimer.cpp.

2928{
2929 const Eigen::VectorXd origin = getFinalCoordOfMidPoint();
2930 const Eigen::Index dof = origin.size();
2931 if (dof < 6 || dof % 3 != 0 || gpr_model == nullptr || !origin.allFinite())
2932 return {};
2933 gpr::Coord R(1, dof);
2934 R.row(0) = origin.transpose();
2935 Eigen::MatrixXd hessian;
2936 if (!gpr_model->calculateMeanHessian(R, hessian)) return {};
2937 return 0.5 * (hessian + hessian.transpose());
2938}

◆ hasUnconditionedObservations()

bool atmd::AtomicDimer::hasUnconditionedObservations ( ) const
inlinenodiscardnoexcept

Retained measurements require conditioning before a posterior can represent the current observed data. The raw model accessor exposes its existing fitted state independently of the measured final point.

Definition at line 991 of file AtomicDimer.h.

992 {
993 return curvature_requires_full_refit_ ||
994 !hasOptimizedCurrentObservedData();
995 }

◆ hasValidAtomsConfiguration()

bool atmd::AtomicDimer::hasValidAtomsConfiguration ( )
inlinenodiscard

Whether the atoms configuration holds the moving-atom set that execute() needs.

execute() returns without searching when this is false; callers that bind the dimer to another language use it to report that as an error.

Definition at line 813 of file AtomicDimer.h.

814 {
815 return isAtomsConfigurationCorrect();
816 }

◆ hdf5TraceEnabled()

bool atmd::AtomicDimer::hdf5TraceEnabled ( ) const
inlinenodiscardnoexcept

Definition at line 2554 of file AtomicDimer.h.

2555 {
2556 return hdf5_trace_enabled_;
2557 }

◆ indexFrequencyResolution()

double atmd::AtomicDimer::indexFrequencyResolution ( ) const
inlinenodiscardnoexcept

Definition at line 2326 of file AtomicDimer.h.

2327 {
2328 return index_frequency_resolution_;
2329 }

◆ initialize()

void atmd::AtomicDimer::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.

Parameters
parametersStructure of parameters from the input file
initial_dataInitial observation (energy, gradients, positions)
middle_pointInitial observation at the middle point (energy, gradients, positions)
initial_orientationInitial orientation of the dimer
init_atom_configStructure with initial configuration of atoms

Definition at line 25 of file AtomicDimerInit.cpp.

30{
31 // Every seed entry uses the same refusal, including a row that never
32 // came from a file. A bad width or a non-finite value stops here.
33 Eigen::Index seed_cols = -1;
34 if (init_middle_point.R.cols() > 0)
35 seed_cols = init_middle_point.R.cols();
36 else if (init_orientation.cols() > 0)
37 seed_cols = init_orientation.cols();
38 gpr::io::refuseNonFiniteSeedRows(init_observations, seed_cols);
39
40 // A non-positive separation is not a dimer stencil. Initialization
41 // refuses it instead of installing a machine-epsilon dedup width.
42 if (!(std::isfinite(parameters.dimer_sep.value) &&
43 parameters.dimer_sep.value > 0.0)) {
44 throw std::invalid_argument("dimer_sep must be finite and positive");
45 }
46 const auto rotation_tolerance_in_range = [](const double value) {
47 return std::isfinite(value) && value > 0.0 &&
48 value < std::numbers::pi_v<double>;
49 };
50 if (!rotation_tolerance_in_range(parameters.T_anglerot_init.value) ||
51 !rotation_tolerance_in_range(parameters.T_anglerot_gp.value)) {
52 throw std::invalid_argument("rotation tolerance must lie in (0, pi)");
53 }
54
55 log_man.setEnabled(parameters.report_level.value >= 1);
56
57 phase_history_.clear();
58 higher_order_restart_ = false;
59 index_search_directions_.resize(0, 0);
60 last_certificate_hessian_.resize(0, 0);
61 last_certificate_positions_.resize(0, 0);
62 last_certificate_force_target_ = std::numeric_limits<double>::infinity();
63 curvature_requires_full_refit_ = false;
64 if (rgmin_trans_) rgmin_trans_->forget();
65 preserve_seed_kernel_ = false;
66
67 if (parameters.method_rot.value == "LBFGS_alg") method_rot = LBFGS_alg;
68 if (parameters.method_trans.value == "LBFGS_alg") method_trans = LBFGS_alg;
69
70 stop_citeria_dimer.force = parameters.T_dimer.value;
71 configured_force_criterion_ = parameters.T_dimer.value;
72 stop_citeria_dimer.angle_rotation = parameters.T_anglerot_init.value;
73
74 convergence_force_norm = static_cast<ConvergenceNormType>(
75 parameters.convergence_force_norm.value);
76
77 stop_citeria_gpr.angle_rotation = parameters.T_anglerot_gp.value;
78 // The live surrogate force stop is surrogateForceTolerance: the current
79 // oracle force divided by divisor_T_dimer_gp, and not below 0.1 * T_dimer.
80 // A non-positive divisor uses that floor alone. stop_citeria_gpr.force is
81 // not that stop.
82 divisor_stop_criteria_gpr = parameters.divisor_T_dimer_gp.value;
83
84 max_iter_init_rot.outer = parameters.num_iter_initrot.value;
85 max_iter_init_rot.inner = parameters.num_iter.value;
86 use_gpr_initial_rotations_ = parameters.initrot_nogp.value == 0;
87
88 max_iter_new_pairs.outer = parameters.num_bigiter.value;
89 max_iter_new_pairs.inner = parameters.num_iter.value;
90
91 max_iter_relax_rot.outer = 1;
92 max_iter_relax_rot.inner = parameters.num_iter_rot_gp.value;
93
94 // A positive value assumes num_iter exceeds what accurate-surface
95 // convergence needs, so a capped inner loop does not resume from the
96 // current geometry. The canonical readcon default 2 and the C default 1
97 // are both on.
98 assume_many_iterations = parameters.islarge_num_iter.value > 0;
99 evaluate_image1_each_phase_ = parameters.eval_image1.value != 0;
100
101 dimer_sep = parameters.dimer_sep.value;
102 ratio_at_limit = parameters.ratio_at_limit.value;
103 actdist_fro = parameters.actdist_fro.value;
104 num_bigiter_initloc = parameters.num_bigiter_initloc.value;
105 num_bigiter_initparam = parameters.num_bigiter_initparam.value;
106
107 // ====================================================================== //
108 // ====================================================================== //
109 gpr::Coord atoms_coords;
110 gpr::FieldMatrixIdx freezed_atoms;
111 cell_dimensions[0] = gpr::vector3_reg(parameters.cell_dimensions.value[0],
112 parameters.cell_dimensions.value[1],
113 parameters.cell_dimensions.value[2]);
114 cell_dimensions[1] = gpr::vector3_reg(parameters.cell_dimensions.value[3],
115 parameters.cell_dimensions.value[4],
116 parameters.cell_dimensions.value[5]);
117 cell_dimensions[2] = gpr::vector3_reg(parameters.cell_dimensions.value[6],
118 parameters.cell_dimensions.value[7],
119 parameters.cell_dimensions.value[8]);
120
121 orient_init = init_orientation;
122
123 middle_point_init = init_middle_point;
124 all_obs = init_observations;
125 refit_oracle_batch_.clear();
126 N_obs_init = all_obs.R.rows();
127 markObservedDataChanged();
128
129 atoms_config = init_atoms_config;
130 if (parameters.gp_nonperiodic.value) {
131 std::fill(std::begin(atoms_config.cell), std::end(atoms_config.cell),
132 0.0);
133 } else {
135 parameters.cell_dimensions.value);
136 }
137
138 // The oracle box stays parameters.cell_dimensions, including a 25 angstrom
139 // vacuum box. copyMicLattice does not install that box on the GP cell, and
140 // gp_nonperiodic zeros only the GP cell. Log the split; do not retarget
141 // the oracle.
142 {
143 const auto oracle_component = [&](const int index) {
144 return cell_dimensions[index / 3](index % 3);
145 };
146 bool cells_differ = false;
147 for (int index = 0; index < 9; ++index) {
148 if (atoms_config.cell[index] != oracle_component(index)) {
149 cells_differ = true;
150 break;
151 }
152 }
153 if (cells_differ) {
154 log_man << "Oracle cell and GP cell differ: oracle";
155 for (int index = 0; index < 9; ++index)
156 log_man << " " << oracle_component(index);
157 log_man << "; GP";
158 for (int index = 0; index < 9; ++index)
159 log_man << " " << atoms_config.cell[index];
160 log_man << ".\n";
161 }
162 }
163
164 // Self-owned path: build the GP descriptor here. External-GP path
165 // (~attachExternalGP~ was called before this): the caller has
166 // already initialised the GP from their session, and re-running
167 // ~initialize~ here would reset SCG/Cholesky scratch and the
168 // hyperparameter state the caller has been accumulating across
169 // outer iterations. Skip in that case.
170 if (!uses_external_gp_) {
171 if (gpr_model == nullptr) {
172 owned_gpr_model_ =
173 std::make_unique<gpr::GaussianProcessRegression>();
174 gpr_model = owned_gpr_model_.get();
175 }
176 gpr_model->initialize(parameters, atoms_config);
177 gpr_model->setModelProfile(self_owned_model_profile_);
178 gpr_model->setUseZBLPriorMean(self_owned_use_zbl_prior_mean_);
179 gpr_model->setUseFFPriorMean(self_owned_use_ff_prior_mean_);
180 // The self-owned surrogate fits exact NLML with SCG. A covering
181 // derivative layout, cutoff 0 included, uses the pair tiles. An
182 // attached session GP keeps the owner's switch.
183 if (gpr_model->pairLocalTilesEnabled())
184 gpr_model->setPairLocalDirectionalTiles(true);
185 }
186
187 transition_param.step_length = parameters.param_trans.value[0];
188 transition_param.max_step_length = parameters.param_trans.value[1];
189 transition_param.rotrem_thresh =
191
192 early_params._dist_metric = parameters.es_dist_metric.value;
193 early_params._threshold = parameters.es_threshold.value;
194 // disp_max is the fixed midpoint displacement cap from the nearest
195 // observation. A positive finite cap tightens the fixed trust threshold.
196 // es_threshold keeps its own default; a non-positive disp_max leaves that
197 // threshold unchanged. The adaptive schedule does not read this value.
198 if (std::isfinite(parameters.disp_max.value) &&
199 parameters.disp_max.value > 0.0) {
200 if (std::isfinite(early_params._threshold)) {
201 early_params._threshold =
202 std::min(early_params._threshold, parameters.disp_max.value);
203 } else {
204 early_params._threshold = parameters.disp_max.value;
205 }
206 }
207
208 // The midpoint dedup threshold is the dimer finite-difference stencil
209 // diameter. Initialization refuses a non-positive separation, so this
210 // width is not replaced by machine epsilon.
211 emd_dedup_threshold_ = 2.0 * dimer_sep;
212
213 // The stencil diameter is also the finest PES structure the dimer's
214 // sampling resolves: floor the kernel length scale there so the MAP
215 // projection cannot keep a collapsed delta-comb fit whose relaxation
216 // endpoints scatter into EMD-distinct probes every phase. Only the
217 // self-owned GP takes the dimer's floor; an attached session GP
218 // carries the chain-derived controls of its owner.
219 if (!uses_external_gp_ && gpr_model != nullptr) {
220 gpr_model->setLengthscaleFloor(emd_dedup_threshold_);
221 }
222
223 early_params._use_adaptive_threshold =
225 early_params._adaptive_A = parameters.es_adaptive_A.value;
226 early_params._adaptive_floor = parameters.es_adaptive_floor.value;
227 early_params._adaptive_t_min = parameters.es_t_min.value;
228 early_params._adaptive_delta_explore = parameters.es_delta_explore.value;
229 early_params._adaptive_half_life = parameters.es_half_life.value;
230
231 debug_output_info.out_dir = parameters.debug_output_dir.value;
232 debug_output_info.file_name_E = parameters.debug_output_file_E.value;
233 debug_output_info.file_name_R = parameters.debug_output_file_R.value;
234 debug_output_info.file_name_G = parameters.debug_output_file_G.value;
235 debug_output_info.file_extension =
237 debug_output_info.offset = parameters.debug_offset_from_mid_point.value;
238 debug_output_info.dy = parameters.debug_dy.value;
239 debug_output_info.dz = parameters.debug_dz.value;
240 debug_level = parameters.debug_level.value;
241 profile_phase_timing_ = parameters.profile_dimer_times.value;
242}
@ LBFGS_alg
Definition Enums.h:32
ConvergenceNormType
Definition Enums.h:48
bool copyMicLattice(double dest[9], const double src[9]) noexcept
Copy src onto dest only when src is a MIC lattice.
Definition MinImage.h:68
void refuseNonFiniteSeedRows(const Observation &observations, Eigen::Index expected_cols)
Definition GpState.cpp:587
Eigen::Vector3d vector3_reg
Definition Macros.h:36
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29
KeyValuePair< double[2]> param_trans
Definition Structures.h:440
KeyValuePair< double > T_anglerot_gp
Definition Structures.h:484
KeyValuePair< double > es_t_min
Definition Structures.h:659
KeyValuePair< std::string > debug_output_file_G
Definition Structures.h:589
KeyValuePair< int > initrot_nogp
Definition Structures.h:467
KeyValuePair< DistanceMetricType > es_dist_metric
Definition Structures.h:652
KeyValuePair< bool > es_use_adaptive_threshold
Definition Structures.h:655
KeyValuePair< double[9]> cell_dimensions
Definition Structures.h:605
KeyValuePair< double > dimer_sep
Definition Structures.h:425
KeyValuePair< int > islarge_num_iter
Definition Structures.h:544
KeyValuePair< int > report_level
Definition Structures.h:673
KeyValuePair< double > rotation_removal_projection_threshold
Definition Structures.h:667
KeyValuePair< double > T_anglerot_init
Definition Structures.h:474
KeyValuePair< std::string > debug_output_dir
Definition Structures.h:584
KeyValuePair< double > ratio_at_limit
Definition Structures.h:512
KeyValuePair< int > debug_level
Definition Structures.h:597
KeyValuePair< std::string > method_trans
Definition Structures.h:435
KeyValuePair< double > debug_dz
Definition Structures.h:596
KeyValuePair< int > gp_nonperiodic
Definition Structures.h:603
KeyValuePair< double > es_delta_explore
Definition Structures.h:660
KeyValuePair< int > num_bigiter_initloc
Definition Structures.h:519
KeyValuePair< int > convergence_force_norm
Definition Structures.h:461
KeyValuePair< double > actdist_fro
Definition Structures.h:379
KeyValuePair< int > num_bigiter_initparam
Definition Structures.h:527
KeyValuePair< std::string > method_rot
Definition Structures.h:430
KeyValuePair< int > divisor_T_dimer_gp
Definition Structures.h:498
KeyValuePair< int > num_iter
Definition Structures.h:537
KeyValuePair< int > num_iter_initrot
Definition Structures.h:479
KeyValuePair< int > eval_image1
Definition Structures.h:446
KeyValuePair< double > debug_offset_from_mid_point
Definition Structures.h:593
KeyValuePair< double > disp_max
Definition Structures.h:505
KeyValuePair< bool > profile_dimer_times
Definition Structures.h:633
KeyValuePair< std::string > debug_output_file_E
Definition Structures.h:587
KeyValuePair< double > es_adaptive_A
Definition Structures.h:657
KeyValuePair< int > es_half_life
Definition Structures.h:661
KeyValuePair< std::string > debug_output_file_extension
Definition Structures.h:591
KeyValuePair< int > num_bigiter
Definition Structures.h:532
KeyValuePair< double > es_threshold
Definition Structures.h:654
KeyValuePair< double > debug_dy
Definition Structures.h:595
KeyValuePair< std::string > debug_output_file_R
Definition Structures.h:585
KeyValuePair< double > es_adaptive_floor
Definition Structures.h:658
KeyValuePair< double > T_dimer
Definition Structures.h:453
KeyValuePair< int > num_iter_rot_gp
Definition Structures.h:490

◆ isApproximateRotationalConvergenceReached()

bool atmd::AtomicDimer::isApproximateRotationalConvergenceReached ( const gpr::Coord & orient,
const gpr::Observation & approx_obs,
const double stop_criteria )

GP-stencil rotational convergence test.

Evaluates the same finite-dimer angle equation used by the rotation optimizer on an approximate midpoint/image-1 stencil.

Definition at line 4148 of file AtomicDimer.cpp.

4151{
4152 if (stop_criteria <= 0.0 || !std::isfinite(stop_criteria)) return false;
4153 if (orient.rows() != 1 || orient.cols() == 0) return false;
4154 if (approx_obs.G.rows() < 2 || approx_obs.G.cols() != orient.cols())
4155 return false;
4156 if (!orient.allFinite() || !approx_obs.G.allFinite()) return false;
4157
4158 dimer::Dimer dimer(dimer_sep, is_subsystem(atoms_config));
4159 dimer.bindRgminTranslation(rgmin_trans_.get());
4160 gpr::Coord F_rot;
4161 dimer.rotateForce(approx_obs.G, orient, F_rot);
4162 const double omega =
4163 dimer.estimateRotationalAngle(orient, approx_obs.G, F_rot);
4164
4165 return std::isfinite(omega) && omega <= stop_criteria;
4166}

◆ isFinalConvergenceReached()

bool atmd::AtomicDimer::isFinalConvergenceReached ( const gpr::Observation & middle_point,
const double stop_criteria )

Final convergence test for force.

Compares forceNormForConvergence of the midpoint gradient to stop_criteria (T_dimer). The default norm is L2 of the full gradient vector (ConvergenceNormType::L2_NORM). Linf and per-atom max are selectable; they are not the default.

Parameters
middle_pointThe current mid-point of the configuration
stop_criteriaThe final convergence threshold
Returns
true if final convergence is reached

Definition at line 1577 of file AtomicDimer.cpp.

1579{
1580 const double max_value = forceNormForConvergence(middle_point);
1581
1582 if (max_value < stop_criteria) return true;
1583 log_man << "Current Max is " << max_value;
1584 if (project_rigid_modes_for_convergence_ && middle_point.G.rows() > 0) {
1585 const double raw_value = forceNormForConvergence(middle_point.G.row(0));
1586 if (std::isfinite(raw_value) && raw_value != max_value) {
1587 log_man << " (raw including rigid gauge modes " << raw_value << ")";
1588 }
1589 }
1590 log_man << "\n";
1591
1592 return false;
1593}

◆ isMinModeAngleCertified()

bool atmd::AtomicDimer::isMinModeAngleCertified ( ) const
inlinenoexcept

True iff the converged min-mode is angle-certified: a converged phase recorded a finite rotation omega within the dimer's own true-PES rotation tolerance (stop_citeria_dimer.angle_rotation) AND the converged curvature is negative (a real saddle direction). Uses the tolerance the dimer already rotated to – no new constant.

Definition at line 857 of file AtomicDimer.h.

858 {
859 return final_converged_ && measuredModeIsCertified();
860 }
bool measuredModeIsCertified() const noexcept

◆ isRotationalConvergenceReached()

bool atmd::AtomicDimer::isRotationalConvergenceReached ( const gpr::Coord & orient,
gpr::Observation & middle_point )

Rotational convergence test.

Parameters
orientCurrent dimer orientation
middle_pointCurrent midpoint observation, including its gradient
Returns
true if rotational convergence is reached

Definition at line 4124 of file AtomicDimer.cpp.

4126{
4127 dimer::Dimer dimer(dimer_sep, is_subsystem(atoms_config));
4128 dimer.bindRgminTranslation(rgmin_trans_.get());
4129 gpr::Coord F_rot;
4130 gpr::Coord G01_loc;
4131 bool is_convergence_rached = false;
4132
4133 G01_loc = middle_point.G;
4134 gpr::field::appendRows(G01_loc, image1.G);
4135
4136 dimer.rotateForce(G01_loc, orient, F_rot);
4137
4138 double omega = dimer.estimateRotationalAngle(orient, G01_loc, F_rot);
4139
4140 if (omega <= stop_citeria_dimer.angle_rotation)
4141 is_convergence_rached = true;
4142 else
4143 is_convergence_rached = false;
4144
4145 return is_convergence_rached;
4146}
void appendRows(Eigen::PlainObjectBase< Derived > &mat, const Eigen::PlainObjectBase< Derived > &other)

◆ kappaDimerBeta()

double atmd::AtomicDimer::kappaDimerBeta ( ) const
inlinenodiscardnoexcept

Definition at line 2537 of file AtomicDimer.h.

2538 {
2539 return kappa_dimer_beta_;
2540 }

◆ lastNegativeModeCount()

Eigen::Index atmd::AtomicDimer::lastNegativeModeCount ( ) const
inlinenodiscardnoexcept

Definition at line 2347 of file AtomicDimer.h.

2348 {
2349 return last_negative_mode_count_;
2350 }

◆ lastRefinementReachedIndexOne()

bool atmd::AtomicDimer::lastRefinementReachedIndexOne ( ) const
inlinenodiscardnoexcept

Whether the last measured partitioned-RFO refinement ended on an index-one model inside the force tolerance.

Definition at line 2371 of file AtomicDimer.h.

2372 {
2373 return last_refinement_reached_index_one_;
2374 }

◆ maxOracleCalls()

gpr::Index_t atmd::AtomicDimer::maxOracleCalls ( ) const
inlinenodiscardnoexcept

Definition at line 2313 of file AtomicDimer.h.

2314 {
2315 return max_oracle_calls_;
2316 }

◆ measureCurvatureProbes()

bool atmd::AtomicDimer::measureCurvatureProbes ( const gpr::Coord & positions,
pot::PotentialWrapper & potential,
gpr::Observation & raw )

Measure an all-moving Cartesian probe batch, one geometry per row. Every rank participates; the root supplies the positions and each point has one owner. Scalar engine calls preserve pointwise values. A batch that exceeds the remaining oracle budget makes no calls. Successful raw rows retain absolute energies and physical gradients in the archive without entering the GP training set. Refusal or an owner failure clears raw; every attempted point is still counted.

Definition at line 7521 of file AtomicDimer.cpp.

7524{
7525 gpr::Observation measured;
7526 measured.R = positions;
7527 raw = gpr::Observation();
7528 broadcastDenseMatrix(measured.R);
7529 const Eigen::Index atoms = atoms_config.is_frozen.size();
7530 bool valid = measured.R.rows() > 0 && atoms > 0 &&
7531 atoms_config.atomicNrs.size() == atoms &&
7532 (atoms_config.is_frozen.array() == MOVING_ATOM).all() &&
7533 measured.R.cols() == 3 * atoms && measured.R.allFinite();
7534 if (max_oracle_calls_ > 0) {
7535 const auto used = getNumEvaluations();
7536 valid = valid && used < max_oracle_calls_ &&
7537 measured.R.rows() <=
7538 static_cast<Eigen::Index>(max_oracle_calls_ - used);
7539 }
7542 valid ? std::string{}
7543 : "curvature probe batch has invalid coordinates or exceeds "
7544 "the remaining oracle budget",
7546 if (status.status != pot::OracleBatchStatus::Ok) return false;
7547 std::string failure;
7548 if (!acquireAccurateProbe(measured, potential, 1, failure)) {
7549 log_man << "Curvature probe batch failed: " << failure << "\n";
7550 return false;
7551 }
7552 raw = std::move(measured);
7553 broadcastObservation(raw);
7554 return true;
7555}
int status
@ Failed
A geometry was refused or a value was not finite; message set.
Definition OracleBatch.h:81
OracleBatchOutcome agreeOracleBatchStatus(OracleBatchStatus local_status, const std::string &local_message, const OracleBatchLayout &layout)
static OracleBatchLayout world(Eigen::Index chunk=0, int owner_offset=0)
The layout of the running communicator (rank 0 of 1 without MPI).

◆ measuredIndexRecoveryEnabled()

bool atmd::AtomicDimer::measuredIndexRecoveryEnabled ( ) const
inlinenodiscardnoexcept

Definition at line 2335 of file AtomicDimer.h.

2336 {
2337 return want_second_negative_mode_ &&
2338 (!external_terminal_certificate_ || higher_order_restart_);
2339 }

◆ measuredModeIsCertified()

bool atmd::AtomicDimer::measuredModeIsCertified ( ) const
noexcept

The recorded terminal mode has negative curvature and either its rotation angle is within the angle tolerance or the measured rotation sequence at its midpoint stopped lowering the residual.

Definition at line 1652 of file AtomicDimer.cpp.

1653{
1654 const double angle_tolerance = stop_citeria_dimer.angle_rotation;
1655 // A negative curvature within its own truncation estimate is not a
1656 // certified negative (17_claisen: -0.007 at the escape dimer's end,
1657 // the validation stencil found no negative mode).
1658 if (!std::isfinite(latest_mode_curvature_) ||
1659 !(latest_mode_curvature_ < -latest_mode_curvature_resolution_))
1660 return false;
1661 const bool angle_certified =
1662 std::isfinite(angle_tolerance) &&
1663 (angle_tolerance <= 0.0 || (std::isfinite(final_rotation_omega_) &&
1664 final_rotation_omega_ <= angle_tolerance));
1665 // The force residual is h * (H v - c v). It can fall below the
1666 // translational force tolerance solely by reducing the separation h,
1667 // with no improvement in orientation. Resolution-limited acceptance
1668 // requires the measured rotation sequence to stop improving.
1669 return angle_certified || measured_rotation_stationary_;
1670}

◆ preserveSeedKernel()

void atmd::AtomicDimer::preserveSeedKernel ( )
inlinenoexcept

Retain an imported kernel's parameters and absolute energy origin.

Definition at line 1184 of file AtomicDimer.h.

1185 {
1186 preserve_seed_kernel_ = true;
1187 }

◆ previewFirstSurrogateAction()

DimerSurrogateActionCertificate atmd::AtomicDimer::previewFirstSurrogateAction ( const gpr::Observation & oracle_middle_point,
const gpr::Coord & initial_orientation )
nodiscard

Evaluate exactly one GP-surrogate relaxation action without invoking the accurate potential. The initialized dimer parameters, model, observation set, force norm, and trust/globalization policy are all reused.

Definition at line 5728 of file AtomicDimer.cpp.

5731{
5732 DimerSurrogateActionCertificate action;
5733 if (gpr_model == nullptr || oracle_middle_point.R.rows() != 1 ||
5734 oracle_middle_point.R.cols() == 0 ||
5735 oracle_middle_point.G.rows() != 1 ||
5736 oracle_middle_point.G.cols() != oracle_middle_point.R.cols() ||
5737 initial_orientation.rows() != 1 ||
5738 initial_orientation.cols() != oracle_middle_point.R.cols() ||
5739 !oracle_middle_point.R.allFinite() ||
5740 !oracle_middle_point.G.allFinite() ||
5741 !initial_orientation.allFinite() ||
5742 !(initial_orientation.norm() > 0.0)) {
5743 return action;
5744 }
5745
5746 gpr::Observation middle_point = oracle_middle_point;
5747 gpr::Coord orient = initial_orientation / initial_orientation.norm();
5748 gpr::Coord R_latest_conv;
5749 gpr::Coord R_previous;
5750 gpr::Coord orient_latest_conv;
5751 gpr::Coord orient_previous;
5752 gpr::Coord R_new;
5753 gpr::Index_t num_esmax = 0;
5754 gpr::Index_t num_es1 = 0;
5755 bool require_midpoint_oracle = false;
5756 const double stop_dimer_gp = surrogateForceTolerance(oracle_middle_point);
5757 try {
5758 (void)performRotationAndTranslationWithGPR(
5759 stop_dimer_gp, middle_point, orient, R_latest_conv, R_previous,
5760 orient_latest_conv, orient_previous, R_new, num_esmax, num_es1,
5761 /*outer_iter_idx=*/0, require_midpoint_oracle, &action,
5762 /*stop_after_first_action=*/true, &oracle_middle_point);
5763 } catch (const std::runtime_error& error) {
5764 log_man << "GP action preview could not certify a step: "
5765 << error.what() << "\n";
5766 first_surrogate_action_ = {};
5767 return {};
5768 }
5769 return action;
5770}

◆ refineMeasuredModeCurvature()

void atmd::AtomicDimer::refineMeasuredModeCurvature ( const gpr::Observation & midpoint,
const gpr::Coord & orientation,
pot::PotentialWrapper & potential,
double surrogate_curvature )

Refine the measured mode curvature with a second image at twice the dimer separation when the single forward difference is within the surrogate's disagreement with it; one oracle call.

Definition at line 1680 of file AtomicDimer.cpp.

1684{
1685 latest_mode_curvature_resolution_ = 0.0;
1686 if (gpr::optim::curvatureResolvedBySurrogate(latest_mode_curvature_,
1687 surrogate_curvature))
1688 return;
1689 if (orientation.rows() != 1 || midpoint.G.rows() != 1 ||
1690 midpoint.G.cols() != orientation.cols() ||
1691 !(std::isfinite(dimer_sep) && dimer_sep > 0.0))
1692 return;
1693 const Eigen::RowVectorXd axis =
1694 orientation.row(0) /
1695 std::max(orientation.row(0).norm(), std::numeric_limits<double>::min());
1696 gpr::Observation far_image;
1697 far_image.R = midpoint.R + 2.0 * dimer_sep * axis;
1698 evaluateAccurateEnergyAndForce(far_image, potential,
1699 /*apply_emd_dedup=*/false);
1700 broadcastObservation(far_image);
1701 synchronizeObservedData();
1702 if (!far_image.G.allFinite() || far_image.G.cols() != orientation.cols())
1703 return;
1704 const double at_2h =
1705 axis.dot(far_image.G.row(0) - midpoint.G.row(0)) / (2.0 * dimer_sep);
1706 const double at_h = latest_mode_curvature_;
1707 latest_mode_curvature_ =
1709 latest_mode_curvature_resolution_ =
1710 std::abs(gpr::optim::richardsonForwardTruncation(at_h, at_2h));
1711 log_man << "Measured mode curvature refined: " << at_h
1712 << " at the dimer separation, " << at_2h << " at twice it, "
1713 << latest_mode_curvature_
1714 << " extrapolated with truncation "
1715 "estimate "
1716 << latest_mode_curvature_resolution_ << " (surrogate "
1717 << surrogate_curvature << ").\n";
1718}
double richardsonForwardTruncation(double at_h, double at_2h) noexcept
bool curvatureResolvedBySurrogate(double measured, double surrogate) noexcept
double richardsonForwardExtrapolate(double at_h, double at_2h) noexcept

◆ refineSaddleFromMeasuredHessian() [1/2]

bool atmd::AtomicDimer::refineSaddleFromMeasuredHessian ( const Eigen::MatrixXd & cartesian_hessian,
pot::PotentialWrapper & potential,
double resolution = 0.0 )

From a converged midpoint whose complete stencil shows a soft second negative mode (a weak mode resolved by the refinement, or a coarse curvature within twice the resolution): the force along it stays below the convergence threshold over displacements far longer than a dimer step, so a force-driven search stops anywhere on that ridge. Starting from the measured cartesian_hessian (eV/A^2), partitioned rational-function steps on the oracle maximize along the lowest mode and minimize along all others, with a Bofill update of a mass-weighted model from each measured gradient, rigid motion projected at the current geometry, and a Cartesian trust radius that starts at the translation limit. The two-sided defect of the modelled energy change over the clamped step, beyond the energy a force at the convergence threshold makes over the step in the configured norm, scores each step under the scale-free trust-region thresholds: a low score rejects the step and halves the radius, a high score after a clamped step restores it. The translation limit bounds the whole step on an inferred model. With complete_stencil, for a Hessian measured on every coordinate, it bounds the largest atomic displacement of the step, so the radius may reach the length at which the most displaced atom moves by the limit. After a rejected step, and before an index-one model ends the walk, the model's two lowest modes, and every further mode whose curvature lies within resolution (eV/(A^2 amu), the empirical resolution of the measurement that produced the Hessian) of zero, are measured by one Hessian action each at the dimer separation. With a positive resolution the walk was seeded by a complete stencil and ends at one, so an index-one model is then tested by the stencil's own four-point difference along the two steering modes (eight calls): a second curvature that is negative beyond its truncation error keeps the walk going. The walk takes the dimer's outer-iteration limit and oracle budget. It stops once the measured model has index one and the force is inside the tolerance, when the radius falls below coordinate resolution, or at the saddle energy floor; the floor and a walk without a step return false and leave the midpoint to the order-one restart, every other end hands the end point to the next search. One oracle call per step; the probes stay out of the training set, the end point becomes its only new row, and the next execute starts from it along the model's lowest mode.

Definition at line 2940 of file AtomicDimer.cpp.

2943{
2944 return refineSaddleFromMeasuredHessian(cartesian_hessian, potential,
2945 nullptr, resolution);
2946}
bool refineSaddleFromMeasuredHessian(const Eigen::MatrixXd &cartesian_hessian, pot::PotentialWrapper &potential, double resolution=0.0)

◆ refineSaddleFromMeasuredHessian() [2/2]

bool atmd::AtomicDimer::refineSaddleFromMeasuredHessian ( const Eigen::MatrixXd & cartesian_hessian,
pot::PotentialWrapper & potential,
gpr::Observation * raw_candidate,
double resolution = 0.0,
bool complete_stencil = false )

Return the exact raw oracle endpoint in packed moving coordinates when an index-one refinement ends strictly inside the force tolerance. This measurement carries no physical-frame or terminal certificate; the two-argument overload retains the same walk and handoff behavior.

Definition at line 2948 of file AtomicDimer.cpp.

2951{
2952 if (raw_candidate != nullptr) *raw_candidate = gpr::Observation();
2953 last_refinement_reached_index_one_ = false;
2954 // A model curvature inside the resolution of the measurement that
2955 // seeded the model carries no sign of its own.
2956 const double unresolved =
2957 std::isfinite(resolution) && resolution > 0.0 ? resolution : 0.0;
2958 const Eigen::VectorXd origin = getFinalCoordOfMidPoint();
2959 const Eigen::Index dof = origin.size();
2960 if (dof < 6 || dof % 3 != 0 || cartesian_hessian.rows() != dof ||
2961 cartesian_hessian.cols() != dof || !cartesian_hessian.allFinite() ||
2962 gpr_model == nullptr)
2963 return false;
2964 const Eigen::VectorXd masses =
2966 Eigen::VectorXd root(dof);
2967 for (Eigen::Index k = 0; k < dof; ++k)
2968 root(k) = std::sqrt(masses(k / 3));
2969 const Eigen::MatrixXd inverse_mass_weight =
2970 root.cwiseInverse() * root.cwiseInverse().transpose();
2971 const Eigen::MatrixXd cartesian_model =
2972 0.5 * (cartesian_hessian + cartesian_hessian.transpose());
2973 const auto vibrational = [&](const Eigen::VectorXd& positions) {
2974 gpr::Coord geometry(1, positions.size());
2975 geometry.row(0) = positions.transpose();
2977 atoms_config);
2978 };
2979 // The model lives on all 3N mass-weighted coordinates; each step
2980 // projects it onto the vibrational complement of rigid motion at the
2981 // current geometry, so the rotation a long walk accumulates against a
2982 // basis fixed at the start does not appear as a flat mode.
2983 Eigen::MatrixXd model = cartesian_model.cwiseProduct(inverse_mass_weight);
2984 if (secant_config_.seed_curvature) {
2985 const gpr::optim::SecantSeedStatus seeded =
2987 model, secant_hessian_, inverse_mass_weight,
2990 std::cout << "[secant-seed] measured walk keeps the surrogate "
2991 "Hessian: "
2992 << gpr::optim::secantSeedStatusName(seeded) << "\n";
2993 }
2994 // Probes stay out of the training set; every rank uses the root's
2995 // measurement, so every rank takes the same steps.
2996 const auto probe = [&](const Eigen::VectorXd& position,
2997 gpr::Observation& out,
2998 gpr::Observation* raw = nullptr) {
2999 if (oracleBudgetSpent()) return false;
3000 out = gpr::Observation();
3001 out.R.resize(1, dof);
3002 out.R.row(0) = position.transpose();
3003 const bool ok = evaluateAccurateProbe(out, potential, raw);
3004 broadcastObservation(out);
3005 if (raw != nullptr) broadcastObservation(*raw);
3006 return ok && out.E.size() == 1 && std::isfinite(out.E(0, 0)) &&
3007 out.G.rows() == 1 && out.G.cols() == dof && out.G.allFinite();
3008 };
3009 // The terminal midpoint holds a measured energy and gradient in the
3010 // same energy gauge as each probe. Keep that measurement at unchanged
3011 // geometry and use the root's row on every rank.
3012 gpr::Observation current = middle_point_final;
3013 gpr::Observation current_raw;
3014 broadcastObservation(current);
3015 const bool measured_origin =
3016 current.R.rows() == 1 && current.R.cols() == dof &&
3017 current.R.allFinite() &&
3018 (current.R.row(0).transpose().array() == origin.array()).all() &&
3019 current.E.size() == 1 && current.E.allFinite() &&
3020 current.G.rows() == 1 && current.G.cols() == dof &&
3021 current.G.allFinite();
3022 if (!measured_origin && !probe(origin, current)) return false;
3023 const double start_energy = current.E(0, 0);
3024 double force = forceNormForConvergence(current.R.row(0), current.G.row(0));
3025 const double tolerance = stop_citeria_dimer.force;
3026 const double limit = std::isfinite(transition_param.max_step_length) &&
3027 transition_param.max_step_length > 0.0
3028 ? transition_param.max_step_length
3029 : std::max(dimer_sep, 1.0e-3);
3030 // The Cartesian radius starts at the translation limit. A Cartesian
3031 // step longer than that along a torsion stretches the bonds of the
3032 // turning fragment at second order, which a quadratic model carried
3033 // along the walk does not predict; the measured energy then departs
3034 // from the model. The energy-model score contracts and restores the
3035 // radius under the scale-free trust-region thresholds. That stretch
3036 // is set by how far each atom of the fragment moves, not by how many
3037 // atoms move. On an inferred model the limit bounds the whole step.
3038 // For a Hessian measured on every coordinate it bounds the largest
3039 // atomic displacement of the step, so the radius may reach the
3040 // length at which the most displaced atom moves by the limit.
3041 //
3042 // That atomic bound is itself a trust region and follows the same
3043 // rule. A walk down a torsion of 30 cm^-1 covers ångströms for a few
3044 // hundredths of an eV; at the fixed bound it took 168 measured steps
3045 // with none refused. A step that sat on the bound, whose energy the
3046 // model predicted and whose measured gradient the model reproduced to
3047 // within the force tolerance, doubles the bound; a refused step halves
3048 // it back toward the limit. The gradient is the witness on a flat mode,
3049 // where the energy change is below its own resolution.
3050 const gpr::ScaleFreeTrustConfig trust_config;
3051 double radius = limit;
3052 double cap_scale = 1.0;
3053 int cap_expansions = 0;
3054 log_man << "Measured partitioned RFO from the stencil Hessian: " << dof
3055 << " coordinates, step limit " << limit << ", radius " << radius
3056 << ", start energy " << start_energy << ", force " << force
3057 << ", tolerance " << tolerance << ", saddle energy floor "
3058 << (std::isfinite(saddle_energy_floor_) && E_zero_level.size() > 0
3059 ? saddle_energy_floor_ - E_zero_level(0, 0)
3060 : std::numeric_limits<double>::quiet_NaN())
3061 << " (relative to the zero level).\n";
3062 bool converged = false;
3063 bool abandoned = false;
3064 bool collapsed = false;
3065 Eigen::Index steps = 0;
3066 Eigen::Index rejected = 0;
3067 Eigen::Index expansions = 0;
3068 Eigen::Index refreshes = 0;
3069 Eigen::Index pair_checks = 0;
3070 bool pair_refused = false;
3071 // A rejected step proved the model wrong at the current point; the
3072 // steering modes are measured there before the next proposal.
3073 bool refresh_due = false;
3074 bool measured_here = false;
3075 Eigen::VectorXd lowest;
3076 const auto bofill = [&](const Eigen::VectorXd& s,
3077 const Eigen::VectorXd& y) {
3080 };
3081 // Each trial is one oracle call, as each outer iteration of the dimer
3082 // is; the walk takes the dimer's outer-iteration limit and its oracle
3083 // budget.
3084 for (Eigen::Index trials = 0;
3085 gpr::iterationAllowedByLimit(trials, max_iter_new_pairs.outer) &&
3086 !oracleBudgetSpent();
3087 ++trials) {
3088 const Eigen::VectorXd x = current.R.row(0).transpose();
3089 const Eigen::MatrixXd basis = vibrational(x);
3090 const Eigen::Index n = basis.cols();
3091 if (n < 2) break;
3092 Eigen::VectorXd curvature;
3093 Eigen::MatrixXd modes;
3094 const auto resolve = [&]() {
3095 const Eigen::MatrixXd reduced = basis.transpose() * model * basis;
3096 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(
3097 0.5 * (reduced + reduced.transpose()));
3098 if (spectrum.info() != Eigen::Success) return false;
3099 curvature = spectrum.eigenvalues();
3100 modes = spectrum.eigenvectors();
3101 // The sign of an eigenvector is the solver's choice; a step
3102 // along a mode with no gradient component takes it. The entry
3103 // of largest magnitude is made positive, so every rank and
3104 // every linear-algebra build walks the same side.
3105 for (Eigen::Index k = 0; k < modes.cols(); ++k) {
3106 Eigen::Index pivot = 0;
3107 modes.col(k).cwiseAbs().maxCoeff(&pivot);
3108 if (modes(pivot, k) < 0.0) modes.col(k) *= -1.0;
3109 }
3110 return true;
3111 };
3112 if (!resolve()) break;
3113 // The walk steers by its two lowest modes. Measuring the Hessian
3114 // action along each of them, one oracle call per mode at the dimer
3115 // separation, corrects the model along those directions. Every
3116 // further mode whose curvature lies inside the resolution of the
3117 // seeding measurement is measured too: a secant model carried over
3118 // a long descent holds the sign of such a mode by inference alone,
3119 // and an inferred index-one point costs a complete stencil.
3120 const auto refresh = [&]() {
3121 // Without a dimer separation there is no displacement to
3122 // measure a Hessian action at; the secant model stands.
3123 if (!(dimer_sep > 0.0)) {
3124 refresh_due = false;
3125 measured_here = true;
3126 return true;
3127 }
3128 std::vector<Eigen::Index> columns{0, 1};
3129 for (Eigen::Index k = 2; k < n; ++k)
3130 if (std::abs(curvature(k)) <= unresolved) columns.push_back(k);
3131 const Eigen::Index measured_count =
3132 static_cast<Eigen::Index>(columns.size());
3133 Eigen::MatrixXd measured_basis(dof, measured_count);
3134 Eigen::MatrixXd measured_actions(dof, measured_count);
3135 for (Eigen::Index j = 0; j < measured_count; ++j) {
3136 const Eigen::Index k = columns[static_cast<std::size_t>(j)];
3137 const Eigen::VectorXd mode = basis * modes.col(k);
3138 Eigen::VectorXd direction = mode.cwiseQuotient(root);
3139 const double norm = direction.norm();
3140 if (!(norm > 0.0) || !std::isfinite(norm)) return false;
3141 direction *= dimer_sep / norm;
3142 gpr::Observation action;
3143 if (!probe(x + direction, action)) return false;
3144 const Eigen::VectorXd s = direction.cwiseProduct(root);
3145 const Eigen::VectorXd y = (action.G.row(0) - current.G.row(0))
3146 .transpose()
3147 .cwiseQuotient(root);
3148 const double length = mode.dot(s);
3149 if (!y.allFinite() || !(length > 0.0) || !std::isfinite(length))
3150 return false;
3151 measured_basis.col(j) = mode;
3152 measured_actions.col(j) = y / length;
3153 }
3154 // Fresh actions constrain their measured block and cross terms.
3155 // The unmeasured block retains its model curvature.
3156 Eigen::MatrixXd refreshed = gpr::optim::completeMeasuredHessian(
3157 model, measured_basis, measured_actions);
3158 if (refreshed.rows() != dof) return false;
3159 model = std::move(refreshed);
3160 refresh_due = false;
3161 measured_here = true;
3162 ++refreshes;
3163 if (!resolve()) return false;
3164 log_man << "Measured partitioned RFO: refreshed the model along "
3165 << columns.size() << " modes after step " << steps
3166 << "; curvatures now " << curvature(0) << " "
3167 << curvature(1) << ".\n";
3168 return true;
3169 };
3170 // An index-one model with the measured force inside the tolerance
3171 // ends the refinement; the complete stencil then judges the point.
3172 const auto index_one_candidate = [&]() {
3173 return steps > 0 && curvature(0) < 0.0 && curvature(1) > 0.0 &&
3174 force <= tolerance;
3175 };
3176 // The two lowest curvatures of a secant model carried over a long
3177 // descent are measured, not inferred, after a rejected step and
3178 // before the complete stencil is spent on an index-one point.
3179 if ((refresh_due || index_one_candidate()) && !measured_here) {
3180 if (!refresh()) break;
3181 }
3182 lowest = basis * modes.col(0);
3183 if (index_one_candidate()) {
3184 // A walk seeded by a complete stencil ends at a complete
3185 // stencil, which signs a weak mode by a four-point difference
3186 // along it. The walk meets a zero of its second curvature
3187 // first, where a one-sided action cannot sign it. The same
3188 // four-point difference along the two steering modes costs
3189 // eight calls, and a second curvature it finds negative
3190 // beyond its truncation error keeps the walk going instead of
3191 // spending the stencil on a point the stencil would refuse.
3192 // The stencil signs every mode inside its resolution, not the
3193 // steering pair alone: a floppy molecule has several, and the
3194 // walk has ended on a positive pair while another weak mode was
3195 // negative, which the stencil then refused. Each further weak
3196 // mode of the model takes the same four-point difference, four
3197 // calls where the refused stencil takes two per coordinate.
3198 if (unresolved > 0.0 && dimer_sep > 0.0) {
3199 std::vector<Eigen::Index> checked{0, 1};
3200 for (Eigen::Index k = 2; k < n; ++k)
3201 if (std::abs(curvature(k)) <= unresolved)
3202 checked.push_back(k);
3203 const Eigen::Index checked_count =
3204 static_cast<Eigen::Index>(checked.size());
3205 Eigen::MatrixXd steering(dof, checked_count);
3206 for (Eigen::Index j = 0; j < checked_count; ++j)
3207 steering.col(j) =
3208 basis * modes.col(checked[static_cast<std::size_t>(j)]);
3209 bool sampled = true;
3210 const auto sample = [&](const Eigen::MatrixXd& points) {
3211 Eigen::MatrixXd rows(points.cols(), dof);
3212 for (Eigen::Index j = 0; sampled && j < points.cols();
3213 ++j) {
3214 gpr::Observation at;
3215 sampled = probe(points.col(j), at);
3216 if (sampled) rows.row(j) = at.G.row(0);
3217 }
3218 return sampled ? rows : Eigen::MatrixXd();
3219 };
3221 x, masses, steering, dimer_sep, sample);
3222 if (!sampled) break;
3223 if (refined.valid &&
3224 refined.curvatures.size() == checked_count &&
3225 refined.action.allFinite()) {
3226 Eigen::MatrixXd measured =
3228 refined.action);
3229 if (measured.rows() == dof && measured.allFinite()) {
3230 model = std::move(measured);
3231 measured_here = true;
3232 ++pair_checks;
3233 if (!resolve()) break;
3234 lowest = basis * modes.col(0);
3235 }
3236 // The lowest of the measured curvatures beyond the
3237 // first decides: the second steering mode or a weak one.
3238 const double lowest_other =
3239 refined.curvatures.tail(checked_count - 1).minCoeff();
3240 const bool refused =
3241 std::isfinite(refined.error) &&
3242 lowest_other < -std::max(refined.error, 0.0);
3243 log_man << "Measured partitioned RFO: four-point "
3244 "curvatures of the steering pair after step "
3245 << steps << " are " << refined.curvatures(0) << " "
3246 << refined.curvatures(1) << " (error "
3247 << refined.error << "; " << checked_count - 2
3248 << " further weak mode(s), lowest of all but the "
3249 "first "
3250 << lowest_other << "); "
3251 << (refused ? "one beyond the first is negative, "
3252 "the walk continues.\n"
3253 : "none beyond the first is "
3254 "negative.\n");
3255 if (refused) pair_refused = true;
3256 }
3257 }
3258 // The model now holds the measured actions of the pair with
3259 // their cross terms, and its second curvature can lie below
3260 // the curvature measured along the earlier direction. The
3261 // walk ends only when that model is still index one: a pair
3262 // measured positive along an inexact direction has ended the
3263 // walk where the complete stencil still found a negative
3264 // second mode.
3265 if (!pair_refused && index_one_candidate()) {
3266 converged = true;
3267 break;
3268 }
3269 pair_refused = false;
3270 }
3271 // Both augmented partitions share a scaling chosen on the
3272 // Cartesian radius, retaining their stationarity equations
3273 // when the unrestricted step is too long.
3274 const Eigen::VectorXd gradient =
3275 basis.transpose() *
3276 current.G.row(0).transpose().cwiseQuotient(root);
3277 const Eigen::VectorXd projected = modes.transpose() * gradient;
3278 const Eigen::MatrixXd weighted_modes = basis * modes;
3279 Eigen::MatrixXd cartesian_modes = weighted_modes;
3280 for (Eigen::Index k = 0; k < dof; ++k)
3281 cartesian_modes.row(k) /= root(k);
3283 curvature, projected, cartesian_modes, radius);
3284 if (!proposal.valid) break;
3285 // Length of a step along the proposal at which its most displaced
3286 // atom moves by the translation limit.
3287 const auto atomic_cap = [&](const Eigen::VectorXd& step) {
3288 double largest = 0.0;
3289 for (Eigen::Index atom = 0; atom < dof / 3; ++atom)
3290 largest = std::max(largest, step.segment(3 * atom, 3).norm());
3291 const double length = step.norm();
3292 return largest > 0.0 && std::isfinite(largest)
3293 ? cap_scale * limit * length / largest
3294 : cap_scale * limit;
3295 };
3296 double radius_cap = limit;
3297 if (complete_stencil) {
3298 radius_cap = atomic_cap(proposal.cartesian_step);
3299 if (proposal.cartesian_step.norm() > radius_cap) {
3300 // The direction changed and an atom would pass the limit.
3301 radius = radius_cap;
3303 curvature, projected, cartesian_modes, radius);
3304 if (!proposal.valid) break;
3305 radius_cap =
3306 std::min(radius_cap, atomic_cap(proposal.cartesian_step));
3307 }
3308 }
3309 const bool clamped = proposal.boundary;
3310 const Eigen::VectorXd weighted = weighted_modes * proposal.eigen_step;
3311 const Eigen::VectorXd& displacement = proposal.cartesian_step;
3312 // Work at the requested force accuracy sets the model-error
3313 // allowance of the energy score. The dual displacement norm bounds
3314 // that work when the error of every atom lines up with its step;
3315 // summed over the atoms of a molecule it grows with their number
3316 // and, on a long step, absorbs a model that predicts the wrong sign
3317 // of the energy change, so the walk accepted and widened steps whose
3318 // force rose fortyfold. Errors of independent atoms add in
3319 // quadrature: the allowance is the tolerance times the Euclidean
3320 // length of the step.
3321 const Eigen::VectorXd predicted_change = model * weighted;
3322 const double predicted_energy_change =
3323 current.G.row(0).transpose().cwiseQuotient(root).dot(weighted) +
3324 0.5 * weighted.dot(predicted_change);
3325 const double energy_floor = tolerance * displacement.norm();
3326 gpr::Observation trial;
3327 gpr::Observation trial_raw;
3328 if (!probe(x + displacement, trial,
3329 raw_candidate != nullptr ? &trial_raw : nullptr))
3330 break;
3331 const double next =
3332 forceNormForConvergence(trial.R.row(0), trial.G.row(0));
3333 const Eigen::RowVectorXd cartesian_change =
3334 trial.G.row(0) - current.G.row(0);
3335 const Eigen::VectorXd change =
3336 cartesian_change.transpose().cwiseQuotient(root);
3337 const Eigen::RowVectorXd cartesian_prediction =
3338 predicted_change.cwiseProduct(root).transpose();
3339 if (!cartesian_change.allFinite() || !cartesian_prediction.allFinite())
3340 break;
3341 const double agreement = gpr::optim::gradientChangeAgreement(
3342 cartesian_change, cartesian_prediction);
3343 // Compare measured and modelled energy changes over the clamped
3344 // step.
3345 const double measured_energy_change = trial.E(0, 0) - current.E(0, 0);
3346 // The score is the two-sided defect of the model beyond that
3347 // allowance, relative to the predicted change; a signed ratio of
3348 // the changes would accept a step whose maximized mode fell while
3349 // the transverse modes fell further.
3350 const double defect = std::max(
3351 0.0, std::abs(measured_energy_change - predicted_energy_change) -
3352 energy_floor);
3353 const double ratio =
3354 defect == 0.0 ? 1.0
3355 : std::abs(predicted_energy_change) > 0.0
3356 ? 1.0 - defect / std::abs(predicted_energy_change)
3357 : 0.0;
3358 // The defect of the modelled gradient at the trial, g + B s, against
3359 // the measured one, in the configured norm, is recorded with the
3360 // step: on a flat mode it resolves the model where the energy
3361 // cannot.
3362 const double gradient_defect = forceNormForConvergence(
3363 trial.R.row(0), cartesian_change - cartesian_prediction);
3364 const bool accepted = ratio >= trust_config.rho_shrink;
3365 log_man << "Measured partitioned RFO step " << trials + 1
3366 << ": accepted " << steps << ", |x-x0| "
3367 << (trial.R.row(0).transpose() - origin).norm() << ", dE "
3368 << trial.E(0, 0) - start_energy << " (step measured "
3369 << measured_energy_change << ", model "
3370 << predicted_energy_change << "), force " << next
3371 << ", curvatures " << curvature(0) << " " << curvature(1)
3372 << ", mode gradients " << projected(0) << " "
3373 << (n > 1 ? projected(1) : 0.0) << ", step "
3374 << displacement.norm() << " of radius " << radius
3375 << ", RFO scaling " << proposal.scaling << ", hard case "
3376 << proposal.hard_case << ", agreement " << agreement
3377 << ", gradient defect " << gradient_defect << ", ratio "
3378 << ratio << (accepted ? ", accepted" : ", rejected") << "\n";
3379 if (!accepted) {
3380 radius *= trust_config.shrink_factor;
3381 cap_scale = std::max(1.0, cap_scale * trust_config.shrink_factor);
3382 ++rejected;
3383 refresh_due = true;
3384 // A trial the stored coordinates cannot tell from the current
3385 // point ends the walk: the radius is below coordinate
3386 // resolution.
3387 if (gpr::optim::coordinatesCoincideAtRoundoff(trial.R, current.R)) {
3388 log_man << "Measured partitioned RFO: the radius collapsed "
3389 "to coordinate resolution after "
3390 << rejected << " rejected steps; the walk ends.\n";
3391 collapsed = true;
3392 break;
3393 }
3394 continue;
3395 }
3396 // A first-order saddle between the endpoints lies above both.
3397 // A trial below the floor leaves the saddle region only when its
3398 // measured energy agrees with the model; inaccurate trials contract
3399 // the radius without moving the accepted point.
3400 if (std::isfinite(saddle_energy_floor_) && E_zero_level.size() > 0 &&
3401 trial.E(0, 0) + E_zero_level(0, 0) < saddle_energy_floor_) {
3402 log_man << "Measured partitioned RFO: step " << steps + 1
3403 << " measured " << trial.E(0, 0) + E_zero_level(0, 0)
3404 << " eV, below the saddle energy floor "
3405 << saddle_energy_floor_ << " eV; abandoning the walk.\n";
3406 abandoned = true;
3407 break;
3408 }
3409 // A clamped step the model predicted well restores the radius up
3410 // to the bound of this walk: the translation limit, or the length
3411 // at which the most displaced atom moves by it.
3412 if (clamped && ratio > trust_config.rho_grow) {
3413 const double next_radius =
3414 std::min(radius_cap, trust_config.grow_factor * radius);
3415 if (next_radius > radius) {
3416 radius = next_radius;
3417 ++expansions;
3418 } else if (complete_stencil && std::isfinite(gradient_defect) &&
3419 gradient_defect <= tolerance) {
3420 // On the atomic bound with a model that reproduced the
3421 // measured gradient: the bound grows for the next step.
3422 cap_scale *= trust_config.grow_factor;
3423 radius *= trust_config.grow_factor;
3424 ++cap_expansions;
3425 }
3426 }
3427 bofill(weighted, change);
3428 current = trial;
3429 if (raw_candidate != nullptr) current_raw = std::move(trial_raw);
3430 force = next;
3431 measured_here = false;
3432 ++steps;
3433 }
3434 // A walk that left the saddle region, or made no step, leaves the
3435 // refused midpoint to the order-one restart. Every other end hands
3436 // its end point to the next search.
3437 if (steps == 0 || abandoned) return false;
3438 last_refinement_reached_index_one_ = converged;
3439 retainStructuralObservation(current);
3440 synchronizeObservedData();
3441 curvature_requires_full_refit_ = true;
3442 middle_point_init = current;
3443 if (raw_candidate != nullptr && converged && force < tolerance)
3444 *raw_candidate = std::move(current_raw);
3445 if (lowest.size() == dof && lowest.norm() > 0.0) {
3446 orient_init.resize(1, dof);
3447 orient_init.row(0) =
3448 lowest.cwiseQuotient(root).normalized().transpose();
3449 } else if (getFinalOrientation().size() == dof) {
3450 orient_init = getFinalOrientation();
3451 }
3452 log_man << "Soft second negative mode: measured partitioned RFO from the "
3453 "stencil Hessian took "
3454 << steps << " steps (" << rejected << " rejected, " << expansions
3455 << " radius expansions, " << cap_expansions
3456 << " atomic bound expansions, " << refreshes
3457 << " measured mode refreshes, " << pair_checks
3458 << " four-point pair checks), moved "
3459 << (current.R.row(0).transpose() - origin).norm()
3460 << ", energy change " << current.E(0, 0) - start_energy
3461 << ", force " << force
3462 << (converged ? ", index-one model."
3463 : collapsed
3464 ? ", radius collapsed; the search continues from here."
3465 : ", index one not reached.")
3466 << "\n";
3467 return true;
3468}
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
const gpr::Coord & getFinalOrientation() const
Return final orientation of the dimer.
static bool update(Eigen::MatrixXd &matrix, SecantHessianMethod method, const Eigen::VectorXd &step, const Eigen::VectorXd &gradient_change)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
Half refined(GaussianProcessRegression &gp, const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &raw_options)
Eigen::MatrixXd completeMeasuredHessian(const Eigen::MatrixXd &prior, const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action)
Eigen::MatrixXd massWeightedPhysicalCurvatureBasis(const gpr::Coord &positions, const gpr::AtomsConfiguration &config, bool exclude_rotations=true)
SecantSeedStatus seedHessianFromSecant(Eigen::MatrixXd &model, const SecantHessian &secant, const Eigen::MatrixXd &weight, SecantSeedSupport support=SecantSeedSupport::WholeHessian)
RestrictedPartitionedRfoStep restrictedPartitionedRfoStep(const Eigen::VectorXd &curvatures, const Eigen::VectorXd &gradient, const Eigen::MatrixXd &cartesian_modes, double radius)
const char * secantSeedStatusName(SecantSeedStatus status) noexcept
RefinedWeakModes refineWeakModes(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, const Eigen::MatrixXd &weak, double step, const Gradients &gradients, double noise_multiplier=0.0)
double gradientChangeAgreement(const Eigen::Ref< const Eigen::RowVectorXd > &measured_change, const Eigen::Ref< const Eigen::RowVectorXd > &predicted_change)
bool coordinatesCoincideAtRoundoff(const Eigen::MatrixBase< Left > &left, const Eigen::MatrixBase< Right > &right) noexcept
constexpr bool iterationAllowedByLimit(Index_t iteration, Index_t configured_limit) noexcept
Definition Structures.h:90
double shrink_factor
0 < shrink_factor < 1
double rho_grow
grow when rho > rho_grow (TREGO)
double rho_shrink
shrink when rho < rho_shrink (TREGO)

◆ restartAlongWeakMode() [1/2]

bool atmd::AtomicDimer::restartAlongWeakMode ( const Eigen::VectorXd & direction,
double length,
const gpr::Observation & measured_rows,
pot::PotentialWrapper & potential )

The complete stencil cannot certify the weak modes of the converged midpoint positive. The curvature of the softest weak mode changes along the flat valley it spans; the search continues from the point length along the unit Cartesian direction, signed so that the curvature rises. The refinement rows become training rows, the moved point is measured, and the next execute starts from it. A supplied Cartesian Hessian carries a measured negative subspace into fresh index probes before the search returns for a complete stencil.

Definition at line 3659 of file AtomicDimer.cpp.

3663{
3664 return restartAlongWeakMode(direction, length, measured_rows, potential,
3665 Eigen::MatrixXd());
3666}
bool restartAlongWeakMode(const Eigen::VectorXd &direction, double length, const gpr::Observation &measured_rows, pot::PotentialWrapper &potential)

◆ restartAlongWeakMode() [2/2]

bool atmd::AtomicDimer::restartAlongWeakMode ( const Eigen::VectorXd & direction,
double length,
const gpr::Observation & measured_rows,
pot::PotentialWrapper & potential,
const Eigen::MatrixXd & cartesian_hessian )

Definition at line 3668 of file AtomicDimer.cpp.

3673{
3674 const Eigen::VectorXd final_position = getFinalCoordOfMidPoint();
3675 const Eigen::Index dof = final_position.size();
3676 if (dof == 0 || direction.size() != dof || !direction.allFinite() ||
3677 !(direction.norm() > 0.0) || !(length > 0.0) ||
3678 !std::isfinite(length) || gpr_model == nullptr ||
3679 (cartesian_hessian.size() != 0 &&
3680 (cartesian_hessian.rows() != dof || cartesian_hessian.cols() != dof ||
3681 !cartesian_hessian.allFinite())))
3682 return false;
3683 if (measured_rows.R.rows() > 0 && measured_rows.G.allFinite()) {
3684 // The rows carry absolute oracle energies; the training set is
3685 // referenced to the search's zero level.
3686 gpr::Observation rows = measured_rows;
3687 aux::ProblemSetUp problem_setup;
3688 problem_setup.cutOffEnergy(E_zero_level, rows.E);
3689 retainStructuralObservation(rows);
3690 synchronizeObservedData();
3691 }
3692 gpr::Observation moved;
3693 moved.R.resize(1, dof);
3694 moved.R.row(0) =
3695 (final_position + length * direction.normalized()).transpose();
3696 evaluateAccurateEnergyAndForce(moved, potential,
3697 /*apply_emd_dedup=*/false);
3698 if (moved.E.size() == 0 || !std::isfinite(moved.E(0, 0)) ||
3699 !moved.G.allFinite())
3700 return false;
3701 broadcastObservation(moved);
3702 synchronizeObservedData();
3703 curvature_requires_full_refit_ = true;
3704 middle_point_init = moved;
3705 if (cartesian_hessian.size() != 0)
3706 retainMeasuredNegativeSubspace(cartesian_hessian, moved.R);
3707 if (getFinalOrientation().size() == dof)
3708 orient_init = getFinalOrientation();
3709 // The step is a finished geometry. A force still under tolerance is
3710 // the result; the caller measures one stencil there instead of
3711 // opening another force loop.
3712 middle_point_final = moved;
3713 if (forceNormForConvergence(moved) < stop_citeria_dimer.force) {
3714 final_converged_ = true;
3715 relaxation_termination_reason_ =
3717 }
3718 log_man << "Weak-mode restart: the complete stencil cannot certify the "
3719 "weak modes positive; continuing "
3720 << length << " along the softest one.\n";
3721 return true;
3722}

◆ restartFromHigherOrderPoint()

bool atmd::AtomicDimer::restartFromHigherOrderPoint ( const Eigen::MatrixXd & cartesian_hessian,
const Eigen::VectorXd & kick,
const gpr::Observation & measured_rows,
pot::PotentialWrapper & potential )

From a converged midpoint the complete stencil shows to be a higher-order saddle: retain the measured rows along its weak negative mode, refit, and run the order-one search on the surrogate from the stencil Hessian (Cartesian, eV/A^2), started one stencil separation along kick on the side the surrogate ranks lower. The returned point is measured, and the next execute starts from it.

Definition at line 2813 of file AtomicDimer.cpp.

2816{
2817 const Eigen::VectorXd final_position = getFinalCoordOfMidPoint();
2818 const Eigen::Index dof = final_position.size();
2819 if (dof == 0 || cartesian_hessian.rows() != dof ||
2820 cartesian_hessian.cols() != dof || kick.size() != dof ||
2821 !cartesian_hessian.allFinite() || !(kick.norm() > 0.0) ||
2822 gpr_model == nullptr)
2823 return false;
2824 if (measured_rows.R.rows() > 0 && measured_rows.G.allFinite()) {
2825 // The rows carry absolute oracle energies; the training set is
2826 // referenced to the search's zero level.
2827 gpr::Observation rows = measured_rows;
2828 aux::ProblemSetUp problem_setup;
2829 problem_setup.cutOffEnergy(E_zero_level, rows.E);
2830 retainStructuralObservation(rows);
2831 synchronizeObservedData();
2832 }
2833 gpr::Observation midpoint;
2834 midpoint.R.resize(1, dof);
2835 midpoint.R.row(0) = final_position.transpose();
2836 curvature_requires_full_refit_ = true;
2837 refitGPRModel(false, midpoint, gpr::Coord(), false);
2838 const double separation = std::max(dimer_sep, 1.0e-3);
2839 const Eigen::VectorXd direction = kick.normalized();
2840 gpr::Observation plus_side, minus_side;
2841 plus_side.R = midpoint.R + separation * direction.transpose();
2842 minus_side.R = midpoint.R - separation * direction.transpose();
2843 calculateApproximatePotential(plus_side);
2844 calculateApproximatePotential(minus_side);
2845 gpr::Observation start = midpoint;
2846 start.R =
2847 plus_side.E(0, 0) <= minus_side.E(0, 0) ? plus_side.R : minus_side.R;
2848 escape_hessian_ = 0.5 * (cartesian_hessian + cartesian_hessian.transpose());
2849 gpr::Observation recovery;
2850 // The session refits again; the rows above are already retained.
2851 if (!escapeByOrderOneSaddleSession(start, potential, recovery) ||
2852 dimerGeometriesCoincide(recovery.R, midpoint.R)) {
2853 // A prefit consumes the curvature even when the surrogate stays at
2854 // the midpoint. Without active row checks, the escape needs a full fit.
2855 curvature_requires_full_refit_ =
2856 curvature_requires_full_refit_ ||
2857 !gpr_model->activePosteriorRefitsEnabled();
2858 // A surrogate that still places the mode positive pulls the
2859 // session back. The escape is then measured: halving finds the
2860 // first downhill trial along the mode, and the displacement
2861 // doubles while the measured energy keeps falling.
2862 gpr::Observation centre;
2863 centre.R = midpoint.R;
2864 evaluateAccurateEnergyAndForce(centre, potential,
2865 /*apply_emd_dedup=*/false);
2866 if (centre.E.size() == 0 || !std::isfinite(centre.E(0, 0)))
2867 return false;
2868 const double step = std::isfinite(transition_param.max_step_length) &&
2869 transition_param.max_step_length > 0.0
2870 ? transition_param.max_step_length
2871 : separation;
2872 const double sign_choice =
2873 plus_side.E(0, 0) <= minus_side.E(0, 0) ? 1.0 : -1.0;
2874 bool escaped = false;
2875 recovery = centre;
2876 // Halving stops once the trial coincides with the midpoint in the
2877 // stored coordinates.
2878 for (double length = step; !escaped; length *= 0.5) {
2879 bool resolved = false;
2880 for (double sign: {sign_choice, -sign_choice}) {
2881 gpr::Observation trial;
2882 trial.R = midpoint.R + sign * length * direction.transpose();
2884 midpoint.R))
2885 continue;
2886 resolved = true;
2887 evaluateAccurateEnergyAndForce(trial, potential,
2888 /*apply_emd_dedup=*/false);
2889 if (trial.E.size() > 0 && trial.G.allFinite() &&
2890 trial.E(0, 0) < centre.E(0, 0)) {
2891 recovery = trial;
2892 escaped = true;
2893 for (double next = 2.0 * length;; next *= 2.0) {
2894 gpr::Observation further;
2895 further.R =
2896 midpoint.R + sign * next * direction.transpose();
2897 gpr::Index_t outside = 0;
2898 if (isInterAtomicDistanceTooBig(further.R, all_obs.R,
2899 outside))
2900 break;
2901 evaluateAccurateEnergyAndForce(
2902 further, potential, /*apply_emd_dedup=*/false);
2903 if (!(further.E.size() > 0 && further.G.allFinite() &&
2904 further.E(0, 0) < recovery.E(0, 0)))
2905 break;
2906 recovery = further;
2907 }
2908 break;
2909 }
2910 }
2911 if (!resolved) break;
2912 }
2913 if (!escaped) return false;
2914 broadcastObservation(recovery);
2915 synchronizeObservedData();
2916 }
2917 middle_point_init = recovery;
2918 retainMeasuredNegativeSubspace(cartesian_hessian, recovery.R);
2919 if (getFinalOrientation().size() == dof)
2920 orient_init = getFinalOrientation();
2921 log_man << "Higher-order restart: complete stencil refused the "
2922 "converged midpoint; order-one search moved "
2923 << (recovery.R - midpoint.R).norm() << ".\n";
2924 return true;
2925}
bool dimerGeometriesCoincide(const gpr::Coord &a, const gpr::Coord &b) noexcept
Numerical geometry identity for cycle detection and measured-force rescue.
bool resolved(Dual value, Dual error, const BridgeResidualOptions &options)

◆ rotateDimer()

bool atmd::AtomicDimer::rotateDimer ( const double stop_criteria,
gpr::Coord & orient,
gpr::LBFGSInfo & rot_info,
gpr::Observation & middle_point,
gpr::Observation & approx_obs )

Rotate the dimer.

Definition at line 4168 of file AtomicDimer.cpp.

4172{
4173 dimer::Dimer dimer(dimer_sep, is_subsystem(atoms_config));
4174 dimer.bindRgminTranslation(rgmin_trans_.get());
4175 // UA-Dimer: hand the rotation the surrogate's per-degree-of-freedom force
4176 // variance at THIS geometry, so it removes the axial component in the
4177 // Sigma^{-1} metric. Probed fresh rather than reusing the gate's scratch:
4178 // that buffer belongs to whatever query last filled it, and a variance
4179 // from the wrong geometry would steer the rotation with stale anisotropy.
4180 if (uncertainty_aware_rotation_ && gpr_model != nullptr &&
4181 middle_point.R.rows() == 1 && middle_point.R.cols() > 0) {
4182 gpr::Observation rotation_variance;
4183 rotation_variance.R = middle_point.R;
4184 calculateApproximateVariance(rotation_variance);
4185 if (rotation_variance.G.rows() >= 1 &&
4186 rotation_variance.G.cols() == orient.cols() &&
4187 rotation_variance.G.row(0).allFinite()) {
4188 dimer.setForceVariance(rotation_variance.G.row(0).transpose());
4189 }
4190 }
4191 gpr::Observation observed{
4192 middle_point}; // observed coordinates, energy and gradient of
4193 // the middle point and the image 1
4194 // For starters it can just be the approx_obs
4195 gpr::Observation reduced_obs;
4196 gpr::Coord orient_old;
4197 double curv_dummy = 0; // dummy variable
4198 bool terminate_loop = false;
4199
4200 // if necessary, rotate the dimer and re-calculate approximated energy and
4201 // gradient at image 1
4202 orient_old = orient;
4203
4204 bool used_analytic_hessian = false;
4205 bool endpoint_is_measured = false;
4206 const bool can_use_analytic_hessian =
4207 gpr_model != nullptr && gpr_model->hasReusableHssvdPosterior() &&
4208 middle_point.R.rows() == 1 && middle_point.R.cols() > 0 &&
4209 approx_obs.G.rows() >= 1 &&
4210 approx_obs.G.cols() == middle_point.R.cols() &&
4211 approx_obs.E.rows() >= 1 && approx_obs.E.cols() >= 1 &&
4212 approx_obs.G.row(0).allFinite() && approx_obs.E.allFinite();
4213 if (can_use_analytic_hessian) {
4214 gpr::GaussianProcessRegression::PreparedHssvdHessianVector
4215 prepared_hssvd;
4216 const bool have_prepared_hssvd =
4217 gpr_model->prepareMeanHessianVectorHssvd(middle_point.R,
4218 prepared_hssvd);
4219 auto apply_hssvd_hvp = [&](const Eigen::VectorXd& dx,
4220 Eigen::VectorXd& hv) -> bool {
4221 if (have_prepared_hssvd)
4222 return gpr_model->applyMeanHessianVectorHssvd(prepared_hssvd,
4223 dx, hv);
4224 return gpr_model->calculateMeanHessianVectorDispatched(
4225 middle_point.R, dx, hv);
4226 };
4227 auto image1_evaluator = [&](gpr::Observation& candidate) -> bool {
4228 if (candidate.R.rows() != 1 ||
4229 candidate.R.cols() != middle_point.R.cols() ||
4230 !candidate.R.allFinite())
4231 return false;
4232 calculateApproximatePotential(candidate);
4233 return candidate.G.rows() == 1 &&
4234 candidate.G.cols() == middle_point.R.cols() &&
4235 candidate.E.rows() == 1 && candidate.E.cols() == 1 &&
4236 candidate.G.allFinite() && candidate.E.allFinite();
4237 };
4238
4239 gpr::Observation trial_observed{middle_point};
4240 gpr::Coord trial_orient = orient;
4241 double trial_curv = 0.0;
4242 const dimer::Dimer::RotationStepResult result = dimer.rotateWithHessian(
4243 middle_point.R, orient_old, approx_obs.G, false, image1_evaluator,
4244 trial_orient, trial_curv, trial_observed, apply_hssvd_hvp);
4246 observed = trial_observed;
4247 orient = trial_orient;
4248 curv_dummy = trial_curv;
4249 used_analytic_hessian = true;
4250 endpoint_is_measured = true;
4251 }
4252 }
4253
4254 if (!used_analytic_hessian) {
4255 dimer.rotate(middle_point.R, orient_old, approx_obs.G, POTENTIAL_GP,
4256 stop_criteria, false, all_obs, gpr_model, rot_info, orient,
4257 curv_dummy, observed);
4258 endpoint_is_measured = true;
4259 }
4260
4261 if (observed.R.size() != 0) {
4262 // NOTE: inline updateLocation for image 1
4263 for (gpr::Index_t n = 0; n < approx_obs.R.cols(); ++n) {
4264 approx_obs.R(1, n) =
4265 middle_point.R(0, n) + orient(0, n) * dimer_sep;
4266 }
4267
4268 const bool matching_endpoint =
4269 endpoint_is_measured && observed.R.rows() == 1 &&
4270 observed.R.cols() == approx_obs.R.cols() &&
4271 observed.G.rows() == 1 &&
4272 observed.G.cols() == approx_obs.G.cols() &&
4273 observed.E.rows() == 1 && observed.E.cols() == 1 &&
4274 observed.G.allFinite() && observed.E.allFinite() &&
4275 (observed.R.row(0) - approx_obs.R.row(1)).squaredNorm() == 0.0;
4276 if (matching_endpoint) {
4277 reduced_obs = std::move(observed);
4278 } else {
4279 gpr::field::appendRow(reduced_obs.R, approx_obs.R, 1);
4280 calculateApproximatePotential(reduced_obs);
4281 }
4282
4283 for (gpr::Index_t j = 0; j < approx_obs.R.cols(); ++j) {
4284 approx_obs.R(1, j) = reduced_obs.R(0, j);
4285 approx_obs.G(1, j) = reduced_obs.G(0, j);
4286 }
4287 approx_obs.E(0, 1) = reduced_obs.E(0, 0);
4288
4289 terminate_loop =
4290 checkRotationalConvergence(orient, orient_old, stop_criteria);
4291 } else {
4292 terminate_loop = true;
4293 log_man << "Dimer rotation converged (omega < T_anglerot); "
4294 "skipping image-1 update\n";
4295 }
4296
4297 return terminate_loop;
4298}
@ POTENTIAL_GP
Definition Enums.h:16
RotationStepResult
Definition Dimer.h:65
void appendRow(Eigen::PlainObjectBase< Derived > &mat, const Eigen::PlainObjectBase< Derived > &other, Eigen::Index i)

◆ secantCounts()

gpr::optim::SecantCurvatureCounts atmd::AtomicDimer::secantCounts ( ) const
nodiscard

Definition at line 840 of file AtomicDimer.cpp.

841{
842 gpr::optim::SecantCurvatureCounts counts = secant_counts_;
843 if (gpr_model != nullptr)
844 counts.quadratic_mean_uses += gpr_model->secantQuadraticPriorUses();
845 return counts;
846}

◆ secantHessian()

const gpr::optim::SecantHessian & atmd::AtomicDimer::secantHessian ( ) const
inlinenodiscardnoexcept

Definition at line 724 of file AtomicDimer.h.

726 {
727 return secant_hessian_;
728 }

◆ secantLedger()

gpr::optim::SecantCurvatureCounts atmd::AtomicDimer::secantLedger ( ) const
inlinenodiscardnoexcept

Pair, probe and rejection counts, without the GP's quadratic-mean uses.

Definition at line 731 of file AtomicDimer.h.

733 {
734 return secant_counts_;
735 }

◆ setAbortOnDegenerateProbes()

void atmd::AtomicDimer::setAbortOnDegenerateProbes ( bool enabled)
inlinenoexcept

Abort the search after ~kMaxConsecutiveDegenerateProbes~ EMD near-duplicate probes even without an alignment reference. The burst gets this through its alignment tolerance; a standalone search (the index-certificate escape) has no reference axis but the same degenerate-probe loop: the surrogate reports convergence at a point whose row it already holds, the oracle disagrees, and every re-measurement coalesces into that row.

Definition at line 2301 of file AtomicDimer.h.

2302 {
2303 abort_on_degenerate_probes_ = enabled;
2304 }

◆ setAbortOnInteratomicCollapse()

void atmd::AtomicDimer::setAbortOnInteratomicCollapse ( bool enabled)
inlinenoexcept

Abort the search when a measured midpoint's shortest interatomic distance drops below ~ratio_at_limit~ times the seed's: the canonical gprd bound on interatomic distances, applied to the measured trajectory. A standalone search on a surrogate that does not hold its rows can slide into a repulsive wall phase after phase (10_tetrazine: 300 phases to 336 eV/A); the bound ends it at the first measured collapse.

Definition at line 2382 of file AtomicDimer.h.

2383 {
2384 abort_on_interatomic_collapse_ = enabled;
2385 }

◆ setAlignmentAbortTol()

void atmd::AtomicDimer::setAlignmentAbortTol ( double tol)
inlinenoexcept

Alignment-governed termination tolerance alpha_tol. When > 0, each outer dimer phase computes alpha = abs(dot(d, tau)) between the current dimer axis and the axis that initialized the burst. The burst terminates when alpha drops below this tolerance. <= 0 disables the check.

Definition at line 2290 of file AtomicDimer.h.

2291 {
2292 alignment_abort_tol_ = tol;
2293 }

◆ setAtomsConfiguration()

void atmd::AtomicDimer::setAtomsConfiguration ( const gpr::AtomsConfiguration & _atoms_config)
inline

Set configuration of the atoms.

Parameters
_atoms_configA reference configuration

Definition at line 178 of file AtomicDimer.inl.

180{
181 atoms_config = _atoms_config;
182}

◆ setConvergenceForce()

void atmd::AtomicDimer::setConvergenceForce ( double force)
inline

Replace the configured true-PES force criterion and the live stop.

Definition at line 1065 of file AtomicDimer.h.

1066 {
1067 if (!(std::isfinite(force) && force > 0.0)) return;
1068 configured_force_criterion_ = force;
1069 stop_citeria_dimer.force = force;
1070 }

◆ setConvergenceForceNorm()

void atmd::AtomicDimer::setConvergenceForceNorm ( int norm_type)
inlinenoexcept

Definition at line 2456 of file AtomicDimer.h.

2457 {
2458 convergence_force_norm = static_cast<ConvergenceNormType>(norm_type);
2459 }

◆ setEvaluateImage1EachPhase()

void atmd::AtomicDimer::setEvaluateImage1EachPhase ( bool enabled)
inlinenoexcept

Definition at line 2448 of file AtomicDimer.h.

2449 {
2450 evaluate_image1_each_phase_ = enabled;
2451 }

◆ setExternalTerminalCertificate()

void atmd::AtomicDimer::setExternalTerminalCertificate ( bool enabled)
inlinenoexcept

Hand a force-converged point with a measured negative direction to the caller's complete-Hessian certificate without rotating its mode. The caller must resolve the index before accepting the saddle.

Definition at line 2343 of file AtomicDimer.h.

2344 {
2345 external_terminal_certificate_ = enabled;
2346 }

◆ setForceStopCertificateStep()

void atmd::AtomicDimer::setForceStopCertificateStep ( double step)
inlinenoexcept

Displacement of the index stencil execute() measures at a force stop before it reports convergence. Defaults to defaultStencilStep(). Zero, or setExternalTerminalCertificate(true), hands the certificate to the caller: execute() then reports the force stop, and the caller must certify it before claiming a saddle.

Definition at line 774 of file AtomicDimer.h.

775 {
776 force_stop_certificate_step_ = step;
777 }

◆ setHdf5TraceEnabled()

void atmd::AtomicDimer::setHdf5TraceEnabled ( bool enabled)
inline

Definition at line 2550 of file AtomicDimer.h.

2551 {
2552 hdf5_trace_enabled_ = enabled;
2553 }

◆ setHdf5TracePath()

void atmd::AtomicDimer::setHdf5TracePath ( const std::string & path)
inline

Definition at line 2514 of file AtomicDimer.h.

2515 {
2516 hdf5_trace_path_ = path;
2517 }

◆ setHssvdModeSelectionPolicy()

void atmd::AtomicDimer::setHssvdModeSelectionPolicy ( HssvdModeSelectionPolicy policy)
inlinenoexcept

Definition at line 2501 of file AtomicDimer.h.

2502 {
2503 hssvd_mode_selection_policy_ = policy;
2504 }

◆ setIndexFrequencyResolution()

void atmd::AtomicDimer::setIndexFrequencyResolution ( double wavenumber)
inlinenoexcept

Wavenumber (cm^-1) below which a mode counts as flat in the in-search index test: a measured curvature softer than this displacement's curvature at that wavenumber neither refuses the midpoint nor is followed. The independent validation reports such modes as unresolved at the same value.

Definition at line 2322 of file AtomicDimer.h.

2323 {
2324 index_frequency_resolution_ = wavenumber;
2325 }

◆ setKappaDimer()

void atmd::AtomicDimer::setKappaDimer ( double beta)

Xiao contour force at nonnegative dimer curvature; the ordinary dimer force once the curvature along the dimer is negative.

Definition at line 4335 of file AtomicDimer.cpp.

4336{
4337 if (!std::isfinite(beta) || beta < 0.0)
4338 throw std::invalid_argument(
4339 "kappa dimer beta must be finite and nonnegative");
4340 if (beta == 0.0) {
4341 kappa_dimer_beta_ = 0.0;
4342 kappa_dimer_client_.reset();
4343 return;
4344 }
4345 if (!kappa_dimer_client_) {
4346 auto client = std::make_unique<gpr::neb::RgsaddleClient>();
4347 if (!client->load() || !client->hasKappaDimer())
4348 throw std::runtime_error(
4349 "kappa dimer requires the linked rgsaddle kappa force ABI: " +
4350 client->lastMessage());
4351 kappa_dimer_client_ = std::move(client);
4352 }
4353 kappa_dimer_beta_ = beta;
4354 if (rgmin_trans_) rgmin_trans_->forget();
4355}

◆ setLeashRelaxWhenClose()

void atmd::AtomicDimer::setLeashRelaxWhenClose ( bool enabled)
inlinenoexcept

When set, the band-tangent alignment-abort leash is suspended once the dimer is close to its force criterion (largest force component under twice the dimer convergence force). The controller enables this only for bursts where the band tangent is an unreliable saddle-mode seed – the GP is over-confident-but-inaccurate at the CI, or the CI has reached the adaptive acceptance threshold. Far from the saddle the leash still holds, so a burst cannot wander onto a wrong saddle while the force is large; near the saddle the dimer is free to rotate onto the true local mode (which legitimately diverges from the coarse chain tangent).

Definition at line 2440 of file AtomicDimer.h.

2441 {
2442 leash_relax_when_close_ = enabled;
2443 }

◆ setLikelihoodNoiseFloorSigma2()

void atmd::AtomicDimer::setLikelihoodNoiseFloorSigma2 ( double floor_sigma2)
inlinenoexcept

Likelihood noise floor (sigma_n^2, energy units squared) applied after every internal hyperparameter refit. The dimer's rows come from the same oracle as the caller's session GP, so its likelihood must carry the same reported-noise floor; the refit re-seeds sigma2 from data statistics and would otherwise fit near-duplicate dimer steps against a vanishing nugget (near-singular local covariance, garbage min-mode curvature). NaN or non-positive disables.

Definition at line 2403 of file AtomicDimer.h.

2404 {
2405 likelihood_noise_floor_sigma2_ = floor_sigma2;
2406 }

◆ setMaxOracleCalls()

void atmd::AtomicDimer::setMaxOracleCalls ( gpr::Index_t calls)
inlinenoexcept

Caller's budget of true potential evaluations. No oracle call is started that would exceed it; the search then stops with DimerRelaxationTerminationReason::OracleBudget, unconverged. Zero or less leaves the search unbounded by calls.

Definition at line 2309 of file AtomicDimer.h.

2310 {
2311 max_oracle_calls_ = calls;
2312 }

◆ setMaxWallSeconds()

void atmd::AtomicDimer::setMaxWallSeconds ( double seconds)
inline

Set a wall-clock cap measured from this call. Non-positive disables.

Definition at line 737 of file AtomicDimer.h.

738 {
739 setWallClockLimit(seconds > 0.0 && std::isfinite(seconds)
740 ? std::make_shared<gpr::WallClockLimit>(seconds)
741 : nullptr);
742 }
void setWallClockLimit(std::shared_ptr< const gpr::WallClockLimit > limit)
Share an enclosing deadline (used by OCI-NEB and deterministic tests).

◆ setMeasuredEnergyCeiling()

void atmd::AtomicDimer::setMeasuredEnergyCeiling ( double ceiling)
inlinenoexcept

A converged midpoint whose measured (absolute) energy lies above ~ceiling~ is not accepted as converged. The escape from a refused index certificate looks for the saddle downhill of the refused point along its offending mode, so the saddle it may return lies below that point; a surrogate overshoot above it during the search is corrected by its own row and is not an abort. NaN disables.

Definition at line 2357 of file AtomicDimer.h.

2358 {
2359 measured_energy_ceiling_ = ceiling;
2360 }

◆ setOracleBatchChunk()

void atmd::AtomicDimer::setOracleBatchChunk ( Eigen::Index chunk)
inlinenoexcept

pot::OracleBatchLayout::chunk of every true-potential call: 0 shares the images out one by one and evaluates a rank's images in one call, K cuts a call into contiguous chunks of K images.

Definition at line 2468 of file AtomicDimer.h.

2469 {
2470 oracle_batch_chunk_ = chunk < 0 ? 0 : chunk;
2471 }

◆ setPreserveInitialAlignmentReference()

void atmd::AtomicDimer::setPreserveInitialAlignmentReference ( bool enabled)
inlinenoexcept

Keep the caller-supplied dimer axis as the alignment reference when analytic HS-SVD installs a minimum mode. OCI-NEB enables this because its supplied axis is the reaction-path tangent: a minimum mode that rotates away from it belongs to a different channel. Standalone dimer searches may instead track the first certified HS-SVD mode.

Definition at line 2391 of file AtomicDimer.h.

2392 {
2393 preserve_initial_alignment_reference_ = enabled;
2394 }

◆ setProfileDimerTimes()

void atmd::AtomicDimer::setProfileDimerTimes ( bool enabled)
inlinenoexcept

Definition at line 2485 of file AtomicDimer.h.

2486 {
2487 setProfilePhaseTiming(enabled);
2488 }
void setProfilePhaseTiming(bool enabled) noexcept

◆ setProfilePhaseTiming()

void atmd::AtomicDimer::setProfilePhaseTiming ( bool enabled)
inlinenoexcept

Definition at line 2477 of file AtomicDimer.h.

2478 {
2479 profile_phase_timing_ = enabled;
2480 }

◆ setProjectMeasuredRotations()

void atmd::AtomicDimer::setProjectMeasuredRotations ( bool enabled)
inlinenoexcept

Exclude molecular rigid rotations from measured orientation searches. Translations, frozen coordinates and index certification keep their physical constraints independently of this search-space choice.

Definition at line 2529 of file AtomicDimer.h.

2530 {
2531 project_measured_rotations_ = enabled;
2532 }

◆ setProjectRigidModesForConvergence()

void atmd::AtomicDimer::setProjectRigidModesForConvergence ( bool enabled)
inlinenoexcept

Definition at line 2460 of file AtomicDimer.h.

2461 {
2462 project_rigid_modes_for_convergence_ = enabled;
2463 }

◆ setRejectHigherIndexSurrogateConvergence()

void atmd::AtomicDimer::setRejectHigherIndexSurrogateConvergence ( bool enabled)
inlinenoexcept

See want_second_negative_mode_.

Definition at line 2331 of file AtomicDimer.h.

2332 {
2333 want_second_negative_mode_ = enabled;
2334 }

◆ setSaddleEnergyFloor()

void atmd::AtomicDimer::setSaddleEnergyFloor ( double floor)
inlinenoexcept

Absolute energy below which no first-order saddle between the search endpoints can lie (the higher endpoint energy). A measured partitioned-RFO refinement that steps below it is abandoned. NaN disables.

Definition at line 2365 of file AtomicDimer.h.

2366 {
2367 saddle_energy_floor_ = floor;
2368 }

◆ setSecantHessianConfig()

void atmd::AtomicDimer::setSecantHessianConfig ( const gpr::optim::SecantHessianConfig & config)

Replace the true-force secant and drop its history.

Definition at line 809 of file AtomicDimer.cpp.

811{
812 // BFGS only accepts positive-curvature pairs. Replacing a saddle model
813 // with that positive-only range can erase its measured negative mode.
814 if (config.seed_curvature &&
816 throw std::invalid_argument(
817 "saddle secant curvature seed does not support the BFGS method");
818 secant_config_ = config;
819 secant_hessian_ = gpr::optim::SecantHessian(config.method);
820 secant_force_samples_.clear();
821 secant_counts_ = {};
822 secant_pairs_checked_ = 0;
823 if (gpr_model != nullptr && !config.quadratic_prior_mean)
824 gpr_model->clearSecantQuadraticPrior();
825 if (!config.enabled()) return;
826 for (Eigen::Index row = 0; row < all_obs.R.rows(); ++row) {
827 if (row >= all_obs.E.rows() || all_obs.E.cols() < 1 ||
828 row >= all_obs.G.rows() || all_obs.G.cols() != all_obs.R.cols())
829 throw std::logic_error(
830 "secant replay is missing a retained true force");
832 secant_hessian_, all_obs.R.row(row).transpose(),
833 all_obs.G.row(row).transpose(), all_obs.E(row, 0), secant_counts_);
834 rememberSecantForceSample(all_obs.R.row(row).transpose(),
835 all_obs.G.row(row).transpose(),
836 all_obs.E(row, 0));
837 }
838}
void recordSecantObservation(SecantHessian &secant, const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, double energy, SecantCurvatureCounts &counts, SecantAccounting accounting=SecantAccounting::Count)
bool enabled() const noexcept

◆ setSecantOrientationSeed()

void atmd::AtomicDimer::setSecantOrientationSeed ( bool enabled)
inlinenoexcept

A caller that already seeded the orientation from a secant of its own turns this off, so the dimer's secant, replayed from whatever rows it was handed, does not replace that seed. The Hessian seeds are kept.

Definition at line 720 of file AtomicDimer.h.

721 {
722 secant_orientation_seed_ = enabled;
723 }

◆ setSelfOwnedModelProfile()

void atmd::AtomicDimer::setSelfOwnedModelProfile ( gpr::GPModelProfile profile)
inlinenoexcept

Model profile for the SELF-OWNED surrogate built by ~initialize~ from ~empty_obs~. An attached external GP keeps its owner's profile; the fresh-bootstrap burst must run the same coherent model family (classic CHEMGP/GPRD_ZBL vs EXTENDED) as the session it rescues.

Definition at line 2412 of file AtomicDimer.h.

2413 {
2414 self_owned_model_profile_ = profile;
2415 }

◆ setSelfOwnedUseFfPriorMean()

void atmd::AtomicDimer::setSelfOwnedUseFfPriorMean ( bool use)
inlinenoexcept

Definition at line 2423 of file AtomicDimer.h.

2424 {
2425 self_owned_use_ff_prior_mean_ = use;
2426 }

◆ setSelfOwnedUseZblPriorMean()

void atmd::AtomicDimer::setSelfOwnedUseZblPriorMean ( bool use)
inlinenoexcept

ZBL residual prior mean for the self-owned surrogate; keeps the fresh-bootstrap burst on the same compression wall as the session model that hands off to it.

Definition at line 2419 of file AtomicDimer.h.

2420 {
2421 self_owned_use_zbl_prior_mean_ = use;
2422 }

◆ setTrainingPolicy() [1/2]

void atmd::AtomicDimer::setTrainingPolicy ( const gpr::policy::TrainingPolicy * policy)

Not owned. The pointer must outlive execute(). Null is the engine.

Definition at line 1050 of file AtomicDimer.cpp.

1051{
1052 training_policy_owner_.reset();
1053 training_policy_ = policy;
1054}

◆ setTrainingPolicy() [2/2]

void atmd::AtomicDimer::setTrainingPolicy ( std::shared_ptr< const gpr::policy::TrainingPolicy > policy)

Keeps a Python adapter alive for execute(), which releases the GIL.

Definition at line 1056 of file AtomicDimer.cpp.

1058{
1059 training_policy_owner_ = std::move(policy);
1060 training_policy_ = training_policy_owner_.get();
1061}

◆ setUncertaintyAwareRotation()

void atmd::AtomicDimer::setUncertaintyAwareRotation ( bool enabled)
inlinenoexcept

Enable the UA-Dimer rotational projection (DOI 10.48550/arxiv.2605.24401).

Definition at line 2521 of file AtomicDimer.h.

2522 {
2523 uncertainty_aware_rotation_ = enabled;
2524 }

◆ setUseHssvdAnalyticCurvature()

void atmd::AtomicDimer::setUseHssvdAnalyticCurvature ( bool enabled)
inlinenoexcept

Definition at line 2493 of file AtomicDimer.h.

2494 {
2495 use_hssvd_analytic_curvature_ = enabled;
2496 }

◆ setVarianceAcceptTau()

void atmd::AtomicDimer::setVarianceAcceptTau ( double tau)
inlinenoexcept

Convenience setter for the absolute accept_tau alone; other fields of the default-constructed VarianceGateConfig are preserved.

Definition at line 2189 of file AtomicDimer.h.

2190 {
2191 variance_gate_.accept_tau = tau;
2192 }

◆ setVarianceAcceptTauRelative()

void atmd::AtomicDimer::setVarianceAcceptTauRelative ( double tau_relative)
inlinenoexcept

Convenience setter for the relative accept_tau alone. The effective absolute threshold is recomputed on every gate call from the current magnSigma2, so this setter need not be re-invoked when SCG re-fits the hyperparameters between outer iterations.

Definition at line 2248 of file AtomicDimer.h.

2249 {
2250 variance_gate_.accept_tau_relative = tau_relative;
2251 }

◆ setVarianceGateConfig()

void atmd::AtomicDimer::setVarianceGateConfig ( const VarianceGateConfig & cfg)
inlinenoexcept

Definition at line 2176 of file AtomicDimer.h.

2177 {
2178 variance_gate_ = cfg;
2179 }

◆ setVibrationalStencil()

void atmd::AtomicDimer::setVibrationalStencil ( gpr::optim::VibrationalStencil mode)
inlinenoexcept

Full measures every coordinate of the force-stop stencil. Vibrational measures vibrationalStencilDirections. Both displace every coordinate of a lone atom.

Definition at line 781 of file AtomicDimer.h.

782 {
783 vibrational_stencil_ = mode;
784 }

◆ setWallClockLimit()

void atmd::AtomicDimer::setWallClockLimit ( std::shared_ptr< const gpr::WallClockLimit > limit)
inline

Share an enclosing deadline (used by OCI-NEB and deterministic tests).

Definition at line 744 of file AtomicDimer.h.

745 {
746 wall_clock_limit_ = std::move(limit);
747 if (gpr_model != nullptr)
748 gpr_model->setWallClockLimit(wall_clock_limit_);
749 }

◆ stopForWallClockLimit()

void atmd::AtomicDimer::stopForWallClockLimit ( )

Mark a deadline raised by certificate/refinement work outside execute(). Restores the latest measured midpoint when one is available.

Definition at line 9162 of file AtomicDimer.cpp.

9163{
9164 if (budget_stop_midpoint_.R.size() > 0) {
9165 middle_point_final = budget_stop_midpoint_;
9166 orient_final = budget_stop_orientation_;
9167 }
9168 final_converged_ = false;
9169 relaxation_termination_reason_ =
9171}

◆ terminalModeIsReady()

bool atmd::AtomicDimer::terminalModeIsReady ( ) const
noexcept

A resolved negative direction suffices for handback when the caller certifies the complete Hessian. Standalone searches require the measured mode's rotation certificate.

Definition at line 1672 of file AtomicDimer.cpp.

1673{
1674 return measuredModeIsCertified() ||
1675 (external_terminal_certificate_ &&
1676 std::isfinite(latest_mode_curvature_) &&
1677 latest_mode_curvature_ < -latest_mode_curvature_resolution_);
1678}

◆ translateDimer()

void atmd::AtomicDimer::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.

Definition at line 4365 of file AtomicDimer.cpp.

4370{
4371 dimer::Dimer dimer(dimer_sep, is_subsystem(atoms_config));
4372 dimer.setProjectRotations(
4374 dimer.bindRgminTranslation(rgmin_trans_.get());
4375 gpr::Coord G01_approx_negative;
4376
4377 gpr::field::appendRow(G01_approx_negative, approx_obs.G, 0);
4378 G01_approx_negative *= -1.;
4379
4380 if (kappa_dimer_beta_ == 0.0) {
4381 if (kappa_dimer_refining_) resetTranslationHistory(trans_info);
4382 kappa_dimer_refining_ = false;
4383 if (curvature < 0.0 &&
4384 projectedTrustRegionStep(middle_point.R, G01_approx_negative,
4385 transition_param.max_step_length, R_new))
4386 return;
4387 dimer.translate(middle_point.R, orient, G01_approx_negative, curvature,
4388 transition_param, trans_info, R_new);
4389 return;
4390 }
4391 const Eigen::Index dof = middle_point.R.cols();
4392 Eigen::MatrixXd excluded(dof, 0);
4394 excluded = dimer::rigid_motion_basis(
4395 middle_point.R,
4397 const Eigen::VectorXd gradient = approx_obs.G.row(0).transpose();
4398 // The contour force is a basin constraint: it keeps a dimer that has
4399 // not yet reached a ridge from converging to a saddle of another basin.
4400 // At certified negative curvature along the dimer the search is on the
4401 // ridge, and Xiao's near-saddle protocol sets both switching
4402 // coefficients to unity, the ordinary dimer force. Near a saddle the
4403 // contour mode is the dimer mode itself: kappa = -nu/|g| diverges as
4404 // the gradient vanishes, the parallel coefficient tends to -1, and the
4405 // contour force walks the dimer back down its own mode. A gradient
4406 // threshold on the switch (12_h2co: 55 of 57 phases measured a step
4407 // that raised the residual, the search alternating between the two
4408 // forces) only moves where that happens.
4409 const bool refine = curvature < 0.0;
4410 if (refine != kappa_dimer_refining_) resetTranslationHistory(trans_info);
4411 kappa_dimer_refining_ = refine;
4412 if (refine) {
4413 log_man << "Kappa dimer refinement: curvature=" << curvature
4414 << " hessian_actions=0\n";
4415 if (projectedTrustRegionStep(middle_point.R, G01_approx_negative,
4416 transition_param.max_step_length, R_new))
4417 return;
4418 dimer.translate(middle_point.R, orient, G01_approx_negative, curvature,
4419 transition_param, trans_info, R_new);
4420 return;
4421 }
4422 prepareIndexOneProjection(middle_point.R);
4423 const auto hessian = gpr_model->prepareMeanHessian(middle_point.R);
4424 std::function<bool(const Eigen::VectorXd&, Eigen::VectorXd&)> action =
4425 [&](const Eigen::VectorXd& v, Eigen::VectorXd& hv) {
4426 const bool ok = hessian && hessian(v, hv);
4427 if (ok) applyIndexOneProjection(v, hv);
4428 return ok;
4429 };
4430 const auto callback = [](void* user, int64_t n, const double* v,
4431 double* hv) -> int {
4432 auto& apply = *static_cast<decltype(action)*>(user);
4433 try {
4434 Eigen::VectorXd result;
4435 if (!apply(Eigen::Map<const Eigen::VectorXd>(v, n), result) ||
4436 result.size() != n || !result.allFinite())
4437 return -1;
4438 Eigen::Map<Eigen::VectorXd>(hv, n) = result;
4439 return 0;
4440 } catch (...) {
4441 return -1;
4442 }
4443 };
4444 // The linked client is ABI minor 71 or later. Pass its minor.
4445 const std::uint32_t kappa_abi_minor =
4446 std::max(kappa_dimer_client_->abiMinor(),
4449 {GPR_RGSADDLE_ABI_MAJOR, kappa_abi_minor},
4450 kappa_dimer_beta_,
4451 1e-5,
4452 100,
4453 12,
4454 14};
4456 gpr::Coord force(1, dof);
4457 const int status = kappa_dimer_client_->kappaDimerForce(
4458 &config, dof, gradient.data(), orient.data(), excluded.cols(),
4459 excluded.data(), callback, &action, force.data(), &report);
4460 if (status != 0) {
4461 // A refused kappa force (a non-finite surrogate Hessian action at
4462 // this midpoint, a solver failure) is a statement about the
4463 // surrogate here, not a reason to end the search: the plain dimer
4464 // translation on the surrogate gradient takes the step, and the
4465 // measured checks of the outer loop judge it. A non-finite
4466 // gradient leaves the midpoint in place for the same judgement.
4467 log_man << "Kappa dimer force unavailable (rgsaddle status " << status
4468 << "); plain dimer translation on the surrogate gradient.\n";
4469 if (!G01_approx_negative.allFinite()) {
4470 R_new = middle_point.R;
4471 return;
4472 }
4473 dimer.translate(middle_point.R, orient, G01_approx_negative, curvature,
4474 transition_param, trans_info, R_new);
4475 return;
4476 }
4477 log_man << "Kappa dimer: kappa=" << report.kappa
4478 << " tangent_curvature=" << report.tangent_curvature
4479 << " hessian_actions=" << report.hessian_actions << "\n";
4480 dimer.translateWithForce(middle_point.R, force, transition_param,
4481 trans_info, R_new);
4482}
static constexpr uint32_t kMinimumAbiMinor
eon_relax_band_t eon_relax_surface_fn void * user
Eigen::MatrixXd rigid_motion_basis(const gpr::Coord &R, bool rotations)
Build an orthonormal basis for rigid-body translations and rotations.
Definition Dimer.cpp:30
rgsaddle_kappa_config_t gpr_rgsaddle_kappa_config_t
rgsaddle_kappa_report_t gpr_rgsaddle_kappa_report_t
#define GPR_RGSADDLE_ABI_MAJOR

◆ updateActiveFrozenAtoms()

bool atmd::AtomicDimer::updateActiveFrozenAtoms ( const gpr::Coord & R_new,
gpr::LBFGSInfo & rot_info,
gpr::LBFGSInfo & trans_info )

Update active frozen atoms.

Returns
True if new atoms are activated

Definition at line 4484 of file AtomicDimer.cpp.

4487{
4488 aux::ProblemSetUp setup;
4489 bool atoms_were_updated = false;
4490
4491 if (debug_level == DEBUG_L1 || debug_level == DEBUG_L2 ||
4492 debug_level == DEBUG_L3) {
4493 log_man << "Frozen:: "
4494 << atoms_config.atoms_froz_active.positions.size()
4495 << " active, "
4496 << atoms_config.atoms_froz_inactive.positions.size()
4497 << " inactive\n"
4498 << "Moving:: " << atoms_config.atoms_mov.positions.size()
4499 << " Total:: " << atoms_config.positions.size() << "\n";
4500 }
4501
4502 if (std::isfinite(actdist_fro)) {
4503 atoms_were_updated =
4504 setup.activateFrozenAtoms(R_new, actdist_fro, atoms_config);
4505 active_frozen_count_ = static_cast<gpr::Index_t>(
4506 atoms_config.atoms_froz_active.positions.cols() / 3);
4507 if (atoms_were_updated) {
4508 ++active_set_change_count_;
4509 if (profile_phase_timing_) {
4510 log_man << "Active-frozen-set change #"
4511 << active_set_change_count_ << ": now "
4512 << active_frozen_count_ << " active frozen atoms.\n";
4513 }
4514 log_man << "More frozen atoms activated. Syncing GPR.\n";
4515
4516 // Keep the GPR model descriptor tables aligned with the
4517 // active/frozen atom partition used by the dimer.
4518 gpr_model->updateConfiguration(atoms_config);
4519
4520 // The optimizer histories depend on the active coordinate
4521 // subspace and are reset when that subspace changes.
4522 rot_info.clear();
4523 resetTranslationHistory(trans_info);
4524
4525 // Hyperparameters are re-optimized after the configuration is
4526 // synchronized in performRotationAndTranslationWithGPR.
4527 }
4528 }
4529 return atoms_were_updated;
4530}
@ DEBUG_L2
Definition Enums.h:42
@ DEBUG_L3
Definition Enums.h:43
bool activateFrozenAtoms(const gpr::Coord &R, const double activation_distance, gpr::AtomsConfiguration &atoms_config)
Update the active frozen-atom set for one or more configurations.

◆ vibrationalStencil()

gpr::optim::VibrationalStencil atmd::AtomicDimer::vibrationalStencil ( ) const
inlinenodiscardnoexcept

Definition at line 785 of file AtomicDimer.h.

787 {
788 return vibrational_stencil_;
789 }

◆ wallClockLimitReached()

bool atmd::AtomicDimer::wallClockLimitReached ( ) const
inlinenodiscard

Definition at line 755 of file AtomicDimer.h.

756 {
757 return wall_clock_limit_ && wall_clock_limit_->reached();
758 }

◆ writeTraceFrame()

void atmd::AtomicDimer::writeTraceFrame ( const gpr::Observation & obs,
const std::string & phase,
size_t idx )

Record one dimer-trace frame. With a corpus attached, writes a one-frame CON (energy, frame_index, phase in prebox1) onto the phase trajectory (1=outer_loop, 2=inner_loop, 3=initial_rotations). With no corpus, falls through to writeHDF5 when WITH_HDF5.

Definition at line 5828 of file AtomicDimer.cpp.

5830{
5831#ifdef USE_READCON_DB
5832 if (trace_corpus_) {
5833 try {
5834 const uint64_t traj = dimerTraceTrajId(phase);
5835 if (traj == 0 || obs.R.rows() < 1 || obs.R.cols() < 3) return;
5836 readcon::RKRConFrame* frame = buildDimerTraceFrame(
5837 obs, phase, idx, atoms_config, cell_dimensions);
5838 if (!frame) return;
5839 // readcon-db's frame ingest casts this handle to its own
5840 // copy of ConFrame. That copy does not share the cdylib's
5841 // column arena, and the cast aborts in the hash table.
5842 // A one-frame file is parsed inside the corpus instead.
5843 uint32_t n_frames = 0;
5844 int st = RKRDB_ERR;
5845 const auto staging =
5846 std::filesystem::temp_directory_path() /
5847 ("gpr-dimer-trace-" + std::to_string(traj) + "-" +
5848 std::to_string(idx) + "-" +
5849 std::to_string(reinterpret_cast<uintptr_t>(frame)) + ".con");
5850 const std::string staging_path = staging.string();
5851 readcon::RKRConFrameWriter* staging_writer =
5852 readcon::create_writer_from_path_c(staging_path.c_str());
5853 if (staging_writer) {
5854 const readcon::RKRConFrame* frames[] = {frame};
5855 const bool wrote =
5856 readcon::rkr_writer_extend(staging_writer, frames, 1) ==
5857 readcon::RKR_STATUS_SUCCESS;
5858 // Close before the corpus reads the path. The writer
5859 // flushes on free.
5860 readcon::free_rkr_writer(staging_writer);
5861 if (wrote) {
5862 st = rkrdb_extend_trajectory(trace_corpus_->id(), traj,
5863 staging_path.c_str(),
5864 &n_frames);
5865 }
5866 }
5867 std::error_code remove_ec;
5868 std::filesystem::remove(staging, remove_ec);
5869 if (!trace_con_path_.empty()) {
5870 readcon::RKRConFrameWriter* writer =
5871 readcon::create_writer_from_path_append_c(
5872 trace_con_path_.c_str());
5873 if (writer) {
5874 const readcon::RKRConFrame* frames[] = {frame};
5875 (void)readcon::rkr_writer_extend(writer, frames, 1);
5876 readcon::free_rkr_writer(writer);
5877 }
5878 }
5879 readcon::free_rkr_frame(frame);
5880 if (st != RKRDB_OK) {
5881 std::cerr << "[dimer] trace corpus extend skipped\n";
5882 }
5883 } catch (const std::exception& e) {
5884 std::cerr << "[dimer] trace corpus write skipped: " << e.what()
5885 << "\n";
5886 }
5887 return;
5888 }
5889#endif
5890#ifdef WITH_HDF5
5891 writeHDF5(obs, phase, idx);
5892#else
5893 (void)obs;
5894 (void)phase;
5895 (void)idx;
5896#endif
5897}

◆ gpr::consumerPublicLayout

◆ gpr::libraryPublicLayout

Member Data Documentation

◆ atoms_config

gpr::AtomsConfiguration atmd::AtomicDimer::atoms_config

Configuration of atoms

Definition at line 1323 of file AtomicDimer.h.


The documentation for this class was generated from the following files: