Loading...
Searching...
No Matches
gpr::optim Namespace Reference

Classes

struct  CompletedSecondMode
struct  EndpointConnectivityReport
struct  EndpointSpectrum
struct  ForceStopCertificateResult
struct  ForceStopMeasurement
struct  ForceStopStencilPlan
struct  ForceStopStencilQuery
struct  FragmentRotations
struct  IrcCertificateRecord
struct  KnownOracleRow
struct  MeasuredCurvatureSpectrum
struct  MeasuredDirectionalCubic
struct  MeasuredHessianColumn
struct  MeasuredIndexDecision
struct  MinimizationConfig
 Configuration for GP-guided minimization. More...
struct  MinimizationLayoutStamp
 Byte counts of the minimization structs this translation unit compiled. More...
struct  MinimizationResult
 Result of GP-guided minimization. More...
struct  MinimumSpectrumCache
struct  NegativePairRejection
struct  NegativeRitzPairRefinement
struct  PairRitzProbe
struct  RefinedCurvatureActions
struct  RefinedWeakModes
struct  RelaxedEndpointCache
struct  RestrictedPartitionedRfoStep
class  RgminStep
struct  SecantConsistency
struct  SecantCurvatureCounts
struct  SecantForceSample
class  SecantHessian
struct  SecantHessianConfig
struct  SecantNewtonFactor
struct  SecantSeed
class  SketchedHessianH0
struct  SmoothedCurvatureSpectrum
struct  SoftModeRefusal
struct  SpectralTrustRegionStep
struct  StationaryCurvaturePosterior
struct  StencilIndex
struct  StencilIndexCertificate
struct  SubspaceRitzProbe
struct  WeakModeContinuation

Typedefs

using OracleFn
 Oracle function: positions -> (energy, gradient).

Enumerations

enum class  RigidMotionMetric { Cartesian , MassWeighted }
enum class  RefinedCurvatureSign { Positive , Negative , Unresolved }
enum class  SecantAccounting { Count , AlreadyCounted }
enum class  SecantSeedStatus {
  Seeded , NoAcceptedPair , DimensionMismatch , NoResolvedCurvature ,
  NoCurrentDirection , NotPositiveDefinite
}
enum class  SecantSeedSupport { WholeHessian , MeasuredSteps }
enum class  SecantHessianMethod { BFGS , SR1 , Bofill }
enum class  StencilAction { Accept , LeaveHigherOrder , ContinueUncertified , AcceptUncertified }
enum class  SaddleSearchFamily { Dimer , MinMode , Neb , OciNeb }
enum class  VibrationalStencil { Full = 0 , Vibrational = 1 }

Functions

Eigen::RowVectorXd consistentGradientPrediction (const Eigen::Ref< const Eigen::RowVectorXd > &measured_reference, const Eigen::Ref< const Eigen::RowVectorXd > &predicted_reference, const Eigen::Ref< const Eigen::RowVectorXd > &predicted_trial)
double gradientChangeAgreement (const Eigen::Ref< const Eigen::RowVectorXd > &measured_change, const Eigen::Ref< const Eigen::RowVectorXd > &predicted_change)
Eigen::RowVectorXd gradientChangeVariance (const Eigen::MatrixXd &covariance, Eigen::Index dimension, double likelihood_variance)
bool measuredForceChangeCalibrated (double error, double variance, double force_scale) noexcept
double measuredTrialTrustAgreement (double rho, bool calibrated, double displacement, double radius, double rho_grow)
template<class Left, class Right>
bool coordinatesCoincideAtRoundoff (const Eigen::MatrixBase< Left > &left, const Eigen::MatrixBase< Right > &right) noexcept
const char * endpointConnectivityLabel (const EndpointConnectivityReport &report) noexcept
double atomicMassAmu (int atomic_number) noexcept
double corderoRadius (int atomic_number) noexcept
std::string bondGraph (const Eigen::VectorXd &positions, const std::vector< int > &atomic_numbers)
Eigen::VectorXd massesFromAtomicNumbers (const std::vector< int > &numbers)
double labelledRmsd (const Eigen::VectorXd &reference, const Eigen::VectorXd &mobile, const std::vector< int > &atomic_numbers)
double permutationAwareRmsd (const Eigen::VectorXd &reference, const Eigen::VectorXd &mobile_in, const std::vector< int > &atomic_numbers)
void appendIrcProfile (std::ostream &line, const EndpointConnectivityReport &report)
std::string formatEndpointConnectivity (const EndpointConnectivityReport &report)
Eigen::MatrixXd ircStencilDirections (const Eigen::VectorXd &center, const Eigen::VectorXd &masses, const Eigen::MatrixXd *held_directions, VibrationalStencil mode=VibrationalStencil::Full)
bool cartesianHessianColumns (Eigen::MatrixXd &columns, double &resolution, const Eigen::VectorXd &center, double step, const Eigen::MatrixXd &directions, const std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> &gradient_at, Eigen::MatrixXd *raw_columns=nullptr)
Eigen::MatrixXd cartesianRigidMotions (const Eigen::VectorXd &positions)
Eigen::VectorXd projectOutRigidMotions (const Eigen::VectorXd &positions, Eigen::VectorXd displacement)
EndpointSpectrum spectrumOfColumns (const Eigen::MatrixXd &hessian, double resolution, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double stiff_floor)
EndpointSpectrum spectrumAt (const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> &gradient_at, double stiff_floor=std::numeric_limits< double >::infinity(), Eigen::MatrixXd *raw_columns=nullptr, const Eigen::MatrixXd *held_directions=nullptr)
template<typename GradientAt>
EndpointSpectrum probeVibrationalMinimum (const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const GradientAt &gradient_at, double stiff_floor=std::numeric_limits< double >::infinity())
template<typename GradientAt>
EndpointSpectrum spectrumForMinimumCheck (const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const GradientAt &gradient_at, MinimumSpectrumCache *cache=nullptr, double stiff_floor=std::numeric_limits< double >::infinity())
EndpointSpectrum spectrumOfModelHessian (const Eigen::MatrixXd &raw, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double stiff_floor)
double endpointMatchBall (double tolerance, double lambda_min, double half_separation) noexcept
bool labelledEndpointsResolve (double separation, double harmonic_reactant, double harmonic_product) noexcept
bool insideEndpointBall (double to_this, double to_other, double ball) noexcept
template<typename Oracle>
EndpointConnectivityReport reportEndpointConnectivity (const Eigen::VectorXd &saddle, const Eigen::VectorXd &masses, double force_tolerance, const Eigen::VectorXd &reactant, const Eigen::VectorXd &product, const std::vector< int > &atomic_numbers, Oracle oracle, RelaxedEndpointCache *cache=nullptr, double hessian_step=defaultStencilStep(), const std::function< bool()> *stop=nullptr, const std::vector< KnownOracleRow > *known=nullptr, const Eigen::MatrixXd *model_hessian=nullptr, const Eigen::MatrixXd *held_directions=nullptr, VibrationalStencil stencil=VibrationalStencil::Full)
bool writeIrcCertificate (const std::string &path, const EndpointConnectivityReport &report, const std::vector< int > &atomic_numbers)
bool readIrcCertificate (const std::string &path, IrcCertificateRecord &record)
FragmentRotations fragmentRotationDirections (const Eigen::VectorXd &positions, const std::vector< std::pair< int, int > > &bonds)
MinimizationLayoutStamp libraryMinimizationLayout ()
 What libgpridge was built with. Defined in the library, not inline.
MinimizationResult gp_minimize (OracleFn oracle, const Eigen::VectorXd &x_init, const AtomsConfiguration &atoms_config, const MinimizationConfig &config, const policy::TrainingPolicy *policy, const Observation *seed=nullptr, const io::TrainedGpState *gp_state=nullptr)
 GP-accelerated geometry minimization with a training policy.
MinimizationResult gp_minimize (OracleFn oracle, const Eigen::VectorXd &x_init, const AtomsConfiguration &atoms_config, const MinimizationConfig &config={})
 GP-accelerated geometry minimization.
MinimizationLayoutStamp compiledMinimizationLayout () noexcept
std::string minimizationLayoutMismatch (const MinimizationLayoutStamp &driver, const MinimizationLayoutStamp &library)
void requireMinimizationLayout ()
void excludeNonPositiveCurvatureBlock (Eigen::VectorXd &s, Eigen::VectorXd &y, Eigen::Index offset, Eigen::Index length)
double barzilaiBorweinInverseScale (const Eigen::VectorXd &s, const Eigen::VectorXd &y, double fallback)
 Scalar BB2 inverse-curvature seed for L-BFGS H0.
Eigen::VectorXd twoLoopRecursion (const std::deque< Eigen::VectorXd > &s_hist, const std::deque< Eigen::VectorXd > &y_hist, const std::deque< double > &rho_hist, const Eigen::VectorXd &force, double H0)
 Nocedal two-loop recursion (the LBFGS kernel).
Eigen::VectorXd twoLoopRecursion (const std::deque< Eigen::VectorXd > &s_hist, const std::deque< Eigen::VectorXd > &y_hist, const std::deque< double > &rho_hist, const Eigen::VectorXd &force, const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> &apply_H0)
 Two-loop recursion with a caller-supplied H0 application.
MeasuredDirectionalCubic refinedDirectionalCubic (const RefinedCurvatureActions &stencil, const Eigen::VectorXd &center_gradient, const Eigen::VectorXd &mode, double step)
double massWeightedMeasuredCurvatureResolution (const gpr::Coord &positions, const gpr::AtomsConfiguration &configuration, const Eigen::MatrixXd &basis, const Eigen::MatrixXd &actions)
double refinedIndexOnePositiveLowerBound (const MeasuredCurvatureSpectrum &complete, Eigen::Index dimension, const RefinedCurvatureActions &refined)
MeasuredCurvatureSpectrum analyzeMeasuredCurvature (const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action)
Eigen::MatrixXd measuredIndexZeroHessian (const Eigen::MatrixXd &basis, const Eigen::MatrixXd &physical, const Eigen::MatrixXd &action)
Eigen::VectorXd measuredModeExpansion (const Eigen::MatrixXd &basis, const Eigen::MatrixXd &physical, const Eigen::VectorXd &action)
double measuredCurvaturePriorScale (const Eigen::MatrixXd &prior, const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action)
Eigen::MatrixXd completeMeasuredHessian (const Eigen::MatrixXd &prior, const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action)
double curvatureAtWavenumber (double wavenumber, const Eigen::VectorXd &direction, const Eigen::VectorXd &atomic_masses)
CompletedSecondMode completedSecondMode (const Eigen::MatrixXd &completed, const Eigen::MatrixXd &basis, Eigen::Index k=1)
CompletedSecondMode completedAdditionalNegativeMode (const Eigen::MatrixXd &completed, const Eigen::MatrixXd &basis, const Eigen::VectorXd &negative_mode)
Eigen::VectorXd nextMeasuredCurvatureDirection (const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action, const MeasuredCurvatureSpectrum &spectrum, const Eigen::MatrixXd &physical, const Eigen::MatrixXd &preferred, const Eigen::MatrixXd &prior=Eigen::MatrixXd{})
Eigen::MatrixXd nextMeasuredCurvatureDirections (const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action, const MeasuredCurvatureSpectrum &spectrum, const Eigen::MatrixXd &physical, const Eigen::MatrixXd &preferred, Eigen::Index count, const Eigen::MatrixXd &prior=Eigen::MatrixXd{})
MeasuredCurvatureSpectrum analyzeRefinedMeasuredCurvature (const Eigen::MatrixXd &basis, const Eigen::MatrixXd &at_h, const Eigen::MatrixXd &at_2h)
template<typename Evaluate>
MeasuredCurvatureSpectrum refineMeasuredCurvature (const Eigen::VectorXd &center, const Eigen::MatrixXd &basis, double step, Evaluate &&evaluate, RefinedCurvatureActions *actions=nullptr)
template<typename Evaluate>
double refinePositiveCurvatureComplement (const MeasuredCurvatureSpectrum &complete, Eigen::Index dimension, const Eigen::VectorXd &center, double step, Evaluate &&evaluate)
Eigen::VectorXd movingAtomicMasses (const gpr::AtomsConfiguration &config, Eigen::Index n_moving)
Eigen::MatrixXd physicalCurvatureBasis (const gpr::Coord &positions, const gpr::AtomsConfiguration &config, bool exclude_rotations=true, RigidMotionMetric metric=RigidMotionMetric::MassWeighted)
Eigen::MatrixXd vibrationalStencilDirections (const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, bool periodic, bool anchored, const Eigen::VectorXi *frozen=nullptr)
Eigen::MatrixXd stencilDirectionsForMode (VibrationalStencil mode, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, bool periodic, bool anchored, const Eigen::VectorXi *frozen=nullptr)
bool directionsAreCoordinateAxes (const Eigen::MatrixXd &directions)
Eigen::MatrixXd centralDifferencePoints (const Eigen::VectorXd &center, double step, const Eigen::MatrixXd &directions)
Eigen::MatrixXd massWeightedPhysicalCurvatureBasis (const gpr::Coord &positions, const gpr::AtomsConfiguration &config, bool exclude_rotations=true)
Eigen::MatrixXd transportPhysicalDirections (const Eigen::MatrixXd &directions, const Eigen::MatrixXd &physical)
Eigen::MatrixXd transportMeasuredHessianActions (const gpr::Coord &positions, const gpr::Coord &gradient, const Eigen::MatrixXd &measured_basis, const Eigen::MatrixXd &measured_action, const Eigen::MatrixXd &physical, bool include_rotations=true)
Eigen::MatrixXd hessianColumnsFromDirections (const Eigen::VectorXd &center, const Eigen::VectorXd &center_gradient, const Eigen::MatrixXd &directions, const Eigen::MatrixXd &actions)
RestrictedPartitionedRfoStep restrictedPartitionedRfoStep (const Eigen::VectorXd &curvatures, const Eigen::VectorXd &gradient, const Eigen::MatrixXd &cartesian_modes, double radius)
Eigen::VectorXd richardsonExtrapolate (const Eigen::VectorXd &at_h, const Eigen::VectorXd &at_2h)
Eigen::VectorXd richardsonTruncation (const Eigen::VectorXd &at_h, const Eigen::VectorXd &at_2h)
double refinedCurvatureResolution (double refined_resolution, double anharmonic_scale) noexcept
RefinedCurvatureSign refinedCurvatureSign (double curvature, double refined_resolution, double anharmonic_scale) noexcept
bool curvatureResolvedByStencil (double measured, double anharmonic_scale) noexcept
bool curvatureResolvedByThirdDerivative (double measured, double third, double step) noexcept
double richardsonForwardExtrapolate (double at_h, double at_2h) noexcept
double richardsonForwardTruncation (double at_h, double at_2h) noexcept
bool curvatureResolvedBySurrogate (double measured, double surrogate) noexcept
int certifiedCurvatureSign (double extrapolated, double estimate) noexcept
void writeSecantCurvatureCounts (std::ostream &out, const SecantCurvatureCounts &counts)
void recordSecantObservation (SecantHessian &secant, const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, double energy, SecantCurvatureCounts &counts, SecantAccounting accounting=SecantAccounting::Count)
const char * secantSeedStatusName (SecantSeedStatus status) noexcept
std::optional< Eigen::VectorXd > secantResolvedNegativeMode (const SecantHessian &secant)
SecantSeed secantSeedDirection (const SecantHessian &secant, const Eigen::VectorXd &current_direction)
std::optional< double > secantPositiveInverseScale (const SecantHessian &secant)
SecantNewtonFactor secantNewtonFactor (const SecantHessian &secant)
SecantSeedStatus seedHessianOnSecantRange (Eigen::MatrixXd &model, const Eigen::MatrixXd &secant_hessian)
SecantSeedStatus seedHessianOnMeasuredStepRange (Eigen::MatrixXd &model, const Eigen::MatrixXd &secant_hessian, const Eigen::MatrixXd &measured_steps)
SecantSeedStatus seedHessianFromSecant (Eigen::MatrixXd &model, const SecantHessian &secant, const Eigen::MatrixXd &weight, SecantSeedSupport support=SecantSeedSupport::WholeHessian)
template<class Prior>
SecantHessian secantFittedToResidual (SecantHessianMethod method, const std::vector< SecantForceSample > &samples, Prior &&prior)
int bofillThroughLoadedRgsaddle (std::int64_t n, double *hessian_row_major, const double *step, const double *gradient_change)
std::string bofillRgsaddleAbiRefusal ()
void setBofillRgsaddleLibrary (const char *path)
SmoothedCurvatureSpectrum smoothMeasuredCurvature (const Eigen::MatrixXd &prior, const std::vector< MeasuredHessianColumn > &columns, const SmoothedCurvatureSpectrum *previous=nullptr, const linalg::MpiContext &context=linalg::MpiContext::local())
Eigen::VectorXd nextSmoothedCurvatureDirection (const SmoothedCurvatureSpectrum &spectrum, Eigen::Index k)
double measuredUpperBound (const SmoothedCurvatureSpectrum &spectrum, const std::vector< MeasuredHessianColumn > &columns, Eigen::Index k)
Eigen::VectorXd softestUnmeasuredDirection (const SmoothedCurvatureSpectrum &spectrum)
Eigen::Index coarseColumnToRefine (const SmoothedCurvatureSpectrum &spectrum, const std::vector< MeasuredHessianColumn > &columns, Eigen::Index k)
Eigen::VectorXd spectralResidualStep (const Eigen::VectorXd &eigenvalues, const Eigen::MatrixXd &modes, const Eigen::VectorXd &gradient, double radius)
SpectralTrustRegionStep spectralTrustRegionStep (const Eigen::VectorXd &curvatures, const Eigen::MatrixXd &modes, Eigen::Index mode_index, const Eigen::VectorXd &force, double radius, const std::vector< std::pair< Eigen::VectorXd, double > > &measured_negative)
double measuredCubicColumnContribution (double overlap, double mode_quadratic, double axis_quadratic)
double axisStencilDirectionalCubic (const Eigen::MatrixXd &axes, const Eigen::MatrixXd &second_differences, const Eigen::VectorXd &mode)
StationaryCurvaturePosterior stationaryCurvaturePosterior (double c, double c_spread, double f, double f_spread, double b, double b_spread, Eigen::Index samples=detail::kSpectrumSamples)
Eigen::MatrixXd massWeightedRigidMotions (const Eigen::VectorXd &positions, const Eigen::VectorXd &masses)
Eigen::MatrixXd vibrationalComplement (const Eigen::VectorXd &positions, const Eigen::VectorXd &masses)
StencilIndex analyzeStencilIndex (const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, const Eigen::MatrixXd *measured=nullptr)
template<typename Gradients>
RefinedWeakModes refineWeakModes (const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, const Eigen::MatrixXd &weak, double step, const Gradients &gradients, double noise_multiplier=0.0)
template<typename Gradients>
SoftModeRefusal refuseSecondNegativeMode (const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, const Eigen::MatrixXd &mass_weighted_modes, double step, const Gradients &gradients, double noise_multiplier=0.0)
double rotatedPositiveRestrictionLowerBound (const Eigen::MatrixXd &block, const Eigen::MatrixXd &errors, const Eigen::MatrixXd &coupling, const Eigen::VectorXd &tail, double allowance)
template<typename Gradients>
StencilIndexCertificate certifyStencilIndex (const StencilIndex &index, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const Gradients &gradients, Eigen::Index minimum_weak=0, double noise_multiplier=0.0)
template<typename Gradients>
MeasuredIndexDecision decideMeasuredIndex (const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const Gradients &gradients, const Eigen::MatrixXd *measured=nullptr)
 measured is analyzeStencilIndex's.
WeakModeContinuation boundedWeakModeContinuation (const Eigen::VectorXd &direction, double third, double step, double lower, double resolution, double step_bound)
WeakModeContinuation weakModeContinuation (const StencilIndexCertificate &certificate, const Eigen::VectorXd &centre_gradient, double resolution, double step_bound)
template<typename Gradients>
NegativePairRejection rejectMeasuredNegativePair (const Eigen::MatrixXd &previous_cartesian_hessian, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, const Eigen::VectorXd &centre_gradient, double step, double step_bound, const Gradients &gradients)
StencilAction nextStencilAction (bool higher_order, bool weak_higher_order, bool weak_uncertified, int &continuations, int maximum_continuations)
constexpr double defaultStencilStep () noexcept
constexpr double stencilStepOrDefault (double requested) noexcept
 The requested stencil step, or the default when none was requested.
constexpr int forceStopAdaptiveStepReductions () noexcept
template<typename Gradients>
StencilIndexCertificate certifyAdaptiveStencilIndex (const StencilIndex &index, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const Gradients &gradients, double noise_multiplier=0.0)
template<typename Gradients>
PairRitzProbe probePairRitz (const Eigen::VectorXd &center, const Eigen::VectorXd &masses, const Eigen::VectorXd &u, const Eigen::VectorXd &v, double step, const Gradients &gradients)
template<typename Gradients>
SubspaceRitzProbe probeSubspaceRitz (const Eigen::VectorXd &center, const Eigen::VectorXd &masses, const Eigen::MatrixXd &candidates, double step, const Gradients &gradients)
bool forceStopMeasurementInconclusiveOrHigher (const ForceStopMeasurement &measured) noexcept
constexpr int forceStopSoftRefinementLimit () noexcept
constexpr int forceStopRefinementCertified () noexcept
constexpr int forceStopRefinementStillHigher () noexcept
bool sameStencilGeometry (const Eigen::VectorXd &first, const Eigen::VectorXd &second) noexcept
 Two geometries share one stencil when a later request has not moved.
constexpr int forceStopMinModeEscapes () noexcept
 Min-mode escapes after a higher-order certificate, for every search.
ForceStopStencilPlan planForceStopStencil (ForceStopStencilQuery query)
ForceStopStencilPlan planForceStopStencil (SaddleSearchFamily family, bool requested)
bool forceStopCertificatePlanned (const ForceStopStencilPlan &plan) noexcept
Eigen::Index forceStopHeldColumn (const Eigen::MatrixXd &held, const Eigen::VectorXd &query, double relative=1e-6)
Eigen::MatrixXd forceStopLowestModes (const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, Eigen::Index count, const Eigen::MatrixXd *measured=nullptr)
bool forceStopStencilCertifies (bool measured, bool first_order) noexcept
template<typename Measure, typename Refine>
ForceStopCertificateResult runForceStopCertificate (Measure measure, Refine refine, ForceStopStencilPlan plan, const ForceStopMeasurement *prior=nullptr)
const char * vibrationalStencilName (VibrationalStencil mode) noexcept
bool parseVibrationalStencil (std::string_view text, VibrationalStencil &out) noexcept
VibrationalStencil vibrationalStencilFromInt (int value)
double maxAtomDisplacement (const Eigen::VectorXd &delta)

Variables

constexpr std::uint32_t kMinimizationLayoutVersion = 2

Typedef Documentation

◆ OracleFn

Initial value:
std::function<std::pair<double, Eigen::VectorXd>(
const Eigen::VectorXd& positions)>

Oracle function: positions -> (energy, gradient).

Definition at line 176 of file GPMinimizer.h.

Enumeration Type Documentation

◆ RefinedCurvatureSign

What a refined (Richardson) curvature says about the sign of a mode. The refinement's own truncation estimate is not the only resolution scale: the coarse stencil that spawned it measured an anharmonicity scale, and a Taylor series that changed sign between h and 2h is not resolved below it. A curvature within the larger of the two scales of zero is unresolved: no stencil the run can afford separates it from a flat mode, and repeating the same measurement cannot either (10_ene: -0.0024 then -0.0007 eV/A^2 against an anharmonic scale of 0.002, each escape returning to the same point at 90 oracle calls; 17_oxycope: -6e-5 against 5e-4).

Enumerator
Positive 
Negative 
Unresolved 

Definition at line 45 of file RichardsonCurvature.h.

◆ RigidMotionMetric

enum class gpr::optim::RigidMotionMetric
strong
Enumerator
Cartesian 
MassWeighted 

Definition at line 19 of file PhysicalCurvatureBasis.h.

◆ SaddleSearchFamily

enum class gpr::optim::SaddleSearchFamily
strong

Every terminal saddle search. The force-stop certificate does not branch on this value: dimer, min-mode, NEB and OCI-NEB share one plan.

Enumerator
Dimer 
MinMode 
Neb 
OciNeb 

Definition at line 1056 of file StencilIndex.h.

◆ SecantAccounting

enum class gpr::optim::SecantAccounting
strong

A true-force measurement is counted by whoever measured it. An owner that receives the measurement afterwards still feeds its Hessian with it, and passes AlreadyCounted so the ledger holds the pair once.

Enumerator
Count 
AlreadyCounted 

Definition at line 46 of file SecantCurvature.h.

◆ SecantHessianMethod

◆ SecantSeedStatus

enum class gpr::optim::SecantSeedStatus
strong

Why a secant did or did not supply a direction. A refusal is an ordinary outcome: the caller keeps what it has and says which refusal it met.

Enumerator
Seeded 
NoAcceptedPair 
DimensionMismatch 
NoResolvedCurvature 
NoCurrentDirection 
NotPositiveDefinite 

Definition at line 72 of file SecantCurvature.h.

◆ SecantSeedSupport

enum class gpr::optim::SecantSeedSupport
strong

Which part of a secant Hessian may replace the model. WholeHessian takes every resolved eigenvector of the secant Hessian, including curvature outside the measured steps; the Hessian-driven walks rely on that. A MeasuredSteps seed takes only the Ritz pairs of the Hessian projected onto the measured steps, so a one-step update's unmeasured curvature never reaches the model.

Enumerator
WholeHessian 
MeasuredSteps 

Definition at line 237 of file SecantCurvature.h.

◆ StencilAction

enum class gpr::optim::StencilAction
strong

What the search does with the verdict of a complete stencil. A midpoint with a second negative mode is left while higher_order allows it, whether the coarse stencil resolves that mode or the refinement of the weak block does, and returned with its verdict once the restarts are spent. A weak second negative mode is not continued from: its force is below the convergence threshold over the whole flat ridge, so a short continuation leaves the midpoint on it. A midpoint whose weak modes are only not certified positive is continued from along the softest weak mode, at most maximum_continuations times, and then returned with the verdict recorded, so a run that cannot certify a flat or zero mode ends and says so.

Enumerator
Accept 
LeaveHigherOrder 
ContinueUncertified 
AcceptUncertified 

Definition at line 751 of file StencilIndex.h.

◆ VibrationalStencil

enum class gpr::optim::VibrationalStencil
strong

Coordinates a true-oracle Hessian stencil displaces. Full measures every Cartesian coordinate. Vibrational measures the complement of mass-weighted rigid motion. The vibrational resolution is the antisymmetric norm of that measured block, so a borderline mode can be called resolved where Full, whose resolution still includes the rigid columns, calls it unresolved.

Enumerator
Full 
Vibrational 

Definition at line 18 of file VibrationalStencil.h.

Function Documentation

◆ analyzeMeasuredCurvature()

MeasuredCurvatureSpectrum gpr::optim::analyzeMeasuredCurvature ( const Eigen::MatrixXd & basis,
const Eigen::MatrixXd & action )
inline

Symmetrize measured Hessian actions and retain their common empirical resolution. Asymmetry and roundoff do not bound symmetric truncation error.

Definition at line 162 of file MeasuredCurvatureSpectrum.h.

164{
166 if (basis.cols() == 0 || basis.rows() != action.rows() ||
167 basis.cols() != action.cols() || !basis.allFinite() ||
168 !action.allFinite())
169 return out;
170 const Eigen::MatrixXd projected = basis.transpose() * action;
171 const Eigen::MatrixXd reduced = 0.5 * (projected + projected.transpose());
172 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(reduced);
173 if (spectrum.info() != Eigen::Success ||
174 !spectrum.eigenvalues().allFinite())
175 return out;
176 out.curvatures = spectrum.eigenvalues();
177 out.modes = basis * spectrum.eigenvectors();
178 out.resolution = std::max(
179 (0.5 * (projected - projected.transpose())).norm(),
180 std::numeric_limits<double>::epsilon() * basis.cols() * reduced.norm());
181 out.valid = out.modes.allFinite() && std::isfinite(out.resolution);
182 return out;
183}
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out

◆ analyzeRefinedMeasuredCurvature()

MeasuredCurvatureSpectrum gpr::optim::analyzeRefinedMeasuredCurvature ( const Eigen::MatrixXd & basis,
const Eigen::MatrixXd & at_h,
const Eigen::MatrixXd & at_2h )
inline

Refine a measured subspace using central stencils at h and 2h. The projected leading truncation correction supplies an empirical resolution; it is not a bound on arbitrary higher derivatives of the potential.

Definition at line 548 of file MeasuredCurvatureSpectrum.h.

551{
552 if (at_h.rows() != at_2h.rows() || at_h.cols() != at_2h.cols() ||
553 !at_h.allFinite() || !at_2h.allFinite())
554 return {};
555 const Eigen::MatrixXd refined_action = (4.0 * at_h - at_2h) / 3.0;
556 auto out = analyzeMeasuredCurvature(basis, refined_action);
557 if (!out.valid) return out;
558 const Eigen::MatrixXd truncation =
559 basis.transpose() * ((at_2h - at_h) / 3.0);
560 out.resolution = std::max(out.resolution, truncation.norm());
561 out.valid = std::isfinite(out.resolution);
562 if (out.valid && basis.cols() == 2) {
563 const Eigen::Matrix2d projected = basis.transpose() * refined_action;
564 const Eigen::Matrix2d symmetric =
565 0.5 * (projected + projected.transpose());
566 const Eigen::Matrix2d errors =
567 0.5 * (truncation.cwiseAbs() + truncation.transpose().cwiseAbs()) +
568 (0.5 * (projected - projected.transpose())).cwiseAbs();
569 // For every symmetric entry error inside this envelope, its
570 // quadratic form at v is bounded above by the majorant at abs(v).
571 // This retains large errors on stiff modes instead of assigning
572 // them to the weak mode through a common matrix norm.
573 const double first = symmetric(0, 0) + errors(0, 0);
574 const double second = symmetric(1, 1) + errors(1, 1);
575 const double high = std::max(first, second);
576 const double half_gap = 0.5 * high - 0.5 * std::min(first, second);
577 const double coupling = std::abs(symmetric(0, 1)) + errors(0, 1);
578 const double denominator = std::hypot(half_gap, coupling) + half_gap;
579 const double roundoff =
580 64.0 * std::numeric_limits<double>::epsilon() *
581 (symmetric.cwiseAbs().sum() + errors.cwiseAbs().sum());
582 const double upper =
583 high +
584 (denominator > 0.0 ? coupling * (coupling / denominator) : 0.0) +
585 roundoff;
586 if (std::isfinite(upper)) out.negative_pair_upper_bound = upper;
587 }
588 return out;
589}
MeasuredCurvatureSpectrum analyzeMeasuredCurvature(const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action)

◆ analyzeStencilIndex()

StencilIndex gpr::optim::analyzeStencilIndex ( const Eigen::MatrixXd & columns,
const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
const Eigen::MatrixXd * measured = nullptr )
inline

columns holds the Cartesian Hessian actions: column j is the central difference of the gradient along Cartesian coordinate j. measured, when it has fewer orthonormal Cartesian columns than there are coordinates, names the directions the stencil displaced along; the other columns of columns were rebuilt, not measured. The resolution is then the antisymmetric norm of the mass-weighted block on the image sqrt(M) measured, which reads only the measured columns. The spectrum is the vibrational complement's when the image contains it (a free molecule, whose image it is, or a periodic cell, whose image adds the rotations), and otherwise the image's own block (the moving coordinates of a geometry with frozen atoms). Either block reads only measured columns.

Definition at line 80 of file StencilIndex.h.

83{
85 const Eigen::Index dof = positions.size();
86 if (columns.rows() != dof || columns.cols() != dof ||
87 masses.size() * 3 != dof || !columns.allFinite())
88 return out;
89 Eigen::VectorXd inverse_root(dof);
90 for (Eigen::Index k = 0; k < dof; ++k)
91 inverse_root(k) = 1.0 / std::sqrt(masses(k / 3));
92 const Eigen::MatrixXd weight = inverse_root * inverse_root.transpose();
93 const Eigen::MatrixXd antisymmetric =
94 (0.5 * (columns - columns.transpose())).cwiseProduct(weight);
95 out.hessian = (0.5 * (columns + columns.transpose())).cwiseProduct(weight);
96 out.resolution = antisymmetric.size() > 0
97 ? Eigen::JacobiSVD<Eigen::MatrixXd>(antisymmetric)
98 .singularValues()(0)
99 : 0.0;
100 const bool reduced = measured != nullptr && measured->rows() == dof &&
101 measured->cols() > 0 && measured->cols() < dof &&
102 measured->allFinite();
103 Eigen::MatrixXd vibrational;
104 if (reduced) {
105 Eigen::VectorXd root(dof);
106 for (Eigen::Index k = 0; k < dof; ++k)
107 root(k) = std::sqrt(masses(k / 3));
108 const Eigen::HouseholderQR<Eigen::MatrixXd> qr(root.asDiagonal() *
109 *measured);
110 const Eigen::MatrixXd image =
111 qr.householderQ() *
112 Eigen::MatrixXd::Identity(dof, measured->cols());
113 const Eigen::MatrixXd block = image.transpose() * antisymmetric * image;
114 out.resolution =
115 Eigen::JacobiSVD<Eigen::MatrixXd>(block).singularValues()(0);
116 // A periodic stencil also measures the rotations, which are not
117 // symmetries there; the spectrum still leaves them out, as it does
118 // for a complete stencil. Directions that do not span the
119 // complement (frozen atoms, other masses) keep their own image.
120 vibrational = vibrationalComplement(positions, masses);
121 const double outside =
122 (vibrational - image * (image.transpose() * vibrational)).norm();
123 if (vibrational.cols() == 0 || !(outside <= 1e-8)) vibrational = image;
124 } else {
125 vibrational = vibrationalComplement(positions, masses);
126 }
127 const Eigen::MatrixXd projected =
128 vibrational.transpose() * out.hessian * vibrational;
129 // A molecule whose rigid motions already span every coordinate has an
130 // empty vibrational block. LAPACKE's DSYEV rejects that 0-by-0 problem
131 // (LDA = 0), and Eigen's solver reads off a 0x0 temporary. A non-finite
132 // projection is not a spectrum either. Leave the index invalid, which
133 // is what a failed solve reports, without calling the solver.
134 if (projected.rows() == 0 || projected.cols() == 0 ||
135 !projected.allFinite())
136 return out;
137 // Materialize before the solver. Passing the expression straight in
138 // makes Eigen's norm reduction read off the end of a temporary.
139 const Eigen::MatrixXd symmetric = 0.5 * (projected + projected.transpose());
140 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(symmetric);
141 if (spectrum.info() != Eigen::Success) return out;
142 out.curvatures = spectrum.eigenvalues();
143 out.modes = vibrational * spectrum.eigenvectors();
144 const double scale = out.curvatures.cwiseAbs().maxCoeff();
145 out.resolution =
146 std::max(out.resolution, std::numeric_limits<double>::epsilon() *
147 static_cast<double>(std::max<Eigen::Index>(
148 1, out.curvatures.size())) *
149 scale);
150 out.valid = true;
151 return out;
152}
Eigen::MatrixXd vibrationalComplement(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses)

◆ appendIrcProfile()

void gpr::optim::appendIrcProfile ( std::ostream & line,
const EndpointConnectivityReport & report )
inline

Definition at line 442 of file EndpointConnectivity.h.

444{
445 line << "\nIRC profile: deposit=" << report.calls_deposit
446 << " endpoint_check=" << report.calls_endpoint_check
447 << " saddle=" << report.calls_saddle
448 << " descent=" << report.calls_descent
449 << " polish=" << report.calls_polish
450 << " end_check=" << report.calls_end_check
451 << " energy=" << report.calls_energy
452 << " oracle_s=" << report.oracle_seconds
453 << " match_s=" << report.match_seconds;
454}

◆ atomicMassAmu()

double gpr::optim::atomicMassAmu ( int atomic_number)
inlinenoexcept

Standard atomic weight (amu) for the elements in the Baker and Birkholz sets. An unlisted element keeps unit mass; the caller can pass masses it already trusts instead.

Definition at line 205 of file EndpointConnectivity.h.

206{
207 switch (atomic_number) {
208 case 1:
209 return 1.008;
210 case 6:
211 return 12.011;
212 case 7:
213 return 14.007;
214 case 8:
215 return 15.999;
216 case 9:
217 return 18.998;
218 case 12:
219 return 24.305;
220 case 14:
221 return 28.085;
222 case 15:
223 return 30.974;
224 case 16:
225 return 32.06;
226 case 17:
227 return 35.45;
228 case 35:
229 return 79.904;
230 default:
231 return 1.0;
232 }
233}

◆ axisStencilDirectionalCubic()

double gpr::optim::axisStencilDirectionalCubic ( const Eigen::MatrixXd & axes,
const Eigen::MatrixXd & second_differences,
const Eigen::VectorXd & mode )
inline

Cubic coefficient along mode from measured axis stencils: column j of second_differences is the gradient second difference along the orthonormal axis u_j (column j of axes), that is T[u_j, u_j, .]. The sum of measuredCubicColumnContribution over the axes is odd in the mode, as the cubic coefficient is, so a mode and its negative give opposite signs.

Definition at line 42 of file StationaryCurvature.h.

45{
46 double coefficient = 0.0;
47 for (Eigen::Index j = 0; j < axes.cols(); ++j) {
48 const Eigen::VectorXd action = second_differences.col(j);
50 axes.col(j).dot(mode), mode.dot(action), axes.col(j).dot(action));
51 }
52 return coefficient;
53}
double measuredCubicColumnContribution(double overlap, double mode_quadratic, double axis_quadratic)

◆ barzilaiBorweinInverseScale()

double gpr::optim::barzilaiBorweinInverseScale ( const Eigen::VectorXd & s,
const Eigen::VectorXd & y,
double fallback )
nodiscard

Scalar BB2 inverse-curvature seed for L-BFGS H0.

Uses the Barzilai-Borwein two-point spectral scale gamma_k = (s_k^T y_k)/(y_k^T y_k) as the scalar inverse-Hessian seed for the two-loop recursion (doi:10.1093/imanum/8.1.141). Degenerate, non-finite, or non-positive curvature pairs return the caller's fallback.

Definition at line 39 of file LBFGS.cpp.

41{
42 const double sy = s.dot(y);
43 const double yy = y.squaredNorm();
44 const double scale = (yy > 0.0 && std::isfinite(yy)) ? sy / yy : fallback;
45 if (sy > 0.0 && std::isfinite(sy) && scale > 0.0 && std::isfinite(scale)) {
46 return scale;
47 }
48 return fallback;
49}
@ y
Definition Enums.h:28

◆ bofillRgsaddleAbiRefusal()

std::string gpr::optim::bofillRgsaddleAbiRefusal ( )

Refusal text for a Bofill call the linked ABI rejects. Names the required rgsaddle ABI major and minor 3, and the major and minor (or stamp status) that were found.

Definition at line 415 of file RgsaddleClient.cpp.

416{
417 if (!bofillAbiRefusalSlot().empty()) return bofillAbiRefusalSlot();
418 rgsaddle_version_t ver{};
419 const int stamp = rgsaddle_abi_stamp(&ver);
420 return formatBofillAbiRefusal(stamp, ver);
421}

◆ bofillThroughLoadedRgsaddle()

int gpr::optim::bofillThroughLoadedRgsaddle ( std::int64_t n,
double * hessian_row_major,
const double * step,
const double * gradient_change )

Bofill through the linked librgsaddle (rgsaddle_hessian_bofill). hessian_row_major is n by n. Returns 1 when the runtime wrote an update, 0 when it refused and left the buffer unchanged, and -1 when the linked ABI stamp is not major 1 with minor at least 3. bofillRgsaddleAbiRefusal names that required ABI and the stamp that was found.

Definition at line 428 of file RgsaddleClient.cpp.

431{
432 if (n < 1 || hessian == nullptr || step == nullptr ||
433 gradient_change == nullptr)
434 return 0;
435 // The recorded path is the index-test choice. The Hessian update is
436 // the linked symbol, present from ABI minor 3.
437 (void)bofillLibraryOverride();
438 rgsaddle_version_t ver{};
439 const int stamp = rgsaddle_abi_stamp(&ver);
440 if (stamp != RGSADDLE_OK || ver.major != RGSADDLE_ABI_MAJOR ||
441 ver.minor < kHessianBofillAbiMinor) {
442 bofillAbiRefusalSlot() = formatBofillAbiRefusal(stamp, ver);
443 return -1;
444 }
445 bofillAbiRefusalSlot().clear();
446 const int status =
447 rgsaddle_hessian_bofill(n, step, gradient_change, hessian);
448 return status == RGSADDLE_OK ? 1 : 0;
449}
int status

◆ bondGraph()

std::string gpr::optim::bondGraph ( const Eigen::VectorXd & positions,
const std::vector< int > & atomic_numbers )
inline

Bonds as sorted index pairs. The cutoff is 1.2 times the sum of the Cordero radii. Atom order is the file order, which the walk keeps.

Definition at line 267 of file EndpointConnectivity.h.

269{
270 std::vector<std::string> edges;
271 const int n = static_cast<int>(atomic_numbers.size());
272 if (positions.size() != 3 * n) return {};
273 for (int i = 0; i < n; ++i) {
274 const double ri =
275 corderoRadius(atomic_numbers[static_cast<std::size_t>(i)]);
276 if (!(ri > 0.0)) continue;
277 for (int j = i + 1; j < n; ++j) {
278 const double rj =
279 corderoRadius(atomic_numbers[static_cast<std::size_t>(j)]);
280 if (!(rj > 0.0)) continue;
281 const double cutoff = 1.2 * (ri + rj);
282 const double dx = positions(3 * i) - positions(3 * j);
283 const double dy = positions(3 * i + 1) - positions(3 * j + 1);
284 const double dz = positions(3 * i + 2) - positions(3 * j + 2);
285 if (dx * dx + dy * dy + dz * dz <= cutoff * cutoff)
286 edges.push_back(std::to_string(i) + "-" + std::to_string(j));
287 }
288 }
289 std::sort(edges.begin(), edges.end());
290 std::ostringstream out;
291 for (std::size_t i = 0; i < edges.size(); ++i) {
292 if (i != 0) out << ",";
293 out << edges[i];
294 }
295 return out.str();
296}
double corderoRadius(int atomic_number) noexcept

◆ boundedWeakModeContinuation()

WeakModeContinuation gpr::optim::boundedWeakModeContinuation ( const Eigen::VectorXd & direction,
double third,
double step,
double lower,
double resolution,
double step_bound )
inline

Definition at line 630 of file StencilIndex.h.

633{
635 if (direction.size() == 0 || !direction.allFinite() ||
636 !(direction.norm() > 0.0) || !(step > 0.0) || !std::isfinite(step) ||
637 !std::isfinite(third))
638 return out;
639 const double deficit = std::isfinite(lower) ? std::max(-lower, 0.0) : 0.0;
640 const double lift = 2.0 * deficit + 0.1 * std::max(resolution, 0.0);
641 const double length = std::abs(third) > 0.0
642 ? lift / std::abs(third)
643 : std::numeric_limits<double>::infinity();
644 const double bound =
645 std::isfinite(step_bound) && step_bound > 0.0 ? step_bound : 0.05;
646 out.direction = (third < 0.0 ? -1.0 : 1.0) * direction.normalized();
647 out.length = std::clamp(length, std::min(step, bound), bound);
648 out.third = third;
649 out.valid = true;
650 return out;
651}
STL namespace.

◆ cartesianHessianColumns()

bool gpr::optim::cartesianHessianColumns ( Eigen::MatrixXd & columns,
double & resolution,
const Eigen::VectorXd & center,
double step,
const Eigen::MatrixXd & directions,
const std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> & gradient_at,
Eigen::MatrixXd * raw_columns = nullptr )
inline

Central-difference Hessian along directions, as Cartesian columns: columns.col(j) is d(gradient)/dx_j (hessianColumnsFromDirections, which reads the center gradient when rigid columns were removed). The resolution is the antisymmetric residual of the measured block: of the whole matrix for a complete stencil, of directions^T raw directions when the rigid columns were rebuilt rather than measured.

Definition at line 552 of file EndpointConnectivity.h.

558{
559 const Eigen::Index dof = center.size();
560 if (!(step > 0.0) || dof == 0 || !center.allFinite() ||
561 directions.rows() != dof || directions.cols() == 0)
562 return false;
563 const Eigen::MatrixXd points =
564 centralDifferencePoints(center, step, directions);
565 Eigen::MatrixXd actions(dof, directions.cols());
566 for (Eigen::Index k = 0; k < directions.cols(); ++k) {
567 Eigen::VectorXd g_plus(dof);
568 Eigen::VectorXd g_minus(dof);
569 if (!gradient_at(points.col(2 * k), g_plus) ||
570 !gradient_at(points.col(2 * k + 1), g_minus))
571 return false;
572 actions.col(k) = (g_plus - g_minus) / (2.0 * step);
573 }
574 Eigen::VectorXd center_gradient;
575 if (directions.cols() < dof) {
576 center_gradient.resize(dof);
577 if (!gradient_at(center, center_gradient)) return false;
578 }
579 const Eigen::MatrixXd raw = hessianColumnsFromDirections(
580 center, center_gradient, directions, actions);
581 if (raw.rows() != dof || raw.cols() != dof) return false;
582 columns.resize(dof, dof);
583 const Eigen::MatrixXd full = 0.5 * (raw - raw.transpose());
584 const Eigen::MatrixXd antisym =
585 directions.cols() < dof
586 ? Eigen::MatrixXd(directions.transpose() * full * directions)
587 : full;
588 resolution =
589 antisym.size() == 0
590 ? 0.0
591 : Eigen::JacobiSVD<Eigen::MatrixXd>(antisym).singularValues()(0);
592 if (raw_columns != nullptr) *raw_columns = raw;
593 columns = 0.5 * (raw + raw.transpose());
594 return columns.allFinite() && std::isfinite(resolution);
595}
Eigen::MatrixXd hessianColumnsFromDirections(const Eigen::VectorXd &center, const Eigen::VectorXd &center_gradient, const Eigen::MatrixXd &directions, const Eigen::MatrixXd &actions)
Eigen::MatrixXd centralDifferencePoints(const Eigen::VectorXd &center, double step, const Eigen::MatrixXd &directions)

◆ cartesianRigidMotions()

Eigen::MatrixXd gpr::optim::cartesianRigidMotions ( const Eigen::VectorXd & positions)
inline

Definition at line 597 of file EndpointConnectivity.h.

598{
599 const Eigen::Index n = positions.size() / 3;
600 Eigen::Vector3d centre = Eigen::Vector3d::Zero();
601 for (Eigen::Index i = 0; i < n; ++i)
602 centre += positions.segment<3>(3 * i);
603 centre /= static_cast<double>(n);
604 Eigen::MatrixXd basis = Eigen::MatrixXd::Zero(positions.size(), 6);
605 for (Eigen::Index i = 0; i < n; ++i) {
606 const Eigen::Vector3d r = positions.segment<3>(3 * i) - centre;
607 for (int k = 0; k < 3; ++k) {
608 basis(3 * i + k, k) = 1.0;
609 Eigen::Vector3d axis = Eigen::Vector3d::Zero();
610 axis(k) = 1.0;
611 basis.block<3, 1>(3 * i, 3 + k) = r.cross(axis);
612 }
613 }
614 return basis;
615}

◆ centralDifferencePoints()

Eigen::MatrixXd gpr::optim::centralDifferencePoints ( const Eigen::VectorXd & center,
double step,
const Eigen::MatrixXd & directions )
inline

Central-difference geometries along each direction: column 2k is center + step d_k and column 2k+1 is center - step d_k. Every stencil forms its points here, so a held row is found again bit for bit.

Definition at line 191 of file PhysicalCurvatureBasis.h.

194{
195 Eigen::MatrixXd points(center.size(), 2 * directions.cols());
196 for (Eigen::Index k = 0; k < directions.cols(); ++k) {
197 points.col(2 * k) = center + step * directions.col(k);
198 points.col(2 * k + 1) = center - step * directions.col(k);
199 }
200 return points;
201}

◆ certifiedCurvatureSign()

int gpr::optim::certifiedCurvatureSign ( double extrapolated,
double estimate )
inlinenoexcept

The sign of the extrapolated curvature certified against its truncation estimate: +1 or -1 when the magnitude exceeds the estimate, 0 when the measurement cannot resolve the sign.

Definition at line 129 of file RichardsonCurvature.h.

130{
131 if (!std::isfinite(extrapolated) || !std::isfinite(estimate)) return 0;
132 const double resolution = std::abs(estimate);
133 if (extrapolated > resolution) return 1;
134 if (extrapolated < -resolution) return -1;
135 return 0;
136}

◆ certifyAdaptiveStencilIndex()

template<typename Gradients>
StencilIndexCertificate gpr::optim::certifyAdaptiveStencilIndex ( const StencilIndex & index,
const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
double step,
const Gradients & gradients,
double noise_multiplier = 0.0 )

Refine the uncertainty that prevents a terminal decision. A weak block whose own sign is unresolved gets a smaller stencil; a positive weak block coupled to an unresolved complement gets another measured mode. Identical Cartesian requests reuse their measured gradients. A smaller step must reduce the whole weak-block error before another reduction is tried; one positive Rayleigh bound does not resolve that block's sign.

Definition at line 804 of file StencilIndex.h.

808{
809 Eigen::MatrixXd retained_points(positions.size(), 0);
810 Eigen::MatrixXd retained_gradients(0, positions.size());
811 const auto measure = [&](const Eigen::MatrixXd& points) -> Eigen::MatrixXd {
812 std::vector<Eigen::Index> slots(points.cols());
813 std::vector<Eigen::Index> missing;
814 const Eigen::Index held = retained_points.cols();
815 for (Eigen::Index j = 0; j < points.cols(); ++j) {
816 Eigen::Index found = 0;
817 while (found < held && !(retained_points.col(found).array() ==
818 points.col(j).array())
819 .all())
820 ++found;
821 if (found == held) {
822 const auto pending =
823 std::find_if(missing.begin(), missing.end(),
824 [&](Eigen::Index candidate) {
825 return (points.col(candidate).array() ==
826 points.col(j).array())
827 .all();
828 });
829 slots[j] = held + std::distance(missing.begin(), pending);
830 if (pending == missing.end()) missing.push_back(j);
831 } else {
832 slots[j] = found;
833 }
834 }
835 if (!missing.empty()) {
836 Eigen::MatrixXd requests(points.rows(), missing.size());
837 for (Eigen::Index j = 0; j < requests.cols(); ++j)
838 requests.col(j) = points.col(missing[j]);
839 const Eigen::MatrixXd measured = gradients(requests);
840 if (measured.rows() != requests.cols() ||
841 measured.cols() != requests.rows() || !measured.allFinite())
842 return Eigen::MatrixXd::Constant(
843 points.cols(), points.rows(),
844 std::numeric_limits<double>::quiet_NaN());
845 retained_points.conservativeResize(Eigen::NoChange,
846 held + requests.cols());
847 retained_gradients.conservativeResize(held + requests.cols(),
848 Eigen::NoChange);
849 retained_points.rightCols(requests.cols()) = requests;
850 retained_gradients.bottomRows(requests.cols()) = measured;
851 }
852 Eigen::MatrixXd result(points.cols(), points.rows());
853 for (Eigen::Index j = 0; j < points.cols(); ++j)
854 result.row(j) = retained_gradients.row(slots[j]);
855 return result;
856 };
857 const auto stamp = [&](StencilIndexCertificate& cert) {
858 cert.refinement_points = retained_points;
859 cert.refinement_gradients = retained_gradients;
860 };
861 auto out = certifyStencilIndex(index, positions, masses, step, measure, 0,
862 noise_multiplier);
863 stamp(out);
864 int step_reductions = 0;
865 while (!out.first_order && !out.higher_order && out.negative_upper < 0.0 &&
866 std::isfinite(out.weak_block_lower) &&
867 std::isfinite(out.weak_block_error)) {
868 Eigen::Index weak = out.refined_positive_modes;
869 const bool smaller_step = out.weak_block_lower <= 0.0;
870 if (smaller_step) {
871 if (step_reductions >= forceStopAdaptiveStepReductions()) break;
872 const double next = 0.5 * step;
873 if (!(next > 0.0) || next == step) break;
874 step = next;
875 ++step_reductions;
876 } else {
877 if (weak + 1 >= index.curvatures.size()) break;
878 ++weak;
879 }
880 auto refined = certifyStencilIndex(index, positions, masses, step,
881 measure, weak, noise_multiplier);
882 stamp(refined);
883 if (refined.first_order || refined.higher_order) return refined;
884 if (smaller_step && !(refined.weak_block_error < out.weak_block_error))
885 break;
886 out = std::move(refined);
887 }
888 stamp(out);
889 return out;
890}
Half measured(const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &options)
Full central difference of the oracle gradient: 2 d calls.
Half refined(GaussianProcessRegression &gp, const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &raw_options)
constexpr int forceStopAdaptiveStepReductions() noexcept
StencilIndexCertificate certifyStencilIndex(const StencilIndex &index, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const Gradients &gradients, Eigen::Index minimum_weak=0, double noise_multiplier=0.0)
Eigen::VectorXd curvatures
Vibrational eigenvalues, ascending, eV/(A^2 amu).

◆ certifyStencilIndex()

template<typename Gradients>
StencilIndexCertificate gpr::optim::certifyStencilIndex ( const StencilIndex & index,
const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
double step,
const Gradients & gradients,
Eigen::Index minimum_weak = 0,
double noise_multiplier = 0.0 )

Refine unresolved modes in one batch and retain the complete positive restriction, including its coupling to the resolved complement. The same comparison matrix determines the independent validation's bound.

Definition at line 391 of file StencilIndex.h.

395{
397 const Eigen::Index dimension = index.curvatures.size();
398 if (!index.valid || dimension == 0) return out;
399 out.hessian = index.hessian;
400 out.negative_upper = index.curvatures(0) + index.resolution;
401 if (dimension > 1 && index.curvatures(1) < -index.resolution) {
402 out.higher_order = true;
403 out.negative_pair_upper = index.curvatures(1) + index.resolution;
404 out.escape = index.modes.col(1);
405 return out;
406 }
407 const bool refine_lowest =
408 std::abs(index.curvatures(0)) <= index.resolution;
409 Eigen::Index weak = 0;
410 while (weak + 1 < dimension &&
411 index.curvatures(weak + 1) <= index.resolution)
412 ++weak;
413 weak = std::max(weak, std::min(minimum_weak, dimension - 1));
414 out.refined_positive_modes = weak;
415 if (weak == 0) {
416 out.positive_lower = dimension > 1
417 ? index.curvatures(1) - index.resolution
418 : std::numeric_limits<double>::infinity();
419 if (!refine_lowest) {
420 out.first_order = out.negative_upper < 0.0;
421 return out;
422 }
423 }
424 if (index.curvatures(0) > index.resolution) return out;
425
426 const Eigen::Index begin = refine_lowest ? 0 : 1;
427 const Eigen::Index count = weak + (refine_lowest ? 1 : 0);
428 const Eigen::MatrixXd basis = index.modes.middleCols(begin, count);
429 const auto refined = refineWeakModes(positions, masses, basis, step,
430 gradients, noise_multiplier);
431 if (!refined.valid) return out;
432 // The pooled refinement spread rests on one difference per refined
433 // mode and can come out small by chance when few modes are refined.
434 // The antisymmetric part of the full stencil pools every entry: its
435 // spectral norm is about sqrt(n) times the noise s of one coarse
436 // curvature. A coarse-minus-fine difference has standard deviation
437 // sqrt(5) s, so the same multiplier on sqrt(5) s is the floor's lower
438 // limit.
439 double noise = refined.noise_floor;
440 if (noise_multiplier > 0.0 && std::isfinite(noise_multiplier))
441 noise = std::max(noise, noise_multiplier * std::sqrt(5.0) *
442 index.resolution /
443 std::sqrt(static_cast<double>(dimension)));
444
445 const Eigen::MatrixXd projected = index.modes.transpose() * refined.action;
446 Eigen::MatrixXd nominal = index.curvatures.asDiagonal();
447 nominal.middleCols(begin, count) = projected;
448 nominal.middleRows(begin, count) = projected.transpose();
449 const Eigen::MatrixXd refined_block = projected.middleRows(begin, count);
450 nominal.block(begin, begin, count, count) =
451 0.5 * (refined_block + refined_block.transpose());
452 Eigen::MatrixXd correction = nominal;
453 correction.diagonal() -= index.curvatures;
454 out.hessian += index.modes * correction * index.modes.transpose();
455
456 if (weak > 0) {
457 out.weak_direction = refined.directions.col(1 - begin);
458 out.weak_even = refined.even.col(1 - begin);
459 out.weak_step = refined.step;
460 out.weak_inverse_mass = refined.inverse_mass(1 - begin);
461 }
462 const auto positive_modes = index.modes.middleCols(1, weak);
463 const auto action = refined.action.rightCols(weak);
464 const auto truncation = refined.truncation.rightCols(weak);
465 const Eigen::MatrixXd block = positive_modes.transpose() * action;
466 const Eigen::MatrixXd symmetric = 0.5 * (block + block.transpose());
467 const Eigen::MatrixXd block_error = positive_modes.transpose() * truncation;
468 Eigen::MatrixXd errors =
469 0.5 * (block_error.cwiseAbs() + block_error.transpose().cwiseAbs()) +
470 (0.5 * (block - block.transpose())).cwiseAbs();
471 errors.array() += noise;
472 Eigen::MatrixXd comparison =
473 Eigen::MatrixXd::Zero(dimension - 1, dimension - 1);
474 comparison.topLeftCorner(weak, weak) = -symmetric.cwiseAbs() - errors;
475 comparison.diagonal().head(weak) = symmetric.diagonal() - errors.diagonal();
476 const Eigen::Index tail = dimension - weak - 1;
477 Eigen::MatrixXd coupling(tail, weak);
478 if (tail > 0) {
479 const auto tail_modes = index.modes.rightCols(tail);
480 coupling = (tail_modes.transpose() * action).cwiseAbs() +
481 (tail_modes.transpose() * truncation).cwiseAbs();
482 coupling.array() += noise;
483 comparison.bottomLeftCorner(tail, weak) = -coupling;
484 comparison.topRightCorner(weak, tail) = -coupling.transpose();
485 comparison.diagonal().tail(tail) =
486 index.curvatures.tail(tail).array() - index.resolution;
487 }
488 const double orthogonality =
489 (index.modes.transpose() * index.modes -
490 Eigen::MatrixXd::Identity(dimension, dimension))
491 .norm();
492 const double allowance =
493 (orthogonality +
494 64.0 * std::numeric_limits<double>::epsilon() * dimension) *
495 (comparison.norm() + refined.action.norm() + refined.truncation.norm() +
496 index.curvatures.norm());
497 if (dimension > 1) {
498 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> lower(
499 comparison, Eigen::EigenvaluesOnly);
500 if (lower.info() != Eigen::Success) return out;
501 out.positive_lower = lower.eigenvalues()(0) - allowance;
502 if (weak > 1 && out.positive_lower <= 0.0)
503 out.positive_lower =
504 std::max(out.positive_lower,
506 symmetric, errors, coupling,
507 comparison.diagonal().tail(tail), allowance));
508 }
509 if (refine_lowest)
510 out.negative_upper =
511 index.modes.col(0).dot(refined.action.col(0)) +
512 std::abs(index.modes.col(0).dot(refined.truncation.col(0))) +
513 noise + allowance;
514 out.first_order = out.negative_upper < 0.0 && out.positive_lower > 0.0;
515
516 if (weak > 0 && out.negative_upper < 0.0) {
517 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(
518 symmetric);
519 if (spectrum.info() != Eigen::Success) return out;
520 const Eigen::VectorXd mode = spectrum.eigenvectors().col(0);
521 const Eigen::VectorXd magnitude = mode.cwiseAbs();
522 out.weak_error = magnitude.dot(errors * magnitude) + allowance;
523 out.weak_lower = spectrum.eigenvalues()(0) - out.weak_error;
524 out.weak_block_error = errors.norm() + allowance;
525 if (weak == dimension - 1) {
526 out.weak_block_lower = out.positive_lower;
527 } else {
528 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> lower(
529 comparison.topLeftCorner(weak, weak), Eigen::EigenvaluesOnly);
530 if (lower.info() != Eigen::Success) return out;
531 out.weak_block_lower = lower.eigenvalues()(0) - allowance;
532 if (weak > 1 && out.weak_block_lower <= 0.0)
533 out.weak_block_lower =
534 std::max(out.weak_block_lower,
536 symmetric, errors, Eigen::MatrixXd(0, weak),
537 Eigen::VectorXd(0), allowance));
538 }
539 // The entrywise envelope bounds this Rayleigh quotient without
540 // assigning errors from other directions to it. Coupling to the
541 // primary negative mode remains in the two-dimensional restriction.
542 const double upper = spectrum.eigenvalues()(0) +
543 magnitude.dot(errors * magnitude) + allowance;
544 Eigen::RowVectorXd cross_error =
545 (index.modes.col(0).transpose() * truncation).cwiseAbs();
546 cross_error.array() += noise;
547 const double coupling =
548 std::abs(index.modes.col(0).dot(action * mode)) +
549 (cross_error * magnitude)(0) + allowance;
550 Eigen::Matrix2d majorant;
551 majorant << out.negative_upper, coupling, coupling, upper;
552 const Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> pair(
553 majorant, Eigen::EigenvaluesOnly);
554 if (pair.info() == Eigen::Success) {
555 out.negative_pair_upper = pair.eigenvalues()(1) + allowance;
556 out.higher_order = out.negative_pair_upper < 0.0;
557 out.weak_higher_order = out.higher_order;
558 if (out.higher_order) out.escape = positive_modes * mode;
559 }
560 }
561 return out;
562}
double rotatedPositiveRestrictionLowerBound(const Eigen::MatrixXd &block, const Eigen::MatrixXd &errors, const Eigen::MatrixXd &coupling, const Eigen::VectorXd &tail, double allowance)
RefinedWeakModes refineWeakModes(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, const Eigen::MatrixXd &weak, double step, const Gradients &gradients, double noise_multiplier=0.0)
Eigen::MatrixXd modes
Mass-weighted eigenvectors on the 3N coordinates.
Eigen::MatrixXd hessian
Symmetrized mass-weighted Hessian on the 3N coordinates.

◆ coarseColumnToRefine()

Eigen::Index gpr::optim::coarseColumnToRefine ( const SmoothedCurvatureSpectrum & spectrum,
const std::vector< MeasuredHessianColumn > & columns,
Eigen::Index k )
inline

The coarse column with the largest overlap with the k-th posterior mode, the one whose refinement most reduces that eigenvalue's spread; -1 when every overlapping column is refined already.

Definition at line 913 of file SmoothedCurvatureSpectrum.h.

916{
917 if (!spectrum.valid || k < 0 || k >= spectrum.modes.cols()) return -1;
918 const double independence =
919 std::sqrt(std::numeric_limits<double>::epsilon() *
920 static_cast<double>(spectrum.modes.rows()));
921 Eigen::Index best = -1;
922 double best_overlap = independence;
923 for (std::size_t j = 0; j < columns.size(); ++j) {
924 if (columns[j].refined) continue;
925 const double overlap =
926 std::abs(columns[j].direction.dot(spectrum.modes.col(k)));
927 if (overlap > best_overlap) {
928 best_overlap = overlap;
929 best = static_cast<Eigen::Index>(j);
930 }
931 }
932 return best;
933}

◆ compiledMinimizationLayout()

MinimizationLayoutStamp gpr::optim::compiledMinimizationLayout ( )
inlinenodiscardnoexcept

Definition at line 135 of file GPMinimizer.h.

136{
138 static_cast<std::uint32_t>(sizeof(MinimizationConfig)),
139 static_cast<std::uint32_t>(sizeof(MinimizationResult))};
140}
constexpr std::uint32_t kMinimizationLayoutVersion
Definition GPMinimizer.h:45
Configuration for GP-guided minimization.
Definition GPMinimizer.h:56
Result of GP-guided minimization.
Definition GPMinimizer.h:96

◆ completedAdditionalNegativeMode()

CompletedSecondMode gpr::optim::completedAdditionalNegativeMode ( const Eigen::MatrixXd & completed,
const Eigen::MatrixXd & basis,
const Eigen::VectorXd & negative_mode )
inline

Eliminate a measured negative direction by congruence before choosing another probe. For H = [a b^T; b D], a < 0, the remaining inertia is that of D - b b^T/a. Lifting its mode y to [-b^T y/a; y] preserves the sign of its quadratic form. This orders measurements only; the measured Ritz pair and the final oracle stencil decide the index.

Definition at line 381 of file MeasuredCurvatureSpectrum.h.

384{
386 const Eigen::Index dimension = completed.rows();
387 if (dimension < 2 || completed.cols() != dimension ||
388 basis.rows() != dimension || negative_mode.size() != dimension ||
389 !completed.allFinite() || !basis.allFinite() ||
390 !negative_mode.allFinite())
391 return out;
392 const double norm = negative_mode.stableNorm();
393 const double scale = completed.cwiseAbs().maxCoeff();
394 if (!(norm > 0.0) || !std::isfinite(norm) || !(scale > 0.0)) return out;
395 const Eigen::VectorXd axis = negative_mode / norm;
396 const Eigen::MatrixXd symmetric =
397 (0.5 * (completed / scale) + 0.5 * (completed.transpose() / scale));
398 const Eigen::VectorXd action = symmetric * axis;
399 const double pivot = axis.dot(action);
400 const double floor = 64.0 * std::numeric_limits<double>::epsilon() *
401 dimension * symmetric.norm();
402 if (!(pivot < -floor)) return out;
403 const Eigen::HouseholderQR<Eigen::MatrixXd> qr(axis);
404 const Eigen::MatrixXd orthogonal =
405 qr.householderQ() * Eigen::MatrixXd::Identity(dimension, dimension);
406 const Eigen::MatrixXd complement = orthogonal.rightCols(dimension - 1);
407 const Eigen::VectorXd coupling = complement.transpose() * action;
408 Eigen::MatrixXd schur = complement.transpose() * symmetric * complement;
409 schur.noalias() -= (coupling / pivot) * coupling.transpose();
410 schur = (0.5 * (schur + schur.transpose())).eval();
411 if (!schur.allFinite()) return out;
412 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(schur);
413 if (solver.info() != Eigen::Success || !solver.eigenvalues().allFinite())
414 return out;
415 const Eigen::VectorXd transverse = solver.eigenvectors().col(0);
416 Eigen::VectorXd lifted =
417 complement * transverse - axis * (coupling.dot(transverse) / pivot);
418 const double lifted_norm = lifted.stableNorm();
419 if (!(lifted_norm > 0.0) || !std::isfinite(lifted_norm)) return out;
420 out.mode = lifted / lifted_norm;
421 out.curvature = out.mode.dot(symmetric * out.mode) * scale;
422 if (!std::isfinite(out.curvature)) return CompletedSecondMode{};
423 Eigen::VectorXd residual = out.mode;
424 for (int pass = 0; pass < 2; ++pass)
425 residual -= basis * (basis.transpose() * residual).eval();
426 const double outside = residual.stableNorm();
427 if (outside > std::sqrt(std::numeric_limits<double>::epsilon() * dimension))
428 out.unmeasured = residual / outside;
429 out.valid = true;
430 return out;
431}

◆ completedSecondMode()

CompletedSecondMode gpr::optim::completedSecondMode ( const Eigen::MatrixXd & completed,
const Eigen::MatrixXd & basis,
Eigen::Index k = 1 )
inline

The direction a completion proposes for measurement: its k-th lowest mode (the second by default). completed is a symmetric completion of the columns measured along the orthonormal basis. This supplies a proposal, not a sign.

Definition at line 350 of file MeasuredCurvatureSpectrum.h.

353{
355 if (k < 0 || completed.rows() <= k ||
356 completed.rows() != completed.cols() ||
357 basis.rows() != completed.rows() || !completed.allFinite() ||
358 !basis.allFinite())
359 return out;
360 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(completed);
361 if (solver.info() != Eigen::Success || !solver.eigenvalues().allFinite())
362 return out;
363 out.curvature = solver.eigenvalues()(k);
364 out.mode = solver.eigenvectors().col(k);
365 Eigen::VectorXd residual = out.mode;
366 for (int pass = 0; pass < 2; ++pass)
367 residual -= basis * (basis.transpose() * residual).eval();
368 const double norm = residual.norm();
369 if (norm > std::sqrt(std::numeric_limits<double>::epsilon() *
370 static_cast<double>(residual.size())))
371 out.unmeasured = residual / norm;
372 out.valid = true;
373 return out;
374}

◆ completeMeasuredHessian()

Eigen::MatrixXd gpr::optim::completeMeasuredHessian ( const Eigen::MatrixXd & prior,
const Eigen::MatrixXd & basis,
const Eigen::MatrixXd & action )
inline

Least-change symmetric completion of measured columns over a prior. An orthonormal basis fixes its measured block and cross terms; the unmeasured block keeps the prior. Incompatible columns are symmetrized within the measured block. This operator supplies proposals, not signs.

Definition at line 284 of file MeasuredCurvatureSpectrum.h.

287{
288 if (prior.rows() == 0 || prior.rows() != prior.cols() ||
289 basis.rows() != prior.rows() || action.rows() != basis.rows() ||
290 action.cols() != basis.cols() || !prior.allFinite() ||
291 !basis.allFinite() || !action.allFinite())
292 return {};
293 const double tolerance =
294 std::sqrt(std::numeric_limits<double>::epsilon() * prior.rows());
295 if ((basis.transpose() * basis -
296 Eigen::MatrixXd::Identity(basis.cols(), basis.cols()))
297 .norm() > tolerance)
298 return {};
299 const Eigen::MatrixXd symmetric = 0.5 * (prior + prior.transpose());
300 const Eigen::MatrixXd residual = action - symmetric * basis;
301 const Eigen::MatrixXd measured = basis.transpose() * residual;
302 Eigen::MatrixXd completed =
303 symmetric + residual * basis.transpose() + basis * residual.transpose();
304 completed -=
305 basis * (0.5 * (measured + measured.transpose())) * basis.transpose();
306 completed = (0.5 * (completed + completed.transpose())).eval();
307 return completed.allFinite() ? completed : Eigen::MatrixXd{};
308}

◆ consistentGradientPrediction()

Eigen::RowVectorXd gpr::optim::consistentGradientPrediction ( const Eigen::Ref< const Eigen::RowVectorXd > & measured_reference,
const Eigen::Ref< const Eigen::RowVectorXd > & predicted_reference,
const Eigen::Ref< const Eigen::RowVectorXd > & predicted_trial )
inline

Anchor a local force-merit model to its measured reference gradient. Both predictions must come from the same posterior. Their difference retains its curvature while cancelling a constant gradient bias.

Definition at line 18 of file ConsistentForceModel.h.

22{
23 if (measured_reference.size() == 0 ||
24 measured_reference.size() != predicted_reference.size() ||
25 measured_reference.size() != predicted_trial.size() ||
26 !measured_reference.allFinite() || !predicted_reference.allFinite() ||
27 !predicted_trial.allFinite()) {
28 throw std::invalid_argument(
29 "consistent gradient prediction requires matching finite "
30 "gradients");
31 }
32 // Subtract the predictions first so a zero step returns the measurement.
33 const Eigen::RowVectorXd predicted_change =
34 predicted_trial - predicted_reference;
35 return measured_reference + predicted_change;
36}

◆ coordinatesCoincideAtRoundoff()

template<class Left, class Right>
bool gpr::optim::coordinatesCoincideAtRoundoff ( const Eigen::MatrixBase< Left > & left,
const Eigen::MatrixBase< Right > & right )
nodiscardnoexcept

Numerical stagnation in stored Cartesian coordinates. Each component has a binary64 roundoff allowance; acquisition distances and force tolerances do not define geometry identity.

Definition at line 17 of file CoordinateResolution.h.

20{
21 if (left.rows() != right.rows() || left.cols() != right.cols() ||
22 left.size() == 0 || !left.allFinite() || !right.allFinite())
23 return false;
24 constexpr double allowance = 8.0 * std::numeric_limits<double>::epsilon();
25 for (Eigen::Index row = 0; row < left.rows(); ++row) {
26 for (Eigen::Index column = 0; column < left.cols(); ++column) {
27 const double a = left(row, column);
28 const double b = right(row, column);
29 const double scale = std::max({1.0, std::abs(a), std::abs(b)});
30 if (std::abs(a - b) > allowance * scale) return false;
31 }
32 }
33 return true;
34}

◆ corderoRadius()

double gpr::optim::corderoRadius ( int atomic_number)
inlinenoexcept

Cordero et al., Dalton Trans. 2008, angstrom. An unlisted element contributes no edges.

Definition at line 237 of file EndpointConnectivity.h.

238{
239 switch (atomic_number) {
240 case 1:
241 return 0.31;
242 case 6:
243 return 0.76;
244 case 7:
245 return 0.71;
246 case 8:
247 return 0.66;
248 case 9:
249 return 0.57;
250 case 14:
251 return 1.11;
252 case 15:
253 return 1.07;
254 case 16:
255 return 1.05;
256 case 17:
257 return 1.02;
258 case 35:
259 return 1.20;
260 default:
261 return 0.0;
262 }
263}

◆ curvatureAtWavenumber()

double gpr::optim::curvatureAtWavenumber ( double wavenumber,
const Eigen::VectorXd & direction,
const Eigen::VectorXd & atomic_masses )
inline

Cartesian curvature of a displacement whose harmonic wavenumber is wavenumber (cm^-1): (2 pi c nu)^2 u^T M u / u^T u, in eV/A^2 for masses in amu. A softer direction is below that frequency resolution whatever its sign. Zero when no masses are given or the sizes disagree.

Definition at line 314 of file MeasuredCurvatureSpectrum.h.

317{
318 if (!(wavenumber > 0.0) || atomic_masses.size() == 0 ||
319 direction.size() != 3 * atomic_masses.size())
320 return 0.0;
321 const double norm = direction.squaredNorm();
322 if (!(norm > 0.0) || !std::isfinite(norm)) return 0.0;
323 double mass = 0.0;
324 for (Eigen::Index atom = 0; atom < atomic_masses.size(); ++atom)
325 mass +=
326 atomic_masses(atom) * direction.segment<3>(3 * atom).squaredNorm();
327 // (2 pi c)^2 amu in eV/A^2 per cm^-2.
328 constexpr double units = 3.6773913171220107e-06;
329 return units * wavenumber * wavenumber * mass / norm;
330}

◆ curvatureResolvedByStencil()

bool gpr::optim::curvatureResolvedByStencil ( double measured,
double anharmonic_scale )
inlinenoexcept

Screen for refining a single-separation curvature: its magnitude against the stencil's own anharmonicity scale, the even residual (F(h) + F(-h))/2 - F(0) = b h^2 of the same three measurements over h. This is not a sign certificate. The even residual is F''(0) h^2 / 2 and vanishes on a symmetric direction whatever the truncation is; the certificate is curvatureResolvedByThirdDerivative.

Definition at line 75 of file RichardsonCurvature.h.

77{
78 if (!std::isfinite(measured)) return false;
79 if (!std::isfinite(anharmonic_scale)) return false;
80 return std::abs(measured) > std::abs(anharmonic_scale);
81}

◆ curvatureResolvedBySurrogate()

bool gpr::optim::curvatureResolvedBySurrogate ( double measured,
double surrogate )
inlinenoexcept

With one measured side there is no even residual; the surrogate's disagreement with the measurement is the only resolution scale a single-separation estimate carries.

Definition at line 118 of file RichardsonCurvature.h.

120{
121 if (!std::isfinite(measured)) return false;
122 if (!std::isfinite(surrogate)) return true;
123 return std::abs(measured) > std::abs(measured - surrogate);
124}

◆ curvatureResolvedByThirdDerivative()

bool gpr::optim::curvatureResolvedByThirdDerivative ( double measured,
double third,
double step )
inlinenoexcept

One central difference resolves the sign of the curvature only against an explicit third-derivative bound. If abs(phi''') <= third on [-step, step], abs((phi(step) - phi(-step)) / (2 * step) - phi'(0)) <= third * step * step / 6 (centralCurvature_error). The even residual (φ(step) + φ(-step)) / 2 - φ(0) is φ''(0) step² / 2 and does not bound that error: φ(t) = t - 100 t³ at step = 0.2 has even residual 0 and a central quotient of -3, while the true curvature is +1.

Definition at line 91 of file RichardsonCurvature.h.

93{
94 if (!std::isfinite(measured) || !std::isfinite(third) || !(third >= 0.0) ||
95 !(step > 0.0) || !std::isfinite(step))
96 return false;
97 return std::abs(measured) > third * step * step / 6.0;
98}

◆ decideMeasuredIndex()

template<typename Gradients>
MeasuredIndexDecision gpr::optim::decideMeasuredIndex ( const Eigen::MatrixXd & columns,
const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
double step,
const Gradients & gradients,
const Eigen::MatrixXd * measured = nullptr )

measured is analyzeStencilIndex's.

Definition at line 578 of file StencilIndex.h.

582{
584 const StencilIndex index =
585 analyzeStencilIndex(columns, positions, masses, measured);
586 if (!index.valid) return out;
587 out.resolution = index.resolution;
588 for (Eigen::Index i = 0; i < index.curvatures.size(); ++i) {
589 const double value = index.curvatures(i);
590 if (value < -index.resolution)
591 ++out.negative;
592 else if (!(value > index.resolution))
593 ++out.unresolved;
594 }
595 const StencilIndexCertificate certified =
596 certifyStencilIndex(index, positions, masses, step, gradients);
597 out.first_order = certified.first_order;
598 out.higher_order = certified.higher_order;
599 if (certified.first_order) {
600 out.negative = 1;
601 out.unresolved = 0;
602 } else if (certified.higher_order) {
603 if (out.negative < 2) out.negative = 2;
604 // A weak mode the refinement proved negative is no longer
605 // unresolved. A second negative the coarse stencil already
606 // resolved leaves any other unresolved mode as it was.
607 if (certified.weak_higher_order) out.unresolved = 0;
608 }
609 return out;
610}
StencilIndex analyzeStencilIndex(const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, const Eigen::MatrixXd *measured=nullptr)

◆ defaultStencilStep()

double gpr::optim::defaultStencilStep ( )
inlineconstexprnoexcept

Cartesian displacement of a central-difference stencil when the caller names none, in the coordinate unit. A stencil on a learned potential needs a step that keeps the noise of the gradient below the curvature it resolves; 0.01 A does so for the potentials the drivers support.

Definition at line 778 of file StencilIndex.h.

779{
780 return 0.01;
781}

◆ directionsAreCoordinateAxes()

bool gpr::optim::directionsAreCoordinateAxes ( const Eigen::MatrixXd & directions)
inline

True when every direction is a distinct coordinate axis: the stencil of a geometry whose other coordinates are frozen. No coordinate axis is orthogonal to the mass-weighted translations, so a vibrational basis never reads as one.

Definition at line 171 of file PhysicalCurvatureBasis.h.

172{
173 for (Eigen::Index k = 0; k < directions.cols(); ++k) {
174 Eigen::Index ones = 0;
175 for (Eigen::Index i = 0; i < directions.rows(); ++i) {
176 const double value = directions(i, k);
177 if (value == 1.0)
178 ++ones;
179 else if (value != 0.0)
180 return false;
181 }
182 if (ones != 1) return false;
183 }
184 return directions.cols() > 0 &&
185 (directions.transpose() * directions).isIdentity(0.0);
186}

◆ endpointConnectivityLabel()

const char * gpr::optim::endpointConnectivityLabel ( const EndpointConnectivityReport & report)
inlinenoexcept

Definition at line 190 of file EndpointConnectivity.h.

192{
193 if (report.skipped) return "skipped";
194 if (report.unresolved) return "unresolved";
195 if (!report.reported) return "unavailable";
196 if (report.ambiguous) return "ambiguous";
197 if (!report.graph_applicable && !report.ball_applicable)
198 return "not applicable";
199 return report.connected ? "connected" : "not connected";
200}
bool graph_applicable
False when the relaxed endpoints have one bond graph.
bool skipped
--irc-certificate off. The walk is not run.

◆ endpointMatchBall()

double gpr::optim::endpointMatchBall ( double tolerance,
double lambda_min,
double half_separation )
inlinenoexcept

Match ball around a relaxed minimum.

A residual max-atom force tolerance moves a quadratic minimum by at most tolerance / λ_min in RMSD. The Cartesian gradient then has L2 norm at most tolerance * sqrt(N), the displacement has L2 norm at most that over λ_min, and dividing by sqrt(N) cancels the atom count. Rigid motions are absent from λ_min and from the Kabsch RMSD, so they do not belong in the ball. Each of the walk and the relaxed endpoint can sit one residual from the true minimum, so the RMSD between them is at most twice that. The ball is also not larger than half the RMSD between the two relaxed minima.

Definition at line 1032 of file EndpointConnectivity.h.

1034{
1035 double ball = std::numeric_limits<double>::infinity();
1036 if (lambda_min > 0.0 && std::isfinite(lambda_min) && tolerance > 0.0)
1037 ball = 2.0 * tolerance / lambda_min;
1038 if (half_separation > 0.0 && std::isfinite(half_separation))
1039 ball = std::min(ball, half_separation);
1040 return ball;
1041}

◆ excludeNonPositiveCurvatureBlock()

void gpr::optim::excludeNonPositiveCurvatureBlock ( Eigen::VectorXd & s,
Eigen::VectorXd & y,
Eigen::Index offset,
Eigen::Index length )

Remove a block's nonpositive secant contribution. Positive curvature is retained, including the reflected unstable direction at an index-one saddle. Invalid blocks and nonfinite curvature leave the pair unchanged for the caller's full-pair validity check.

Definition at line 25 of file LBFGS.cpp.

27{
28 if (s.size() != y.size() || offset < 0 || length <= 0 ||
29 length > s.size() || offset > s.size() - length)
30 return;
31 const double curvature =
32 s.segment(offset, length).dot(y.segment(offset, length));
33 if (std::isfinite(curvature) && curvature <= 0.0) {
34 s.segment(offset, length).setZero();
35 y.segment(offset, length).setZero();
36 }
37}

◆ forceStopAdaptiveStepReductions()

int gpr::optim::forceStopAdaptiveStepReductions ( )
inlineconstexprnoexcept

Step halvings while a weak block's error keeps falling. Truncation error shrinks with the step, so an unbounded loop chases it to underflow without ever signing the mode.

Definition at line 792 of file StencilIndex.h.

793{
794 return 4;
795}

◆ forceStopCertificatePlanned()

bool gpr::optim::forceStopCertificatePlanned ( const ForceStopStencilPlan & plan)
inlinenoexcept

True when the plan spends evaluations on an index certificate at this stage: a stencil to measure, or stored columns to read.

Definition at line 1233 of file StencilIndex.h.

◆ forceStopHeldColumn()

Eigen::Index gpr::optim::forceStopHeldColumn ( const Eigen::MatrixXd & held,
const Eigen::VectorXd & query,
double relative = 1e-6 )
inline

True when query is a column already stored at held. A later certificate at an unchanged geometry uses the stored gradient.

Definition at line 1241 of file StencilIndex.h.

1244{
1245 if (held.rows() != query.size() || held.cols() == 0 || !query.allFinite())
1246 return -1;
1247 Eigen::Index nearest = -1;
1248 double best = std::numeric_limits<double>::infinity();
1249 for (Eigen::Index col = 0; col < held.cols(); ++col) {
1250 if (!held.col(col).allFinite()) continue;
1251 const double distance = (held.col(col) - query).norm();
1252 if (distance < best) {
1253 best = distance;
1254 nearest = col;
1255 }
1256 }
1257 if (nearest < 0 || !(best <= relative * (1.0 + query.norm()))) return -1;
1258 return nearest;
1259}

◆ forceStopLowestModes()

Eigen::MatrixXd gpr::optim::forceStopLowestModes ( const Eigen::MatrixXd & columns,
const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
Eigen::Index count,
const Eigen::MatrixXd * measured = nullptr )
inline

Lowest Cartesian modes of a measured Hessian, lowest curvature first. measured is analyzeStencilIndex's.

Definition at line 1263 of file StencilIndex.h.

1267{
1268 const StencilIndex index =
1269 analyzeStencilIndex(columns, positions, masses, measured);
1270 if (!index.valid || index.modes.cols() == 0 || count <= 0) return {};
1271 const Eigen::Index n = std::min(count, index.modes.cols());
1272 Eigen::VectorXd root(positions.size());
1273 for (Eigen::Index k = 0; k < positions.size(); ++k)
1274 root(k) = std::sqrt(masses(k / 3));
1275 Eigen::MatrixXd cartesian(positions.size(), n);
1276 for (Eigen::Index j = 0; j < n; ++j) {
1277 Eigen::VectorXd direction = index.modes.col(j).cwiseQuotient(root);
1278 const double norm = direction.norm();
1279 cartesian.col(j) = norm > 0.0 ? direction / norm : direction;
1280 }
1281 return cartesian;
1282}

◆ forceStopMeasurementInconclusiveOrHigher()

bool gpr::optim::forceStopMeasurementInconclusiveOrHigher ( const ForceStopMeasurement & measured)
inlinenoexcept

A measured stencil that is not index-one. Higher-order and unresolved both qualify: neither certifies the stopped geometry.

Definition at line 1142 of file StencilIndex.h.

1144{
1145 return measured.measured && !measured.first_order;
1146}
std::vector< int > measured
1 for a mode at least 99% inside the measured directions.

◆ forceStopMinModeEscapes()

int gpr::optim::forceStopMinModeEscapes ( )
inlineconstexprnoexcept

Min-mode escapes after a higher-order certificate, for every search.

Definition at line 1186 of file StencilIndex.h.

1187{
1188 return 16;
1189}

◆ forceStopRefinementCertified()

int gpr::optim::forceStopRefinementCertified ( )
inlineconstexprnoexcept

refine returns this when the soft-mode walk itself reached an index-one point inside the force tolerance. The certificate accepts that point. Another full stencil is not started: the walk already measured the modes, and a fresh 3N stencil after the report line is what kept a converged search from printing its call total.

Definition at line 1161 of file StencilIndex.h.

1162{
1163 return 0;
1164}

◆ forceStopRefinementStillHigher()

int gpr::optim::forceStopRefinementStillHigher ( )
inlineconstexprnoexcept

refine returns this when the soft-mode walk is still higher-order. The low modes were measured, so another full Cartesian stencil is not started. The certificate refines again or leaves along the extra mode.

Definition at line 1169 of file StencilIndex.h.

1170{
1171 return -2;
1172}

◆ forceStopSoftRefinementLimit()

int gpr::optim::forceStopSoftRefinementLimit ( )
inlineconstexprnoexcept

How many soft-mode refinements follow a higher-order stencil. One walk, then a fresh stencil. A second walk was still higher-order on the cells that needed an escape, and it paid another full stencil.

Definition at line 1151 of file StencilIndex.h.

1152{
1153 return 1;
1154}

◆ forceStopStencilCertifies()

bool gpr::optim::forceStopStencilCertifies ( bool measured,
bool first_order )
inlinenoexcept

An unmeasured stop is uncertified. 0fa3c694 returned there. Certification is the measured stencil reporting one negative mode.

Definition at line 1286 of file StencilIndex.h.

1287{
1288 return measured && first_order;
1289}

◆ formatEndpointConnectivity()

std::string gpr::optim::formatEndpointConnectivity ( const EndpointConnectivityReport & report)
inline

Definition at line 456 of file EndpointConnectivity.h.

458{
459 std::ostringstream line;
460 line << std::setprecision(8);
461 line << "Endpoint connectivity: " << endpointConnectivityLabel(report);
462 if (report.skipped) {
463 line << "\n ball=skipped graph=skipped";
464 return line.str();
465 }
466 if (!report.reported) {
467 appendIrcProfile(line, report);
468 return line.str();
469 }
470 line << "\n separation_A=" << report.separation
471 << " reactant_ball_A=" << report.reactant_ball
472 << " product_ball_A=" << report.product_ball
473 << " lambda_reactant=" << report.lambda_reactant
474 << " lambda_product=" << report.lambda_product
475 << " lowest_reactant=" << report.lowest_reactant
476 << " lowest_product=" << report.lowest_product
477 << " resolution_reactant=" << report.resolution_reactant
478 << " resolution_product=" << report.resolution_product;
479 if (report.saddle_index_measured) {
480 line << " saddle_curvature=" << report.saddle_curvature;
481 } else {
482 line
483 << " directional_curvature=" << report.directional_curvature
484 << "\nSaddle index: descent direction verified; index not measured";
485 }
486 line << "\n forward_reactant_A=" << report.forward_reactant
487 << " forward_product_A=" << report.forward_product
488 << " reverse_reactant_A=" << report.reverse_reactant
489 << " reverse_product_A=" << report.reverse_product
490 << "\n deposited_forward_reactant_A="
492 << " deposited_forward_product_A=" << report.deposited_forward_product
493 << " deposited_reverse_reactant_A="
495 << " deposited_reverse_product_A=" << report.deposited_reverse_product
496 << "\n forward_force=" << report.forward_force
497 << " reverse_force=" << report.reverse_force
498 << " forward_calls=" << report.forward_calls
499 << " reverse_calls=" << report.reverse_calls
500 << " forward_steps=" << report.forward_steps
501 << " reverse_steps=" << report.reverse_steps
502 << " walk_separation_A=" << report.walk_separation
503 << " comparison_force=" << report.comparison_tolerance
504 << " calls=" << report.calls
505 << " reactant_energy=" << report.reactant_energy
506 << " product_energy=" << report.product_energy
507 << " forward_energy=" << report.forward_energy
508 << " reverse_energy=" << report.reverse_energy << " ball="
509 << (report.unresolved ? "unresolved"
510 : (!report.ball_applicable
511 ? "na"
512 : (report.ball_matched ? "yes" : "no")))
513 << " graph="
514 << (report.unresolved
515 ? "unresolved"
516 : (!report.graph_applicable
517 ? "na"
518 : (report.graph_connected ? "yes" : "no")))
519 << "\n reactant_bonds=" << report.reactant_bonds
520 << "\n product_bonds=" << report.product_bonds
521 << "\n forward_bonds=" << report.forward_bonds
522 << "\n reverse_bonds=" << report.reverse_bonds;
523 appendIrcProfile(line, report);
524 return line.str();
525}
void appendIrcProfile(std::ostream &line, const EndpointConnectivityReport &report)
const char * endpointConnectivityLabel(const EndpointConnectivityReport &report) noexcept
std::string line(const std::string &topic, const std::vector< Field > &fields)
int forward_steps
Steepest-descent steps plus L-BFGS steps on that side.
std::string reactant_bonds
Bond graphs: sorted "i-j" pairs inside 1.2 times the Cordero radii.

◆ fragmentRotationDirections()

FragmentRotations gpr::optim::fragmentRotationDirections ( const Eigen::VectorXd & positions,
const std::vector< std::pair< int, int > > & bonds )
inline

Definition at line 26 of file FragmentRotations.h.

29{
31 const Eigen::Index dof = positions.size();
32 if (dof < 6 || dof % 3 != 0 || !positions.allFinite()) return out;
33 const int n = static_cast<int>(dof / 3);
34 std::vector<std::vector<int>> adjacent(static_cast<std::size_t>(n));
35 for (const auto& [a, b]: bonds) {
36 if (a < 0 || b < 0 || a >= n || b >= n || a == b) continue;
37 adjacent[static_cast<std::size_t>(a)].push_back(b);
38 adjacent[static_cast<std::size_t>(b)].push_back(a);
39 }
40 const auto atom = [&](int i) {
41 return Eigen::Vector3d(positions.segment<3>(3 * i));
42 };
43 // The atoms reached from `from` without crossing the bond (from, other).
44 const auto side = [&](int from, int other) {
45 std::vector<char> seen(static_cast<std::size_t>(n), 0);
46 std::vector<int> stack{from};
47 seen[static_cast<std::size_t>(from)] = 1;
48 while (!stack.empty()) {
49 const int here = stack.back();
50 stack.pop_back();
51 for (const int next: adjacent[static_cast<std::size_t>(here)]) {
52 if (here == from && next == other) continue;
53 if (seen[static_cast<std::size_t>(next)]) continue;
54 seen[static_cast<std::size_t>(next)] = 1;
55 stack.push_back(next);
56 }
57 }
58 return seen;
59 };
60 std::vector<Eigen::VectorXd> columns;
61 for (const auto& [a, b]: bonds) {
62 if (a < 0 || b < 0 || a >= n || b >= n || a == b) continue;
63 std::vector<char> reached = side(a, b);
64 if (reached[static_cast<std::size_t>(b)]) continue; // on a ring
65 int count = 0;
66 for (const char flag: reached)
67 count += flag;
68 if (2 * count > n) {
69 reached = side(b, a);
70 }
71 const Eigen::Vector3d origin = atom(a);
72 Eigen::Vector3d axis = atom(b) - origin;
73 const double length = axis.norm();
74 if (!(length > 0.0)) continue;
75 axis /= length;
76 Eigen::VectorXd direction = Eigen::VectorXd::Zero(dof);
77 double scale = 0.0;
78 for (int i = 0; i < n; ++i) {
79 if (!reached[static_cast<std::size_t>(i)]) continue;
80 const Eigen::Vector3d arm = atom(i) - origin;
81 scale = std::max(scale, arm.norm());
82 direction.segment<3>(3 * i) = axis.cross(arm);
83 }
84 const double norm = direction.norm();
85 // A side on the axis moves by nothing beyond roundoff of its reach.
86 if (!(norm > std::numeric_limits<double>::epsilon() * dof * scale))
87 continue;
88 columns.push_back(direction / norm);
89 out.bonds.emplace_back(a, b);
90 }
91 out.directions.resize(dof, static_cast<Eigen::Index>(columns.size()));
92 for (std::size_t j = 0; j < columns.size(); ++j)
93 out.directions.col(static_cast<Eigen::Index>(j)) = columns[j];
94 return out;
95}

◆ gp_minimize() [1/2]

MinimizationResult gpr::optim::gp_minimize ( OracleFn oracle,
const Eigen::VectorXd & x_init,
const AtomsConfiguration & atoms_config,
const MinimizationConfig & config,
const policy::TrainingPolicy * policy,
const Observation * seed = nullptr,
const io::TrainedGpState * gp_state = nullptr )

GP-accelerated geometry minimization with a training policy.

Parameters
oracleEnergy and gradient evaluator.
x_initStarting Cartesian coordinates, flattened in atom order.
atoms_configAtomic configuration for the GP kernel.
configSurrogate and minimization settings.
policyTraining policy. Null keeps the engine's decisions.
seedObservations already paid for. A row at x_init is reused and is not an oracle call. Null starts from the oracle.
gp_stateSaved hyperparameters. Null keeps a cold first fit.

Definition at line 202 of file GPMinimizer.cpp.

208{
209 refuseStaleMinimizationConfig(config);
210 if (config.max_inner_steps < 1) {
211 throw std::invalid_argument(
212 "MinimizationConfig::max_inner_steps must be >= 1");
213 }
214 // Direct BFGS maintains positive definiteness for positive-curvature
215 // secants. SR1 and Bofill deliberately retain indefinite curvature, so
216 // they cannot safely initialise a minimization Newton solve.
217 if (config.secant.seed_curvature &&
219 throw std::invalid_argument(
220 "minimization secant curvature seed requires the BFGS method");
221 const int d = static_cast<int>(x_init.size());
222 MinimizationResult result;
223 result.x_final = x_init;
224
228 session.gp_setup = [&](InputParameters& params, AtomsConfiguration& ac) {
229 params.gp_sigma2.value = 1e-8;
230 params.jitter_sigma2.value = config.jitter_sigma2;
231 params.sigma2.value = 1e-8;
232 params.magnSigma2.value = 0.0;
233 params.constSigma2.value = 0.0;
234 params.prior_mu.value = 0;
235 params.prior_nu.value = 20;
236 params.prior_s2.value = 1;
237 params.optimization_alg.value = "SCG_opt";
238 params.max_iter.value = config.gp_train_iter;
239 params.tolerance_func.value = 1e-4;
240 params.tolerance_sol.value = 1e-4;
241 params.report_level.value = config.verbose ? 1 : 0;
242 params.fps_history.value = config.fps_history;
243 ac = atoms_config;
244 };
245 session.initialise();
246 session.gp.setHssvdBackend(config.use_hssvd_solver);
249
250 bool warm_kernel_pending = false;
251 if (seed != nullptr || gp_state != nullptr) {
252 io::TrainedGpState warm;
253 if (gp_state != nullptr) warm = *gp_state;
254 if (seed != nullptr && seed->R.rows() > 0)
256 if (warm.observations.R.rows() > 0 || warm.has_pair_kernel) {
257 result.prior_observations = io::seedSession(
258 session, warm, /*require_identity=*/true, x_init.size());
259 warm_kernel_pending = warm.has_pair_kernel;
260 }
261 }
262
263 int hyperparameter_refits = 0;
264 bool has_fitted_gp = false;
265 bool has_conditioned_gp = false;
266 Eigen::Index seeded_row_count = 0;
267 SecantHessian secant(config.secant.method);
268 std::size_t checked_secant_pairs = 0;
269 std::size_t prior_secant_pairs = 0;
270 SecantNewtonFactor newton_factor;
271 std::size_t newton_factor_pairs = 0;
272 // A secant Newton step moves no atom farther than one trusted step.
273 double seed_bound = std::numeric_limits<double>::infinity();
274 if (config.max_move > 0.0 && std::isfinite(config.max_move))
275 seed_bound = config.max_move;
276 if (config.trust_radius > 0.0 && std::isfinite(config.trust_radius))
277 seed_bound = std::min(seed_bound, config.trust_radius);
278
279 // Every attempted evaluation counts toward max_oracle_calls, finite or
280 // not, and no evaluation is started once the budget is spent.
281 const auto budget_allows = [&]() {
282 return config.max_oracle_calls <= 0 ||
283 result.oracle_calls < config.max_oracle_calls;
284 };
285 const auto measure = [&](const Eigen::VectorXd& x) {
286 ++result.oracle_calls;
287 auto measured = oracle(x);
288 // A non-finite energy is still an observation. The secant then drops
289 // its reference energy instead of keeping the previous geometry's.
290 if (config.secant.enabled() && measured.second.size() == x.size() &&
291 measured.second.allFinite()) {
292 const bool had_reference =
293 secant.referencePosition().size() == x.size();
294 const bool moved =
295 had_reference &&
296 !(secant.referencePosition().array() == x.array()).all();
297 const bool updated =
298 secant.observe(x, measured.second, measured.first);
299 if (moved && !updated) ++result.secant_update_failures;
300 result.secant_pairs = static_cast<int>(secant.pairs());
301 }
302 return measured;
303 };
304 const auto allow_call = [&](policy::OracleRole role,
305 const Eigen::VectorXd& x, double variance,
306 double distance, bool within_trust,
307 bool surrogate_stop) {
308 if (!budget_allows()) return false;
309 if (policy == nullptr) return true;
310 policy::SearchState state;
311 state.kind = policy::SearchKind::Minimize;
312 state.role = role;
313 state.iteration = result.total_iterations;
314 state.oracle_calls = result.oracle_calls;
315 state.training_size = static_cast<int>(session.training_obs.R.rows());
316 state.hyperparameter_refits = hyperparameter_refits;
317 state.posterior_variance = variance;
318 state.trust_radius = config.trust_radius;
319 state.distance_to_training = distance;
320 state.within_trust = within_trust;
321 state.surrogate_proposes_stop = surrogate_stop;
322 state.engine_would_call_oracle = true;
323 state.positions = x.data();
324 state.n_coords = d;
325 state.gp = has_conditioned_gp ? &session.gp : nullptr;
326 return policy::consensusShouldCallOracle(*policy, state);
327 };
328 double best_observed_energy = std::numeric_limits<double>::infinity();
329 Eigen::VectorXd best_observed_x = x_init;
330 Eigen::VectorXd best_observed_g = Eigen::VectorXd::Zero(d);
331 bool has_best_observed = false;
332 result.e_final = std::numeric_limits<double>::quiet_NaN();
333 result.g_final =
334 Eigen::VectorXd::Constant(d, std::numeric_limits<double>::quiet_NaN());
335
336 // Exact, unmerged oracle evaluations. ActiveLearningSession merges
337 // near-coincident rows (within 1e-6) by averaging targets, so convergence
338 // checks and returned results must never read from session.training_obs.
339 struct RawOracleObservation {
340 Eigen::VectorXd x;
341 double energy = 0.0;
342 Eigen::VectorXd gradient;
343 };
344 std::vector<RawOracleObservation> raw_oracle_obs;
345 const auto find_exact_raw_observation =
346 [&](const Eigen::VectorXd& x) -> const RawOracleObservation* {
347 for (auto it = raw_oracle_obs.rbegin(); it != raw_oracle_obs.rend();
348 ++it) {
349 if (it->x.size() == x.size() &&
350 (it->x.array() == x.array()).all()) {
351 return &(*it);
352 }
353 }
354 return nullptr;
355 };
356
357 bool pending_retain = false;
358 const auto admit = [&](const Eigen::VectorXd& x, double energy,
359 const Eigen::VectorXd& gradient, bool engine_would) {
360 if (!engine_would) return false;
361 bool add = true;
362 if (policy != nullptr) {
363 policy::CandidatePoint candidate;
364 candidate.positions = x;
365 candidate.energy = energy;
366 candidate.gradient = gradient;
367 const std::vector<Eigen::VectorXd> current_rows =
368 trainingPositions(session.training_obs);
369 const std::vector<int> indices =
370 policy::consensusSelectTrainingPoints(*policy, {candidate},
371 current_rows);
372 add = policy::admitsFirstCandidate(indices);
373 }
374 if (add) {
375 session.appendObservation(x, energy, gradient);
376 }
377 if (config.max_training_points > 0 &&
378 session.training_obs.R.rows() > config.max_training_points) {
379 const Eigen::VectorXd anchor =
380 has_best_observed ? best_observed_x : x;
381 RecentAnchoredSizeCapPolicy cap(config.max_training_points, anchor);
382 session.retainTrainingRowsForPolicy(cap);
383 }
384 pending_retain = true;
385 return add &&
386 neb::detail::findPositionRow(session.training_obs, x) >= 0;
387 };
388 // retain_training_rows runs once after the initial design and once per
389 // outer step, after that step's admission.
390 const auto retain_admitted = [&]() {
391 if (policy != nullptr && pending_retain) {
392 session.retainTrainingRowsForPolicy(*policy);
393 }
394 pending_retain = false;
395 };
396
397 const auto record_initial_observation =
398 [&](const Eigen::VectorXd& x, double energy,
399 const Eigen::VectorXd& gradient) {
400 if (!std::isfinite(energy) || gradient.size() != d ||
401 !gradient.allFinite()) {
402 return false;
403 }
404 raw_oracle_obs.push_back({x, energy, gradient});
405 result.energy_trajectory.push_back(energy);
406 if (!has_best_observed || energy < best_observed_energy) {
407 best_observed_energy = energy;
408 best_observed_x = x;
409 best_observed_g = gradient;
410 has_best_observed = true;
411 result.x_final = x;
412 result.e_final = energy;
413 result.g_final = gradient;
414 }
415 return admit(x, energy, gradient, true);
416 };
417
418 for (Eigen::Index row = 0; row < session.training_obs.R.rows(); ++row) {
419 const Eigen::VectorXd seeded_x =
420 session.training_obs.R.row(row).transpose();
421 const double seeded_energy = session.training_obs.E(row, 0);
422 const Eigen::VectorXd seeded_gradient =
423 session.training_obs.G.row(row).transpose();
424 if (seeded_x.size() != d)
425 throw std::runtime_error(
426 "gp-state.npz coordinates do not match this search (" +
427 std::to_string(seeded_x.size()) + " columns, this search has " +
428 std::to_string(d) + ")");
429 if (!seeded_x.allFinite() || !std::isfinite(seeded_energy) ||
430 seeded_gradient.size() != d || !seeded_gradient.allFinite())
431 throw std::runtime_error("gp-state.npz seed row " +
432 std::to_string(row) + " is non-finite");
433 raw_oracle_obs.push_back({seeded_x, seeded_energy, seeded_gradient});
434 }
435
436 // Step 1: Initial oracle evaluations. A seed row at x_init is prior
437 // data and is not an oracle call.
438 if (const RawOracleObservation* seeded =
439 find_exact_raw_observation(x_init)) {
440 result.energy_trajectory.push_back(seeded->energy);
441 best_observed_energy = seeded->energy;
442 best_observed_x = seeded->x;
443 best_observed_g = seeded->gradient;
444 has_best_observed = true;
445 result.x_final = seeded->x;
446 result.e_final = seeded->energy;
447 result.g_final = seeded->gradient;
448 } else if (allow_call(policy::OracleRole::InitialDesign, x_init,
449 std::numeric_limits<double>::quiet_NaN(),
450 std::numeric_limits<double>::infinity(), false,
451 false)) {
452 auto [e_init, g_init] = measure(x_init);
453 record_initial_observation(x_init, e_init, g_init);
454 }
455 if (!has_best_observed && result.oracle_calls == 0) return result;
456
457 // Optional initial perturbations for GP diversity
458 std::mt19937 rng(config.seed);
459 std::uniform_real_distribution<double> dist(-0.5, 0.5);
460 for (int k = 0; k < config.n_initial_perturb; ++k) {
461 if (!budget_allows()) break;
462 Eigen::VectorXd x_p = x_init;
463 for (int i = 0; i < d; ++i) {
464 x_p(i) += dist(rng) * config.perturb_scale;
465 }
466 if (!allow_call(policy::OracleRole::InitialDesign, x_p,
467 std::numeric_limits<double>::quiet_NaN(),
468 std::numeric_limits<double>::infinity(), false,
469 false)) {
470 continue;
471 }
472 auto [e_p, g_p] = measure(x_p);
473 record_initial_observation(x_p, e_p, g_p);
474 }
475 retain_admitted();
476
477 if (!has_best_observed) {
478 return result;
479 }
480
481 if (best_observed_g.size() == d && best_observed_g.allFinite() &&
482 best_observed_g.norm() < config.conv_tol) {
483 result.converged = true;
484 result.x_final = best_observed_x;
485 result.e_final = best_observed_energy;
486 result.g_final = best_observed_g;
487 return result;
488 }
489
490 if (session.training_obs.R.rows() == 0) {
491 return result;
492 }
493
494 Eigen::VectorXd x_curr = best_observed_x;
495 RgminStep gp_stepper;
496
497 // Step 2: Main outer loop
498 for (int outer = 0; outer < config.max_iter; ++outer) {
499 if (!budget_allows()) break;
500 if (session.training_obs.R.rows() == 0) break;
501
502 if (warm_kernel_pending) {
503 session.applySeededModel();
504 if (session.gp.hasBeenOptimized()) {
506 seeded_row_count = session.training_obs.R.rows();
507 has_fitted_gp = true;
508 has_conditioned_gp = true;
509 gp_stepper.forget();
510 }
511 warm_kernel_pending = false;
512 }
513
514 session.publishPolicyProgress(
515 result.total_iterations, result.oracle_calls, hyperparameter_refits,
516 static_cast<int>(session.training_obs.R.rows()));
517 // The GP is conditioned on the residual of the latest secant
518 // quadratic, which moves with every accepted pair.
519 bool secant_prior_moved = false;
520 if (config.secant.quadratic_prior_mean && secant.available() &&
521 prior_secant_pairs != secant.pairs()) {
522 // referenceEnergy() throws when the accepted geometry had a
523 // non-finite oracle energy. Refuse that pair here, with the
524 // reason, instead of aborting inside the accessor.
525 if (!secant.hasReferenceEnergy())
526 throw std::runtime_error(
527 "secant quadratic prior mean requires a finite oracle "
528 "energy at the reference geometry");
530 secant.referencePosition(), secant.referenceGradient(),
531 secant.hessian(), secant.referenceEnergy());
532 prior_secant_pairs = secant.pairs();
533 secant_prior_moved = true;
534 }
535 if (!session.hyperparametersNeedRefit() && secant_prior_moved) {
537 has_conditioned_gp = true;
538 gp_stepper.forget();
539 }
540 if (session.hyperparametersNeedRefit()) {
542 const Eigen::Index current_rows = session.training_obs.R.rows();
543 const bool reinit_seeds =
544 !has_fitted_gp ||
545 (seeded_row_count < 3 && current_rows > seeded_row_count);
546 if (session.refitGP(reinit_seeds)) {
547 ++hyperparameter_refits;
548 has_fitted_gp = true;
549 if (reinit_seeds) {
550 seeded_row_count = std::min<Eigen::Index>(
551 3, std::max(seeded_row_count, current_rows));
552 }
553 }
554 has_conditioned_gp = true;
555 gp_stepper.forget();
556 }
557
558 // Compare the posterior Hessian action with the latest true-gradient
559 // secant. A disagreement buys exactly one forward force probe along
560 // that visited direction; the next outer conditions the posterior on
561 // the resulting row.
562 if (config.secant.consistency_check && secant.available() &&
563 secant.pairs() > checked_secant_pairs) {
564 const Eigen::VectorXd direction =
565 secant.lastDirection().normalized();
566 Coord at_reference(1, d);
567 at_reference.row(0) = secant.referencePosition().transpose();
568 Eigen::VectorXd posterior_action;
570 at_reference, direction, posterior_action)) {
571 throw std::runtime_error(
572 "secant consistency requested but GP Hessian action "
573 "is unavailable");
574 }
575 const SecantConsistency consistency = secant.consistency(
576 posterior_action, config.secant.consistency_relative_tolerance);
577 if (!consistency.available)
578 throw std::runtime_error(
579 "secant consistency requested but comparison is invalid");
580 result.last_secant_relative_error = consistency.relative_error;
581 checked_secant_pairs = secant.pairs();
582 if (!consistency.trusted &&
583 result.finite_difference_hvp_calls == 0 && budget_allows()) {
584 if (!(config.secant.finite_difference_step > 0.0) ||
585 !std::isfinite(config.secant.finite_difference_step))
586 throw std::invalid_argument(
587 "secant finite-difference step must be positive");
588 const Eigen::VectorXd probe =
589 secant.referencePosition() +
591 consistency.direction;
592 const double variance = energyVarianceAt(session.gp, probe);
593 const double probe_distance =
594 minTrainingAtomDistance(session.training_obs, probe);
595 const bool probe_within_trust =
596 config.trust_radius > 0.0 &&
597 std::isfinite(config.trust_radius) &&
598 probe_distance < config.trust_radius;
599 if (allow_call(policy::OracleRole::TrustExit, probe, variance,
600 probe_distance, probe_within_trust, false)) {
601 auto [probe_energy, probe_gradient] = measure(probe);
602 if (!std::isfinite(probe_energy) ||
603 probe_gradient.size() != d ||
604 !probe_gradient.allFinite())
605 break;
606 raw_oracle_obs.push_back(
607 {probe, probe_energy, probe_gradient});
608 admit(probe, probe_energy, probe_gradient, true);
609 retain_admitted();
610 result.energy_trajectory.push_back(probe_energy);
611 ++result.finite_difference_hvp_calls;
612 gp_stepper.forget();
613 if (probe_energy <= best_observed_energy) {
614 best_observed_energy = probe_energy;
615 best_observed_x = probe;
616 best_observed_g = probe_gradient;
617 x_curr = probe;
618 } else {
619 x_curr = best_observed_x;
620 }
621 if (probe_gradient.norm() < config.conv_tol) {
622 result.converged = true;
623 result.x_final = probe;
624 result.e_final = probe_energy;
625 result.g_final = probe_gradient;
626 break;
627 }
628 continue;
629 }
630 }
631 }
632
633 const double trust_boundary_tol =
634 1e-9 * std::max(1.0, config.trust_radius);
635 const int max_inner_steps = config.max_inner_steps;
636 Eigen::VectorXd x_inner = x_curr;
637 bool surrogate_converged = false;
638 bool left_trust_region = false;
639 bool inner_stopped = false;
640 bool retried_overshoot = false;
641 double exit_min_dist = 0.0;
642
643 for (int inner = 0; inner < max_inner_steps; ++inner) {
644 Observation query;
645 query.R.resize(1, d);
646 query.R.row(0) = x_inner.transpose();
647 session.gp.calculatePotentialDispatched(query);
648 const double e_curr = query.E(0, 0);
649 Eigen::VectorXd g_pred = query.G.row(0).transpose();
650 double g_norm = g_pred.norm();
651 if (!std::isfinite(e_curr) || !g_pred.allFinite() ||
652 !std::isfinite(g_norm)) {
653 inner_stopped = true;
654 break;
655 }
656
657 // The gradient the step is taken from belongs to the surrogate
658 // unless a held exact evaluation replaces it below. The stepper
659 // drops its curvature history when this changes between steps.
660 RgminStep::Objective step_objective =
662
663 // The surrogate gradient only proposes a stop. Convergence,
664 // x_final, e_final and g_final must come from an actual oracle
665 // evaluation at that exact point; a measured gradient above the
666 // tolerance becomes the step direction.
667 if (g_norm < config.conv_tol) {
668 if (const RawOracleObservation* held =
669 find_exact_raw_observation(x_inner)) {
670 if (held->gradient.norm() < config.conv_tol) {
671 result.converged = true;
672 result.x_final = held->x;
673 result.e_final = held->energy;
674 result.g_final = held->gradient;
675 inner_stopped = true;
676 break;
677 }
678 gp_stepper.forget();
679 step_objective = RgminStep::Objective::Exact;
680 g_pred = held->gradient;
681 g_norm = g_pred.norm();
682 } else {
683 surrogate_converged = true;
684 break;
685 }
686 }
687
688 Eigen::VectorXd x_trial = x_inner;
689 bool secant_step = false;
690 if (config.secant.seed_curvature && secant.available()) {
691 if (newton_factor_pairs != secant.pairs()) {
692 newton_factor = secantNewtonFactor(secant);
693 newton_factor_pairs = secant.pairs();
694 }
695 SecantSeedStatus status = newton_factor.status;
696 Eigen::VectorXd seed_step;
698 seed_step = newton_factor.factor.solve(-g_pred);
699 const double reach = maxAtomDisplacement(seed_step);
700 if (!seed_step.allFinite() || !std::isfinite(reach))
702 else if (reach > seed_bound)
703 seed_step *= seed_bound / reach;
704 }
706 x_trial += seed_step;
707 secant_step = true;
708 ++result.secant_curvature_seed_steps;
709 } else {
710 if (config.verbose &&
711 (result.secant_curvature_seed_refusals == 0 ||
712 status != result.last_secant_seed_status))
713 std::cout << "[secant-seed] minimization keeps the "
714 "surrogate step: "
715 << secantSeedStatusName(status) << "\n";
716 ++result.secant_curvature_seed_refusals;
717 }
718 result.last_secant_seed_status = status;
719 }
720
721 // An empty curvature memory makes the step steepest descent.
722 // Clipping an unscaled -g to max_move lands on the default
723 // trust radius, so the first inner step leaves the region and
724 // spends the oracle call max_inner_steps was meant to withhold.
725 // The same cap the rgmin stepper uses on an empty memory keeps
726 // that step inside.
727 double empty_scale = 1.0;
728 const double g_atom_max = maxAtomDisplacement(g_pred);
729 const double probe_cap =
730 session.training_obs.R.rows() == 1
731 ? (0.5 * config.max_move)
732 : (0.25 * std::min(config.max_move, config.trust_radius));
733 if (probe_cap > 0.0 && std::isfinite(probe_cap) &&
734 g_atom_max > probe_cap) {
735 empty_scale = probe_cap / g_atom_max;
736 }
737 if (!secant_step && !gp_stepper.step(x_trial, g_pred, 0.0,
738 empty_scale, step_objective)) {
739 inner_stopped = true;
740 break;
741 }
742 Eigen::VectorXd step = x_trial - x_inner;
743 if (!step.allFinite()) {
744 inner_stopped = true;
745 break;
746 }
747 clipAtomMaxMove(step, config.max_move);
748 Eigen::VectorXd x_next = x_inner + step;
749 ++result.total_iterations;
750
751 const bool trust_active =
752 config.trust_radius > 0.0 && std::isfinite(config.trust_radius);
753 bool crossed_trust_boundary = false;
754 if (trust_active) {
755 // The step is trusted only while every point of it lies in
756 // some training row's ball. The end point alone is not enough:
757 // a step can leave one ball, cross the gap and end inside
758 // another. The first uncovered point is where it exits.
759 const double covered = detail::trustCoveredFraction(
760 session.training_obs.R, x_inner, x_next,
761 config.trust_radius);
762 const double raw_min_dist =
763 minTrainingAtomDistance(session.training_obs, x_next);
764 const bool leaves_union = covered < 1.0;
765 crossed_trust_boundary =
766 leaves_union ||
767 raw_min_dist >= config.trust_radius - trust_boundary_tol;
768 if (leaves_union) {
769 x_next = x_inner + covered * (x_next - x_inner);
770 step = x_next - x_inner;
771 }
772 }
773
774 if (crossed_trust_boundary) {
775 if (!retried_overshoot && std::isfinite(e_curr) &&
776 g_pred.dot(step) < 0.0) {
777 Observation probe;
778 probe.R.resize(1, d);
779 probe.R.row(0) = x_next.transpose();
780 session.gp.calculatePotentialDispatched(probe);
781 const double e_next = probe.E(0, 0);
782 const Eigen::VectorXd g_next = probe.G.row(0).transpose();
783 if (std::isfinite(e_next) && g_next.allFinite() &&
784 e_next > e_curr && g_next.dot(step) > 0.0) {
785 gp_stepper.forget();
786 const double dg0 = -g_pred.dot(step);
787 const double dg1 = g_next.dot(step);
788 const double alpha =
789 std::clamp(dg0 / (dg0 + dg1), 0.1, 0.5);
790 x_inner += alpha * step;
791 retried_overshoot = true;
792 continue;
793 }
794 }
795 x_inner = x_next;
796 left_trust_region = true;
797 exit_min_dist =
798 minTrainingAtomDistance(session.training_obs, x_inner);
799 break;
800 }
801
802 x_inner = x_next;
803 if (step.norm() <= 1e-14) {
804 break;
805 }
806 }
807
808 if (result.converged || inner_stopped) {
809 break;
810 }
811
812 if (surrogate_converged) {
813 if (find_exact_raw_observation(x_inner) != nullptr) {
814 break;
815 }
816 const double min_dist =
817 minTrainingAtomDistance(session.training_obs, x_inner);
818 const double variance =
819 policy == nullptr ? std::numeric_limits<double>::quiet_NaN()
820 : energyVarianceAt(session.gp, x_inner);
821 if (!allow_call(policy::OracleRole::ConvergenceCheck, x_inner,
822 variance, min_dist, true, true)) {
823 break;
824 }
825 auto [e_true, g_true] = measure(x_inner);
826 if (!std::isfinite(e_true) || g_true.size() != d ||
827 !g_true.allFinite()) {
828 break;
829 }
830 raw_oracle_obs.push_back({x_inner, e_true, g_true});
831 admit(x_inner, e_true, g_true, true);
832 retain_admitted();
833 result.energy_trajectory.push_back(e_true);
834 if (e_true <= best_observed_energy) {
835 best_observed_energy = e_true;
836 x_curr = x_inner;
837 best_observed_x = x_inner;
838 best_observed_g = g_true;
839 } else {
840 gp_stepper.forget();
841 x_curr = best_observed_x;
842 }
843 if (g_true.norm() < config.conv_tol) {
844 result.converged = true;
845 result.x_final = x_inner;
846 result.e_final = e_true;
847 result.g_final = g_true;
848 break;
849 }
850 continue;
851 }
852
853 if (!left_trust_region) {
854 if (neb::detail::positionsCoincide(x_inner, x_curr)) {
855 break;
856 }
857 x_curr = x_inner;
858 continue;
859 }
860
861 if (const RawOracleObservation* held =
862 find_exact_raw_observation(x_inner)) {
863 // A measured row that retention or the size cap removed is
864 // admitted again from its record. It is not a new oracle result,
865 // so the trajectory and the best observation do not change.
866 if (neb::detail::findPositionRow(session.training_obs, x_inner) >=
867 0) {
868 break;
869 }
870 const RawOracleObservation record = *held;
871 admit(record.x, record.energy, record.gradient, true);
872 retain_admitted();
873 if (neb::detail::findPositionRow(session.training_obs, x_inner) <
874 0) {
875 break;
876 }
877 if (record.energy <= best_observed_energy) {
878 x_curr = x_inner;
879 } else {
880 gp_stepper.forget();
881 x_curr = best_observed_x;
882 }
883 continue;
884 }
885 if (!budget_allows()) break;
886 const double variance = policy == nullptr
887 ? std::numeric_limits<double>::quiet_NaN()
888 : energyVarianceAt(session.gp, x_inner);
889 if (!allow_call(policy::OracleRole::TrustExit, x_inner, variance,
890 exit_min_dist, false, false)) {
891 break;
892 }
893
894 auto [e_new, g_new] = measure(x_inner);
895 if (!std::isfinite(e_new) || g_new.size() != d || !g_new.allFinite()) {
896 break;
897 }
898 raw_oracle_obs.push_back({x_inner, e_new, g_new});
899 admit(x_inner, e_new, g_new, true);
900 retain_admitted();
901 result.energy_trajectory.push_back(e_new);
902
903 if (e_new <= best_observed_energy) {
904 best_observed_energy = e_new;
905 x_curr = x_inner;
906 best_observed_x = x_inner;
907 best_observed_g = g_new;
908 } else {
909 gp_stepper.forget();
910 x_curr = best_observed_x;
911 }
912
913 if (g_new.norm() < config.conv_tol) {
914 result.converged = true;
915 result.x_final = x_inner;
916 result.e_final = e_new;
917 result.g_final = g_new;
918 break;
919 }
920 }
921
922 if (!result.converged) {
923 result.x_final = best_observed_x;
924 result.e_final = best_observed_energy;
925 result.g_final = best_observed_g;
926 }
927
928 return result;
929}
@ x
Definition Enums.h:28
void setObjectiveStationaritySkipAuto(bool use) noexcept
void setOptimizationSubsetHistory(int rows) noexcept
void setSecantQuadraticPrior(const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, const Eigen::MatrixXd &hessian, double reference_energy)
bool calculateMeanHessianVectorDispatched(const Coord &R, const Eigen::VectorXd &direction, Eigen::VectorXd &hessian_vector)
void setHssvdBackend(bool enabled) noexcept
void calculatePotentialDispatched(Observation &image1)
Definition Predict.cpp:982
TrainedGpState observationState(const Observation &observations)
A state that carries observations and no pair kernel.
Definition GpState.cpp:556
int seedSession(neb::ActiveLearningSession &session, const TrainedGpState &state, bool require_identity, Eigen::Index expected_cols)
Definition GpState.cpp:638
SecantNewtonFactor secantNewtonFactor(const SecantHessian &secant)
double maxAtomDisplacement(const Eigen::VectorXd &delta)
const char * secantSeedStatusName(SecantSeedStatus status) noexcept
bool admitsFirstCandidate(const std::vector< int > &indices)
bool consensusShouldCallOracle(const TrainingPolicy &policy, const SearchState &state)
std::vector< int > consensusSelectTrainingPoints(const TrainingPolicy &policy, const std::vector< CandidatePoint > &candidates, const std::vector< Eigen::VectorXd > &current_set)
double variance(const Weights &w, const Matrix &covariance)
FieldMatrixd Coord
Definition Macros.h:35
Stores configurations of all atoms in the system.
Definition Structures.h:832
Structure of the input parameters. All input parameters are pairs of string names and values.
Definition Structures.h:370
KeyValuePair< double > prior_s2
Definition Structures.h:650
KeyValuePair< int > max_iter
Definition Structures.h:674
KeyValuePair< std::string > optimization_alg
Definition Structures.h:614
KeyValuePair< int > fps_history
Definition Structures.h:665
KeyValuePair< double > prior_nu
Definition Structures.h:649
KeyValuePair< int > report_level
Definition Structures.h:673
KeyValuePair< double > jitter_sigma2
Definition Structures.h:613
KeyValuePair< double > constSigma2
Definition Structures.h:618
KeyValuePair< double > tolerance_func
Definition Structures.h:675
KeyValuePair< double > tolerance_sol
Definition Structures.h:676
KeyValuePair< double > prior_mu
Definition Structures.h:648
KeyValuePair< double > sigma2
Definition Structures.h:616
KeyValuePair< double > magnSigma2
Definition Structures.h:617
KeyValuePair< double > gp_sigma2
Definition Structures.h:612
FieldMatrixd E
Observation observations
Definition GpState.h:22
void noteExternalHyperparameterFit() noexcept
Definition Session.h:1325
std::function< void(gpr::InputParameters &, gpr::AtomsConfiguration &)> gp_setup
Definition Session.h:1141
bool hyperparametersNeedRefit() const noexcept
Definition Session.h:3292
gpr::Observation training_obs
Definition Session.h:246
bool retainTrainingRowsForPolicy(const policy::TrainingPolicy &policy)
Definition Session.h:1777
bool refitGP(bool reinit_seeds)
Definition Session.h:3111
void publishPolicyProgress(int iteration, int oracle_calls, int refits, int training_size) noexcept
Definition Session.h:3281
gpr::GaussianProcessRegression gp
Definition Session.h:471
void appendObservation(const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient, ObservationRetention retention=ObservationRetention::RecordAcquisition, optim::SecantAccounting secant_accounting=optim::SecantAccounting::Count)
Definition Session.h:1574
SecantHessianConfig secant
True-force secant curvature features. Every member is off by default.
Definition GPMinimizer.h:82
bool enabled() const noexcept

◆ gp_minimize() [2/2]

MinimizationResult gpr::optim::gp_minimize ( OracleFn oracle,
const Eigen::VectorXd & x_init,
const AtomsConfiguration & atoms_config,
const MinimizationConfig & config = {} )

GP-accelerated geometry minimization.

Parameters
oracleEnergy/gradient evaluation function
x_initInitial positions (flat 3*N_atoms vector)
atoms_configAtomic configuration for GP kernel
configMinimization parameters
Returns
MinimizationResult

The four-argument overload is the original symbol. A defaulted fifth parameter would change that mangled name, so the policy is a separate overload and is not defaulted.

Definition at line 931 of file GPMinimizer.cpp.

934{
935 return gp_minimize(std::move(oracle), x_init, atoms_config, config,
936 nullptr);
937}
MinimizationResult gp_minimize(OracleFn oracle, const Eigen::VectorXd &x_init, const AtomsConfiguration &atoms_config, const MinimizationConfig &config, const policy::TrainingPolicy *policy, const Observation *seed, const io::TrainedGpState *gp_state)
GP-accelerated geometry minimization with a training policy.

◆ gradientChangeAgreement()

double gpr::optim::gradientChangeAgreement ( const Eigen::Ref< const Eigen::RowVectorXd > & measured_change,
const Eigen::Ref< const Eigen::RowVectorXd > & predicted_change )
inline

Agreement of measured and predicted gradient changes, in [-1, 1]. Dimer steps can increase the force norm, so model validity is independent of a monotone force merit. Zero changes carry no radius information.

Definition at line 41 of file ConsistentForceModel.h.

44{
45 if (measured_change.size() == 0 ||
46 measured_change.size() != predicted_change.size() ||
47 !measured_change.allFinite() || !predicted_change.allFinite()) {
48 throw std::invalid_argument(
49 "gradient change agreement requires matching finite gradients");
50 }
51 const double scale = std::max(measured_change.cwiseAbs().maxCoeff(),
52 predicted_change.cwiseAbs().maxCoeff());
53 if (scale == 0.0) return 0.5;
54 // Scale before taking norms to avoid overflow or underflow in squares.
55 const Eigen::RowVectorXd measured = measured_change / scale;
56 const Eigen::RowVectorXd predicted = predicted_change / scale;
57 const double error = (measured - predicted).norm();
58 const double magnitude = std::max(measured.norm(), predicted.norm());
59 return std::clamp(1.0 - error / magnitude, -1.0, 1.0);
60}

◆ gradientChangeVariance()

Eigen::RowVectorXd gpr::optim::gradientChangeVariance ( const Eigen::MatrixXd & covariance,
Eigen::Index dimension,
double likelihood_variance )
inline

Marginal variances of a noisy gradient difference at two query points. Joint channels contain two energies followed by two values per gradient coordinate. Correlated latent errors cancel through the cross covariance; independent likelihood errors contribute twice their physical variance.

Definition at line 66 of file ConsistentForceModel.h.

69{
70 if (dimension <= 0 || covariance.rows() != 2 * (dimension + 1) ||
71 covariance.cols() != covariance.rows() || !covariance.allFinite() ||
72 !std::isfinite(likelihood_variance) || likelihood_variance < 0.0)
73 throw std::invalid_argument("invalid gradient-change covariance");
74 Eigen::RowVectorXd variance(dimension);
75 const double eps = std::numeric_limits<double>::epsilon();
76 const double gamma3 = 3.0 * eps / (1.0 - 3.0 * eps);
77 for (Eigen::Index k = 0; k < dimension; ++k) {
78 const Eigen::Index a = 2 + 2 * k, b = a + 1;
79 const double diagonal = covariance(a, a) + covariance(b, b);
80 const double cross = covariance(a, b) + covariance(b, a);
81 const double latent = diagonal - cross;
82 const double magnitude =
83 std::abs(covariance(a, a)) + std::abs(covariance(b, b)) +
84 std::abs(covariance(a, b)) + std::abs(covariance(b, a));
85 if (latent < -gamma3 * magnitude)
86 throw std::domain_error("negative gradient-change variance");
87 variance(k) = std::max(0.0, latent) + 2.0 * likelihood_variance;
88 }
89 return variance;
90}

◆ hessianColumnsFromDirections()

Eigen::MatrixXd gpr::optim::hessianColumnsFromDirections ( const Eigen::VectorXd & center,
const Eigen::VectorXd & center_gradient,
const Eigen::MatrixXd & directions,
const Eigen::MatrixXd & actions )
inline

Cartesian Hessian columns of a stencil measured along orthonormal directions, with actions.col(k) the central difference of the gradient along direction k. A complete set is the measurement itself. Otherwise the removed rigid columns are the identities of transportMeasuredHessianActions, about the measured center gradient: rotations when more than translations were removed. The columns along the directions stay the measured ones, so the vibrational block of the result is the measured block exactly, and only full-Cartesian consumers read the rigid columns: the spectrum and its resolution are taken on the measured block (analyzeStencilIndex). Coordinate-axis directions leave frozen coordinates, which carry no curvature: the result is the measured moving block with zero frozen rows and columns. Empty when the inputs cannot form that matrix.

Definition at line 334 of file PhysicalCurvatureBasis.h.

337{
338 const Eigen::Index dimension = center.size();
339 if (dimension == 0 || directions.rows() != dimension ||
340 directions.cols() == 0 || directions.cols() > dimension ||
341 actions.rows() != dimension || actions.cols() != directions.cols() ||
342 !actions.allFinite())
343 return {};
344 if (directions.cols() == dimension) {
345 if (directions.isIdentity(0.0)) return actions;
346 return actions * directions.transpose();
347 }
348 if (directionsAreCoordinateAxes(directions))
349 return directions * (directions.transpose() * actions) *
350 directions.transpose();
351 if (center_gradient.size() != dimension) return {};
353 center.transpose(), center_gradient.transpose(), directions, actions,
354 Eigen::MatrixXd::Identity(dimension, dimension),
355 dimension - directions.cols() > 3);
356}
bool directionsAreCoordinateAxes(const Eigen::MatrixXd &directions)
Eigen::MatrixXd transportMeasuredHessianActions(const gpr::Coord &positions, const gpr::Coord &gradient, const Eigen::MatrixXd &measured_basis, const Eigen::MatrixXd &measured_action, const Eigen::MatrixXd &physical, bool include_rotations=true)

◆ insideEndpointBall()

bool gpr::optim::insideEndpointBall ( double to_this,
double to_other,
double ball )
inlinenoexcept

Definition at line 1060 of file EndpointConnectivity.h.

1062{
1063 return std::isfinite(to_this) && std::isfinite(to_other) &&
1064 std::isfinite(ball) && ball > 0.0 && to_this < to_other &&
1065 to_this < ball;
1066}

◆ ircStencilDirections()

Eigen::MatrixXd gpr::optim::ircStencilDirections ( const Eigen::VectorXd & center,
const Eigen::VectorXd & masses,
const Eigen::MatrixXd * held_directions,
VibrationalStencil mode = VibrationalStencil::Full )
inline

Directions of the IRC's Hessian stencils at a free geometry: the held validation directions when they fit, so rows measured at the saddle are read again, and otherwise the requested stencil. Full is every coordinate. Vibrational is vibrationalStencilDirections.

Definition at line 531 of file EndpointConnectivity.h.

535{
536 if (held_directions != nullptr &&
537 held_directions->rows() == center.size() &&
538 held_directions->cols() > 0 &&
539 held_directions->cols() <= center.size() &&
540 held_directions->allFinite())
541 return *held_directions;
542 return stencilDirectionsForMode(mode, center, masses, /*periodic=*/false,
543 /*anchored=*/false);
544}
Eigen::MatrixXd stencilDirectionsForMode(VibrationalStencil mode, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, bool periodic, bool anchored, const Eigen::VectorXi *frozen=nullptr)

◆ labelledEndpointsResolve()

bool gpr::optim::labelledEndpointsResolve ( double separation,
double harmonic_reactant,
double harmonic_product )
inlinenoexcept

The harmonic radius is the largest distance the force tolerance still counts as one minimum. The endpoints are two centres when the labelled separation exceeds both radii. A smaller separation is one minimum counted twice: the field is ball=na, and the radius used for a resolved pair is unchanged.

Definition at line 1048 of file EndpointConnectivity.h.

1051{
1052 if (!(separation > 0.0) || !std::isfinite(separation)) return false;
1053 const auto outside = [&](double harmonic) {
1054 if (!std::isfinite(harmonic) || !(harmonic > 0.0)) return true;
1055 return separation > harmonic;
1056 };
1057 return outside(harmonic_reactant) && outside(harmonic_product);
1058}

◆ labelledRmsd()

double gpr::optim::labelledRmsd ( const Eigen::VectorXd & reference,
const Eigen::VectorXd & mobile,
const std::vector< int > & atomic_numbers )
inline

Rigidly aligned RMSD in the file's atom order. Rigid motion is removed and atoms are not re-paired. The bond graph is indexed the same way, so a label swap that keeps the permutation-aware distance at zero stays a real separation here.

Definition at line 310 of file EndpointConnectivity.h.

313{
314 const Eigen::Index n = reference.size();
315 const int n_atoms = static_cast<int>(atomic_numbers.size());
316 if (n_atoms * 3 != static_cast<int>(n))
317 return std::numeric_limits<double>::quiet_NaN();
318 return aux::rigidAlignedRmsd(reference, mobile);
319}
double rigidAlignedRmsd(const Eigen::VectorXd &reference, const Eigen::VectorXd &mobile)

◆ libraryMinimizationLayout()

MinimizationLayoutStamp gpr::optim::libraryMinimizationLayout ( )
nodiscard

What libgpridge was built with. Defined in the library, not inline.

Definition at line 197 of file GPMinimizer.cpp.

198{
200}
MinimizationLayoutStamp compiledMinimizationLayout() noexcept

◆ massesFromAtomicNumbers()

Eigen::VectorXd gpr::optim::massesFromAtomicNumbers ( const std::vector< int > & numbers)
inline

Definition at line 298 of file EndpointConnectivity.h.

299{
300 Eigen::VectorXd masses(static_cast<Eigen::Index>(numbers.size()));
301 for (std::size_t i = 0; i < numbers.size(); ++i)
302 masses(static_cast<Eigen::Index>(i)) = atomicMassAmu(numbers[i]);
303 return masses;
304}
double atomicMassAmu(int atomic_number) noexcept

◆ massWeightedMeasuredCurvatureResolution()

double gpr::optim::massWeightedMeasuredCurvatureResolution ( const gpr::Coord & positions,
const gpr::AtomsConfiguration & configuration,
const Eigen::MatrixXd & basis,
const Eigen::MatrixXd & actions )
inline

Empirical resolution in the mass-weighted physical coordinates of the refinement, in eV/(A^2 amu). The Cartesian measured map is B (B^T A) B^T with zero action outside the measured space. Its congruence on D Q is C^T (B^T A) C, where D = M^(-1/2), Q is the physical basis of the refinement and C = B^T D Q. Raw actions retain the measured asymmetry.

Definition at line 16 of file MeasuredCurvatureMetric.h.

19{
20 const Eigen::Index dimension = positions.cols();
21 if (basis.rows() != dimension || basis.cols() == 0 ||
22 actions.rows() != dimension || actions.cols() != basis.cols() ||
23 !basis.allFinite() || !actions.allFinite())
24 return std::numeric_limits<double>::infinity();
25 Eigen::MatrixXd cartesian_directions =
26 massWeightedPhysicalCurvatureBasis(positions, configuration);
27 const Eigen::Index physical_dimension = cartesian_directions.cols();
28 if (physical_dimension == 0) return std::numeric_limits<double>::infinity();
29 const Eigen::VectorXd masses =
30 movingAtomicMasses(configuration, dimension / 3);
31 for (Eigen::Index atom = 0; atom < masses.size(); ++atom)
32 cartesian_directions.middleRows(3 * atom, 3) /= std::sqrt(masses(atom));
33 const Eigen::MatrixXd coefficients =
34 basis.transpose() * cartesian_directions;
35 const Eigen::MatrixXd projected =
36 coefficients.transpose() * (basis.transpose() * actions) * coefficients;
37 return analyzeMeasuredCurvature(Eigen::MatrixXd::Identity(
38 physical_dimension, physical_dimension),
39 projected)
41}
Eigen::MatrixXd massWeightedPhysicalCurvatureBasis(const gpr::Coord &positions, const gpr::AtomsConfiguration &config, bool exclude_rotations=true)
Eigen::VectorXd movingAtomicMasses(const gpr::AtomsConfiguration &config, Eigen::Index n_moving)

◆ massWeightedPhysicalCurvatureBasis()

Eigen::MatrixXd gpr::optim::massWeightedPhysicalCurvatureBasis ( const gpr::Coord & positions,
const gpr::AtomsConfiguration & config,
bool exclude_rotations = true )
inline

Orthonormal physical step directions in mass-weighted coordinates. Cartesian directions in ker(R^T M) map through sqrt(M) to the complement of the mass-weighted rigid motions. Frozen anchors retain every moving coordinate; periodic cells exclude translations and retain rotations.

Definition at line 207 of file PhysicalCurvatureBasis.h.

210{
211 const Eigen::Index dimension = positions.cols();
212 if ((positions.rows() != 1 && !(positions.rows() == 0 && dimension == 0)) ||
213 dimension % 3 != 0 || !positions.allFinite())
214 throw std::invalid_argument(
215 "finite packed Cartesian geometry required");
216 const Eigen::VectorXd masses = movingAtomicMasses(config, dimension / 3);
217 if (dimension == 0) return Eigen::MatrixXd(0, 0);
218 Eigen::MatrixXd basis = physicalCurvatureBasis(
219 positions, config, exclude_rotations, RigidMotionMetric::MassWeighted);
220 if (basis.cols() == 0) return Eigen::MatrixXd(dimension, 0);
221 if (basis.cols() == dimension)
222 return Eigen::MatrixXd::Identity(dimension, dimension);
223 for (Eigen::Index atom = 0; atom < masses.size(); ++atom)
224 basis.middleRows(3 * atom, 3) *= std::sqrt(masses(atom));
225 const Eigen::HouseholderQR<Eigen::MatrixXd> qr(basis);
226 return qr.householderQ() *
227 Eigen::MatrixXd::Identity(dimension, basis.cols());
228}
Eigen::MatrixXd physicalCurvatureBasis(const gpr::Coord &positions, const gpr::AtomsConfiguration &config, bool exclude_rotations=true, RigidMotionMetric metric=RigidMotionMetric::MassWeighted)

◆ massWeightedRigidMotions()

Eigen::MatrixXd gpr::optim::massWeightedRigidMotions ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses )
inline

Mass-weighted translations and rotations as columns, about the centre of mass.

Definition at line 36 of file StencilIndex.h.

38{
39 const Eigen::Index n = masses.size();
40 Eigen::Vector3d centre = Eigen::Vector3d::Zero();
41 for (Eigen::Index i = 0; i < n; ++i)
42 centre += masses(i) * positions.segment<3>(3 * i);
43 centre /= masses.sum();
44 Eigen::MatrixXd basis = Eigen::MatrixXd::Zero(3 * n, 6);
45 for (Eigen::Index i = 0; i < n; ++i) {
46 const double root = std::sqrt(masses(i));
47 const Eigen::Vector3d r = positions.segment<3>(3 * i) - centre;
48 for (int k = 0; k < 3; ++k) {
49 basis(3 * i + k, k) = root;
50 Eigen::Vector3d axis = Eigen::Vector3d::Zero();
51 axis(k) = 1.0;
52 basis.block<3, 1>(3 * i, 3 + k) = root * r.cross(axis);
53 }
54 }
55 return basis;
56}

◆ maxAtomDisplacement()

double gpr::optim::detail::maxAtomDisplacement ( const Eigen::VectorXd & delta)
inline

Largest displacement of one atom, with a short coordinate tail counted as a final group.

Definition at line 36 of file TrustRegionSegment.h.

37{
38 const Eigen::Index d = delta.size();
39 const Eigen::Index n_atoms = d / 3;
40 double max_disp = 0.0;
41 for (Eigen::Index a = 0; a < n_atoms; ++a) {
42 max_disp = std::max(max_disp, delta.segment<3>(3 * a).norm());
43 }
44 if (3 * n_atoms < d) {
45 max_disp = std::max(max_disp, delta.tail(d - 3 * n_atoms).norm());
46 }
47 return max_disp;
48}

◆ measuredCubicColumnContribution()

double gpr::optim::measuredCubicColumnContribution ( double overlap,
double mode_quadratic,
double axis_quadratic )
inline

Contribution of a measured axis u to the cubic along v. The measured gradient second difference supplies T[u,u]; overlap is u dot v. Summing over orthonormal measured axes retains every symmetric cubic coefficient with a repeated axis index. Coefficients with three distinct unmeasured index combinations are zero in this model; two axes determine a full bivariate cubic. Reversing u preserves this contribution, while reversing v reverses its sign.

Definition at line 29 of file StationaryCurvature.h.

32{
33 return overlap * overlap *
34 (3.0 * mode_quadratic - 2.0 * overlap * axis_quadratic);
35}

◆ measuredCurvaturePriorScale()

double gpr::optim::measuredCurvaturePriorScale ( const Eigen::MatrixXd & prior,
const Eigen::MatrixXd & basis,
const Eigen::MatrixXd & action )
inline

Positive least-squares scale of a prior's measured Hessian actions. Orthogonal changes of physical basis and curvature units preserve this fit. A zero or oppositely correlated prior supplies no positive scale. Leave-one-direction-out prediction must improve on the unscaled prior. This calibrates probe proposals; measured actions determine the index.

Definition at line 232 of file MeasuredCurvatureSpectrum.h.

235{
236 if (prior.rows() == 0 || prior.rows() != prior.cols() ||
237 basis.rows() != prior.rows() || basis.cols() < 2 ||
238 action.rows() != basis.rows() || action.cols() != basis.cols() ||
239 !prior.allFinite() || !basis.allFinite() || !action.allFinite())
240 return 1.0;
241 Eigen::MatrixXd predicted = (0.5 * prior + 0.5 * prior.transpose()) * basis;
242 if (!predicted.allFinite()) return 1.0;
243 const double magnitude =
244 std::max(predicted.cwiseAbs().maxCoeff(), action.cwiseAbs().maxCoeff());
245 if (!(magnitude > 0.0)) return 1.0;
246 predicted /= magnitude;
247 const Eigen::MatrixXd measured = action / magnitude;
248 const double denominator = predicted.squaredNorm();
249 if (!(denominator > 0.0)) return 1.0;
250 const double scale = predicted.cwiseProduct(measured).sum() / denominator;
251 if (!(scale > 0.0) || !std::isfinite(scale) ||
252 (scale > 1.0 && prior.cwiseAbs().maxCoeff() >
253 std::numeric_limits<double>::max() / scale))
254 return 1.0;
255 const Eigen::VectorXd column_norms =
256 predicted.colwise().squaredNorm().transpose();
257 const Eigen::VectorXd column_products =
258 predicted.cwiseProduct(measured).colwise().sum().transpose();
259 const double numerator = column_products.sum();
260 double predicted_error = 0.0;
261 const double roundoff =
262 64.0 * std::numeric_limits<double>::epsilon() * predicted.size();
263 for (Eigen::Index j = 0; j < basis.cols(); ++j) {
264 const double remaining = denominator - column_norms(j);
265 if (!(remaining > roundoff * denominator)) return 1.0;
266 const double held_out_scale =
267 (numerator - column_products(j)) / remaining;
268 if (!(held_out_scale > 0.0) || !std::isfinite(held_out_scale))
269 return 1.0;
270 predicted_error +=
271 (measured.col(j) - held_out_scale * predicted.col(j)).squaredNorm();
272 }
273 const double unscaled_error = (measured - predicted).squaredNorm();
274 if (!(predicted_error + roundoff * (predicted_error + unscaled_error) <
275 unscaled_error))
276 return 1.0;
277 return scale;
278}

◆ measuredForceChangeCalibrated()

bool gpr::optim::measuredForceChangeCalibrated ( double error,
double variance,
double force_scale )
inlinenoexcept

Statistical agreement certifies a force-change model only when the error also resolves the physical force scale on which the step acts. Likelihood regularization cannot enlarge that scale as a root is approached.

Definition at line 95 of file ConsistentForceModel.h.

97{
98 return std::isfinite(error) && error >= 0.0 && std::isfinite(variance) &&
99 variance >= 0.0 && std::isfinite(force_scale) && force_scale > 0.0 &&
100 error <= std::min(std::sqrt(variance), force_scale);
101}

◆ measuredIndexZeroHessian()

Eigen::MatrixXd gpr::optim::measuredIndexZeroHessian ( const Eigen::MatrixXd & basis,
const Eigen::MatrixXd & physical,
const Eigen::MatrixXd & action )
inline

Cartesian Hessian of a complete measured expansion that resolves no negative curvature. The basis must span the supplied physical space, so the excluded rigid directions carry zero curvature. Empty when the expansion is incomplete or invalid, or when its lowest curvature lies below minus its own resolution.

Definition at line 190 of file MeasuredCurvatureSpectrum.h.

193{
194 if (physical.cols() == 0 || basis.rows() != physical.rows() ||
195 basis.cols() != physical.cols())
196 return {};
197 const MeasuredCurvatureSpectrum spectrum =
198 analyzeMeasuredCurvature(basis, action);
199 if (!spectrum.valid || !(spectrum.curvatures(0) >= -spectrum.resolution))
200 return {};
201 return spectrum.modes * spectrum.curvatures.asDiagonal() *
202 spectrum.modes.transpose();
203}

◆ measuredModeExpansion()

Eigen::VectorXd gpr::optim::measuredModeExpansion ( const Eigen::MatrixXd & basis,
const Eigen::MatrixXd & physical,
const Eigen::VectorXd & action )
inline

Independent part of a measured lowest-mode action at a fixed midpoint. Two projection passes keep stiff directions out of the retained basis; a residual within projection roundoff supplies no new measured column.

Definition at line 208 of file MeasuredCurvatureSpectrum.h.

211{
212 if (basis.rows() != physical.rows() || action.size() != basis.rows() ||
213 basis.cols() >= physical.cols() || !basis.allFinite() ||
214 !physical.allFinite() || !action.allFinite())
215 return {};
216 Eigen::VectorXd direction = physical * (physical.transpose() * action);
217 const double scale = direction.stableNorm();
218 for (int pass = 0; pass < 2; ++pass)
219 direction -= basis * (basis.transpose() * direction).eval();
220 const double norm = direction.stableNorm();
221 const double roundoff =
222 64.0 * std::numeric_limits<double>::epsilon() * basis.rows() * scale;
223 if (!(norm > roundoff) || !std::isfinite(norm)) return {};
224 return direction / norm;
225}

◆ measuredTrialTrustAgreement()

double gpr::optim::measuredTrialTrustAgreement ( double rho,
bool calibrated,
double displacement,
double radius,
double rho_grow )
inline

Radius agreement for a measured gradient-change model. A discrepancy resolved beyond its predictive spread uses rho. An unresolved discrepancy does not justify contraction; a trial at the boundary enlarges the domain in which the search can resolve a change. Final force acceptance is separate.

Definition at line 108 of file ConsistentForceModel.h.

111{
112 if (!calibrated) return rho;
113 if (radius > 0.0 && displacement >= 0.9 * radius) return 1.0;
114 return std::max(rho, rho_grow);
115}

◆ measuredUpperBound()

double gpr::optim::measuredUpperBound ( const SmoothedCurvatureSpectrum & spectrum,
const std::vector< MeasuredHessianColumn > & columns,
Eigen::Index k )
inline

Bauer-Fike verdict on a mode: with u in the measured span, H u is a combination of measured columns, the Rayleigh quotient theta and the residual ||H u - theta u|| are measured, and some eigenvalue of H lies within the residual of theta (Bauer 1960, Parlett 1998 Thm 4.5.1). The upper bound theta + ||r|| below zero certifies a negative eigenvalue from measurements alone. Returns the bound; +infinity when the mode leaves the measured span beyond floating-point resolution.

Definition at line 853 of file SmoothedCurvatureSpectrum.h.

856{
857 const double infinity = std::numeric_limits<double>::infinity();
858 if (!spectrum.valid || k < 0 || k >= spectrum.modes.cols() ||
859 columns.empty())
860 return infinity;
861 const Eigen::VectorXd u = spectrum.modes.col(k);
862 const Eigen::Index m = static_cast<Eigen::Index>(columns.size());
863 Eigen::VectorXd weights(m);
864 Eigen::VectorXd in_span = Eigen::VectorXd::Zero(u.size());
865 Eigen::VectorXd action = Eigen::VectorXd::Zero(u.size());
866 for (Eigen::Index j = 0; j < m; ++j) {
867 weights(j) = columns[static_cast<std::size_t>(j)].direction.dot(u);
868 in_span += weights(j) * columns[static_cast<std::size_t>(j)].direction;
869 action += weights(j) * columns[static_cast<std::size_t>(j)].action;
870 }
871 const double outside = (u - in_span).norm();
872 if (!(outside <= std::sqrt(std::numeric_limits<double>::epsilon() *
873 static_cast<double>(u.size()))))
874 return infinity;
875 const double theta = u.dot(action);
876 const double residual = (action - theta * u).norm();
877 return theta + residual;
878}

◆ minimizationLayoutMismatch()

std::string gpr::optim::minimizationLayoutMismatch ( const MinimizationLayoutStamp & driver,
const MinimizationLayoutStamp & library )
inlinenodiscard

Definition at line 145 of file GPMinimizer.h.

148{
149 if (driver.version == library.version &&
150 driver.config_bytes == library.config_bytes &&
151 driver.result_bytes == library.result_bytes)
152 return {};
153 return "libgpridge minimization layout mismatch: this program was "
154 "built against layout " +
155 std::to_string(driver.version) + " (MinimizationConfig " +
156 std::to_string(driver.config_bytes) + " bytes, MinimizationResult " +
157 std::to_string(driver.result_bytes) +
158 " bytes) but the loaded library reports layout " +
159 std::to_string(library.version) + " (MinimizationConfig " +
160 std::to_string(library.config_bytes) +
161 " bytes, MinimizationResult " +
162 std::to_string(library.result_bytes) +
163 " bytes). Rebuild the caller against this libgpridge.";
164}

◆ movingAtomicMasses()

Eigen::VectorXd gpr::optim::movingAtomicMasses ( const gpr::AtomsConfiguration & config,
Eigen::Index n_moving )
inline

Positive finite masses in the packed moving-coordinate order. With a mobility mask, input masses describe the full frame and moving entries are selected in mask order. Empty input masses select unit masses.

Definition at line 24 of file PhysicalCurvatureBasis.h.

26{
27 if (n_moving < 0)
28 throw std::invalid_argument("moving atom count must be nonnegative");
29 const Eigen::Index atoms = config.is_frozen.size();
30 if (atoms > 0) {
31 if (config.is_frozen.rows() != 1)
32 throw std::invalid_argument("mobility flags require one row");
33 Eigen::Index moving = 0;
34 for (Eigen::Index atom = 0; atom < atoms; ++atom) {
35 const auto flag = config.is_frozen(0, atom);
36 if (flag != MOVING_ATOM && flag != FROZEN_ATOM)
37 throw std::invalid_argument("invalid atom mobility flag");
38 if (flag == MOVING_ATOM) ++moving;
39 }
40 if (moving != n_moving)
41 throw std::invalid_argument(
42 "mobility flags and moving coordinates differ");
43 }
44 const auto& supplied = config.atomic_masses;
45 if (supplied.size() == 0) return Eigen::VectorXd::Ones(n_moving);
46 if (supplied.size() != (atoms > 0 ? atoms : n_moving) ||
47 !supplied.allFinite() || (supplied.array() <= 0.0).any())
48 throw std::invalid_argument(
49 "physical curvature requires one positive finite mass per input "
50 "atom");
51 if (atoms == 0) return supplied;
52 Eigen::VectorXd masses(n_moving);
53 Eigen::Index moving = 0;
54 for (Eigen::Index atom = 0; atom < atoms; ++atom)
55 if (config.is_frozen(0, atom) == MOVING_ATOM)
56 masses(moving++) = supplied(atom);
57 return masses;
58}
@ FROZEN_ATOM
Definition Enums.h:36
@ MOVING_ATOM
Definition Enums.h:35
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
Definition Structures.h:834
Eigen::VectorXd atomic_masses
Per-atom input masses; empty selects unit masses.
Definition Structures.h:838

◆ nextMeasuredCurvatureDirection()

Eigen::VectorXd gpr::optim::nextMeasuredCurvatureDirection ( const Eigen::MatrixXd & basis,
const Eigen::MatrixXd & action,
const MeasuredCurvatureSpectrum & spectrum,
const Eigen::MatrixXd & physical,
const Eigen::MatrixXd & preferred,
const Eigen::MatrixXd & prior = Eigen::MatrixXd{} )
inline

Expand toward the second mode of a measured completion when a prior is available, then the second Ritz residual. An invariant subspace needs an independent seed; the physical basis guarantees complement coverage.

Definition at line 436 of file MeasuredCurvatureSpectrum.h.

440 {})
441{
442 if (!spectrum.valid || spectrum.modes.cols() < 2 ||
443 basis.rows() != action.rows() || basis.cols() != action.cols() ||
444 physical.rows() != basis.rows() || physical.cols() <= basis.cols())
445 return {};
446 const double independence =
447 std::sqrt(std::numeric_limits<double>::epsilon() * basis.rows());
448 const auto orthogonal = [&](Eigen::VectorXd direction) -> Eigen::VectorXd {
449 if (direction.size() != basis.rows() || !direction.allFinite())
450 return {};
451 direction = (physical * (physical.transpose() * direction)).eval();
452 for (int pass = 0; pass < 2; ++pass)
453 direction -= basis * (basis.transpose() * direction).eval();
454 return direction;
455 };
456 if (prior.rows() == basis.rows() && prior.cols() == basis.rows()) {
457 const Eigen::MatrixXd completed = completeMeasuredHessian(
458 physical.transpose() * prior * physical,
459 physical.transpose() * basis, physical.transpose() * action);
460 if (completed.rows() == physical.cols()) {
461 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> proposed(
462 completed);
463 if (proposed.info() == Eigen::Success) {
464 for (Eigen::Index mode = 1;
465 mode < proposed.eigenvectors().cols(); ++mode) {
466 const Eigen::VectorXd direction = orthogonal(
467 physical * proposed.eigenvectors().col(mode));
468 if (direction.size() && direction.norm() > independence)
469 return direction.normalized();
470 }
471 }
472 }
473 }
474 Eigen::VectorXd residual =
475 orthogonal(action * (basis.transpose() * spectrum.modes.col(1)));
476 const double residual_floor =
477 std::max(spectrum.resolution, independence * action.norm());
478 if (residual.size() && residual.norm() > residual_floor)
479 return residual.normalized();
480 for (const auto* candidates: {&preferred, &physical}) {
481 if (candidates->rows() != basis.rows()) continue;
482 for (Eigen::Index column = 0; column < candidates->cols(); ++column) {
483 Eigen::VectorXd direction = orthogonal(candidates->col(column));
484 if (direction.size() && direction.norm() > independence)
485 return direction.normalized();
486 }
487 }
488 return {};
489}
Eigen::MatrixXd completeMeasuredHessian(const Eigen::MatrixXd &prior, const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action)

◆ nextMeasuredCurvatureDirections()

Eigen::MatrixXd gpr::optim::nextMeasuredCurvatureDirections ( const Eigen::MatrixXd & basis,
const Eigen::MatrixXd & action,
const MeasuredCurvatureSpectrum & spectrum,
const Eigen::MatrixXd & physical,
const Eigen::MatrixXd & preferred,
Eigen::Index count,
const Eigen::MatrixXd & prior = Eigen::MatrixXd{} )
inline

Expand by independent physical directions that can share an oracle batch. The leading column follows the completed prior or second Ritz residual. Further residuals and physical seeds fill its orthogonal complement.

Definition at line 494 of file MeasuredCurvatureSpectrum.h.

498 {})
499{
500 const Eigen::VectorXd first = nextMeasuredCurvatureDirection(
501 basis, action, spectrum, physical, preferred, prior);
502 if (count <= 0 || first.size() != basis.rows()) return {};
503 count = std::min(count, physical.cols() - basis.cols());
504 Eigen::MatrixXd directions(basis.rows(), count);
505 directions.col(0) = first;
506 Eigen::Index filled = 1;
507 const double independence =
508 std::sqrt(std::numeric_limits<double>::epsilon() * basis.rows());
509 const auto append = [&](Eigen::VectorXd candidate) {
510 if (filled == count || candidate.size() != basis.rows() ||
511 !candidate.allFinite())
512 return;
513 candidate = (physical * (physical.transpose() * candidate)).eval();
514 for (int pass = 0; pass < 2; ++pass) {
515 candidate -= basis * (basis.transpose() * candidate).eval();
516 candidate -=
517 directions.leftCols(filled) *
518 (directions.leftCols(filled).transpose() * candidate).eval();
519 }
520 const double norm = candidate.norm();
521 if (norm > independence) directions.col(filled++) = candidate / norm;
522 };
523 for (Eigen::Index mode = 0; mode < spectrum.modes.cols() && filled < count;
524 ++mode) {
525 const Eigen::VectorXd residual =
526 action * (basis.transpose() * spectrum.modes.col(mode));
527 // Numerical remnants of an invariant Ritz vector must not outrank
528 // an independent physical seed.
529 const double floor =
530 std::max(spectrum.resolution, independence * action.norm());
531 Eigen::VectorXd orthogonal =
532 physical * (physical.transpose() * residual);
533 orthogonal -= basis * (basis.transpose() * orthogonal).eval();
534 if (orthogonal.norm() > floor) append(residual);
535 }
536 for (const auto* candidates: {&preferred, &physical}) {
537 if (candidates->rows() != basis.rows()) continue;
538 for (Eigen::Index column = 0;
539 column < candidates->cols() && filled < count; ++column)
540 append(candidates->col(column));
541 }
542 return directions.leftCols(filled);
543}
Eigen::VectorXd nextMeasuredCurvatureDirection(const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action, const MeasuredCurvatureSpectrum &spectrum, const Eigen::MatrixXd &physical, const Eigen::MatrixXd &preferred, const Eigen::MatrixXd &prior=Eigen::MatrixXd{})

◆ nextSmoothedCurvatureDirection()

Eigen::VectorXd gpr::optim::nextSmoothedCurvatureDirection ( const SmoothedCurvatureSpectrum & spectrum,
Eigen::Index k )
inline

The direction to measure for the k-th eigenvalue: the part of its posterior mode outside the measured span, normalized. Empty when the mode lies in the span to floating-point resolution, in which case no further column changes the eigenvalue's first-order posterior.

Definition at line 831 of file SmoothedCurvatureSpectrum.h.

833{
834 if (!spectrum.valid || k < 0 || k >= spectrum.modes.cols()) return {};
835 Eigen::VectorXd residual = spectrum.modes.col(k);
836 const auto& span = spectrum.measured_span;
837 for (int pass = 0; pass < 2; ++pass)
838 residual -= span * (span.transpose() * residual).eval();
839 const double norm = residual.norm();
840 if (!(norm > std::sqrt(std::numeric_limits<double>::epsilon() *
841 static_cast<double>(residual.size()))))
842 return {};
843 return residual / norm;
844}

◆ nextStencilAction()

StencilAction gpr::optim::nextStencilAction ( bool higher_order,
bool weak_higher_order,
bool weak_uncertified,
int & continuations,
int maximum_continuations )
inline

Definition at line 758 of file StencilIndex.h.

763{
764 if (higher_order) return StencilAction::LeaveHigherOrder;
765 if (weak_higher_order) return StencilAction::AcceptUncertified;
766 if (!weak_uncertified) return StencilAction::Accept;
767 if (continuations < maximum_continuations) {
768 ++continuations;
770 }
772}

◆ parseVibrationalStencil()

bool gpr::optim::parseVibrationalStencil ( std::string_view text,
VibrationalStencil & out )
inlinenoexcept

Definition at line 28 of file VibrationalStencil.h.

30{
31 if (text == "full") {
33 return true;
34 }
35 if (text == "vibrational") {
37 return true;
38 }
39 return false;
40}

◆ permutationAwareRmsd()

double gpr::optim::permutationAwareRmsd ( const Eigen::VectorXd & reference,
const Eigen::VectorXd & mobile_in,
const std::vector< int > & atomic_numbers )
inline

RMSD after a rigid alignment and a re-pairing that only exchanges atoms of the same element. The length is the root mean square over atoms. One start pairs by sorted distances, which a rotation does not change; the other pairs in the lab frame. Both are repeated until the assignment stops improving, and the smaller RMSD is kept. The certificate distance does not use this: a degenerate rearrangement would then sit on top of itself.

Definition at line 328 of file EndpointConnectivity.h.

331{
332 const Eigen::Index n = reference.size();
333 const int n_atoms = static_cast<int>(atomic_numbers.size());
334 if (n == 0 || n != mobile_in.size() || n % 3 != 0 ||
335 n_atoms * 3 != static_cast<int>(n) || !reference.allFinite() ||
336 !mobile_in.allFinite())
337 return std::numeric_limits<double>::quiet_NaN();
338 std::vector<int> elements = atomic_numbers;
339 std::sort(elements.begin(), elements.end());
340 elements.erase(std::unique(elements.begin(), elements.end()),
341 elements.end());
342 const auto signature = [&](const Eigen::VectorXd& geometry, int atom) {
343 std::vector<double> out;
344 const Eigen::Vector3d here = geometry.segment<3>(3 * atom);
345 for (const int element: elements) {
346 std::vector<double> distances;
347 for (int other = 0; other < n_atoms; ++other) {
348 if (other == atom) continue;
349 if (atomic_numbers[static_cast<std::size_t>(other)] != element)
350 continue;
351 distances.push_back(
352 (geometry.segment<3>(3 * other) - here).norm());
353 }
354 std::sort(distances.begin(), distances.end());
355 out.insert(out.end(), distances.begin(), distances.end());
356 }
357 return out;
358 };
359 const auto assign = [&](const Eigen::VectorXd& from, auto cost_of) {
360 double diameter2 = 0.0;
361 for (int i = 0; i < n_atoms; ++i)
362 for (int j = 0; j < n_atoms; ++j)
363 diameter2 = std::max(diameter2, (reference.segment<3>(3 * i) -
364 from.segment<3>(3 * j))
365 .squaredNorm());
366 const double blocked =
367 diameter2 * static_cast<double>(n_atoms) + diameter2;
368 Eigen::MatrixXd cost(n_atoms, n_atoms);
369 for (int i = 0; i < n_atoms; ++i) {
370 for (int j = 0; j < n_atoms; ++j) {
371 if (atomic_numbers[static_cast<std::size_t>(i)] !=
372 atomic_numbers[static_cast<std::size_t>(j)]) {
373 cost(i, j) = blocked;
374 continue;
375 }
376 cost(i, j) = cost_of(i, j);
377 }
378 }
380 };
381 const auto permute = [&](const Eigen::VectorXd& source,
382 const std::vector<int>& assignment) {
383 Eigen::VectorXd out(n);
384 for (int i = 0; i < n_atoms; ++i)
385 out.segment<3>(3 * i) =
386 source.segment<3>(3 * assignment[static_cast<std::size_t>(i)]);
387 return out;
388 };
389 std::vector<std::vector<double>> reference_signature(n_atoms);
390 std::vector<std::vector<double>> mobile_signature(n_atoms);
391 for (int atom = 0; atom < n_atoms; ++atom) {
392 reference_signature[static_cast<std::size_t>(atom)] =
393 signature(reference, atom);
394 mobile_signature[static_cast<std::size_t>(atom)] =
395 signature(mobile_in, atom);
396 }
397 const auto by_signature = assign(mobile_in, [&](int i, int j) {
398 const auto& left = reference_signature[static_cast<std::size_t>(i)];
399 const auto& right = mobile_signature[static_cast<std::size_t>(j)];
400 double sum = 0.0;
401 for (std::size_t k = 0; k < left.size() && k < right.size(); ++k) {
402 const double gap = left[k] - right[k];
403 sum += gap * gap;
404 }
405 return sum;
406 });
407 if (by_signature.size() != static_cast<std::size_t>(n_atoms))
408 return std::numeric_limits<double>::quiet_NaN();
409 const auto iterated = [&](Eigen::VectorXd mobile) {
410 double best = std::numeric_limits<double>::infinity();
411 for (int round = 0; round < n_atoms; ++round) {
412 const Eigen::VectorXd aligned =
413 aux::kabschAlignProductToReactant(reference, mobile);
414 if (aligned.size() != n || !aligned.allFinite())
415 return std::numeric_limits<double>::quiet_NaN();
416 const double rmsd = (aligned - reference).norm() /
417 std::sqrt(static_cast<double>(n_atoms));
418 if (!(rmsd < best)) break;
419 best = rmsd;
420 const auto assignment = assign(aligned, [&](int i, int j) {
421 return (reference.segment<3>(3 * i) - aligned.segment<3>(3 * j))
422 .squaredNorm();
423 });
424 if (assignment.size() != static_cast<std::size_t>(n_atoms))
425 return std::numeric_limits<double>::quiet_NaN();
426 bool identity = true;
427 for (int i = 0; i < n_atoms; ++i)
428 identity =
429 identity && assignment[static_cast<std::size_t>(i)] == i;
430 if (identity) break;
431 mobile = permute(mobile, assignment);
432 }
433 return best;
434 };
435 const double from_geometry = iterated(mobile_in);
436 const double from_signature = iterated(permute(mobile_in, by_signature));
437 if (!std::isfinite(from_geometry)) return from_signature;
438 if (!std::isfinite(from_signature)) return from_geometry;
439 return std::min(from_geometry, from_signature);
440}
Eigen::VectorXd kabschAlignProductToReactant(const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions)
std::vector< int > solve_assignment_indices(const Eigen::MatrixXd &cost_matrix)
Like solve_assignment_problem, but returns the optimal assignment.
Definition Distance.cpp:193

◆ physicalCurvatureBasis()

Eigen::MatrixXd gpr::optim::physicalCurvatureBasis ( const gpr::Coord & positions,
const gpr::AtomsConfiguration & config,
bool exclude_rotations = true,
RigidMotionMetric metric = RigidMotionMetric::MassWeighted )
inline

Cartesian orthonormal basis for the physical vibrational subspace. If R spans rigid displacements and M contains atomic masses, the Cartesian image of the mass-weighted vibrational space is ker(R^T M). Congruence on this space preserves the index without changing Cartesian probe lengths.

Definition at line 102 of file PhysicalCurvatureBasis.h.

106{
107 const Eigen::Index dimension = positions.cols();
108 const bool anchored = config.atoms_froz_active.positions.size() > 0 ||
109 config.atoms_froz_inactive.positions.size() > 0 ||
110 (config.is_frozen.array() == FROZEN_ATOM).any();
111 if (anchored || positions.rows() != 1 || dimension % 3 != 0)
112 return Eigen::MatrixXd::Identity(dimension, dimension);
113 return detail::rigidMotionComplement(
114 positions,
116 : Eigen::VectorXd(),
117 exclude_rotations && !gpr::geometry::cellIsMicLattice(config.cell));
118}
bool cellIsMicLattice(const double cell[9]) noexcept
Nonzero ASE 3x3 that is not the 25 A vacuum convention.
Definition MinImage.h:56
AtomsPositionAndType atoms_froz_inactive
Info on inactive frozen atoms.
Definition Structures.h:843
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841

◆ planForceStopStencil() [1/2]

ForceStopStencilPlan gpr::optim::planForceStopStencil ( ForceStopStencilQuery query)
inline

Definition at line 1191 of file StencilIndex.h.

1192{
1194 // The family is recorded so a caller can show the plan does not
1195 // branch on it. It is not a switch.
1196 (void)query.family;
1197 if (!query.requested) {
1198 plan.measure_stencil = false;
1199 plan.refine_soft_modes = false;
1200 return plan;
1201 }
1202 if (query.columns_already_measured) {
1203 plan.measure_stencil = false;
1204 plan.reuse_columns = true;
1205 plan.refine_soft_modes = !query.following_stage_owns_certificate;
1206 plan.hand_off = query.following_stage_owns_certificate;
1207 return plan;
1208 }
1210 // The band stencil on a following saddle is not the certificate.
1211 // It ends with unresolved modes and is measured again after the
1212 // saddle moves. Hand the climbing image over and measure once,
1213 // at the final saddle.
1214 plan.measure_stencil = false;
1215 plan.refine_soft_modes = false;
1216 plan.defer_certificate = true;
1217 plan.hand_off = true;
1218 }
1219 return plan;
1220}
bool columns_already_measured
Finite-difference columns at this geometry were already paid for.

◆ planForceStopStencil() [2/2]

ForceStopStencilPlan gpr::optim::planForceStopStencil ( SaddleSearchFamily family,
bool requested )
inline

Definition at line 1222 of file StencilIndex.h.

1224{
1226 query.family = family;
1227 query.requested = requested;
1228 return planForceStopStencil(query);
1229}
ForceStopStencilPlan planForceStopStencil(ForceStopStencilQuery query)

◆ probePairRitz()

template<typename Gradients>
PairRitzProbe gpr::optim::probePairRitz ( const Eigen::VectorXd & center,
const Eigen::VectorXd & masses,
const Eigen::VectorXd & u,
const Eigen::VectorXd & v,
double step,
const Gradients & gradients )

Definition at line 911 of file StencilIndex.h.

915{
917 const Eigen::Index dof = center.size();
918 if (masses.size() * 3 != dof || u.size() != dof || v.size() != dof ||
919 !(step > 0.0))
920 return out;
921 Eigen::VectorXd root(dof);
922 for (Eigen::Index k = 0; k < dof; ++k)
923 root(k) = std::sqrt(masses(k / 3));
924 Eigen::VectorXd yu = root.cwiseProduct(u);
925 if (!(yu.norm() > 0.0)) return out;
926 yu.normalize();
927 Eigen::VectorXd yv = root.cwiseProduct(v);
928 yv -= yu.dot(yv) * yu;
929 if (!(yv.norm() > 1e-8)) return out;
930 yv.normalize();
931 out.points.resize(dof, 4);
932 const Eigen::VectorXd xu = yu.cwiseQuotient(root);
933 const Eigen::VectorXd xv = yv.cwiseQuotient(root);
934 out.points.col(0) = center + step * xu;
935 out.points.col(1) = center - step * xu;
936 out.points.col(2) = center + step * xv;
937 out.points.col(3) = center - step * xv;
938 out.gradients = gradients(out.points);
939 if (out.gradients.rows() != 4 || out.gradients.cols() != dof ||
940 !out.gradients.allFinite())
941 return out;
942 // H_mw y = M^{-1/2} H x, H x by the central difference.
943 const Eigen::VectorXd hu =
944 ((out.gradients.row(0) - out.gradients.row(1)).transpose() /
945 (2.0 * step))
946 .cwiseQuotient(root);
947 const Eigen::VectorXd hv =
948 ((out.gradients.row(2) - out.gradients.row(3)).transpose() /
949 (2.0 * step))
950 .cwiseQuotient(root);
951 const double a = yu.dot(hu);
952 const double d = yv.dot(hv);
953 const double b_uv = yu.dot(hv);
954 const double b_vu = yv.dot(hu);
955 const double b = 0.5 * (b_uv + b_vu);
956 const double radius = std::hypot(0.5 * (a - d), b);
957 out.lower = 0.5 * (a + d) - radius;
958 out.upper = 0.5 * (a + d) + radius;
959 out.asymmetry = 0.5 * std::abs(b_uv - b_vu);
960 out.measured = std::isfinite(out.lower) && std::isfinite(out.upper);
961 return out;
962}

◆ probeSubspaceRitz()

template<typename Gradients>
SubspaceRitzProbe gpr::optim::probeSubspaceRitz ( const Eigen::VectorXd & center,
const Eigen::VectorXd & masses,
const Eigen::MatrixXd & candidates,
double step,
const Gradients & gradients )

Definition at line 989 of file StencilIndex.h.

993{
995 const Eigen::Index dof = center.size();
996 if (masses.size() * 3 != dof || candidates.rows() != dof ||
997 candidates.cols() == 0 || !(step > 0.0) || !candidates.allFinite())
998 return out;
999 Eigen::VectorXd root(dof);
1000 for (Eigen::Index k = 0; k < dof; ++k)
1001 root(k) = std::sqrt(masses(k / 3));
1002 std::vector<Eigen::VectorXd> kept;
1003 for (Eigen::Index c = 0; c < candidates.cols(); ++c) {
1004 Eigen::VectorXd y = root.cwiseProduct(candidates.col(c));
1005 if (!(y.norm() > 0.0)) continue;
1006 y.normalize();
1007 for (int pass = 0; pass < 2; ++pass)
1008 for (const auto& k: kept)
1009 y -= k.dot(y) * k;
1010 if (!(y.norm() > 1e-8)) continue;
1011 y.normalize();
1012 kept.push_back(y);
1013 }
1014 const Eigen::Index m = static_cast<Eigen::Index>(kept.size());
1015 if (m == 0) return out;
1016 out.basis.resize(dof, m);
1017 out.points.resize(dof, 2 * m);
1018 for (Eigen::Index j = 0; j < m; ++j) {
1019 out.basis.col(j) = kept[static_cast<std::size_t>(j)];
1020 const Eigen::VectorXd x = out.basis.col(j).cwiseQuotient(root);
1021 out.points.col(2 * j) = center + step * x;
1022 out.points.col(2 * j + 1) = center - step * x;
1023 }
1024 out.gradients = gradients(out.points);
1025 if (out.gradients.rows() != 2 * m || out.gradients.cols() != dof ||
1026 !out.gradients.allFinite())
1027 return out;
1028 // H_mw y_j = M^{-1/2} H x_j by the central difference.
1029 Eigen::MatrixXd actions(dof, m);
1030 for (Eigen::Index j = 0; j < m; ++j)
1031 actions.col(j) =
1032 ((out.gradients.row(2 * j) - out.gradients.row(2 * j + 1))
1033 .transpose() /
1034 (2.0 * step))
1035 .cwiseQuotient(root);
1036 const Eigen::MatrixXd block = out.basis.transpose() * actions;
1037 const Eigen::MatrixXd symmetric = 0.5 * (block + block.transpose());
1038 out.asymmetry = 0.5 * (block - block.transpose()).cwiseAbs().maxCoeff();
1039 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(symmetric);
1040 if (spectrum.info() != Eigen::Success) return out;
1041 out.values = spectrum.eigenvalues();
1042 out.directions.resize(dof, m);
1043 for (Eigen::Index j = 0; j < m; ++j) {
1044 Eigen::VectorXd direction =
1045 (out.basis * spectrum.eigenvectors().col(j)).cwiseQuotient(root);
1046 const double norm = direction.norm();
1047 out.directions.col(j) = norm > 0.0 ? direction / norm : direction;
1048 }
1049 out.measured = out.values.allFinite() && out.directions.allFinite() &&
1050 std::isfinite(out.asymmetry);
1051 return out;
1052}

◆ probeVibrationalMinimum()

template<typename GradientAt>
EndpointSpectrum gpr::optim::probeVibrationalMinimum ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
double step,
const GradientAt & gradient_at,
double stiff_floor = std::numeric_limits<double>::infinity() )

Lanczos on the Cartesian vibrational complement, with true-oracle Hessian-vector products.

Central differences along the orthonormal complement of rigid motion are the vibrational operator. A Ritz value is an upper bound on the lowest eigenvalue (Courant–Fischer), so one below minus the measured asymmetry, with its full-space residual inside both that asymmetry and the gap to the next Ritz value, proves a negative mode. The same residual test cannot prove there is no negative mode: a direction outside an invariant subspace can carry either sign (scripts/derive_krylov_index_certificate.py). Positive definiteness is the spectrum at exhaustion of the complement. A Krylov subspace that stalls is extended by the least-represented complement direction. The probe reports nothing when that extension is impossible or a product cannot be measured; the caller then builds the complete stencil.

Definition at line 814 of file EndpointConnectivity.h.

818{
820 const Eigen::Index dof = positions.size();
821 if (!(step > 0.0) || dof == 0 || dof % 3 != 0 || masses.size() * 3 != dof ||
822 !positions.allFinite() || !masses.allFinite() ||
823 (masses.array() <= 0.0).any())
824 return out;
825 const Eigen::MatrixXd rigid = cartesianRigidMotions(positions);
826 const Eigen::JacobiSVD<Eigen::MatrixXd> svd(rigid, Eigen::ComputeFullU);
827 const Eigen::Index rank = svd.rank();
828 if (rank < 0 || rank >= dof) return out;
829 const Eigen::MatrixXd basis = svd.matrixU().rightCols(dof - rank);
830 const Eigen::Index m = basis.cols();
831 if (m <= 0) return out;
832 const double roundoff = std::sqrt(std::numeric_limits<double>::epsilon()) *
833 std::sqrt(static_cast<double>(m));
834
835 const auto product = [&](const Eigen::VectorXd& reduced,
836 Eigen::VectorXd& action) {
837 const Eigen::VectorXd direction = basis * reduced;
838 if (!(direction.norm() > 0.0) || !direction.allFinite()) return false;
839 const Eigen::MatrixXd points =
840 centralDifferencePoints(positions, step, direction);
841 Eigen::VectorXd plus(dof);
842 Eigen::VectorXd minus(dof);
843 if (!gradient_at(points.col(0), plus) ||
844 !gradient_at(points.col(1), minus) || plus.size() != dof ||
845 minus.size() != dof || !plus.allFinite() || !minus.allFinite())
846 return false;
847 action = basis.transpose() * ((plus - minus) / (2.0 * step));
848 return action.size() == m && action.allFinite();
849 };
850 const auto orthogonalize = [&](Eigen::VectorXd& direction,
851 const Eigen::MatrixXd& span,
852 Eigen::Index columns) {
853 if (columns <= 0) return;
854 const Eigen::MatrixXd basis_now = span.leftCols(columns);
855 for (int pass = 0; pass < 2; ++pass)
856 direction -= basis_now * (basis_now.transpose() * direction);
857 };
858
859 Eigen::MatrixXd directions(m, m);
860 Eigen::MatrixXd actions(m, m);
861 Eigen::Index columns = 0;
862 while (columns < m) {
863 Eigen::VectorXd direction(m);
864 if (columns == 0) {
865 direction.setOnes();
866 } else {
867 const Eigen::MatrixXd projected =
868 directions.leftCols(columns).transpose() *
869 actions.leftCols(columns);
870 const Eigen::MatrixXd symmetric =
871 0.5 * (projected + projected.transpose());
872 const Eigen::MatrixXd antisymmetric =
873 0.5 * (projected - projected.transpose());
874 const double resolution =
875 antisymmetric.size() == 0
876 ? 0.0
877 : Eigen::JacobiSVD<Eigen::MatrixXd>(antisymmetric)
878 .singularValues()(0);
879 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(
880 symmetric);
881 if (spectrum.info() != Eigen::Success ||
882 !spectrum.eigenvalues().allFinite())
883 return {};
884 const Eigen::VectorXd coordinate = spectrum.eigenvectors().col(0);
885 const double theta = spectrum.eigenvalues()(0);
886 Eigen::VectorXd residual =
887 actions.leftCols(columns) * coordinate -
888 theta * (directions.leftCols(columns) * coordinate);
889 // Full residual, before the part inside the Krylov subspace is
890 // removed. That norm bounds the distance from theta to the
891 // spectrum.
892 const double residual_norm = residual.norm();
893 if (columns >= 2 && std::isfinite(theta) &&
894 std::isfinite(residual_norm) && std::isfinite(resolution)) {
895 const double next = spectrum.eigenvalues()(1);
896 const double gap = next - theta;
897 const double noise = std::max(resolution, roundoff);
898 // The interval (theta ± residual) contains an eigenvalue of
899 // the vibrational operator. Inside the gap, and inside the
900 // stencil's own asymmetry, the Ritz vector is that mode.
901 if (theta + residual_norm < -resolution &&
902 gap > residual_norm && residual_norm <= noise) {
903 out.resolution = resolution;
904 out.lowest = theta;
905 out.lambda_max = spectrum.eigenvalues()(columns - 1);
906 const double floor = std::max(resolution, 0.0);
907 for (Eigen::Index i = 0; i < columns; ++i) {
908 const double value = spectrum.eigenvalues()(i);
909 if (value > floor && !std::isfinite(out.lambda_min))
910 out.lambda_min = value;
911 }
912 Eigen::VectorXd cartesian =
913 basis * (directions.leftCols(columns) * coordinate);
914 const double norm = cartesian.norm();
915 if (!(norm > 0.0) || !cartesian.allFinite()) return {};
916 cartesian /= norm;
917 out.cartesian_lowest = cartesian;
918 out.cartesian = cartesian;
919 double mass_norm = 0.0;
920 for (Eigen::Index atom = 0; atom < masses.size(); ++atom)
921 mass_norm +=
922 masses(atom) *
923 cartesian.segment<3>(3 * atom).squaredNorm();
924 out.curvature = mass_norm > 0.0 ? theta / mass_norm : theta;
925 out.ok = std::isfinite(out.curvature);
926 return out;
927 }
928 }
929 orthogonalize(residual, directions, columns);
930 const double outside =
931 roundoff * (1.0 + actions.leftCols(columns).norm());
932 if (!(residual.norm() > outside)) {
933 Eigen::Index least = 0;
934 double smallest = std::numeric_limits<double>::infinity();
935 const Eigen::MatrixXd span = directions.leftCols(columns);
936 for (Eigen::Index i = 0; i < m; ++i) {
937 const double represented = span.row(i).norm();
938 if (represented < smallest) {
939 smallest = represented;
940 least = i;
941 }
942 }
943 residual = Eigen::VectorXd::Unit(m, least);
944 orthogonalize(residual, directions, columns);
945 }
946 direction = residual;
947 }
948 const double norm = direction.norm();
949 if (!(norm > roundoff) || !direction.allFinite()) return {};
950 direction /= norm;
951 Eigen::VectorXd action;
952 if (!product(direction, action)) return {};
953 directions.col(columns) = direction;
954 actions.col(columns) = action;
955 ++columns;
956 }
957
958 const Eigen::MatrixXd projected = directions.transpose() * actions;
959 const Eigen::MatrixXd symmetric = 0.5 * (projected + projected.transpose());
960 const Eigen::MatrixXd antisymmetric =
961 0.5 * (projected - projected.transpose());
962 const double resolution =
963 antisymmetric.size() == 0
964 ? 0.0
965 : Eigen::JacobiSVD<Eigen::MatrixXd>(antisymmetric)
966 .singularValues()(0);
967 if (!symmetric.allFinite() || !std::isfinite(resolution)) return {};
968 const Eigen::MatrixXd hessian =
969 basis * (directions * symmetric * directions.transpose()) *
970 basis.transpose();
971 return spectrumOfColumns(hessian, resolution, positions, masses,
972 stiff_floor);
973}
Eigen::MatrixXd cartesianRigidMotions(const Eigen::VectorXd &positions)
EndpointSpectrum spectrumOfColumns(const Eigen::MatrixXd &hessian, double resolution, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double stiff_floor)

◆ projectOutRigidMotions()

Eigen::VectorXd gpr::optim::projectOutRigidMotions ( const Eigen::VectorXd & positions,
Eigen::VectorXd displacement )
inline

Component of displacement orthogonal to rigid translation and rotation at positions. The rank is the numerical rank of that basis.

Definition at line 619 of file EndpointConnectivity.h.

621{
622 if (displacement.size() != positions.size() || positions.size() < 3 ||
623 !displacement.allFinite())
624 return displacement;
625 const Eigen::MatrixXd rigid = cartesianRigidMotions(positions);
626 const Eigen::JacobiSVD<Eigen::MatrixXd> svd(
627 rigid, Eigen::ComputeThinU | Eigen::ComputeThinV);
628 const Eigen::Index rank = svd.rank();
629 if (rank <= 0) return displacement;
630 const Eigen::MatrixXd span = svd.matrixU().leftCols(rank);
631 displacement -= span * (span.transpose() * displacement);
632 return displacement;
633}

◆ readIrcCertificate()

bool gpr::optim::readIrcCertificate ( const std::string & path,
IrcCertificateRecord & record )
inline

Definition at line 2119 of file EndpointConnectivity.h.

2121{
2122 std::ifstream in(path);
2123 if (!in) return false;
2124 std::string label;
2125 int version = 0;
2126 if (!(in >> label >> version) || label != "irc-certificate" || version != 1)
2127 return false;
2128 std::size_t n_atoms = 0;
2129 if (!(in >> label >> n_atoms) || label != "n_atoms") return false;
2130 if (!(in >> label) || label != "atomic_numbers") return false;
2131 record.atomic_numbers.resize(n_atoms);
2132 for (std::size_t i = 0; i < n_atoms; ++i) {
2133 if (!(in >> record.atomic_numbers[i])) return false;
2134 }
2135 const auto scalar = [&](const char* name, double& value) {
2136 std::string got;
2137 return static_cast<bool>(in >> got >> value) && got == name;
2138 };
2139 const auto integer = [&](const char* name, int& value) {
2140 std::string got;
2141 return static_cast<bool>(in >> got >> value) && got == name;
2142 };
2143 if (!scalar("kick", record.kick) ||
2144 !scalar("forward_energy", record.forward_energy) ||
2145 !scalar("forward_force", record.forward_force) ||
2146 !integer("forward_steps", record.forward_steps) ||
2147 !integer("forward_calls", record.forward_calls) ||
2148 !scalar("reverse_energy", record.reverse_energy) ||
2149 !scalar("reverse_force", record.reverse_force) ||
2150 !integer("reverse_steps", record.reverse_steps) ||
2151 !integer("reverse_calls", record.reverse_calls) ||
2152 !scalar("reactant_energy", record.reactant_energy) ||
2153 !scalar("product_energy", record.product_energy))
2154 return false;
2155 const auto vector = [&](const char* name, Eigen::VectorXd& values) {
2156 std::string got;
2157 if (!(in >> got) || got != name) return false;
2158 values.resize(static_cast<Eigen::Index>(3 * n_atoms));
2159 for (Eigen::Index i = 0; i < values.size(); ++i) {
2160 if (!(in >> values(i))) return false;
2161 }
2162 return true;
2163 };
2164 return vector("saddle", record.saddle) && vector("mode", record.mode) &&
2165 vector("forward", record.forward) &&
2166 vector("reverse", record.reverse);
2167}

◆ recordSecantObservation()

void gpr::optim::recordSecantObservation ( SecantHessian & secant,
const Eigen::VectorXd & position,
const Eigen::VectorXd & gradient,
double energy,
SecantCurvatureCounts & counts,
SecantAccounting accounting = SecantAccounting::Count )
inline

Record one true-force geometry. A nonzero displacement that the selected update refuses is a rejected pair; the first geometry is neither. The energy joins the reference only with the geometry it was measured at.

Definition at line 51 of file SecantCurvature.h.

56{
57 const bool had_reference =
58 secant.referencePosition().size() == position.size();
59 const bool moved =
60 had_reference &&
61 (secant.referencePosition() - position).squaredNorm() > 0.0;
62 const bool accepted = secant.observe(position, gradient, energy);
63 if (accounting == SecantAccounting::AlreadyCounted) return;
64 if (accepted)
65 ++counts.pairs_accepted;
66 else if (moved)
67 ++counts.pairs_rejected;
68}
const Eigen::VectorXd & referencePosition() const noexcept
bool observe(const Eigen::VectorXd &position, const Eigen::VectorXd &gradient)

◆ refinedCurvatureResolution()

double gpr::optim::refinedCurvatureResolution ( double refined_resolution,
double anharmonic_scale )
inlinenoexcept

Definition at line 47 of file RichardsonCurvature.h.

49{
50 double resolution =
51 std::isfinite(refined_resolution) ? std::abs(refined_resolution) : 0.0;
52 if (std::isfinite(anharmonic_scale))
53 resolution = std::max(resolution, std::abs(anharmonic_scale));
54 return resolution;
55}

◆ refinedCurvatureSign()

RefinedCurvatureSign gpr::optim::refinedCurvatureSign ( double curvature,
double refined_resolution,
double anharmonic_scale )
inlinenoexcept

Definition at line 57 of file RichardsonCurvature.h.

60{
61 const double resolution =
62 refinedCurvatureResolution(refined_resolution, anharmonic_scale);
63 if (!std::isfinite(curvature)) return RefinedCurvatureSign::Unresolved;
64 if (curvature > resolution) return RefinedCurvatureSign::Positive;
65 if (curvature < -resolution) return RefinedCurvatureSign::Negative;
67}
double refinedCurvatureResolution(double refined_resolution, double anharmonic_scale) noexcept

◆ refinedDirectionalCubic()

MeasuredDirectionalCubic gpr::optim::refinedDirectionalCubic ( const RefinedCurvatureActions & stencil,
const Eigen::VectorXd & center_gradient,
const Eigen::VectorXd & mode,
double step )
inline

The complete cubic within a refined two-dimensional plane. Even gradient residuals at h and h/2 identify its four symmetric coefficients. Richardson extrapolation removes the leading fifth-energy-derivative term. The error is an empirical stencil estimate plus roundoff, not a global Taylor bound.

Definition at line 21 of file MeasuredCubicStencil.h.

25{
27 const auto& basis = stencil.basis;
28 const auto& coarse_mean = stencil.coarse_mean_gradient;
29 const auto& fine_mean = stencil.fine_mean_gradient;
30 if (basis.cols() != 2 || basis.rows() != center_gradient.size() ||
31 mode.size() != basis.rows() || coarse_mean.rows() != basis.rows() ||
32 fine_mean.rows() != basis.rows() || coarse_mean.cols() != 2 ||
33 fine_mean.cols() != 2 || !basis.allFinite() ||
34 !center_gradient.allFinite() || !mode.allFinite() ||
35 !coarse_mean.allFinite() || !fine_mean.allFinite() || !(step > 0.0) ||
36 !std::isfinite(step))
37 return out;
38 const double eps = std::numeric_limits<double>::epsilon();
39 const Eigen::Vector2d overlaps = basis.transpose() * mode;
40 if ((basis.transpose() * basis - Eigen::Matrix2d::Identity()).norm() >
41 std::sqrt(eps) ||
42 (mode - basis * overlaps).norm() >
43 std::sqrt(eps) * std::max(1.0, mode.norm()))
44 return out;
45 out.error = 0.0;
46 for (Eigen::Index j = 0; j < 2; ++j) {
47 const Eigen::VectorXd coarse =
48 (2.0 / (step * step)) * (coarse_mean.col(j) - center_gradient);
49 const Eigen::VectorXd fine =
50 (8.0 / (step * step)) * (fine_mean.col(j) - center_gradient);
51 const Eigen::VectorXd refined = (4.0 * fine - coarse) / 3.0;
52 const Eigen::VectorXd roundoff =
53 (64.0 * eps / (step * step)) *
54 (coarse_mean.col(j).cwiseAbs() + fine_mean.col(j).cwiseAbs() +
55 2.0 * center_gradient.cwiseAbs());
56 const Eigen::VectorXd error =
57 ((coarse - fine) / 3.0).cwiseAbs() + roundoff;
58 const double overlap = overlaps(j);
60 overlap, mode.dot(refined), basis.col(j).dot(refined));
61 out.error +=
62 overlap * overlap *
63 (3.0 * mode.cwiseAbs().dot(error) +
64 2.0 * std::abs(overlap) * basis.col(j).cwiseAbs().dot(error));
65 }
66 out.valid = std::isfinite(out.coefficient) && std::isfinite(out.error);
67 return out;
68}

◆ refinedIndexOnePositiveLowerBound()

double gpr::optim::refinedIndexOnePositiveLowerBound ( const MeasuredCurvatureSpectrum & complete,
Eigen::Index dimension,
const RefinedCurvatureActions & refined )
inline

Lower bound on the positive codimension-one restriction, conditional on the complete stencil and refined weak directions' empirical error bounds. Nonpositive results do not certify the index.

Definition at line 66 of file MeasuredCurvatureSpectrum.h.

69{
70 const double refused = -std::numeric_limits<double>::infinity();
71 const Eigen::Index weak = refined.basis.cols();
72 if (!complete.valid || dimension < 2 || weak < 1 || weak >= dimension ||
73 complete.curvatures.size() != dimension ||
74 complete.modes.cols() != dimension ||
75 complete.modes.rows() < dimension ||
76 refined.basis.rows() != complete.modes.rows() ||
77 refined.action.rows() != refined.basis.rows() ||
78 refined.action.cols() != weak ||
79 refined.error.rows() != refined.basis.rows() ||
80 refined.error.cols() != weak || !complete.curvatures.allFinite() ||
81 !complete.modes.allFinite() || !refined.basis.allFinite() ||
82 !refined.action.allFinite() || !refined.error.allFinite() ||
83 !std::isfinite(complete.resolution) || complete.resolution < 0.0 ||
84 !(complete.curvatures(0) < -complete.resolution))
85 return refused;
86 // The refined columns are the weak modes of the complete measured
87 // spectrum. Any unresolved direction outside this block prevents a
88 // positive lower bound for the untouched complement.
89 if (!(refined.basis.array() == complete.modes.middleCols(1, weak).array())
90 .all())
91 return refused;
92 const Eigen::Index tail = dimension - weak - 1;
93 if (tail > 0 &&
94 !(complete.curvatures.tail(tail).array() > complete.resolution).all())
95 return refused;
96 const double orthogonality_error =
97 (complete.modes.transpose() * complete.modes -
98 Eigen::MatrixXd::Identity(dimension, dimension))
99 .norm();
100 if (orthogonality_error > std::sqrt(std::numeric_limits<double>::epsilon()))
101 return refused;
102
103 const Eigen::MatrixXd projected =
104 refined.basis.transpose() * refined.action;
105 const Eigen::MatrixXd symmetric = 0.5 * (projected + projected.transpose());
106 const Eigen::MatrixXd truncation =
107 refined.basis.transpose() * refined.error;
108 const Eigen::MatrixXd errors =
109 0.5 * (truncation.cwiseAbs() + truncation.transpose().cwiseAbs()) +
110 (0.5 * (projected - projected.transpose())).cwiseAbs();
111 Eigen::MatrixXd nominal =
112 Eigen::MatrixXd::Zero(dimension - 1, dimension - 1);
113 Eigen::MatrixXd envelope = nominal;
114 nominal.topLeftCorner(weak, weak) = symmetric;
115 envelope.topLeftCorner(weak, weak) = errors;
116 if (tail > 0) {
117 const auto complement = complete.modes.rightCols(tail);
118 const Eigen::MatrixXd coupling =
119 complement.transpose() * refined.action;
120 const Eigen::MatrixXd coupling_error =
121 (complement.transpose() * refined.error).cwiseAbs();
122 nominal.bottomLeftCorner(tail, weak) = coupling;
123 nominal.topRightCorner(weak, tail) = coupling.transpose();
124 envelope.bottomLeftCorner(tail, weak) = coupling_error;
125 envelope.topRightCorner(weak, tail) = coupling_error.transpose();
126 nominal.diagonal().tail(tail) =
127 complete.curvatures.tail(tail).array() - complete.resolution;
128 }
129 Eigen::MatrixXd comparison = -nominal.cwiseAbs() - envelope;
130 comparison.diagonal() = nominal.diagonal() - envelope.diagonal();
131 // For any physical vector, this matrix bounds the positive restriction's
132 // quadratic form at its absolute coordinates. The tail bound is in the
133 // Loewner order; refined cross terms retain their componentwise errors.
134 if (!comparison.allFinite()) return refused;
135 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(
136 comparison, Eigen::EigenvaluesOnly);
137 if (spectrum.info() != Eigen::Success) return refused;
138 const double roundoff =
139 (orthogonality_error +
140 64.0 * std::numeric_limits<double>::epsilon() * dimension) *
141 (comparison.norm() + refined.action.norm() + refined.error.norm() +
142 complete.curvatures.norm());
143 const double comparison_lower = spectrum.eigenvalues()(0) - roundoff;
144 if (comparison_lower > 0.0) return comparison_lower;
145
146 // Sign cycles can make the magnitude comparison indefinite even when
147 // the measured restriction is positive. When each entry of D is bounded
148 // by the corresponding envelope entry, Frobenius Cauchy-Schwarz gives
149 // abs(v^T D v) <= ||envelope||_F ||v||^2. The untouched
150 // tail adds a positive-semidefinite remainder to nominal, so Weyl's
151 // bound retains the measured signs without weakening the error bounds.
152 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> signed_spectrum(
153 nominal, Eigen::EigenvaluesOnly);
154 if (signed_spectrum.info() != Eigen::Success) return comparison_lower;
155 const double signed_lower =
156 signed_spectrum.eigenvalues()(0) - envelope.norm() - roundoff;
157 return std::max(comparison_lower, signed_lower);
158}

◆ refineMeasuredCurvature()

template<typename Evaluate>
MeasuredCurvatureSpectrum gpr::optim::refineMeasuredCurvature ( const Eigen::VectorXd & center,
const Eigen::MatrixXd & basis,
double step,
Evaluate && evaluate,
RefinedCurvatureActions * actions = nullptr )

Measure central actions at h and h/2 in one owned batch. The evaluator accepts row-wise Cartesian positions, returns their energy gradients, and owns distribution and retention of every true observation.

Definition at line 595 of file MeasuredCurvatureSpectrum.h.

598{
599 if (actions) *actions = {};
600 if (center.size() == 0 || basis.rows() != center.size() ||
601 basis.cols() == 0 || !center.allFinite() || !basis.allFinite() ||
602 !(step > 0.0) || !std::isfinite(step))
603 return {};
604 Eigen::MatrixXd positions(4 * basis.cols(), center.size());
605 for (Eigen::Index j = 0; j < basis.cols(); ++j) {
606 const Eigen::VectorXd offset = step * basis.col(j);
607 positions.row(4 * j) = (center + offset).transpose();
608 positions.row(4 * j + 1) = (center - offset).transpose();
609 positions.row(4 * j + 2) = (center + 0.5 * offset).transpose();
610 positions.row(4 * j + 3) = (center - 0.5 * offset).transpose();
611 }
612 const Eigen::MatrixXd gradients = evaluate(positions);
613 if (gradients.rows() != positions.rows() ||
614 gradients.cols() != positions.cols() || !gradients.allFinite())
615 return {};
616 Eigen::MatrixXd coarse(basis.rows(), basis.cols()),
617 fine(basis.rows(), basis.cols());
618 for (Eigen::Index j = 0; j < basis.cols(); ++j) {
619 coarse.col(j) =
620 (gradients.row(4 * j) - gradients.row(4 * j + 1)).transpose() /
621 (2.0 * step);
622 fine.col(j) =
623 (gradients.row(4 * j + 2) - gradients.row(4 * j + 3)).transpose() /
624 step;
625 }
626 if (actions) {
627 actions->basis = basis;
628 actions->action = (4.0 * fine - coarse) / 3.0;
629 actions->error = (coarse - fine) / 3.0;
630 actions->coarse_mean_gradient.resize(basis.rows(), basis.cols());
631 actions->fine_mean_gradient.resize(basis.rows(), basis.cols());
632 for (Eigen::Index j = 0; j < basis.cols(); ++j) {
633 actions->coarse_mean_gradient.col(j) =
634 (0.5 * (gradients.row(4 * j) + gradients.row(4 * j + 1)))
635 .transpose();
636 actions->fine_mean_gradient.col(j) =
637 (0.5 * (gradients.row(4 * j + 2) + gradients.row(4 * j + 3)))
638 .transpose();
639 }
640 }
641 return analyzeRefinedMeasuredCurvature(basis, fine, coarse);
642}
MeasuredCurvatureSpectrum analyzeRefinedMeasuredCurvature(const Eigen::MatrixXd &basis, const Eigen::MatrixXd &at_h, const Eigen::MatrixXd &at_2h)
VecchiaResult evaluate(const Eigen::MatrixXd &points, const Eigen::VectorXd &y, double lengthscale, double noise, int max_neighbours)

◆ refinePositiveCurvatureComplement()

template<typename Evaluate>
double gpr::optim::refinePositiveCurvatureComplement ( const MeasuredCurvatureSpectrum & complete,
Eigen::Index dimension,
const Eigen::VectorXd & center,
double step,
Evaluate && evaluate )

Refine every unresolved positive mode while retaining the measured lower bound on the rest of the complete physical space. The evaluator owns every acquisition, including repeated positions and their multiplicities.

Definition at line 648 of file MeasuredCurvatureSpectrum.h.

651{
652 const double refused = -std::numeric_limits<double>::infinity();
653 if (!complete.valid || dimension < 2 ||
654 complete.curvatures.size() != dimension ||
655 complete.modes.cols() != dimension ||
656 !(complete.curvatures(0) < -complete.resolution))
657 return refused;
658 Eigen::Index weak = 0;
659 while (weak + 1 < dimension &&
660 complete.curvatures(weak + 1) <= complete.resolution)
661 ++weak;
662 if (weak == 0) return complete.curvatures(1) - complete.resolution;
664 const auto spectrum = refineMeasuredCurvature(
665 center, complete.modes.middleCols(1, weak), step, evaluate, &refined);
666 if (!spectrum.valid) return refused;
667 return refinedIndexOnePositiveLowerBound(complete, dimension, refined);
668}
double refinedIndexOnePositiveLowerBound(const MeasuredCurvatureSpectrum &complete, Eigen::Index dimension, const RefinedCurvatureActions &refined)
MeasuredCurvatureSpectrum refineMeasuredCurvature(const Eigen::VectorXd &center, const Eigen::MatrixXd &basis, double step, Evaluate &&evaluate, RefinedCurvatureActions *actions=nullptr)

◆ refineWeakModes()

template<typename Gradients>
RefinedWeakModes gpr::optim::refineWeakModes ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
const Eigen::MatrixXd & weak,
double step,
const Gradients & gradients,
double noise_multiplier = 0.0 )

weak holds mass-weighted mode columns. gradients takes Cartesian positions as columns and returns their gradients as rows, so the host can evaluate the whole batch at once.

The difference of the two stencils estimates truncation only when the oracle is exact. With gradient noise of standard deviation s in each coarse curvature, the half step doubles it, the difference has standard deviation sqrt(5) s and the Richardson value sqrt(65)/3 s, so one third of the absolute coarse-minus-fine difference understates the error of the Richardson value by a factor of about 3.6. A positive noise_multiplier m adds m times the root mean square of the coarse-minus-fine curvatures, pooled over the refined modes, to every entry of the error envelope. m = 3.6 is three standard deviations of the Richardson value when the differences are noise.

Definition at line 200 of file StencilIndex.h.

205{
207 const Eigen::Index dof = positions.size();
208 const Eigen::Index k = weak.cols();
209 if (k == 0 || weak.rows() != dof) return out;
210 Eigen::VectorXd root(dof);
211 for (Eigen::Index i = 0; i < dof; ++i)
212 root(i) = std::sqrt(masses(i / 3));
213 Eigen::MatrixXd directions(dof, k);
214 Eigen::VectorXd norms(k);
215 for (Eigen::Index j = 0; j < k; ++j) {
216 const Eigen::VectorXd cartesian = weak.col(j).cwiseQuotient(root);
217 norms(j) = cartesian.norm();
218 if (!(norms(j) > 0.0)) return out;
219 directions.col(j) = cartesian / norms(j);
220 }
221 Eigen::MatrixXd points(dof, 4 * k);
222 const double offsets[4] = {step, -step, 0.5 * step, -0.5 * step};
223 for (Eigen::Index j = 0; j < k; ++j)
224 for (int o = 0; o < 4; ++o)
225 points.col(4 * j + o) = positions + offsets[o] * directions.col(j);
226 const Eigen::MatrixXd g = gradients(points);
227 if (g.rows() != 4 * k || g.cols() != dof || !g.allFinite()) return out;
228 Eigen::MatrixXd action(dof, k), truncation(dof, k), even(dof, k);
229 for (Eigen::Index j = 0; j < k; ++j) {
230 const Eigen::VectorXd coarse =
231 (g.row(4 * j) - g.row(4 * j + 1)).transpose() / (2.0 * step);
232 const Eigen::VectorXd fine =
233 (g.row(4 * j + 2) - g.row(4 * j + 3)).transpose() / step;
234 // Mass-weighted action of the unit mass-weighted mode.
235 action.col(j) =
236 ((4.0 * fine - coarse) / 3.0).cwiseQuotient(root) * norms(j);
237 truncation.col(j) =
238 ((coarse - fine) / 3.0).cwiseQuotient(root) * norms(j);
239 even.col(j) = 0.5 * (g.row(4 * j) + g.row(4 * j + 1)).transpose();
240 }
241 const Eigen::MatrixXd projected = weak.transpose() * action;
242 const Eigen::MatrixXd symmetric = 0.5 * (projected + projected.transpose());
243 const Eigen::MatrixXd projected_error = weak.transpose() * truncation;
244 if (noise_multiplier > 0.0 && std::isfinite(noise_multiplier)) {
245 // projected_error holds (coarse - fine) / 3 on the refined modes.
246 const double spread =
247 3.0 * std::sqrt(projected_error.diagonal().squaredNorm() /
248 static_cast<double>(k));
249 out.noise_floor = noise_multiplier * spread;
250 }
251 Eigen::MatrixXd envelope =
252 0.5 * (projected_error.cwiseAbs() +
253 projected_error.transpose().cwiseAbs()) +
254 (0.5 * (projected - projected.transpose())).cwiseAbs();
255 envelope.array() += out.noise_floor;
256 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(symmetric);
257 if (spectrum.info() != Eigen::Success) return out;
258 out.curvatures = spectrum.eigenvalues();
259 out.modes = weak * spectrum.eigenvectors();
260 out.error = Eigen::JacobiSVD<Eigen::MatrixXd>(envelope).singularValues()(0);
261 out.action = action;
262 out.truncation = truncation;
263 out.directions = directions;
264 out.inverse_mass = norms.array().square();
265 out.even = even;
266 out.step = step;
267 out.valid = true;
268 return out;
269}

◆ refuseSecondNegativeMode()

template<typename Gradients>
SoftModeRefusal gpr::optim::refuseSecondNegativeMode ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
const Eigen::MatrixXd & mass_weighted_modes,
double step,
const Gradients & gradients,
double noise_multiplier = 0.0 )

Definition at line 281 of file StencilIndex.h.

285{
287 if (mass_weighted_modes.cols() < 2 || !(step > 0.0)) return out;
288 const Eigen::MatrixXd modes = mass_weighted_modes.leftCols(2);
289 const auto refined = refineWeakModes(positions, masses, modes, step,
290 gradients, noise_multiplier);
291 if (!refined.valid || refined.curvatures.size() < 2) return out;
292 out.second = refined.curvatures(1);
293 out.error = refined.error;
294 out.higher_order = std::isfinite(refined.curvatures(1)) &&
295 std::isfinite(refined.error) &&
296 refined.curvatures(1) < -std::max(refined.error, 0.0);
297 return out;
298}

◆ rejectMeasuredNegativePair()

template<typename Gradients>
NegativePairRejection gpr::optim::rejectMeasuredNegativePair ( const Eigen::MatrixXd & previous_cartesian_hessian,
const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
const Eigen::VectorXd & centre_gradient,
double step,
double step_bound,
const Gradients & gradients )

Definition at line 683 of file StencilIndex.h.

688{
690 if (positions.size() < 6 || masses.size() * 3 != positions.size() ||
691 centre_gradient.size() != positions.size() || !positions.allFinite() ||
692 !masses.allFinite() || (masses.array() <= 0.0).any() ||
693 !centre_gradient.allFinite() || !(step > 0.0) || !std::isfinite(step))
694 return out;
695 // The Hessian selects a physical basis at this geometry. Its curvatures
696 // are proposals; only the fresh actions determine the rejection.
697 const auto proposal =
698 analyzeStencilIndex(previous_cartesian_hessian, positions, masses);
699 if (!proposal.valid || proposal.modes.cols() < 2) return out;
700 const Eigen::MatrixXd basis = proposal.modes.leftCols(2);
701 const auto refined =
702 refineWeakModes(positions, masses, basis, step, gradients);
703 if (!refined.valid) return out;
704 const Eigen::Matrix2d block = basis.transpose() * refined.action;
705 const Eigen::Matrix2d symmetric = 0.5 * (block + block.transpose());
706 const Eigen::Matrix2d projected_error =
707 basis.cwiseAbs().transpose() * refined.truncation.cwiseAbs();
708 const Eigen::Matrix2d error =
709 0.5 * (projected_error + projected_error.transpose()) +
710 (0.5 * (block - block.transpose())).cwiseAbs();
711 const double gram_defect =
712 (basis.transpose() * basis - Eigen::Matrix2d::Identity()).norm();
713 const double allowance =
714 (gram_defect + 64.0 * std::numeric_limits<double>::epsilon() *
715 static_cast<double>(positions.size())) *
716 (symmetric.norm() + refined.action.norm() + refined.truncation.norm());
717 if (!(gram_defect < 1.0) || !error.allFinite() || !std::isfinite(allowance))
718 return out;
719 Eigen::Matrix2d majorant = symmetric.cwiseAbs() + error;
720 majorant.diagonal() = symmetric.diagonal() + error.diagonal();
721 const Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> spectrum(majorant);
722 if (spectrum.info() != Eigen::Success) return out;
723 // For abs(D) <= error, z^T (block + D) z is bounded by the
724 // majorant evaluated at abs(z). A negative upper bound gives two negative
725 // modes by restriction, conditional on the measured truncation envelope.
726 out.upper = spectrum.eigenvalues()(1) + allowance;
727 out.higher_order = out.upper < 0.0;
728 if (!out.higher_order) return out;
729 const Eigen::VectorXd direction = refined.directions.col(1);
730 const double third = 2.0 * refined.inverse_mass(1) *
731 direction.dot(refined.even.col(1) - centre_gradient) /
732 (step * step);
733 out.continuation = boundedWeakModeContinuation(
734 direction, third, step, symmetric(1, 1) - error(1, 1) - allowance,
735 error(1, 1) + allowance, step_bound);
736 return out;
737}
WeakModeContinuation boundedWeakModeContinuation(const Eigen::VectorXd &direction, double third, double step, double lower, double resolution, double step_bound)

◆ reportEndpointConnectivity()

template<typename Oracle>
EndpointConnectivityReport gpr::optim::reportEndpointConnectivity ( const Eigen::VectorXd & saddle,
const Eigen::VectorXd & masses,
double force_tolerance,
const Eigen::VectorXd & reactant,
const Eigen::VectorXd & product,
const std::vector< int > & atomic_numbers,
Oracle oracle,
RelaxedEndpointCache * cache = nullptr,
double hessian_step = defaultStencilStep(),
const std::function< bool()> * stop = nullptr,
const std::vector< KnownOracleRow > * known = nullptr,
const Eigen::MatrixXd * model_hessian = nullptr,
const Eigen::MatrixXd * held_directions = nullptr,
VibrationalStencil stencil = VibrationalStencil::Full )

Relax the deposited endpoints once, walk downhill both ways from the saddle with the same L-BFGS and the same force tolerance, and decide whether those walks are the two relaxed minima. held_directions are the directions of a stencil the search measured at the saddle, whose rows known carries; the saddle Hessian is measured along them.

Definition at line 1277 of file EndpointConnectivity.h.

1288{
1290 const Eigen::Index dof = saddle.size();
1291 const Eigen::Index n_atoms = masses.size();
1292 if (dof == 0 || dof % 3 != 0 || n_atoms * 3 != dof ||
1293 reactant.size() != dof || product.size() != dof ||
1294 static_cast<Eigen::Index>(atomic_numbers.size()) != n_atoms ||
1295 !saddle.allFinite() || !masses.allFinite() ||
1296 (masses.array() <= 0.0).any() || !reactant.allFinite() ||
1297 !product.allFinite() || !(force_tolerance > 0.0) ||
1298 !std::isfinite(force_tolerance) || !(hessian_step > 0.0))
1299 return report;
1300
1301 // A replay from the saved saddle must not inherit the search's
1302 // BLAS thread count. A threaded GEMM changes the Hessian's
1303 // summation order, the imaginary mode moves by a few ulps, and
1304 // L-BFGS ends in the same basin at a different point. The mode
1305 // sign is fixed below, so the two directions do not swap. L-BFGS
1306 // is a new solver on each walk; it does not keep the search's pairs.
1307 Eigen::setNbThreads(1);
1308#ifdef GPR_HAVE_OPENBLAS
1309 openblas_set_num_threads(1);
1310#endif
1311
1312 endpoint_detail::MinimizerState state;
1313 state.n = dof;
1314 endpoint_detail::OracleMemory memory;
1315 if (known != nullptr) {
1316 for (const KnownOracleRow& row: *known)
1317 memory.add(row.position, row.energy, row.gradient);
1318 }
1319 int* call_bucket = &report.calls_deposit;
1320 state.oracle = [&](const Eigen::VectorXd& position, double& energy,
1321 Eigen::VectorXd& gradient) {
1322 if (stop != nullptr && (*stop)()) {
1323 state.stopped = true;
1324 return false;
1325 }
1326 if (memory.recall(position, energy, gradient)) return true;
1327 const auto started = std::chrono::steady_clock::now();
1328 const auto sample = oracle(position);
1329 report.oracle_seconds += std::chrono::duration<double>(
1330 std::chrono::steady_clock::now() - started)
1331 .count();
1332 energy = sample.first;
1333 gradient = sample.second;
1334 if (!(std::isfinite(energy) && gradient.size() == position.size() &&
1335 gradient.allFinite()))
1336 return false;
1337 memory.add(position, energy, gradient);
1338 ++state.calls;
1339 ++*call_bucket;
1340 return true;
1341 };
1342 const auto gradient_at = [&](const Eigen::VectorXd& position,
1343 Eigen::VectorXd& gradient) {
1344 double energy = 0.0;
1345 if (!state.oracle(position, energy, gradient)) {
1346 if (!state.stopped) state.failed = true;
1347 return false;
1348 }
1349 return true;
1350 };
1351 // Endpoint and walk-end minima. The saddle stencil below stays the
1352 // complete measurement. A vibrational product that cannot be taken
1353 // does not by itself fail the certificate: the complete stencil is
1354 // the measurement when the sign is unresolved. A wall stop is not
1355 // that stencil.
1356 MinimumSpectrumCache minimum_cache;
1357 const auto minimum_at = [&](const Eigen::VectorXd& position) {
1358 EndpointSpectrum cached;
1359 if (minimum_cache.recall(position, cached)) return cached;
1360 const auto sample = [&](const Eigen::VectorXd& queried,
1361 Eigen::VectorXd& gradient) {
1362 double energy = 0.0;
1363 return state.oracle(queried, energy, gradient);
1364 };
1365 const EndpointSpectrum vibrational =
1366 probeVibrationalMinimum(position, masses, hessian_step, sample);
1367 if (state.stopped) return EndpointSpectrum{};
1368 // An unresolved curvature is still this probe's spectrum. Building
1369 // the complete stencil as well repeats the minimum measurement.
1371 vibrational.ok
1372 ? vibrational
1373 : spectrumAt(position, masses, hessian_step, gradient_at);
1374 if (out.ok) minimum_cache.store(position, out);
1375 return out;
1376 };
1377
1378 const double reach =
1379 std::max((saddle - reactant).norm(), (saddle - product).norm());
1380 // The L-BFGS memory is one vibrational window. Filling it and then
1381 // walking it again is what puts the deposit under the force tolerance.
1382 // One window can leave the force above the tolerance, and the certificate
1383 // then has nothing to report. The force test stops earlier. The reach
1384 // bound is the distance the walk can be asked to travel, in the steps
1385 // that measured the curvature.
1386 const int vibrational = std::max(1, static_cast<int>(dof) - 6);
1387 const int max_steps =
1388 std::max(vibrational + vibrational,
1389 static_cast<int>(
1390 std::ceil(std::max(reach, hessian_step) / hessian_step)));
1391
1392 const bool cache_hit = cache != nullptr && cache->ready &&
1393 cache->tolerance == force_tolerance &&
1394 cache->atomic_numbers == atomic_numbers &&
1395 cache->deposited_reactant.size() == dof &&
1396 cache->deposited_product.size() == dof &&
1397 cache->deposited_reactant == reactant &&
1398 cache->deposited_product == product &&
1399 cache->relaxed_reactant.size() == dof &&
1400 cache->relaxed_product.size() == dof;
1401
1402 Eigen::VectorXd relaxed_reactant;
1403 Eigen::VectorXd relaxed_product;
1404 if (cache_hit) {
1405 relaxed_reactant = cache->relaxed_reactant;
1406 relaxed_product = cache->relaxed_product;
1407 report.lambda_reactant = cache->lambda_reactant;
1408 report.lambda_product = cache->lambda_product;
1409 } else {
1410 // A deposited endpoint can already be under the force tolerance
1411 // and still have a negative mode (CH3O's reactant). The same
1412 // L-BFGS then stops on the force and never enters the basin the
1413 // saddle walk finds. Leave each resolved negative mode before
1414 // the match.
1415 const auto settle = [&](const Eigen::VectorXd& start) {
1416 endpoint_detail::RelaxedPoint point =
1417 endpoint_detail::relaxWithLbfgs(
1418 state, start, force_tolerance, max_steps, hessian_step,
1419 std::max(reach, hessian_step), vibrational, stop);
1420 EndpointSpectrum spec;
1421 for (int pass = 0;
1422 pass < vibrational && point.converged && !state.failed;
1423 ++pass) {
1424 call_bucket = &report.calls_endpoint_check;
1425 spec = minimum_at(point.position);
1426 call_bucket = &report.calls_deposit;
1427 if (!spec.ok || !(spec.lowest < -spec.resolution)) break;
1428 Eigen::VectorXd direction = projectOutRigidMotions(
1429 point.position, spec.cartesian_lowest);
1430 if (!(direction.norm() > 0.0)) break;
1431 direction.normalize();
1432 const double alpha =
1433 force_tolerance /
1434 std::max(std::abs(spec.lowest), spec.resolution);
1435 const Eigen::VectorXd kick = alpha * direction;
1436 double energy_plus = 0.0;
1437 double energy_minus = 0.0;
1438 Eigen::VectorXd gradient(dof);
1439 const Eigen::VectorXd plus = point.position + kick;
1440 const Eigen::VectorXd minus = point.position - kick;
1441 if (!state.oracle(plus, energy_plus, gradient) ||
1442 !state.oracle(minus, energy_minus, gradient)) {
1443 if (state.stopped)
1444 point.stopped = true;
1445 else
1446 state.failed = true;
1447 break;
1448 }
1449 const double sign = energy_plus < energy_minus ? 1.0 : -1.0;
1450 Eigen::VectorXd walked = point.position + sign * kick;
1451 double energy =
1452 energy_plus < energy_minus ? energy_plus : energy_minus;
1453 const int push_cap = std::max(
1454 1, static_cast<int>(
1455 std::ceil(std::max(reach, kick.norm()) /
1456 std::max(kick.norm(), hessian_step))));
1457 for (int pushed = 1; pushed < push_cap && !state.failed;
1458 ++pushed) {
1459 const Eigen::VectorXd trial = walked + sign * kick;
1460 double trial_energy = 0.0;
1461 if (!state.oracle(trial, trial_energy, gradient)) {
1462 if (state.stopped)
1463 point.stopped = true;
1464 else
1465 state.failed = true;
1466 break;
1467 }
1468 if (!(trial_energy < energy)) break;
1469 const double travelled = permutationAwareRmsd(
1470 point.position, trial, atomic_numbers);
1471 walked = trial;
1472 energy = trial_energy;
1473 if (std::isfinite(travelled) && reach > 0.0 &&
1474 travelled > reach)
1475 break;
1476 if (gpr::forceNorm(gradient,
1478 force_tolerance)
1479 break;
1480 }
1481 point = endpoint_detail::relaxWithLbfgs(
1482 state, walked, force_tolerance, max_steps,
1483 kick.norm() > 0.0 ? kick.norm() : hessian_step,
1484 std::max(reach, kick.norm()), vibrational, stop);
1485 if (point.stopped) break;
1486 }
1487 if (point.converged && !state.failed && !spec.ok) {
1488 call_bucket = &report.calls_endpoint_check;
1489 spec = minimum_at(point.position);
1490 call_bucket = &report.calls_deposit;
1491 }
1492 return std::pair{point, spec};
1493 };
1494 const auto reactant_settled = settle(reactant);
1495 const auto product_settled = settle(product);
1496 const auto& reactant_min = reactant_settled.first;
1497 const auto& product_min = product_settled.first;
1498 const auto& reactant_spectrum = reactant_settled.second;
1499 const auto& product_spectrum = product_settled.second;
1500 if (reactant_min.stopped || product_min.stopped || state.stopped) {
1501 report.calls = state.calls;
1502 report.unresolved = true;
1503 report.reported = true;
1504 return report;
1505 }
1506 if (!reactant_min.converged || !product_min.converged || state.failed) {
1507 report.calls = state.calls;
1508 report.ambiguous = true;
1509 report.reported = false;
1510 return report;
1511 }
1512 relaxed_reactant = reactant_min.position;
1513 relaxed_product = product_min.position;
1514 if (!reactant_spectrum.ok || !product_spectrum.ok || state.failed) {
1515 report.calls = state.calls;
1516 return report;
1517 }
1518 report.lambda_reactant = reactant_spectrum.lambda_min;
1519 report.lambda_product = product_spectrum.lambda_min;
1520 report.lowest_reactant = reactant_spectrum.lowest;
1521 report.lowest_product = product_spectrum.lowest;
1522 report.resolution_reactant = reactant_spectrum.resolution;
1523 report.resolution_product = product_spectrum.resolution;
1524 if (cache != nullptr) {
1525 cache->deposited_reactant = reactant;
1526 cache->deposited_product = product;
1527 cache->atomic_numbers = atomic_numbers;
1528 cache->tolerance = force_tolerance;
1529 cache->relaxed_reactant = relaxed_reactant;
1530 cache->relaxed_product = relaxed_product;
1531 cache->lambda_reactant = report.lambda_reactant;
1532 cache->lambda_product = report.lambda_product;
1533 cache->ready = true;
1534 }
1535 }
1536
1537 report.separation =
1538 labelledRmsd(relaxed_reactant, relaxed_product, atomic_numbers);
1539 const double half_separation =
1540 report.separation > 0.0 ? 0.5 * report.separation : 0.0;
1541 const double harmonic_reactant =
1542 endpointMatchBall(force_tolerance, report.lambda_reactant,
1543 std::numeric_limits<double>::infinity());
1544 const double harmonic_product =
1545 endpointMatchBall(force_tolerance, report.lambda_product,
1546 std::numeric_limits<double>::infinity());
1548 report.separation, harmonic_reactant, harmonic_product);
1550 force_tolerance, report.lambda_reactant, half_separation);
1552 force_tolerance, report.lambda_product, half_separation);
1553
1554 // A mode is stiff when it is stiffer than the imaginary mode and a
1555 // stencil step along it already exceeds the force tolerance. The
1556 // first bound keeps a mode softer than the reaction coordinate in
1557 // the descent. The second is the bond stretch whose λ_max made
1558 // force/λ_max creep. Floppy modes stay.
1559 call_bucket = &report.calls_saddle;
1560 const double stiff_floor = force_tolerance / hessian_step;
1561 // The saddle is measured along the validation stencil's directions, so
1562 // the rows the search measured there are read again.
1563 const Eigen::MatrixXd saddle_directions =
1564 ircStencilDirections(saddle, masses, held_directions, stencil);
1565 const Eigen::MatrixXd saddle_points =
1566 centralDifferencePoints(saddle, hessian_step, saddle_directions);
1567 bool stencil_held = saddle_points.cols() > 0;
1568 for (Eigen::Index j = 0; j < saddle_points.cols() && stencil_held; ++j)
1569 stencil_held = memory.holds(saddle_points.col(j));
1570 // The vibrational index rule. A stored stencil was already judged by
1571 // the search, so only a Hessian this walk measures is reported here.
1572 const auto note_measured_index = [&](const Eigen::MatrixXd& raw) {
1573 if (stencil_held) return;
1574 const auto decision = decideMeasuredIndex(
1575 raw, saddle, masses, hessian_step,
1576 [&](const Eigen::MatrixXd& points) {
1577 Eigen::MatrixXd rows(points.cols(), points.rows());
1578 for (Eigen::Index i = 0; i < points.cols(); ++i) {
1579 double energy = 0.0;
1580 Eigen::VectorXd gradient(points.rows());
1581 if (!state.oracle(points.col(i), energy, gradient)) {
1582 rows.resize(0, 0);
1583 return rows;
1584 }
1585 rows.row(i) = gradient.transpose();
1586 }
1587 return rows;
1588 },
1589 &saddle_directions);
1590 if (!std::isfinite(decision.resolution)) return;
1591 report.measured_index = true;
1592 report.index_resolution = decision.resolution;
1593 report.index_calls = report.calls_saddle;
1594 report.index_negative = decision.negative;
1595 report.index_unresolved = decision.unresolved;
1596 report.index_first_order = decision.first_order;
1597 report.index_higher_order = decision.higher_order;
1598 };
1599 EndpointSpectrum saddle_spectrum;
1600 bool model_mode = false;
1601 Eigen::MatrixXd measured_columns;
1602 if (!stencil_held && model_hessian != nullptr) {
1603 saddle_spectrum =
1604 spectrumOfModelHessian(*model_hessian, saddle, masses, stiff_floor);
1605 model_mode = saddle_spectrum.ok &&
1606 saddle_spectrum.curvature < -saddle_spectrum.resolution;
1607 }
1608 if (!model_mode) {
1609 saddle_spectrum =
1610 spectrumAt(saddle, masses, hessian_step, gradient_at, stiff_floor,
1611 &measured_columns, &saddle_directions);
1612 if (saddle_spectrum.ok) note_measured_index(measured_columns);
1613 }
1614 call_bucket = &report.calls_descent;
1615 if (saddle_spectrum.ok) report.saddle_curvature = saddle_spectrum.curvature;
1616 // A negative eigenvalue inside the stencil resolution is not an
1617 // imaginary mode. Rigid translation and rotation are removed before
1618 // the step: a mass-weighted mode can still carry them in Cartesian,
1619 // and stepping along that part leaves the IRC.
1620 if (state.stopped) {
1621 report.calls = state.calls;
1622 report.unresolved = true;
1623 report.reported = true;
1624 return report;
1625 }
1626 if (!saddle_spectrum.ok ||
1627 !(saddle_spectrum.curvature < -saddle_spectrum.resolution) ||
1628 state.failed) {
1629 report.calls = state.calls;
1630 return report;
1631 }
1632 // The eigensolver's sign is arbitrary. Orient forward toward the
1633 // product along the Kabsch-aligned endpoint chord when that
1634 // projection resolves the sign; otherwise make the first component
1635 // within a relative 1e-3 of the maximum magnitude positive so a
1636 // symmetric saddle does not flip forward and reverse on 1e-5 noise.
1637 const Eigen::VectorXd aligned_reactant =
1638 aux::kabschAlignProductToReactant(saddle, relaxed_reactant);
1639 const Eigen::VectorXd aligned_product =
1640 aux::kabschAlignProductToReactant(saddle, relaxed_product);
1641 Eigen::VectorXd reaction_chord;
1642 if (aligned_reactant.size() == dof && aligned_product.size() == dof &&
1643 aligned_reactant.allFinite() && aligned_product.allFinite()) {
1644 reaction_chord =
1645 projectOutRigidMotions(saddle, aligned_product - aligned_reactant);
1646 const double chord_norm = reaction_chord.norm();
1647 if (chord_norm > 0.0)
1648 reaction_chord /= chord_norm;
1649 else
1650 reaction_chord.resize(0);
1651 }
1652 const auto signed_mode = [&](const EndpointSpectrum& spec) {
1653 Eigen::VectorXd direction =
1654 projectOutRigidMotions(saddle, spec.cartesian);
1655 if (!(direction.norm() > 0.0)) return direction;
1656 direction.normalize();
1657 constexpr double kRelativeTieTolerance = 1e-3;
1658 if (reaction_chord.size() == dof) {
1659 const double projection = direction.dot(reaction_chord);
1660 if (std::abs(projection) > kRelativeTieTolerance) {
1661 if (projection < 0.0) direction = -direction;
1662 return direction;
1663 }
1664 }
1665 const double biggest = direction.cwiseAbs().maxCoeff();
1666 const double tie_floor = (1.0 - kRelativeTieTolerance) * biggest;
1667 Eigen::Index pivot = 0;
1668 for (Eigen::Index i = 0; i < direction.size(); ++i) {
1669 if (std::abs(direction(i)) >= tie_floor) {
1670 pivot = i;
1671 break;
1672 }
1673 }
1674 if (direction(pivot) < 0.0) direction = -direction;
1675 return direction;
1676 };
1677 Eigen::VectorXd mode = signed_mode(saddle_spectrum);
1678 // A model Hessian is not the measured stencil. Keep it only when it
1679 // produced a direction and the true force confirms that direction is
1680 // imaginary: the central difference of the directional derivative is
1681 // negative. Otherwise the measured stencil decides, as it does when
1682 // no model is supplied.
1683 const auto measure_saddle = [&]() {
1684 if (state.stopped) return false;
1685 call_bucket = &report.calls_saddle;
1686 saddle_spectrum =
1687 spectrumAt(saddle, masses, hessian_step, gradient_at, stiff_floor,
1688 &measured_columns, &saddle_directions);
1689 call_bucket = &report.calls_descent;
1690 if (saddle_spectrum.ok) note_measured_index(measured_columns);
1691 if (!saddle_spectrum.ok ||
1692 !(saddle_spectrum.curvature < -saddle_spectrum.resolution) ||
1693 state.failed)
1694 return false;
1695 report.saddle_curvature = saddle_spectrum.curvature;
1696 mode = signed_mode(saddle_spectrum);
1697 return mode.norm() > 0.0;
1698 };
1699 if (model_mode && mode.norm() > 0.0) {
1700 call_bucket = &report.calls_saddle;
1701 Eigen::VectorXd slope_plus(dof);
1702 Eigen::VectorXd slope_minus(dof);
1703 const bool probed =
1704 gradient_at(saddle + hessian_step * mode, slope_plus) &&
1705 gradient_at(saddle - hessian_step * mode, slope_minus);
1706 call_bucket = &report.calls_descent;
1707 const double directional =
1708 probed ? (slope_plus - slope_minus).dot(mode) / (2.0 * hessian_step)
1709 : 0.0;
1710 const bool imaginary = probed && directional < 0.0;
1711 if (imaginary) {
1712 // The model eigenvalue is not a measured spectrum. The true
1713 // number is the curvature of this one direction, and it does
1714 // not say how many other directions are negative.
1715 report.saddle_index_measured = false;
1716 report.directional_curvature = directional;
1717 report.saddle_curvature = std::numeric_limits<double>::quiet_NaN();
1718 }
1719 if (!imaginary) {
1720 if (state.stopped) {
1721 report.calls = state.calls;
1722 report.unresolved = true;
1723 report.reported = true;
1724 return report;
1725 }
1726 if (!measure_saddle()) {
1727 report.calls = state.calls;
1728 return report;
1729 }
1730 }
1731 } else if (model_mode && !measure_saddle()) {
1732 report.calls = state.calls;
1733 return report;
1734 }
1735 if (!(mode.norm() > 0.0)) {
1736 report.calls = state.calls;
1737 return report;
1738 }
1739 report.saddle_positions = saddle;
1740 report.mode = mode;
1741 double alpha = force_tolerance / std::abs(saddle_spectrum.curvature);
1742 if (half_separation > 0.0) {
1743 const double kick_rmsd =
1744 (alpha * mode).norm() / std::sqrt(static_cast<double>(n_atoms));
1745 if (kick_rmsd > half_separation) alpha *= half_separation / kick_rmsd;
1746 }
1747 report.kick = alpha;
1748
1749 const auto irc = [&](double sign) {
1750 endpoint_detail::RelaxedPoint out;
1751 out.position = saddle + sign * alpha * mode;
1752 double energy = 0.0;
1753 Eigen::VectorXd gradient(dof);
1754 if (!state.oracle(out.position, energy, gradient)) {
1755 if (state.stopped)
1756 out.stopped = true;
1757 else
1758 state.failed = true;
1759 return out;
1760 }
1761 out.energy = energy;
1762 out.max_force =
1764 // λ_max is the stiffest vibrational mode. The descent direction
1765 // is -g_i/m_i with the saddle modes stiffer than
1766 // tolerance/stencil removed, and the length is the Newton step
1767 // of the curvature that direction meets,
1768 // E(s) = E - slope·s + ½ k s². force/λ_max is the Newton step
1769 // of a bond stretch, so it creeps when the force is soft and
1770 // the walk spends the reach/stencil cap. k above the stencil
1771 // resolution gives slope/k. k below it does not bound the step:
1772 // the probe is a descent, and the next length grows by the
1773 // ratio of the slopes at its ends, up to the endpoint reach.
1774 // A rise shortens the trial to slope/k. The descent stops when
1775 // a step no longer lowers the energy. That force is not the end.
1776 const double floor_curvature = saddle_spectrum.resolution;
1777 double carried_step = hessian_step;
1778 for (int step = 0; step < max_steps && !state.failed; ++step) {
1779 if (stop != nullptr && (*stop)()) {
1780 out.stopped = true;
1781 break;
1782 }
1783 if (out.max_force < force_tolerance) break;
1784 Eigen::VectorXd driving = gradient;
1785 if (saddle_spectrum.stiff.cols() > 0 &&
1786 saddle_spectrum.stiff.rows() == gradient.size()) {
1787 const Eigen::VectorXd coeff =
1788 saddle_spectrum.stiff.transpose() * gradient;
1789 const Eigen::VectorXd soft =
1790 gradient - saddle_spectrum.stiff * coeff;
1791 if (soft.norm() > 0.0) driving = soft;
1792 }
1793 Eigen::VectorXd direction(dof);
1794 for (Eigen::Index k = 0; k < dof; ++k)
1795 direction(k) = -driving(k) / masses(k / 3);
1796 if (!(direction.norm() > 0.0)) break;
1797 direction.normalize();
1798 const double slope = -gradient.dot(direction);
1799 if (!(slope > 0.0)) break;
1800 double step_length =
1801 carried_step > 0.0 ? carried_step : hessian_step;
1802 if (reach > 0.0) step_length = std::min(step_length, reach);
1803 bool accepted = false;
1804 bool extended = false;
1805 for (int trial_index = 0;
1806 trial_index < vibrational && step_length > 0.0;
1807 ++trial_index) {
1808 const Eigen::VectorXd trial =
1809 out.position + step_length * direction;
1810 double trial_energy = 0.0;
1811 Eigen::VectorXd trial_gradient(dof);
1812 if (!state.oracle(trial, trial_energy, trial_gradient)) {
1813 if (state.stopped)
1814 out.stopped = true;
1815 else
1816 state.failed = true;
1817 break;
1818 }
1819 const double curvature =
1820 2.0 * (trial_energy - energy + slope * step_length) /
1821 (step_length * step_length);
1822 const bool bounded =
1823 curvature > floor_curvature && std::isfinite(curvature);
1824 const bool descends = trial_energy < energy;
1825 if (bounded) {
1826 double newton = slope / curvature;
1827 if (!std::isfinite(newton) || !(newton > 0.0)) break;
1828 if (reach > 0.0) newton = std::min(newton, reach);
1829 if (descends && !extended && newton > step_length) {
1830 step_length = newton;
1831 extended = true;
1832 continue;
1833 }
1834 if (!descends && newton < step_length) {
1835 step_length = newton;
1836 continue;
1837 }
1838 } else if (!descends) {
1839 break;
1840 }
1841 if (!descends) break;
1842 out.position = trial;
1843 energy = trial_energy;
1844 out.energy = energy;
1845 const double slope_trial = -trial_gradient.dot(direction);
1846 gradient = std::move(trial_gradient);
1847 out.max_force = gpr::forceNorm(
1849 if (!bounded && slope_trial > slope) {
1850 carried_step = step_length * (slope_trial / slope);
1851 if (reach > 0.0)
1852 carried_step = std::min(carried_step, reach);
1853 } else {
1854 carried_step = step_length;
1855 }
1856 accepted = true;
1857 ++out.steps;
1858 break;
1859 }
1860 if (out.stopped || !accepted) break;
1861 }
1862 // The descent has slowed. Finish on the true surface with
1863 // rgmin's L-BFGS, then leave a negative mode the force test
1864 // would have kept.
1865 if (!out.stopped) {
1866 const int descended = out.steps;
1867 call_bucket = &report.calls_polish;
1868 out = endpoint_detail::relaxWithLbfgs(
1869 state, out.position, force_tolerance, max_steps, carried_step,
1870 std::max(reach, carried_step), vibrational, stop);
1871 out.steps += descended;
1872 if (stop != nullptr && (*stop)()) out.stopped = true;
1873 }
1874 call_bucket = &report.calls_end_check;
1875 // The L-BFGS geometry is the end. A negative mode is stepped off
1876 // and relaxed again. Ambiguous means that mode is still there.
1877 EndpointSpectrum spec;
1878 for (int pass = 0; pass < vibrational && !state.failed && !out.stopped;
1879 ++pass) {
1880 if (stop != nullptr && (*stop)()) {
1881 out.stopped = true;
1882 break;
1883 }
1884 spec = minimum_at(out.position);
1885 if (!spec.ok || !(spec.lowest < -spec.resolution)) break;
1886 Eigen::VectorXd direction =
1887 projectOutRigidMotions(out.position, spec.cartesian_lowest);
1888 if (!(direction.norm() > 0.0)) break;
1889 direction.normalize();
1890 const double leave =
1891 force_tolerance /
1892 std::max(std::abs(spec.lowest), spec.resolution);
1893 double energy_plus = 0.0;
1894 double energy_minus = 0.0;
1895 Eigen::VectorXd probe(dof);
1896 if (!state.oracle(out.position + leave * direction, energy_plus,
1897 probe) ||
1898 !state.oracle(out.position - leave * direction, energy_minus,
1899 probe)) {
1900 if (state.stopped)
1901 out.stopped = true;
1902 else
1903 state.failed = true;
1904 break;
1905 }
1906 const double side = energy_plus < energy_minus ? 1.0 : -1.0;
1907 const int before_leave = out.steps;
1908 out = endpoint_detail::relaxWithLbfgs(
1909 state, out.position + side * leave * direction, force_tolerance,
1910 max_steps, leave, std::max(reach, leave), vibrational, stop);
1911 out.steps += before_leave;
1912 if (out.stopped) break;
1913 spec = EndpointSpectrum{};
1914 }
1915 if (!spec.ok && !state.failed) spec = minimum_at(out.position);
1916 out.negative_remains = spec.ok && spec.lowest < -spec.resolution;
1917 return out;
1918 };
1919
1920 const int forward_before = state.calls;
1921 const auto forward = irc(1.0);
1922 report.forward_calls = state.calls - forward_before;
1923 const int reverse_before = state.calls;
1924 const auto reverse = irc(-1.0);
1925 report.reverse_calls = state.calls - reverse_before;
1926 report.calls = state.calls;
1927 report.unresolved = forward.stopped || reverse.stopped || state.stopped;
1928 if (state.failed || !forward.position.allFinite() ||
1929 !reverse.position.allFinite() || forward.position.size() != dof ||
1930 reverse.position.size() != dof) {
1931 if (report.unresolved) report.reported = true;
1932 return report;
1933 }
1934
1935 report.forward_force = forward.max_force;
1936 report.reverse_force = reverse.max_force;
1937 report.forward_steps = forward.steps;
1938 report.reverse_steps = reverse.steps;
1939 report.forward_position = forward.position;
1940 report.reverse_position = reverse.position;
1941 report.forward_energy = forward.energy;
1942 report.reverse_energy = reverse.energy;
1943 const auto match_started = std::chrono::steady_clock::now();
1944 report.forward_reactant =
1945 labelledRmsd(relaxed_reactant, forward.position, atomic_numbers);
1946 report.forward_product =
1947 labelledRmsd(relaxed_product, forward.position, atomic_numbers);
1948 report.reverse_reactant =
1949 labelledRmsd(relaxed_reactant, reverse.position, atomic_numbers);
1950 report.reverse_product =
1951 labelledRmsd(relaxed_product, reverse.position, atomic_numbers);
1953 permutationAwareRmsd(reactant, forward.position, atomic_numbers);
1955 permutationAwareRmsd(product, forward.position, atomic_numbers);
1957 permutationAwareRmsd(reactant, reverse.position, atomic_numbers);
1959 permutationAwareRmsd(product, reverse.position, atomic_numbers);
1961 forward.position, reverse.position, atomic_numbers);
1962 report.comparison_tolerance = force_tolerance;
1963 report.reported = true;
1964 report.ambiguous = forward.negative_remains || reverse.negative_remains;
1965 report.reactant_bonds = bondGraph(relaxed_reactant, atomic_numbers);
1966 report.product_bonds = bondGraph(relaxed_product, atomic_numbers);
1967 report.forward_bonds = bondGraph(forward.position, atomic_numbers);
1968 report.reverse_bonds = bondGraph(reverse.position, atomic_numbers);
1969 report.match_seconds = std::chrono::duration<double>(
1970 std::chrono::steady_clock::now() - match_started)
1971 .count();
1972 const bool forward_reactant_graph =
1973 report.forward_bonds == report.reactant_bonds &&
1974 report.forward_bonds != report.product_bonds;
1975 const bool forward_product_graph =
1976 report.forward_bonds == report.product_bonds &&
1977 report.forward_bonds != report.reactant_bonds;
1978 const bool reverse_reactant_graph =
1979 report.reverse_bonds == report.reactant_bonds &&
1980 report.reverse_bonds != report.product_bonds;
1981 const bool reverse_product_graph =
1982 report.reverse_bonds == report.product_bonds &&
1983 report.reverse_bonds != report.reactant_bonds;
1984 if (report.reactant_bonds == report.product_bonds) {
1985 report.graph_applicable = false;
1986 } else {
1987 report.graph_connected =
1988 !report.unresolved &&
1989 forward_reactant_graph != forward_product_graph &&
1990 reverse_reactant_graph != reverse_product_graph &&
1991 forward_reactant_graph != reverse_reactant_graph;
1992 }
1993 const auto matched = [&](const EndpointConnectivityReport& current) {
1994 const bool forward_reactant =
1995 insideEndpointBall(current.forward_reactant,
1996 current.forward_product, current.reactant_ball);
1997 const bool forward_product =
1998 insideEndpointBall(current.forward_product,
1999 current.forward_reactant, current.product_ball);
2000 const bool reverse_reactant =
2001 insideEndpointBall(current.reverse_reactant,
2002 current.reverse_product, current.reactant_ball);
2003 const bool reverse_product =
2004 insideEndpointBall(current.reverse_product,
2005 current.reverse_reactant, current.product_ball);
2006 const bool forward_one = forward_reactant != forward_product;
2007 const bool reverse_one = reverse_reactant != reverse_product;
2008 return forward_one && reverse_one &&
2009 forward_reactant != reverse_reactant;
2010 };
2011 report.ball_matched =
2012 !report.unresolved && report.ball_applicable && matched(report);
2013 // A conformer is another minimum of the same bond graph. The
2014 // half-separation ball rejects it. When the graphs differ, the
2015 // end is the endpoint's if it is a minimum and carries that graph.
2016 // Energy and the fixed-label distances above stay diagnostics.
2017 // Identical graphs cannot be assigned that way, so the balls decide.
2018 const bool minima = report.forward_force < force_tolerance &&
2019 report.reverse_force < force_tolerance;
2020 if (!report.graph_applicable) {
2021 report.connected = !report.unresolved && !report.ambiguous &&
2022 report.ball_matched && minima;
2023 } else {
2024 report.connected = !report.unresolved && !report.ambiguous && minima &&
2025 report.graph_connected;
2026 }
2027 call_bucket = &report.calls_energy;
2028 const auto energy_of = [&](const Eigen::VectorXd& position) {
2029 double energy = 0.0;
2030 Eigen::VectorXd gradient(dof);
2031 if (!state.oracle(position, energy, gradient))
2032 return std::numeric_limits<double>::quiet_NaN();
2033 return energy;
2034 };
2035 // Fill only energies the walk did not already take at that
2036 // geometry. A later oracle call can be refused by the wall, and
2037 // must not wipe an energy the accepted step recorded.
2038 if (!std::isfinite(report.reactant_energy))
2039 report.reactant_energy = energy_of(relaxed_reactant);
2040 if (!std::isfinite(report.product_energy))
2041 report.product_energy = energy_of(relaxed_product);
2042 if (!std::isfinite(report.forward_energy))
2043 report.forward_energy = energy_of(forward.position);
2044 if (!std::isfinite(report.reverse_energy))
2045 report.reverse_energy = energy_of(reverse.position);
2046 report.calls = state.calls;
2047 return report;
2048}
double labelledRmsd(const Eigen::VectorXd &reference, const Eigen::VectorXd &mobile, const std::vector< int > &atomic_numbers)
double permutationAwareRmsd(const Eigen::VectorXd &reference, const Eigen::VectorXd &mobile_in, const std::vector< int > &atomic_numbers)
EndpointSpectrum probeVibrationalMinimum(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const GradientAt &gradient_at, double stiff_floor=std::numeric_limits< double >::infinity())
Eigen::MatrixXd ircStencilDirections(const Eigen::VectorXd &center, const Eigen::VectorXd &masses, const Eigen::MatrixXd *held_directions, VibrationalStencil mode=VibrationalStencil::Full)
MeasuredIndexDecision decideMeasuredIndex(const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const Gradients &gradients, const Eigen::MatrixXd *measured=nullptr)
measured is analyzeStencilIndex's.
bool labelledEndpointsResolve(double separation, double harmonic_reactant, double harmonic_product) noexcept
EndpointSpectrum spectrumOfModelHessian(const Eigen::MatrixXd &raw, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double stiff_floor)
EndpointSpectrum spectrumAt(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> &gradient_at, double stiff_floor=std::numeric_limits< double >::infinity(), Eigen::MatrixXd *raw_columns=nullptr, const Eigen::MatrixXd *held_directions=nullptr)
double endpointMatchBall(double tolerance, double lambda_min, double half_separation) noexcept
Eigen::VectorXd projectOutRigidMotions(const Eigen::VectorXd &positions, Eigen::VectorXd displacement)
bool insideEndpointBall(double to_this, double to_other, double ball) noexcept
std::string bondGraph(const Eigen::VectorXd &positions, const std::vector< int > &atomic_numbers)
double forceNorm(const Eigen::MatrixBase< Derived > &force, ConvergenceNormType norm)
Definition ForceNorm.h:45

◆ requireMinimizationLayout()

void gpr::optim::requireMinimizationLayout ( )
inline

Definition at line 166 of file GPMinimizer.h.

167{
168 const std::string message = minimizationLayoutMismatch(
170 if (!message.empty()) throw std::runtime_error(message);
171}
std::string minimizationLayoutMismatch(const MinimizationLayoutStamp &driver, const MinimizationLayoutStamp &library)
MinimizationLayoutStamp libraryMinimizationLayout()
What libgpridge was built with. Defined in the library, not inline.

◆ restrictedPartitionedRfoStep()

RestrictedPartitionedRfoStep gpr::optim::restrictedPartitionedRfoStep ( const Eigen::VectorXd & curvatures,
const Eigen::VectorXd & gradient,
const Eigen::MatrixXd & cartesian_modes,
double radius )
inline

Restricted partitioned RFO on an ascending Hessian spectrum. rgsaddle_prfo_step mass-weights a Cartesian Hessian and brackets alpha by doubling and bisection. rgsaddle_trust_update is Sella's rho schedule. Neither is this secular problem on a supplied basis whose columns need not be orthonormal, so this walk does not call them and there is no second copy kept for a build without rgsaddle. Mode zero is maximized and its complement is minimized. The full-column- rank map cartesian_modes converts eigenbasis coefficients to Cartesian displacement; its columns need not be orthonormal. Both partitions share alpha = c^2, with c >= 1, and the Cartesian norm supplies the restriction.

Regular steps satisfy (D - mu I) s = -g and mu = c^2 g.s in each partition. A feasible pure step has c = 1. A binding step retains the feasible side of a continuous secular branch until the c bracket reaches floating-point resolution; no monotonicity of the Cartesian norm is required. An exact homogeneous hard case retains a boundary direction, rather than claiming a finite alpha resolves a vanishing affine coordinate. Scalar secular arithmetic uses the extended exponent range of long double. Targets where long double has only binary64 range can decline extreme inputs.

Definition at line 46 of file RestrictedPartitionedRfo.h.

49{
51 const Eigen::Index n = curvatures.size();
52 if (n < 2 || gradient.size() != n || cartesian_modes.cols() != n ||
53 cartesian_modes.rows() == 0 || !curvatures.allFinite() ||
54 !gradient.allFinite() || !cartesian_modes.allFinite() ||
55 !(radius > 0.0) || !std::isfinite(radius))
56 return out;
57 for (Eigen::Index k = 1; k < n; ++k)
58 if (curvatures(k) < curvatures(k - 1)) return out;
59
60 // Stable and direct Euclidean norms can round to adjacent values at
61 // the radius. The feasible bracket must satisfy both evaluations;
62 // the stable value also handles overflow in the direct sum of squares.
63 const auto cartesian_length = [](const Eigen::VectorXd &step) {
64 const double stable = step.stableNorm();
65 const double direct = step.norm();
66 return std::isfinite(direct) ? std::max(stable, direct) : stable;
67 };
68
69 const auto boundary_step = [&](Eigen::VectorXd direction) {
70 RestrictedPartitionedRfoStep result;
71 Eigen::VectorXd cartesian = cartesian_modes * direction;
72 double length = cartesian_length(cartesian);
73 if (!(length > 0.0) || !std::isfinite(length) || !cartesian.allFinite())
74 return result;
75 direction *= radius / length;
76 if (!direction.allFinite()) return result;
77 cartesian = cartesian_modes * direction;
78 length = cartesian_length(cartesian);
79 // Reconstruction is checked in the physical metric. A downward
80 // rounding of the radial factor keeps a boundary point feasible.
81 while (length > radius && std::isfinite(length)) {
82 const double factor = std::nextafter(radius / length, 0.0);
83 if (!(factor > 0.0 && factor < 1.0)) return result;
84 const Eigen::VectorXd smaller = direction * factor;
85 if ((smaller.array() == direction.array()).all()) return result;
86 direction = smaller;
87 cartesian = cartesian_modes * direction;
88 length = cartesian_length(cartesian);
89 }
90 if (!(length > 0.0 && length <= radius) || !direction.allFinite() ||
91 !cartesian.allFinite())
92 return result;
93 result.valid = true;
94 result.boundary = true;
95 result.hard_case = true;
96 result.eigen_step = std::move(direction);
97 result.cartesian_step = std::move(cartesian);
98 return result;
99 };
100
101 // A nonnegative maximized mode with zero gradient has no preferred
102 // affine displacement. Its canonical boundary direction also covers
103 // a flat selected mode without inventing a nonzero gradient.
104 if (gradient(0) == 0.0 && curvatures(0) >= 0.0)
105 return boundary_step(Eigen::VectorXd::Unit(n, 0));
106
107 struct Evaluation {
108 bool valid = false;
109 bool hard_case = false;
110 double length = std::numeric_limits<double>::infinity();
111 Eigen::VectorXd eigen_step;
112 Eigen::VectorXd cartesian_step;
113 Eigen::VectorXd hard_direction;
114 };
115
116 const auto evaluate = [&](double c) {
117 Evaluation value;
118 if (!(c >= 1.0) || !std::isfinite(c)) return value;
119
120 // The lowest arrowhead eigenvalue is mu = b_min - delta. Its
121 // positive gap solves a strictly increasing secular equation:
122 // delta - b_min = sum_i (c*g_i)^2 / (b_i - b_min + delta).
123 // Forming the gap directly retains tiny coupled negative modes
124 // without subtracting equal eigenvalues or deflating their coupling.
125 using Wide = long double;
126 const Wide minimum = static_cast<Wide>(curvatures(1));
127 std::vector<Wide> gaps(static_cast<std::size_t>(n - 1));
128 std::vector<Wide> coupling(static_cast<std::size_t>(n - 1));
129 Wide total_norm = 0.0L;
130 Wide minimum_norm = 0.0L;
131 bool coupled_minimum = false;
132 for (Eigen::Index k = 1; k < n; ++k) {
133 const auto i = static_cast<std::size_t>(k - 1);
134 gaps[i] = static_cast<Wide>(curvatures(k)) - minimum;
135 coupling[i] = static_cast<Wide>(c) * static_cast<Wide>(gradient(k));
136 if (!std::isfinite(coupling[i])) return value;
137 total_norm = std::hypot(total_norm, coupling[i]);
138 if (gaps[i] == 0.0L) {
139 minimum_norm = std::hypot(minimum_norm, coupling[i]);
140 if (gradient(k) != 0.0) coupled_minimum = true;
141 }
142 }
143 Eigen::VectorXd tail_step = Eigen::VectorXd::Zero(n - 1);
144 if (!(total_norm == 0.0L && minimum >= 0.0L)) {
145 if (!coupled_minimum) {
146 Wide at_zero = -minimum;
147 for (Eigen::Index k = 1; k < n; ++k) {
148 const auto i = static_cast<std::size_t>(k - 1);
149 if (gaps[i] > 0.0L)
150 at_zero -= coupling[i] * (coupling[i] / gaps[i]);
151 }
152 if (!std::isfinite(at_zero)) return value;
153 if (minimum < 0.0L && at_zero >= 0.0L) {
154 value.valid = true;
155 value.hard_case = true;
156 value.hard_direction = Eigen::VectorXd::Unit(n, 1);
157 return value;
158 }
159 }
160 // Omitting higher eigenspaces gives a lower gap bound; treating
161 // every denominator as delta gives an upper bound. The
162 // rationalized negative-curvature root avoids cancellation.
163 const auto gap_bound = [&](Wide norm) {
164 if (norm == 0.0L) return std::max(minimum, 0.0L);
165 const Wide root = std::hypot(0.5L * minimum, norm);
166 return minimum >= 0.0L
167 ? 0.5L * minimum + root
168 : (norm / (root - 0.5L * minimum)) * norm;
169 };
170 Wide lower_gap = gap_bound(minimum_norm);
171 Wide upper_gap = gap_bound(total_norm);
172 if (!(upper_gap >= lower_gap) || !std::isfinite(upper_gap))
173 return value;
174 if (!(upper_gap > 0.0L)) {
175 value.valid = true;
176 return value;
177 }
178 for (;;) {
179 Wide middle = lower_gap > 0.0L
180 ? std::sqrt(lower_gap) * std::sqrt(upper_gap)
181 : 0.5L * upper_gap;
182 if (!(middle > lower_gap && middle < upper_gap))
183 middle = lower_gap + 0.5L * (upper_gap - lower_gap);
184 if (!(middle > lower_gap && middle < upper_gap)) break;
185 Wide residual = middle - minimum;
186 for (Eigen::Index k = 1; k < n; ++k) {
187 const auto i = static_cast<std::size_t>(k - 1);
188 residual -=
189 coupling[i] * (coupling[i] / (gaps[i] + middle));
190 }
191 if (!std::isfinite(residual)) return value;
192 if (residual > 0.0L) {
193 upper_gap = middle;
194 } else if (residual < 0.0L) {
195 lower_gap = middle;
196 } else {
197 lower_gap = middle;
198 upper_gap = middle;
199 break;
200 }
201 }
202 for (Eigen::Index k = 1; k < n; ++k) {
203 const auto i = static_cast<std::size_t>(k - 1);
204 const Wide denominator = gaps[i] + upper_gap;
205 if (denominator == 0.0L && gradient(k) == 0.0) continue;
206 const Wide coefficient =
207 -static_cast<Wide>(gradient(k)) / denominator;
208 if (!std::isfinite(coefficient) ||
209 std::abs(coefficient) >
210 static_cast<Wide>(std::numeric_limits<double>::max())) {
211 value.valid = true;
212 return value;
213 }
214 tail_step(k - 1) = static_cast<double>(coefficient);
215 }
216 }
217
218 double up_head = 0.0;
219 double up_tail = 1.0;
220 if (gradient(0) != 0.0) {
221 const double b = curvatures(0) / c;
222 const double up_scale =
223 std::max(std::abs(b), std::abs(gradient(0)));
224 const double half_b = 0.5 * (b / up_scale);
225 const double g = gradient(0) / up_scale;
226 const double root = std::hypot(half_b, g);
227 if (curvatures(0) < 0.0) {
228 up_head = g;
229 up_tail = -half_b + root;
230 } else {
231 up_head = half_b + root;
232 up_tail = g;
233 }
234 const double up_norm =
235 std::max(std::abs(up_head), std::abs(up_tail));
236 up_head /= up_norm;
237 up_tail /= up_norm;
238 if (up_tail < 0.0) {
239 up_head = -up_head;
240 up_tail = -up_tail;
241 }
242 }
243 if (up_tail == 0.0) {
244 value.valid = true;
245 return value;
246 }
247 value.eigen_step.resize(n);
248 value.eigen_step(0) = up_head / (c * up_tail);
249 value.eigen_step.tail(n - 1) = tail_step;
250 value.valid = true;
251 // An unrepresentable affine step cannot supply a finite stored
252 // candidate; larger c is still tried.
253 if (!value.eigen_step.allFinite()) return value;
254 value.cartesian_step = cartesian_modes * value.eigen_step;
255 if (!value.cartesian_step.allFinite()) return value;
256 value.length = cartesian_length(value.cartesian_step);
257 return value;
258 };
259
260 Evaluation candidate = evaluate(1.0);
261 if (!candidate.valid) return out;
262 if (candidate.hard_case) return boundary_step(candidate.hard_direction);
263 if (candidate.length <= radius) {
264 if (!(candidate.length > 0.0)) return out;
265 out.valid = true;
266 out.eigen_step = std::move(candidate.eigen_step);
267 out.cartesian_step = std::move(candidate.cartesian_step);
268 return out;
269 }
270
271 double lower = 1.0;
272 double upper = 1.0;
273 Evaluation feasible;
274 for (;;) {
275 const double largest = std::numeric_limits<double>::max();
276 const double next = upper > largest / 2.0 ? largest : 2.0 * upper;
277 if (!(next > upper)) return out;
278 upper = next;
279 candidate = evaluate(upper);
280 if (!candidate.valid) return out;
281 if (candidate.hard_case) return boundary_step(candidate.hard_direction);
282 if (candidate.length <= radius) {
283 feasible = std::move(candidate);
284 break;
285 }
286 lower = upper;
287 }
288 for (;;) {
289 const double middle = lower + 0.5 * (upper - lower);
290 if (!(middle > lower && middle < upper)) break;
291 candidate = evaluate(middle);
292 if (!candidate.valid) return out;
293 if (candidate.hard_case) return boundary_step(candidate.hard_direction);
294 if (candidate.length <= radius) {
295 upper = middle;
296 feasible = std::move(candidate);
297 } else {
298 lower = middle;
299 }
300 }
301 if (!(feasible.length > 0.0 && feasible.length <= radius) ||
302 !feasible.eigen_step.allFinite() ||
303 !feasible.cartesian_step.allFinite())
304 return out;
305 out.valid = true;
306 out.boundary = true;
307 out.scaling = upper;
308 out.eigen_step = std::move(feasible.eigen_step);
309 out.cartesian_step = std::move(feasible.cartesian_step);
310 return out;
311}

◆ richardsonExtrapolate()

Eigen::VectorXd gpr::optim::richardsonExtrapolate ( const Eigen::VectorXd & at_h,
const Eigen::VectorXd & at_2h )
inline

Central-difference curvature measurements along a direction drop every even power of the displacement, so the separations h and 2h combine into an estimate exact through the quartic force term (scripts/derive_richardson_transverse_curvature.py, proofs/lean/GPRidge/RichardsonCurvature.lean): c_R = (4 c(h) - c(2h)) / 3, delta = (c(2h) - c(h)) / 3 = d h^2, where delta is the truncation term the single-separation estimate carried. The same combination applies entrywise to the measured Hessian actions the Rayleigh-Ritz curvatures are built from.

Definition at line 23 of file RichardsonCurvature.h.

25{
26 return (4.0 * at_h - at_2h) / 3.0;
27}

◆ richardsonForwardExtrapolate()

double gpr::optim::richardsonForwardExtrapolate ( double at_h,
double at_2h )
inlinenoexcept

One measured side only (the dimer axis: the midpoint and one image): the forward difference c_f(h) = (F(h) - F(0))/h carries c + b h + d h^2, and 2 c_f(h) - c_f(2h) = c - 2 d h^2 is exact through the quadratic force term; c_f(2h) - c_f(h) = b h + 3 d h^2 is the first-order truncation the single estimate carried.

Definition at line 105 of file RichardsonCurvature.h.

106{
107 return 2.0 * at_h - at_2h;
108}

◆ richardsonForwardTruncation()

double gpr::optim::richardsonForwardTruncation ( double at_h,
double at_2h )
inlinenoexcept

Definition at line 110 of file RichardsonCurvature.h.

111{
112 return at_2h - at_h;
113}

◆ richardsonTruncation()

Eigen::VectorXd gpr::optim::richardsonTruncation ( const Eigen::VectorXd & at_h,
const Eigen::VectorXd & at_2h )
inline

Definition at line 29 of file RichardsonCurvature.h.

31{
32 return (at_2h - at_h) / 3.0;
33}

◆ rotatedPositiveRestrictionLowerBound()

double gpr::optim::rotatedPositiveRestrictionLowerBound ( const Eigen::MatrixXd & block,
const Eigen::MatrixXd & errors,
const Eigen::MatrixXd & coupling,
const Eigen::VectorXd & tail,
double allowance )
inline

A second comparison bound in the eigenbasis of the weak block. For abs(D) <= E, and abs(U^T D U) <= abs(U)^T E abs(U); the complete tail coupling is bounded by C abs(U). The Gram defect accounts for a computed rotation that is not exactly orthogonal. All bounds remain conditional on E.

Definition at line 341 of file StencilIndex.h.

345{
346 const double unresolved = -std::numeric_limits<double>::infinity();
347 const Eigen::Index weak = block.rows();
348 const Eigen::Index dimension = weak + tail.size();
349 if (weak < 2) return unresolved;
350 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(block);
351 if (spectrum.info() != Eigen::Success) return unresolved;
352 const Eigen::MatrixXd rotation = spectrum.eigenvectors();
353 const Eigen::MatrixXd magnitude = rotation.cwiseAbs();
354 const Eigen::MatrixXd transformed = rotation.transpose() * block * rotation;
355 const Eigen::MatrixXd symmetric =
356 0.5 * (transformed + transformed.transpose());
357 const Eigen::MatrixXd envelope = magnitude.transpose() * errors * magnitude;
358 const Eigen::MatrixXd cross = coupling * magnitude;
359 Eigen::MatrixXd comparison = Eigen::MatrixXd::Zero(dimension, dimension);
360 comparison.topLeftCorner(weak, weak) = -symmetric.cwiseAbs() - envelope;
361 comparison.diagonal().head(weak) =
362 symmetric.diagonal() - envelope.diagonal();
363 comparison.bottomLeftCorner(tail.size(), weak) = -cross;
364 comparison.topRightCorner(weak, tail.size()) = -cross.transpose();
365 comparison.diagonal().tail(tail.size()) = tail;
366 const double roundoff =
367 64.0 * std::numeric_limits<double>::epsilon() * dimension;
368 const double gram_defect = (rotation.transpose() * rotation -
369 Eigen::MatrixXd::Identity(weak, weak))
370 .norm() +
371 roundoff * magnitude.squaredNorm();
372 if (!(gram_defect < 1.0) || !comparison.allFinite()) return unresolved;
373 const double scale =
374 (magnitude.transpose() * (block.cwiseAbs() + errors) * magnitude)
375 .norm() +
376 cross.norm() + comparison.norm();
377 // Congruence also transports the original roundoff perturbation.
378 const double rotated_allowance =
379 (1.0 + gram_defect) * allowance + roundoff * scale;
380 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> lower(
381 comparison, Eigen::EigenvaluesOnly);
382 if (lower.info() != Eigen::Success) return unresolved;
383 const double bound = lower.eigenvalues()(0) - rotated_allowance;
384 return bound / (bound >= 0.0 ? 1.0 + gram_defect : 1.0 - gram_defect);
385}

◆ runForceStopCertificate()

template<typename Measure, typename Refine>
ForceStopCertificateResult gpr::optim::runForceStopCertificate ( Measure measure,
Refine refine,
ForceStopStencilPlan plan,
const ForceStopMeasurement * prior = nullptr )

One certificate for every search. measure reads one stencil at the stopped geometry. refine moves only along the soft modes of a higher-order stencil. It returns a negative value when it cannot, forceStopRefinementStillHigher() when the low modes are still higher-order and a full stencil would only repeat that, forceStopRefinementCertified() when the walk reached an index-one point inside the force tolerance, and a positive call count when the point has to be measured again. A higher-order result that survives that walk sets needs_min_mode_escape. The force loop is not resumed. A following saddle defers the stencil. A prior measurement at this geometry is the hand-off: its columns are not requested again, and an inconclusive or higher-order reading is given to that saddle.

Definition at line 1304 of file StencilIndex.h.

1307{
1309 out.resume_force_loop = plan.resume_force_loop;
1310 const auto finish = [&]() {
1311 out.needs_min_mode_escape =
1312 out.measured && out.higher_order && !out.certified && !out.hand_off;
1313 return out;
1314 };
1315 const bool have_prior =
1316 plan.reuse_columns && prior != nullptr && prior->measured;
1317 if (plan.defer_certificate && !have_prior) {
1318 out.deferred_to_following_stage = true;
1319 out.hand_off = true;
1320 return out;
1321 }
1322 bool measure_now = true;
1323 for (int pass = 0;; ++pass) {
1324 if (measure_now) {
1325 ForceStopMeasurement got;
1326 if (pass == 0 && have_prior) {
1327 const bool inconclusive = prior->measured &&
1328 !prior->first_order &&
1329 !prior->higher_order;
1330 const bool hand_reading =
1331 plan.hand_off &&
1332 (inconclusive || prior->higher_order || prior->first_order);
1333 // The stored columns are the measurement. A final stage
1334 // whose prior is only unresolved still asks `measure` for
1335 // new displacements; that callback must not repeat these
1336 // columns.
1337 if (hand_reading || prior->first_order || prior->higher_order) {
1338 got = *prior;
1339 got.calls = 0;
1340 out.reused_columns = true;
1341 } else if (plan.measure_stencil) {
1342 got = measure();
1343 out.reused_columns = true;
1344 } else {
1345 got = *prior;
1346 got.calls = 0;
1347 out.reused_columns = true;
1348 }
1349 } else {
1350 if (!plan.measure_stencil && pass == 0) return finish();
1351 got = measure();
1352 }
1353 out.measured = got.measured;
1354 out.higher_order = got.higher_order;
1355 out.first_order =
1356 got.measured && got.first_order && !got.higher_order;
1357 out.measurements += 1;
1358 out.calls += got.calls;
1359 if (pass == 0) out.handed = got;
1360 const bool inconclusive =
1361 got.measured && !out.first_order && !out.higher_order;
1362 if (plan.hand_off && pass == 0 && have_prior &&
1363 (inconclusive || got.higher_order)) {
1364 out.hand_off = true;
1365 out.certified = false;
1366 out.handed = got;
1367 out.handed.calls = 0;
1368 return finish();
1369 }
1370 if (forceStopStencilCertifies(got.measured, out.first_order)) {
1371 out.certified = true;
1372 return finish();
1373 }
1374 }
1375 measure_now = true;
1376 const bool refine_now = plan.refine_soft_modes && out.measured &&
1377 out.higher_order &&
1379 if (!refine_now) return finish();
1380 const int spent = refine();
1381 if (spent == forceStopRefinementStillHigher()) {
1382 out.soft_refinements += 1;
1383 out.measured = true;
1384 out.higher_order = true;
1385 out.first_order = false;
1386 out.certified = false;
1387 measure_now = false;
1388 continue;
1389 }
1390 if (spent < 0) return finish();
1391 out.soft_refinements += 1;
1392 if (spent == forceStopRefinementCertified()) {
1393 out.certified = true;
1394 out.first_order = true;
1395 out.higher_order = false;
1396 return finish();
1397 }
1398 out.calls += spent;
1399 }
1400}
constexpr int forceStopRefinementCertified() noexcept
constexpr int forceStopSoftRefinementLimit() noexcept
bool forceStopStencilCertifies(bool measured, bool first_order) noexcept
constexpr int forceStopRefinementStillHigher() noexcept
Panel finish(Real left, Real right, const Value &k, const Value &g, const Value &absolute)
bool defer_certificate
Do not measure. The following saddle certifies the point it reaches.

◆ sameStencilGeometry()

bool gpr::optim::sameStencilGeometry ( const Eigen::VectorXd & first,
const Eigen::VectorXd & second )
inlinenoexcept

Two geometries share one stencil when a later request has not moved.

Definition at line 1175 of file StencilIndex.h.

1177{
1178 if (first.size() == 0 || first.size() != second.size() ||
1179 !first.allFinite() || !second.allFinite())
1180 return false;
1181 return (first - second).norm() <=
1182 1e-8 * (1.0 + std::max(first.norm(), second.norm()));
1183}

◆ secantFittedToResidual()

template<class Prior>
SecantHessian gpr::optim::secantFittedToResidual ( SecantHessianMethod method,
const std::vector< SecantForceSample > & samples,
Prior && prior )
nodiscard

Fit q to (E - m, F - grad m). prior writes the exact prior energy and Cartesian gradient at a geometry. The returned secant is the production residual quadratic.

Definition at line 376 of file SecantCurvature.h.

379{
380 SecantHessian secant(method);
382 for (const SecantForceSample& sample: samples) {
383 double prior_energy = 0.0;
384 Eigen::VectorXd prior_gradient;
385 prior(sample.position, prior_energy, prior_gradient);
386 if (!std::isfinite(prior_energy) ||
387 prior_gradient.size() != sample.gradient.size() ||
388 !prior_gradient.allFinite())
389 throw std::runtime_error(
390 "secant quadratic mean requires a finite prior gradient");
391 recordSecantObservation(secant, sample.position,
392 sample.gradient - prior_gradient,
393 sample.energy - prior_energy, counts);
394 }
395 return secant;
396}
void recordSecantObservation(SecantHessian &secant, const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, double energy, SecantCurvatureCounts &counts, SecantAccounting accounting=SecantAccounting::Count)

◆ secantNewtonFactor()

SecantNewtonFactor gpr::optim::secantNewtonFactor ( const SecantHessian & secant)
inlinenodiscard

Definition at line 200 of file SecantCurvature.h.

202{
204 if (!secant.available()) return out;
205 const Eigen::MatrixXd symmetric =
206 0.5 * (secant.hessian() + secant.hessian().transpose());
207 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(
208 symmetric, Eigen::EigenvaluesOnly);
209 if (spectrum.info() != Eigen::Success ||
210 !spectrum.eigenvalues().allFinite()) {
212 return out;
213 }
214 const double scale = spectrum.eigenvalues().cwiseAbs().maxCoeff();
215 if (!(scale > 0.0)) {
217 return out;
218 }
219 if (!(spectrum.eigenvalues().minCoeff() >
220 scale * std::sqrt(std::numeric_limits<double>::epsilon()))) {
222 return out;
223 }
224 out.factor.compute(symmetric);
225 out.status = out.factor.info() == Eigen::Success
228 return out;
229}
bool available() const noexcept
const Eigen::MatrixXd & hessian() const noexcept

◆ secantPositiveInverseScale()

std::optional< double > gpr::optim::secantPositiveInverseScale ( const SecantHessian & secant)
inline

Inverse curvature 1 / (u^T H u) along the latest accepted step, when that curvature is positive. Empty means the secant does not define a descent scale.

Definition at line 179 of file SecantCurvature.h.

181{
182 if (!secant.available()) return std::nullopt;
183 const Eigen::VectorXd& step = secant.lastDirection();
184 const double ss = step.squaredNorm();
185 if (!(ss > 0.0) || !step.allFinite()) return std::nullopt;
186 const double curvature = step.dot(secant.hessian() * step) / ss;
187 if (!(curvature > 0.0) || !std::isfinite(curvature)) return std::nullopt;
188 return 1.0 / curvature;
189}
const Eigen::VectorXd & lastDirection() const noexcept

◆ secantResolvedNegativeMode()

std::optional< Eigen::VectorXd > gpr::optim::secantResolvedNegativeMode ( const SecantHessian & secant)
inline

Lowest Ritz vector of the secant Hessian on the measured-step span when its Ritz value is a resolved negative curvature. Curvature outside that span is not measured; in particular, a one-step Bofill update from zero can create a spurious negative eigenvalue on a convex surface. Empty when the secant has no accepted pair or the projection resolves no negative mode.

Definition at line 107 of file SecantCurvature.h.

109{
110 if (!secant.available()) return std::nullopt;
111 const Eigen::MatrixXd& basis = secant.measuredSteps();
112 if (basis.rows() != secant.hessian().rows() || basis.cols() == 0)
113 return std::nullopt;
114 const Eigen::MatrixXd projected =
115 basis.transpose() * secant.hessian() * basis;
116 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(
117 0.5 * (projected + projected.transpose()));
118 if (spectrum.info() != Eigen::Success ||
119 !spectrum.eigenvalues().allFinite() ||
120 !spectrum.eigenvectors().allFinite())
121 throw std::runtime_error("secant curvature seed eigensolve failed");
122 const double scale = spectrum.eigenvalues().cwiseAbs().maxCoeff();
123 const double tolerance =
124 scale * std::sqrt(std::numeric_limits<double>::epsilon());
125 if (!(spectrum.eigenvalues()(0) < -tolerance)) return std::nullopt;
126 Eigen::VectorXd mode = basis * spectrum.eigenvectors().col(0);
127 const double norm = mode.norm();
128 if (!(norm > 0.0) || !std::isfinite(norm))
129 throw std::runtime_error("secant curvature seed mode is degenerate");
130 mode /= norm;
131 return mode;
132}
const Eigen::MatrixXd & measuredSteps() const noexcept

◆ secantSeedDirection()

SecantSeed gpr::optim::secantSeedDirection ( const SecantHessian & secant,
const Eigen::VectorXd & current_direction )
inlinenodiscard

Definition at line 144 of file SecantCurvature.h.

146{
147 SecantSeed seed;
148 const double norm = current_direction.norm();
149 const bool usable = current_direction.size() > 0 &&
150 current_direction.allFinite() && norm > 0.0 &&
151 std::isfinite(norm);
152 if (usable) seed.direction = current_direction / norm;
153 if (!secant.available()) {
155 return seed;
156 }
157 if (!usable) {
159 return seed;
160 }
161 if (seed.direction.size() != secant.hessian().rows()) {
163 return seed;
164 }
165 std::optional<Eigen::VectorXd> mode = secantResolvedNegativeMode(secant);
166 if (!mode) {
168 return seed;
169 }
170 if (mode->dot(seed.direction) < 0.0) *mode *= -1.0;
171 seed.direction = std::move(*mode);
173 return seed;
174}
std::optional< Eigen::VectorXd > secantResolvedNegativeMode(const SecantHessian &secant)
Eigen::VectorXd direction
SecantSeedStatus status

◆ secantSeedStatusName()

const char * gpr::optim::secantSeedStatusName ( SecantSeedStatus status)
inlinenodiscardnoexcept

Definition at line 81 of file SecantCurvature.h.

83{
84 switch (status) {
86 return "seeded";
88 return "no accepted pair";
90 return "secant and model dimensions differ";
92 return "no resolved curvature";
94 return "no usable current direction";
96 return "not positive definite";
97 }
98 return "unknown";
99}

◆ seedHessianFromSecant()

SecantSeedStatus gpr::optim::seedHessianFromSecant ( Eigen::MatrixXd & model,
const SecantHessian & secant,
const Eigen::MatrixXd & weight,
SecantSeedSupport support = SecantSeedSupport::WholeHessian )
inlinenodiscard

Seed model from secant, whose Hessian is first weighted entry by entry by weight (the mass weighting the model lives in). Refuses, leaving model unchanged, when the secant has no accepted pair or was measured in another dimension.

support picks the part of the weighted Hessian that is taken. A MeasuredSteps seed projects onto the measured steps in the weighted coordinates: weight is the outer product w w^T of the coordinate scale w (M^{-1/2} for a mass weighting), so a Cartesian step s becomes s / w. The two agree only when w is constant. In that mode the diagonal of weight must be positive and finite, otherwise std::invalid_argument is thrown.

Definition at line 342 of file SecantCurvature.h.

346{
347 if (!secant.available()) return SecantSeedStatus::NoAcceptedPair;
348 if (secant.hessian().rows() != model.rows() ||
349 weight.rows() != model.rows() || weight.cols() != model.cols())
351 const Eigen::MatrixXd weighted = secant.hessian().cwiseProduct(weight);
352 if (support == SecantSeedSupport::WholeHessian)
353 return seedHessianOnSecantRange(model, weighted);
354 const Eigen::VectorXd diagonal = weight.diagonal();
355 if (!(diagonal.array() > 0.0).all() || !diagonal.allFinite())
356 throw std::invalid_argument(
357 "measured-step secant seed requires a positive coordinate weight");
358 const Eigen::MatrixXd steps =
359 (secant.measuredSteps().array().colwise() / diagonal.array().sqrt())
360 .matrix();
361 return seedHessianOnMeasuredStepRange(model, weighted, steps);
362}
SecantSeedStatus seedHessianOnSecantRange(Eigen::MatrixXd &model, const Eigen::MatrixXd &secant_hessian)
SecantSeedStatus seedHessianOnMeasuredStepRange(Eigen::MatrixXd &model, const Eigen::MatrixXd &secant_hessian, const Eigen::MatrixXd &measured_steps)

◆ seedHessianOnMeasuredStepRange()

SecantSeedStatus gpr::optim::seedHessianOnMeasuredStepRange ( Eigen::MatrixXd & model,
const Eigen::MatrixXd & secant_hessian,
const Eigen::MatrixXd & measured_steps )
inlinenodiscard

As above, but only on the Ritz pairs of secant_hessian projected onto the span of measured_steps. Curvature outside that span is not evidence for modifying the model. The tolerance is relative to the largest projected magnitude. measured_steps must be expressed in the coordinates of model and secant_hessian.

Definition at line 305 of file SecantCurvature.h.

308{
309 if (model.rows() == 0 || model.rows() != model.cols() ||
310 secant_hessian.rows() != model.rows() ||
311 secant_hessian.cols() != model.cols() || !model.allFinite() ||
312 !secant_hessian.allFinite() || measured_steps.rows() != model.rows() ||
313 !measured_steps.allFinite())
314 throw std::invalid_argument(
315 "secant curvature seed requires matching finite Hessians and "
316 "steps");
317 if (measured_steps.cols() == 0)
319 const Eigen::ColPivHouseholderQR<Eigen::MatrixXd> step_qr(measured_steps);
320 const Eigen::Index rank = step_qr.rank();
321 if (rank == 0) return SecantSeedStatus::NoResolvedCurvature;
322 const Eigen::MatrixXd basis =
323 step_qr.householderQ() * Eigen::MatrixXd::Identity(model.rows(), rank);
324 const Eigen::MatrixXd symmetric =
325 0.5 * (secant_hessian + secant_hessian.transpose());
326 const Eigen::MatrixXd projected = basis.transpose() * symmetric * basis;
327 return detail::seedModelOnRitzSpan(
328 model, 0.5 * (projected + projected.transpose()), &basis);
329}

◆ seedHessianOnSecantRange()

SecantSeedStatus gpr::optim::seedHessianOnSecantRange ( Eigen::MatrixXd & model,
const Eigen::MatrixXd & secant_hessian )
inlinenodiscard

Replace model on the range of secant_hessian with that Hessian's action and leave the orthogonal complement unchanged. An eigenvalue is in the range when its magnitude exceeds the square root of epsilon times the largest magnitude, so the criterion has no units. A secant with no such eigenvalue carries no curvature to seed, and model stays as it is.

Definition at line 286 of file SecantCurvature.h.

288{
289 if (model.rows() == 0 || model.rows() != model.cols() ||
290 secant_hessian.rows() != model.rows() ||
291 secant_hessian.cols() != model.cols() || !model.allFinite() ||
292 !secant_hessian.allFinite())
293 throw std::invalid_argument(
294 "secant curvature seed requires matching finite Hessians");
295 const Eigen::MatrixXd symmetric =
296 0.5 * (secant_hessian + secant_hessian.transpose());
297 return detail::seedModelOnRitzSpan(model, symmetric, nullptr);
298}

◆ setBofillRgsaddleLibrary()

void gpr::optim::setBofillRgsaddleLibrary ( const char * path)

Records the index-test choice before the first Bofill call. The update uses the linked library, so the path is not opened. Null or empty clears the recorded choice.

Definition at line 423 of file RgsaddleClient.cpp.

424{
425 bofillLibraryOverride() = path == nullptr ? std::string() : path;
426}

◆ smoothMeasuredCurvature()

SmoothedCurvatureSpectrum gpr::optim::smoothMeasuredCurvature ( const Eigen::MatrixXd & prior,
const std::vector< MeasuredHessianColumn > & columns,
const SmoothedCurvatureSpectrum * previous = nullptr,
const linalg::MpiContext & context = linalg::MpiContext::local() )
inline

Condition measured Hessian columns, then distribute independent spectrum samples over the supplied process group. Local contexts enter no MPI.

Definition at line 716 of file SmoothedCurvatureSpectrum.h.

721{
722 auto prepared = detail::prepareSmoothedCurvature(prior, columns, previous);
723 double failed = prepared.valid ? 0.0 : 1.0;
724 linalg::ordered_sum_bcast(&failed, 1, context);
725 if (failed != 0.0) return {};
726 auto out = std::move(prepared.spectrum);
727 const Eigen::Index d = prior.rows();
728 const Eigen::Index entries = prepared.precision.size();
729 const auto& H = prepared.mean;
730 const auto& precision = prepared.precision;
731 const auto& posterior = prepared.posterior;
732 const auto& floor_posterior = prepared.floor_posterior;
733 // Posterior of the sorted eigenvalues from correlated Gaussian matrix
734 // samples around the posterior mean. The spreads describe posterior
735 // uncertainty; their Monte Carlo estimation error is separate.
736 const Eigen::Index samples = detail::kSpectrumSamples;
737 // Saved stream states reproduce the serial draws without storing an
738 // entries-by-samples noise matrix. Each callback owns its random state.
739 struct RandomState {
740 std::mt19937_64 engine{0x5eedu};
741 std::normal_distribution<double> normal;
742 };
743 RandomState stream;
744 std::vector<RandomState> streams;
745 streams.reserve(samples);
746 for (Eigen::Index n = 0; n < samples; ++n) {
747 streams.push_back(stream);
748 for (Eigen::Index j = 0; j < entries + d; ++j)
749 (void)stream.normal(stream.engine);
750 }
751 Eigen::MatrixXd drawn = Eigen::MatrixXd::Zero(samples, d);
752 Eigen::MatrixXd drawn_floor = drawn, drawn_measured = drawn;
753 Eigen::VectorXi owned = Eigen::VectorXi::Zero(samples);
754 const auto sample = [&](int n) {
755 auto random = streams[static_cast<std::size_t>(n)];
756 Eigen::VectorXd entry_noise(entries), latent_noise(d);
757 for (Eigen::Index j = 0; j < entries; ++j)
758 entry_noise(j) = random.normal(random.engine);
759 for (Eigen::Index k = 0; k < d; ++k)
760 latent_noise(k) = random.normal(random.engine);
761 Eigen::MatrixXd perturbed(d, d);
762 const Eigen::VectorXd draw =
763 posterior.independent_deviation.cwiseProduct(entry_noise) +
764 posterior.correlated_factor * latent_noise;
765 const Eigen::VectorXd floor_draw =
766 floor_posterior.independent_deviation.cwiseProduct(entry_noise) +
767 floor_posterior.correlated_factor * latent_noise;
768 for (int pass = 0; pass < 3; ++pass) {
769 const Eigen::VectorXd& delta = pass == 1 ? floor_draw : draw;
770 perturbed = H;
771 Eigen::Index entry = 0;
772 for (Eigen::Index a = 0; a < d; ++a)
773 for (Eigen::Index b = a; b < d; ++b) {
774 if (pass != 2 || precision(entry) > 0.0)
775 perturbed(a, b) += delta(entry);
776 perturbed(b, a) = perturbed(a, b);
777 ++entry;
778 }
779 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> sampled(
780 perturbed, Eigen::EigenvaluesOnly);
781 if (sampled.info() != Eigen::Success ||
782 !sampled.eigenvalues().allFinite())
783 return std::numeric_limits<double>::quiet_NaN();
784 (pass == 0 ? drawn
785 : pass == 1 ? drawn_floor
786 : drawn_measured)
787 .row(n) = sampled.eigenvalues().transpose();
788 }
789 owned(n) = 1;
790 return 1.0;
791 };
792 const auto status = linalg::ProbeExecutor{}.run(
793 static_cast<int>(samples), sample,
795 if (!status.allFinite()) return out;
796 out.local_samples = owned.sum();
797 linalg::disjoint_sum_bcast(drawn.data(), static_cast<int>(drawn.size()),
798 context);
799 linalg::disjoint_sum_bcast(drawn_floor.data(),
800 static_cast<int>(drawn_floor.size()), context);
801 linalg::disjoint_sum_bcast(drawn_measured.data(),
802 static_cast<int>(drawn_measured.size()),
803 context);
804 out.curvatures = drawn.colwise().mean().transpose();
805 out.spreads.resize(d);
806 out.floors.resize(d);
807 out.measured_spreads.resize(d);
808 const Eigen::VectorXd floor_mean = drawn_floor.colwise().mean().transpose();
809 const Eigen::VectorXd measured_mean =
810 drawn_measured.colwise().mean().transpose();
811 const auto deviation = [&](const Eigen::MatrixXd& rows, Eigen::Index k,
812 double mean) {
813 return std::sqrt((rows.col(k).array() - mean).square().sum() /
814 static_cast<double>(samples - 1));
815 };
816 for (Eigen::Index k = 0; k < d; ++k) {
817 out.spreads(k) = deviation(drawn, k, out.curvatures(k));
818 out.floors(k) = deviation(drawn_floor, k, floor_mean(k));
819 out.measured_spreads(k) =
820 deviation(drawn_measured, k, measured_mean(k));
821 }
822 out.valid = out.modes.allFinite() && out.spreads.allFinite() &&
823 out.floors.allFinite() && out.measured_spreads.allFinite();
824 return out;
825}
void disjoint_sum_bcast(double *data, int count, const MpiContext &context)
void ordered_sum_bcast(double *data, int count, const MpiContext &context)

◆ softestUnmeasuredDirection()

Eigen::VectorXd gpr::optim::softestUnmeasuredDirection ( const SmoothedCurvatureSpectrum & spectrum)
inline

The softest direction of the posterior mean restricted to the unmeasured complement, normalized; empty when nothing is unmeasured.

Definition at line 882 of file SmoothedCurvatureSpectrum.h.

884{
885 if (!spectrum.valid) return {};
886 const Eigen::Index d = spectrum.hessian.rows();
887 const Eigen::Index m = spectrum.measured_span.cols();
888 if (m >= d) return {};
889 // Orthonormal complement of the measured span.
890 Eigen::MatrixXd Q = Eigen::MatrixXd::Identity(d, d);
891 {
892 const Eigen::HouseholderQR<Eigen::MatrixXd> qr(spectrum.measured_span);
893 Q = qr.householderQ() * Q;
894 }
895 const Eigen::MatrixXd complement = Q.rightCols(d - m);
896 const Eigen::MatrixXd block =
897 complement.transpose() * spectrum.hessian * complement;
898 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(
899 0.5 * (block + block.transpose()));
900 if (solver.info() != Eigen::Success) return {};
901 Eigen::VectorXd direction = complement * solver.eigenvectors().col(0);
902 for (int pass = 0; pass < 2; ++pass)
903 direction -= spectrum.measured_span *
904 (spectrum.measured_span.transpose() * direction).eval();
905 const double norm = direction.norm();
906 if (!(norm > 0.0)) return {};
907 return direction / norm;
908}

◆ spectralResidualStep()

Eigen::VectorXd gpr::optim::spectralResidualStep ( const Eigen::VectorXd & eigenvalues,
const Eigen::MatrixXd & modes,
const Eigen::VectorXd & gradient,
double radius )
inline

Minimize ||g + H s||^2 within a Euclidean trust radius on a supplied orthonormal Hessian spectrum. The normal equations give s_i = -lambda_i g_i / (lambda_i^2 + shift), with shift >= 0. This is a local force-root proposal; the measured saddle index decides whether a converged root belongs to the saddle search.

Definition at line 17 of file SpectralResidualStep.h.

21{
22 if (eigenvalues.size() == 0 || modes.cols() != eigenvalues.size() ||
23 modes.rows() != gradient.size() || !eigenvalues.allFinite() ||
24 !modes.allFinite() || !gradient.allFinite() || !(radius > 0.0) ||
25 !std::isfinite(radius))
26 return {};
27 const double scale = eigenvalues.cwiseAbs().maxCoeff();
28 if (!(scale > 0.0)) return {};
29 const Eigen::VectorXd values = eigenvalues / scale;
30 const Eigen::VectorXd projected = (modes.transpose() * gradient) / scale;
31 if (!projected.allFinite()) return {};
32 const Eigen::VectorXd numerator = -values.cwiseProduct(projected);
33 const auto coefficients = [&](double shift) -> Eigen::VectorXd {
34 Eigen::VectorXd result = Eigen::VectorXd::Zero(values.size());
35 for (Eigen::Index i = 0; i < values.size(); ++i) {
36 if (values(i) == 0.0) continue;
37 // The unshifted quotient avoids squaring a small eigenvalue.
38 result(i) = shift == 0.0
39 ? -projected(i) / values(i)
40 : numerator(i) / (values(i) * values(i) + shift);
41 }
42 return result;
43 };
44 Eigen::VectorXd step = coefficients(0.0);
45 if (!(step.stableNorm() <= radius)) {
46 double lower = 0.0;
47 double upper = numerator.stableNorm() / radius;
48 if (!(upper > 0.0) || !std::isfinite(upper)) return {};
49 // This upper bound gives ||s|| <= ||numerator|| / upper = radius.
50 // Retain the feasible side of the monotone secular equation.
51 step = coefficients(upper);
52 for (;;) {
53 const double middle = lower + 0.5 * (upper - lower);
54 if (!(middle > lower && middle < upper)) break;
55 Eigen::VectorXd trial = coefficients(middle);
56 const double norm = trial.stableNorm();
57 if (norm > radius) {
58 lower = middle;
59 } else {
60 upper = middle;
61 step = std::move(trial);
62 if (radius - norm <=
63 8.0 * std::numeric_limits<double>::epsilon() * radius)
64 break;
65 }
66 }
67 }
68 Eigen::VectorXd cartesian = modes * step;
69 if (!cartesian.allFinite() || !(cartesian.stableNorm() > 0.0)) return {};
70 return cartesian;
71}

◆ spectralTrustRegionStep()

SpectralTrustRegionStep gpr::optim::spectralTrustRegionStep ( const Eigen::VectorXd & curvatures,
const Eigen::MatrixXd & modes,
Eigen::Index mode_index,
const Eigen::VectorXd & force,
double radius,
const std::vector< std::pair< Eigen::VectorXd, double > > & measured_negative )
inline

The exact trust-region minimizer (More and Sorensen 1983) of the modified quadratic model m(s) = -F.s + s^T M s / 2 with M = sum_k mu_k q_k q_k^T on the eigenbasis ~modes~ (columns) with ~curvatures~, the selected curvature reversed (Banerjee 1985; Baker 1986). A transverse mode with nonpositive curvature has no minimizer and is left out unless a direction in ~measured_negative~ (Cartesian direction, measured curvature) covers it by majority overlap, in which case its measured curvature enters and the step descends along it to the boundary. The Levenberg shift is solved on the secular equation so the step lies within ~radius~.

Definition at line 45 of file SpectralTrustRegion.h.

49{
51 const Eigen::Index m = curvatures.size();
52 if (m == 0 || modes.cols() != m || modes.rows() != force.size() ||
53 mode_index < 0 || mode_index >= m || !(radius > 0.0) ||
54 !std::isfinite(radius) || !force.allFinite() ||
55 !(curvatures(mode_index) < 0.0))
56 return out;
57 Eigen::VectorXd mu = curvatures;
58 mu(mode_index) = -mu(mode_index);
59 Eigen::VectorXd c = modes.transpose() * force;
60 c(mode_index) = -c(mode_index);
61 if (!c.allFinite()) return out;
62 double requested_residual = -1.0;
63 for (Eigen::Index k = 0; k < m; ++k) {
64 if (k == mode_index || mu(k) > 0.0) {
65 out.kept_residual_sq += c(k) * c(k);
66 continue;
67 }
68 bool measured = false;
69 for (const auto& [direction, measured_curvature]: measured_negative) {
70 if (direction.size() != modes.rows()) continue;
71 const double overlap = direction.dot(modes.col(k));
72 if (overlap * overlap > 0.5 * direction.squaredNorm()) {
73 mu(k) = measured_curvature;
74 measured = true;
75 break;
76 }
77 }
78 if (measured) {
79 out.kept_residual_sq += c(k) * c(k);
80 if (c(k) != 0.0) out.descends_measured = true;
81 continue;
82 }
83 out.flat_residual_sq += c(k) * c(k);
84 if (std::abs(c(k)) > requested_residual) {
85 out.request = k;
86 requested_residual = std::abs(c(k));
87 }
88 c(k) = 0.0;
89 mu(k) = 0.0;
90 ++out.flat;
91 }
92 Eigen::Index minimum_mode;
93 const double mu_min = mu.minCoeff(&minimum_mode);
94 const double sigma_floor = std::max(0.0, -mu_min);
95 auto step_norm = [&](double sigma) {
96 double sum = 0.0;
97 for (Eigen::Index k = 0; k < m; ++k) {
98 const double d = mu(k) + sigma;
99 if (!(d > 0.0)) {
100 if (c(k) != 0.0) return std::numeric_limits<double>::infinity();
101 continue;
102 }
103 sum += (c(k) / d) * (c(k) / d);
104 }
105 return std::sqrt(sum);
106 };
107 double sigma = sigma_floor;
108 double length = step_norm(sigma);
109 if (!(length <= radius)) {
110 // Newton on 1/|s(sigma)| - 1/radius, monotone and nearly linear
111 // in sigma; bisection safeguards the bracket.
112 double lower = sigma_floor;
113 double upper = sigma_floor + c.norm() / radius;
114 while (step_norm(upper) > radius)
115 upper = 2.0 * upper + c.norm() / radius;
116 sigma = upper;
117 for (int iteration = 0; iteration < 200; ++iteration) {
118 const double s_norm = step_norm(sigma);
119 if (std::isfinite(s_norm) && s_norm > 0.0) {
120 double derivative = 0.0;
121 for (Eigen::Index k = 0; k < m; ++k) {
122 const double d = mu(k) + sigma;
123 if (d > 0.0) derivative += (c(k) * c(k)) / (d * d * d);
124 }
125 derivative /= (s_norm * s_norm * s_norm);
126 const double phi = 1.0 / s_norm - 1.0 / radius;
127 if (std::abs(phi) * radius <= 1.0e-10) break;
128 if (s_norm > radius)
129 lower = sigma;
130 else
131 upper = sigma;
132 double next = sigma - phi / derivative;
133 if (!(next > lower) || !(next < upper) || !std::isfinite(next))
134 next = 0.5 * (lower + upper);
135 sigma = next;
136 } else {
137 lower = sigma;
138 sigma = 0.5 * (lower + upper);
139 }
140 if (upper - lower <= 1.0e-14 * std::max(1.0, upper)) break;
141 }
142 length = step_norm(sigma);
143 }
144 Eigen::VectorXd step = Eigen::VectorXd::Zero(modes.rows());
145 for (Eigen::Index k = 0; k < m; ++k) {
146 const double d = mu(k) + sigma;
147 if (d > 0.0) step += (c(k) / d) * modes.col(k);
148 }
149 if (sigma_floor > 0.0 && sigma == sigma_floor && length < radius) {
150 // In the hard case the force is orthogonal to the most negative
151 // eigenspace. The shifted solution needs its nullspace component
152 // to reach the boundary and minimize the indefinite quadratic.
153 const double relative_length = length / radius;
154 const double remaining =
155 radius * std::sqrt(std::max(0.0, (1.0 - relative_length) *
156 (1.0 + relative_length)));
157 step += remaining * modes.col(minimum_mode);
158 out.descends_measured = true;
159 }
160 if (!step.allFinite() || !(step.norm() > 0.0)) return out;
161 out.valid = true;
162 out.step = step;
163 out.sigma = sigma;
164 out.length = step.norm();
165 return out;
166}

◆ spectrumAt()

EndpointSpectrum gpr::optim::spectrumAt ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
double step,
const std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> & gradient_at,
double stiff_floor = std::numeric_limits<double>::infinity(),
Eigen::MatrixXd * raw_columns = nullptr,
const Eigen::MatrixXd * held_directions = nullptr )
inline

The spectrum of one Hessian stencil along held_directions, or along the default full Cartesian stencil at positions (ircStencilDirections).

Definition at line 728 of file EndpointConnectivity.h.

736{
738 Eigen::MatrixXd hessian;
739 if (positions.size() == 0 || positions.size() % 3 != 0 ||
740 masses.size() * 3 != positions.size())
741 return out;
743 hessian, out.resolution, positions, step,
744 ircStencilDirections(positions, masses, held_directions),
745 gradient_at, raw_columns))
746 return out;
747 return spectrumOfColumns(hessian, out.resolution, positions, masses,
748 stiff_floor);
749}
bool cartesianHessianColumns(Eigen::MatrixXd &columns, double &resolution, const Eigen::VectorXd &center, double step, const Eigen::MatrixXd &directions, const std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> &gradient_at, Eigen::MatrixXd *raw_columns=nullptr)

◆ spectrumForMinimumCheck()

template<typename GradientAt>
EndpointSpectrum gpr::optim::spectrumForMinimumCheck ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
double step,
const GradientAt & gradient_at,
MinimumSpectrumCache * cache = nullptr,
double stiff_floor = std::numeric_limits<double>::infinity() )

Vibrational Lanczos when the probe produced a spectrum. The complete stencil (spectrumAt) is used only when the probe cannot be measured. A spectrum stored at these coordinates is returned as it stands. A curvature inside the measured asymmetry is not a second stencil: the sign test is the same comparison, lowest < -resolution.

Definition at line 982 of file EndpointConnectivity.h.

987{
988 if (cache != nullptr) {
989 EndpointSpectrum cached;
990 if (cache->recall(positions, cached)) return cached;
991 }
992 const EndpointSpectrum vibrational = probeVibrationalMinimum(
993 positions, masses, step, gradient_at, stiff_floor);
994 EndpointSpectrum out =
995 vibrational.ok
996 ? vibrational
997 : spectrumAt(positions, masses, step, gradient_at, stiff_floor);
998 if (cache != nullptr && out.ok) cache->store(positions, out);
999 return out;
1000}
void store(const Eigen::VectorXd &position, const EndpointSpectrum &spectrum)
bool recall(const Eigen::VectorXd &position, EndpointSpectrum &out) const

◆ spectrumOfColumns()

EndpointSpectrum gpr::optim::spectrumOfColumns ( const Eigen::MatrixXd & hessian,
double resolution,
const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
double stiff_floor )
inline

Definition at line 653 of file EndpointConnectivity.h.

658{
660 out.resolution = resolution;
661 if (hessian.rows() != positions.size() ||
662 hessian.cols() != positions.size() || !hessian.allFinite() ||
663 !std::isfinite(resolution))
664 return out;
665 const Eigen::Index dof = positions.size();
666 Eigen::VectorXd inv_root(dof);
667 for (Eigen::Index k = 0; k < dof; ++k)
668 inv_root(k) = 1.0 / std::sqrt(masses(k / 3));
669 const Eigen::MatrixXd weighted =
670 hessian.cwiseProduct(inv_root * inv_root.transpose());
671 const Eigen::MatrixXd vibrational =
672 vibrationalComplement(positions, masses);
673 if (vibrational.cols() == 0) return out;
674 const Eigen::MatrixXd reduced =
675 vibrational.transpose() * weighted * vibrational;
676 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(reduced);
677 if (solver.info() != Eigen::Success) return out;
678 const Eigen::VectorXd mass_weighted =
679 vibrational * solver.eigenvectors().col(0);
680 out.cartesian.resize(dof);
681 for (Eigen::Index k = 0; k < dof; ++k)
682 out.cartesian(k) = mass_weighted(k) * inv_root(k);
683 out.curvature = solver.eigenvalues()(0);
684 if (!(out.cartesian.norm() > 0.0) || !out.cartesian.allFinite() ||
685 !std::isfinite(out.curvature))
686 return out;
687
688 const Eigen::MatrixXd rigid = cartesianRigidMotions(positions);
689 const Eigen::JacobiSVD<Eigen::MatrixXd> svd(rigid, Eigen::ComputeFullU);
690 const Eigen::MatrixXd cartesian_vib =
691 svd.matrixU().rightCols(dof - svd.rank());
692 if (cartesian_vib.cols() == 0) return out;
693 const Eigen::MatrixXd cartesian_reduced =
694 cartesian_vib.transpose() * hessian * cartesian_vib;
695 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> cartesian_solver(
696 cartesian_reduced);
697 if (cartesian_solver.info() != Eigen::Success) return out;
698 if (cartesian_solver.eigenvalues().size() > 0) {
699 out.lowest = cartesian_solver.eigenvalues()(0);
700 out.cartesian_lowest =
701 cartesian_vib * cartesian_solver.eigenvectors().col(0);
702 const double norm = out.cartesian_lowest.norm();
703 if (norm > 0.0) out.cartesian_lowest /= norm;
704 }
705 const double floor = std::max(out.resolution, 0.0);
706 std::vector<Eigen::Index> stiff_cols;
707 for (Eigen::Index i = 0; i < cartesian_solver.eigenvalues().size(); ++i) {
708 const double value = cartesian_solver.eigenvalues()(i);
709 if (value > floor && !std::isfinite(out.lambda_min))
710 out.lambda_min = value;
711 if (std::isfinite(value)) out.lambda_max = value;
712 if (value > std::max(std::abs(out.curvature), stiff_floor))
713 stiff_cols.push_back(i);
714 }
715 if (!stiff_cols.empty()) {
716 out.stiff.resize(dof, static_cast<Eigen::Index>(stiff_cols.size()));
717 for (Eigen::Index c = 0; c < out.stiff.cols(); ++c)
718 out.stiff.col(c) =
719 cartesian_vib * cartesian_solver.eigenvectors().col(
720 stiff_cols[static_cast<std::size_t>(c)]);
721 }
722 out.ok = true;
723 return out;
724}

◆ spectrumOfModelHessian()

EndpointSpectrum gpr::optim::spectrumOfModelHessian ( const Eigen::MatrixXd & raw,
const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
double stiff_floor )
inline

A symmetric matrix from a model, judged with the same resolution as a measured stencil: the singular value of its antisymmetric part.

Definition at line 1004 of file EndpointConnectivity.h.

1008{
1009 if (raw.rows() != positions.size() || raw.cols() != positions.size() ||
1010 !raw.allFinite())
1011 return {};
1012 const Eigen::MatrixXd antisym = 0.5 * (raw - raw.transpose());
1013 const double resolution =
1014 antisym.size() == 0
1015 ? 0.0
1016 : Eigen::JacobiSVD<Eigen::MatrixXd>(antisym).singularValues()(0);
1017 return spectrumOfColumns(0.5 * (raw + raw.transpose()), resolution,
1018 positions, masses, stiff_floor);
1019}

◆ stationaryCurvaturePosterior()

StationaryCurvaturePosterior gpr::optim::stationaryCurvaturePosterior ( double c,
double c_spread,
double f,
double f_spread,
double b,
double b_spread,
Eigen::Index samples = detail::kSpectrumSamples )
inline

Definition at line 82 of file StationaryCurvature.h.

85{
87 if (!(std::isfinite(c) && std::isfinite(c_spread) && std::isfinite(f) &&
88 std::isfinite(f_spread) && std::isfinite(b) &&
89 std::isfinite(b_spread)) ||
90 samples < 4)
91 return out;
92 // A mode and its negative describe the same stationary point. Reflect
93 // both odd coefficients into one frame so a fixed finite sample also
94 // preserves that symmetry, not only its limiting distribution.
95 if (f < 0.0 || (f == 0.0 && b < 0.0)) {
96 f = -f;
97 b = -b;
98 }
99 std::mt19937_64 rng(0x5C0FFEEULL + static_cast<std::uint64_t>(samples));
100 std::normal_distribution<double> normal(0.0, 1.0);
101 std::vector<double> roots;
102 roots.reserve(static_cast<std::size_t>(samples));
103 Eigen::Index undetermined = 0;
104 for (Eigen::Index n = 0; n < samples; ++n) {
105 const double cs = c + c_spread * normal(rng);
106 const double fs = f + f_spread * normal(rng);
107 const double bs = b + b_spread * normal(rng);
108 const double discriminant = cs * cs - 2.0 * bs * fs;
109 if (discriminant < 0.0) {
110 ++undetermined;
111 continue;
112 }
113 roots.push_back(std::copysign(std::sqrt(discriminant), cs));
114 }
115 std::sort(roots.begin(), roots.end());
116 const auto total = static_cast<double>(samples);
117 out.undetermined = static_cast<double>(undetermined) / total;
118 // One-spread quantiles over every sample: an undetermined sample sits
119 // below every root for the lower bound and above every root for the
120 // upper bound.
121 const double q = 0.1587;
122 const auto rank_low = static_cast<Eigen::Index>(std::floor(q * total));
123 const auto rank_high =
124 static_cast<Eigen::Index>(std::floor((1.0 - q) * total));
125 const Eigen::Index n_roots = static_cast<Eigen::Index>(roots.size());
126 out.lower = rank_low < undetermined
127 ? -std::numeric_limits<double>::infinity()
128 : roots[static_cast<std::size_t>(
129 std::min(rank_low - undetermined, n_roots - 1))];
130 out.upper = rank_high >= n_roots
131 ? std::numeric_limits<double>::infinity()
132 : roots[static_cast<std::size_t>(rank_high)];
133 if (n_roots == 0) {
134 out.lower = -std::numeric_limits<double>::infinity();
135 out.upper = std::numeric_limits<double>::infinity();
136 }
137 // Solve c^2 - 2 abs(b) t = hypot(s_0, 2 s_b t) for t >= 0, where
138 // s_0 is the discriminant spread at zero force. The cubic error shrinks
139 // with the force being converged; using its value at the current force
140 // can incorrectly declare every positive target unresolvable.
141 const double curvature_squared = c * c;
142 const double zero_force_spread =
143 2.0 * std::hypot(c * c_spread, b * f_spread);
144 out.force_target = 0.0;
145 if (curvature_squared > zero_force_spread) {
146 const double ratio = zero_force_spread / curvature_squared;
147 const double slope = 2.0 * std::abs(b);
148 // Rationalizing the smaller quadratic root avoids subtracting
149 // nearly equal terms and also covers a zero mean cubic coefficient.
150 const double denominator =
151 slope + std::hypot(slope * ratio,
152 2.0 * b_spread *
153 std::sqrt((1.0 - ratio) * (1.0 + ratio)));
154 out.force_target = denominator > 0.0
155 ? (curvature_squared - zero_force_spread) *
156 (1.0 + ratio) / denominator
157 : std::numeric_limits<double>::infinity();
158 }
159 out.force_decidable =
160 std::isfinite(out.force_target) && out.force_target >= f_spread;
161 out.valid = true;
162 return out;
163}

◆ stencilDirectionsForMode()

Eigen::MatrixXd gpr::optim::stencilDirectionsForMode ( VibrationalStencil mode,
const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
bool periodic,
bool anchored,
const Eigen::VectorXi * frozen = nullptr )
inline

Full measures every Cartesian coordinate: all 3 coordinates for N=1, and all 3N when atoms are frozen, so measureVibrationalIndex(frozen, Full) probes all 3N. Vibrational uses vibrationalStencilDirections. A lone atom is the identity in both.

Definition at line 156 of file PhysicalCurvatureBasis.h.

160{
162 return vibrationalStencilDirections(positions, masses, periodic,
163 anchored, frozen);
164 return Eigen::MatrixXd::Identity(positions.size(), positions.size());
165}
Eigen::MatrixXd vibrationalStencilDirections(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, bool periodic, bool anchored, const Eigen::VectorXi *frozen=nullptr)

◆ stencilStepOrDefault()

double gpr::optim::stencilStepOrDefault ( double requested)
inlineconstexprnoexcept

The requested stencil step, or the default when none was requested.

Definition at line 784 of file StencilIndex.h.

785{
786 return requested > 0.0 ? requested : defaultStencilStep();
787}
constexpr double defaultStencilStep() noexcept

◆ transportMeasuredHessianActions()

Eigen::MatrixXd gpr::optim::transportMeasuredHessianActions ( const gpr::Coord & positions,
const gpr::Coord & gradient,
const Eigen::MatrixXd & measured_basis,
const Eigen::MatrixXd & measured_action,
const Eigen::MatrixXd & physical,
bool include_rotations = true )
inline

Express measured Cartesian Hessian actions in another complete physical basis at the same geometry. Rigid translations have zero action; rotational invariance gives H (omega x R) = omega x gradient, including at nonstationary points. These identities supply the rigid part removed when changing between mass-weighted and Cartesian constraints.

Definition at line 256 of file PhysicalCurvatureBasis.h.

261{
262 const Eigen::Index dimension = positions.cols();
263 const Eigen::Index columns = measured_basis.cols();
264 if (positions.rows() != 1 || gradient.rows() != 1 || dimension == 0 ||
265 dimension % 3 != 0 || gradient.cols() != dimension || columns == 0 ||
266 measured_basis.rows() != dimension ||
267 measured_action.rows() != dimension ||
268 measured_action.cols() != columns || physical.rows() != dimension ||
269 !positions.allFinite() || !gradient.allFinite() ||
270 !measured_basis.allFinite() || !measured_action.allFinite() ||
271 !physical.allFinite())
272 return {};
273 const Eigen::Index rigid =
274 columns == dimension ? 0 : (include_rotations ? 6 : 3);
275 Eigen::MatrixXd directions =
276 Eigen::MatrixXd::Zero(dimension, columns + rigid);
277 Eigen::MatrixXd actions = directions;
278 directions.leftCols(columns) = measured_basis;
279 actions.leftCols(columns) = measured_action;
280 if (rigid > 0) {
281 Eigen::Vector3d center = Eigen::Vector3d::Zero();
282 for (Eigen::Index atom = 0; atom < dimension / 3; ++atom)
283 center += positions.row(0).segment<3>(3 * atom).transpose();
284 center /= dimension / 3;
285 for (Eigen::Index atom = 0; atom < dimension / 3; ++atom) {
286 const Eigen::Vector3d r =
287 positions.row(0).segment<3>(3 * atom).transpose() - center;
288 const Eigen::Vector3d g =
289 gradient.row(0).segment<3>(3 * atom).transpose();
290 for (Eigen::Index axis = 0; axis < 3; ++axis) {
291 directions(3 * atom + axis, columns + axis) = 1.0;
292 if (rigid == 6) {
293 const Eigen::Vector3d generator =
294 Eigen::Vector3d::Unit(axis);
295 directions.block<3, 1>(3 * atom, columns + 3 + axis) =
296 generator.cross(r);
297 actions.block<3, 1>(3 * atom, columns + 3 + axis) =
298 generator.cross(g);
299 }
300 }
301 }
302 for (Eigen::Index j = columns; j < directions.cols(); ++j) {
303 const double norm = directions.col(j).stableNorm();
304 if (norm > 0.0) {
305 directions.col(j) /= norm;
306 actions.col(j) /= norm;
307 }
308 }
309 }
310 const Eigen::ColPivHouseholderQR<Eigen::MatrixXd> decomposition(directions);
311 if (decomposition.rank() != dimension) return {};
312 const Eigen::MatrixXd coefficients = decomposition.solve(physical);
313 const double roundoff =
314 64.0 * std::numeric_limits<double>::epsilon() * dimension;
315 if (!coefficients.allFinite() ||
316 !(directions * coefficients).isApprox(physical, roundoff))
317 return {};
318 return physical * (physical.transpose() * (actions * coefficients));
319}

◆ transportPhysicalDirections()

Eigen::MatrixXd gpr::optim::transportPhysicalDirections ( const Eigen::MatrixXd & directions,
const Eigen::MatrixXd & physical )
inline

Reproject search directions in their supplied order. Curvature signs require fresh measurements; projection alone carries no certificate.

Definition at line 232 of file PhysicalCurvatureBasis.h.

234{
235 if (directions.rows() != physical.rows() || directions.cols() == 0 ||
236 directions.cols() > physical.cols() || !directions.allFinite())
237 return Eigen::MatrixXd(physical.rows(), 0);
238 const Eigen::MatrixXd projected =
239 physical * (physical.transpose() * directions);
240 Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr(projected);
241 qr.setThreshold(std::sqrt(std::numeric_limits<double>::epsilon()));
242 if (qr.rank() != directions.cols())
243 return Eigen::MatrixXd(physical.rows(), 0);
244 // Pivoting establishes rank but cannot choose the returned column order:
245 // the leading direction carries the dimer axis and the second its escape.
246 const Eigen::HouseholderQR<Eigen::MatrixXd> ordered(projected);
247 return ordered.householderQ() *
248 Eigen::MatrixXd::Identity(physical.rows(), directions.cols());
249}

◆ twoLoopRecursion() [1/2]

Eigen::VectorXd gpr::optim::twoLoopRecursion ( const std::deque< Eigen::VectorXd > & s_hist,
const std::deque< Eigen::VectorXd > & y_hist,
const std::deque< double > & rho_hist,
const Eigen::VectorXd & force,
const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> & apply_H0 )
nodiscard

Two-loop recursion with a caller-supplied H0 application.

Identical to the scalar overload except H0 is consumed via apply_H0(q) -> H0 q. Used by callers that supply a Nystrom-sketched (or otherwise structured) initial inverse Hessian: the scalar form is just apply_H0 = [&](v){ return H0_scalar * v; }.

The kernel does not touch the H0 functor's internals – it is the caller's responsibility to keep the sketch consistent with the history vectors it pairs with (typically: rebuild the sketch once per outer iter at the same band position the latest (s, y) was collected from).

Definition at line 78 of file LBFGS.cpp.

83{
84 const auto n = static_cast<std::size_t>(force.size());
85 auto raise_rgmin = []() {
86 const char* msg = rgmin_last_error();
87 const std::string text = msg != nullptr && msg[0] != '\0'
88 ? msg
89 : "rgmin L-BFGS direction failed";
90 throw std::runtime_error(text);
91 };
92 if (n == 0 || s_hist.size() != y_hist.size() ||
93 s_hist.size() != rho_hist.size()) {
94 throw std::runtime_error(
95 "rgmin L-BFGS direction: history does not match the force");
96 }
97 rgmin_lbfgs_pairs_t* pairs = rgmin_lbfgs_pairs_create(n, s_hist.size());
98 if (pairs == nullptr) raise_rgmin();
99 for (std::size_t k = 0; k < s_hist.size(); ++k) {
100 const auto len = static_cast<std::size_t>(s_hist[k].size());
101 if (static_cast<std::size_t>(y_hist[k].size()) != len) {
102 rgmin_lbfgs_pairs_free(pairs);
103 throw std::runtime_error(
104 "rgmin L-BFGS direction: a pair is not one length");
105 }
106 int32_t stored = 0;
107 // stored == 0 is the relative-curvature gate (s·y <= 1e-8
108 // ||s|| ||y||) or a rho that is not finite and positive. The
109 // pair stays out of the handle. A failed call throws
110 // rgmin_last_error() and does not run another two-loop.
111 if (rgmin_lbfgs_pairs_push_rho(pairs, s_hist[k].data(),
112 y_hist[k].data(), rho_hist[k], len,
113 &stored) != RGMIN_SUCCESS) {
114 const char* msg = rgmin_last_error();
115 const std::string text = msg != nullptr ? msg : "";
116 rgmin_lbfgs_pairs_free(pairs);
117 throw std::runtime_error(
118 text.empty() ? "rgmin_lbfgs_pairs_push_rho failed" : text);
119 }
120 if (stored == 0) continue;
121 }
122 Eigen::VectorXd direction(force.size());
123 const auto status = rgmin_lbfgs_direction(
124 pairs, force.data(), nullptr, gprLbfgsApplyH0,
125 const_cast<void*>(static_cast<const void*>(&apply_H0)),
126 direction.data(), n);
127 rgmin_lbfgs_pairs_free(pairs);
128 if (status != RGMIN_SUCCESS) {
129 const char* msg = rgmin_last_error();
130 const std::string text = msg != nullptr ? msg : "";
131 throw std::runtime_error(text.empty() ? "rgmin_lbfgs_direction failed"
132 : text);
133 }
134 return direction;
135}

◆ twoLoopRecursion() [2/2]

Eigen::VectorXd gpr::optim::twoLoopRecursion ( const std::deque< Eigen::VectorXd > & s_hist,
const std::deque< Eigen::VectorXd > & y_hist,
const std::deque< double > & rho_hist,
const Eigen::VectorXd & force,
double H0 )
nodiscard

Nocedal two-loop recursion (the LBFGS kernel).

Computes z = H^{-1} (-force) where H is the inverse-Hessian approximation reconstructed from m curvature pairs (s_k, y_k) and their reciprocal dot products rho_k = 1 / (y_k . s_k). The caller applies the step as x <- x - z (force-convention: z points downhill when force is the negative gradient).

H0 is the initial-iter inverse-Hessian diagonal scaling. The scalar BB2 seed is gamma = s_{m-1}^T y_{m-1} / y_{m-1}^T y_{m-1}; on empty history (m == 0) the caller supplies the fallback scale.

No internal mutation of the history; the caller owns appending, trimming, and resetting. gpr::neb::detail::GlobalLBFGSOptimizer calls into this kernel so the recursion is defined once.

Definition at line 51 of file LBFGS.cpp.

55{
56 return twoLoopRecursion(
57 s_hist, y_hist, rho_hist, force,
58 [H0](const Eigen::VectorXd& v) -> Eigen::VectorXd { return H0 * v; });
59}
Eigen::VectorXd twoLoopRecursion(const std::deque< Eigen::VectorXd > &s_hist, const std::deque< Eigen::VectorXd > &y_hist, const std::deque< double > &rho_hist, const Eigen::VectorXd &force, double H0)
Nocedal two-loop recursion (the LBFGS kernel).
Definition LBFGS.cpp:51

◆ vibrationalComplement()

Eigen::MatrixXd gpr::optim::vibrationalComplement ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses )
inline

Orthonormal basis of the mass-weighted coordinates orthogonal to the rigid motions at positions: the left singular vectors of the rigid basis beyond its numerical rank (five for a linear molecule, six otherwise).

Definition at line 62 of file StencilIndex.h.

64{
65 const Eigen::MatrixXd rigid = massWeightedRigidMotions(positions, masses);
66 const Eigen::JacobiSVD<Eigen::MatrixXd> svd(rigid, Eigen::ComputeFullU);
67 return svd.matrixU().rightCols(positions.size() - svd.rank());
68}
Eigen::MatrixXd massWeightedRigidMotions(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses)

◆ vibrationalStencilDirections()

Eigen::MatrixXd gpr::optim::vibrationalStencilDirections ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
bool periodic,
bool anchored,
const Eigen::VectorXi * frozen = nullptr )
inline

Displacement directions of the vibrational stencil: the orthonormal Cartesian basis B of ker(R^T M), 3N-6 columns (3N-5 for a linear molecule, 3N-3 in a periodic cell, where rotations are not symmetries). An anchored geometry keeps every coordinate, and so does a lone atom, whose energy can only vary in an external field. Frozen atoms (nonzero frozen flags, one per atom) anchor the rest and never move: the directions are then the moving atoms' coordinate axes. With Q the mass-weighted vibrational basis, M^{-1/2} Q = B C for C = B^T M^{-1/2} Q, so Q^T M^{-1/2} H M^{-1/2} Q = C^T (B^T H B) C reads only H B: the vibrational index needs no rigid column and no invariance of the oracle.

Definition at line 130 of file PhysicalCurvatureBasis.h.

133{
134 const Eigen::Index dimension = positions.size();
135 if (frozen != nullptr && frozen->size() * 3 == dimension) {
136 const Eigen::Index moving = (frozen->array() == 0).count();
137 Eigen::MatrixXd axes = Eigen::MatrixXd::Zero(dimension, 3 * moving);
138 Eigen::Index column = 0;
139 for (Eigen::Index atom = 0; atom < frozen->size(); ++atom) {
140 if ((*frozen)(atom) != 0) continue;
141 for (int axis = 0; axis < 3; ++axis)
142 axes(3 * atom + axis, column++) = 1.0;
143 }
144 return axes;
145 }
146 if (anchored || dimension == 3 || dimension % 3 != 0)
147 return Eigen::MatrixXd::Identity(dimension, dimension);
148 return detail::rigidMotionComplement(positions.transpose(), masses,
149 !periodic);
150}

◆ vibrationalStencilFromInt()

VibrationalStencil gpr::optim::vibrationalStencilFromInt ( int value)
inline

Definition at line 42 of file VibrationalStencil.h.

43{
44 if (value == static_cast<int>(VibrationalStencil::Full))
46 if (value == static_cast<int>(VibrationalStencil::Vibrational))
48 throw std::invalid_argument(
49 "vibrational_stencil must be 0 (full) or 1 (vibrational)");
50}

◆ vibrationalStencilName()

const char * gpr::optim::vibrationalStencilName ( VibrationalStencil mode)
inlinenoexcept

Definition at line 23 of file VibrationalStencil.h.

24{
25 return mode == VibrationalStencil::Vibrational ? "vibrational" : "full";
26}

◆ weakModeContinuation()

WeakModeContinuation gpr::optim::weakModeContinuation ( const StencilIndexCertificate & certificate,
const Eigen::VectorXd & centre_gradient,
double resolution,
double step_bound )
inline

Definition at line 653 of file StencilIndex.h.

657{
658 const double h = certificate.weak_step;
659 const double inverse_mass = certificate.weak_inverse_mass;
660 const Eigen::VectorXd& d = certificate.weak_direction;
661 if (d.size() != centre_gradient.size() ||
662 certificate.weak_even.size() != d.size() || !(h > 0.0) ||
663 !std::isfinite(h) || !centre_gradient.allFinite() ||
664 !certificate.weak_even.allFinite() || !(inverse_mass > 0.0) ||
665 !std::isfinite(inverse_mass))
666 return {};
667 const double third = 2.0 * inverse_mass *
668 d.dot(certificate.weak_even - centre_gradient) /
669 (h * h);
670 return boundedWeakModeContinuation(d, third, h, certificate.positive_lower,
671 resolution, step_bound);
672}
double weak_inverse_mass
Converts the Cartesian curvature rate to eV/(A^3 amu).

◆ writeIrcCertificate()

bool gpr::optim::writeIrcCertificate ( const std::string & path,
const EndpointConnectivityReport & report,
const std::vector< int > & atomic_numbers )
inline

Exact record of the saddle, the mode, and both walk ends. Hex floating point round-trips, so a replay from the written saddle sees the same bits the walk used.

Definition at line 2053 of file EndpointConnectivity.h.

2056{
2057 if (!report.reported || report.saddle_positions.size() == 0 ||
2058 report.saddle_positions.size() != report.mode.size() ||
2059 report.forward_position.size() != report.saddle_positions.size() ||
2060 report.reverse_position.size() != report.saddle_positions.size() ||
2061 static_cast<Eigen::Index>(atomic_numbers.size()) * 3 !=
2062 report.saddle_positions.size())
2063 return false;
2064 std::ofstream out(path);
2065 if (!out) return false;
2066 // max_digits10 round-trips a double through extraction. Hex floats
2067 // do not: operator>> reads the leading 0 and stops.
2068 out << std::setprecision(std::numeric_limits<double>::max_digits10);
2069 out << "irc-certificate 1\n";
2070 out << "n_atoms " << atomic_numbers.size() << "\n";
2071 out << "atomic_numbers";
2072 for (const int z: atomic_numbers)
2073 out << ' ' << z;
2074 out << "\nkick " << report.kick << "\n";
2075 out << "forward_energy " << report.forward_energy << "\n";
2076 out << "forward_force " << report.forward_force << "\n";
2077 out << "forward_steps " << report.forward_steps << "\n";
2078 out << "forward_calls " << report.forward_calls << "\n";
2079 out << "reverse_energy " << report.reverse_energy << "\n";
2080 out << "reverse_force " << report.reverse_force << "\n";
2081 out << "reverse_steps " << report.reverse_steps << "\n";
2082 out << "reverse_calls " << report.reverse_calls << "\n";
2083 out << "reactant_energy " << report.reactant_energy << "\n";
2084 out << "product_energy " << report.product_energy << "\n";
2085 const auto row = [&](const char* name, const Eigen::VectorXd& values) {
2086 out << name;
2087 for (Eigen::Index i = 0; i < values.size(); ++i)
2088 out << ' ' << values(i);
2089 out << '\n';
2090 };
2091 row("saddle", report.saddle_positions);
2092 row("mode", report.mode);
2093 row("forward", report.forward_position);
2094 row("reverse", report.reverse_position);
2095 if (!report.saddle_index_measured)
2096 out << "descent direction verified; index not measured\n";
2097 return static_cast<bool>(out);
2098}
@ z
Definition Enums.h:28

◆ writeSecantCurvatureCounts()

void gpr::optim::writeSecantCurvatureCounts ( std::ostream & out,
const SecantCurvatureCounts & counts )
inline

Definition at line 32 of file SecantCurvature.h.

34{
35 out << "Secant pairs accepted: " << counts.pairs_accepted << "\n";
36 out << "Secant pairs rejected: " << counts.pairs_rejected << "\n";
37 out << "Secant HVP calls: " << counts.hvp_calls << "\n";
38 out << "Secant Hessian-consistency rejections: "
39 << counts.consistency_rejections << "\n";
40 out << "Secant quadratic-mean uses: " << counts.quadratic_mean_uses << "\n";
41}

Variable Documentation

◆ kMinimizationLayoutVersion

std::uint32_t gpr::optim::kMinimizationLayoutVersion = 2
inlineconstexpr

Layout of MinimizationConfig and MinimizationResult. Bump when either struct's layout changes, including a reorder that keeps the size. 2: MinimizationResult::prior_observations.

Definition at line 45 of file GPMinimizer.h.