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

The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition, IDPP start. More...

Namespaces

namespace  oie

Classes

struct  ActiveGpRgsaddleUser
struct  ActiveLearningSession
class  AdaptiveSo3Policy
class  AdaptiveSo3SessionPolicy
 Run-scoped adaptive SO(3) state. More...
struct  BandForceStall
struct  BandLayout
 Map between caller coordinates and the moving coordinates of a band. More...
struct  BandMidpointCertificate
struct  CartesianOracleCenter
struct  CartesianOracleStencil
struct  CartesianStencilRefinement
struct  ClimbingImageIndexCertificate
struct  EndpointSymmetry
class  EonRelaxClient
struct  ForceStopHandoffStencil
struct  GPNEBConfig
 Configuration for GP-NEB. More...
struct  GPNEBResult
struct  GprRgsaddleUser
 GP-NEB GaussianProcessRegression as dest PointSurface. More...
struct  Image
 A single image on the NEB path. More...
struct  IndexEscapeResult
class  LocalCartesianGP
 Squared-exponential Gaussian process with partial gradients. More...
struct  MMFRunResult
 Result of one ~OCINEBController::run~ invocation. More...
struct  NEBOracleEvaluationContext
struct  NEBOracleOptimizationOutcome
struct  NEBOracleSessionCheckpoint
class  NEBPath
 NEB path: chain of images between two endpoints. More...
struct  ObservationVariance
 Predictive variance of one joint energy-and-gradient observation. More...
struct  OCINEBConfig
class  OCINEBController
struct  OCINEBDiagnostics
class  OCINEBOracleCallLedger
struct  OCINEBOracleCallSummary
struct  OCINEBResult
struct  OieBandTraceRecord
struct  OieFixedImageLease
class  OracleForceProgressTracker
struct  OracleSessionRestartRequested
struct  OuterIterCompositionCertificates
struct  OuterIterCompositionTraceRecord
 One outer-iteration composition snapshot. More...
class  PairSplineModel
 Pair-additive energy with a cubic B-spline radial function. More...
struct  PeriodicBandDefaults
 The numbers a caller reads without building a band. More...
struct  PosteriorFactorizationCounts
class  PosteriorFactorizationScope
class  RgMinMode
class  RgsaddleClient
class  RgSellaMin
class  RgSellaSaddle
struct  SaddleCertificateReport
struct  SaddlePolishResult
 Outcome of a saddle polish (see polishSaddleOnSurrogate). More...
struct  SharedParameterState
struct  StagedDimerObservation
struct  VibrationalIndexClass
struct  VibrationalIndexDecision
struct  VibrationalIndexMeasurement
 Float64 central-difference index of one geometry. More...

Typedefs

using NEBOracle
 Oracle function: positions -> (energy, gradient).
using NEBBatchOracle
using ObservationVarianceEstimator
 Posterior variance estimator for one joint oracle observation.

Enumerations

enum class  AcquisitionType {
  MaxVariance , MaxForce , UCB , ThompsonSampling ,
  IMSPE , ExpectedImprovement , PriorityCascade , TPE ,
  PSBAX
}
 Available acquisition strategies for image selection. More...
enum class  BandStallAction { Continue , Restore , Stop }
 What to do when the max band force stops falling. More...
enum class  NEBMode {
  Standard , AIE , OIE , GP_AIE ,
  GP_OIE , GP_LOCAL
}
 NEB evaluation mode. More...
enum class  AdaptiveSo3EvaluationMode { Raw , ScatterProbe , Averaged }
enum class  GPNEBConvergenceStatus { NotConverged = 0 , ForceTolerance = 1 , ModelNoiseFloor = 2 }
enum class  GPNEBStopReason { Unspecified , Converged , IterationBudget , WallClockLimit }
 Result of GP-NEB optimization. More...
enum class  MetatomicSO3Policy { Raw , Adaptive , Always }
 Rotational averaging policy shared by file and command-line configuration. More...
enum class  MMFStatus : int { Helped = 0 , MaxIterations = 1 , Skipped = -1 , PositiveCurvature = -2 }
 Outcome of one MMF burst, mirroring eOn's enum class. More...
enum class  MMFRejectKind {
  None = 0 , UncertifiedPath , ForceOnlyBelowEndpoint , SeedEnergyDescent ,
  Displacement , RecoveryPortfolioExhausted
}
enum class  MmfHandoffPolicy : std::uint8_t { Auto = 0 , ClassicalAdaptive , GpBandFallback }
enum class  PeriodicBandInitial { Linear = 0 , Idpp = 1 , Sidpp = 2 }
 How the initial path is built. More...
enum class  ObservationRetention { RecordAcquisition , AlreadyRecorded }
 Whether an acquisition still needs a ledger entry when admitted to a model. More...
enum class  IndexGateAction { Accept , Continue , Exhausted }

Functions

double perpendicularSigma (const Eigen::VectorXd &gradient_variance, const Eigen::VectorXd &tangent)
 Compute perpendicular GP variance (variance orthogonal to path tangent).
int selectNextImage (const std::vector< Eigen::VectorXd > &neb_forces, const std::vector< ObservationVariance > &variances, const std::vector< Eigen::VectorXd > &tangents, const std::vector< bool > &evaluated, AcquisitionType strategy, double kappa=1.0, std::mt19937 *rng=nullptr)
 Select the next unevaluated intermediate image by a per-image score.
std::vector< int > expandToTriplet (int center, int n_total)
 Expand a single image index to a triplet {i-1, i, i+1}.
int bandStallWindow (int n_images, int polished_dofs) noexcept
void noteLowestCertifiedClimb (BandForceStall &stall, const NEBPath &path, int image)
BandStallAction observeMaxBandForce (BandForceStall &stall, double max_force, double force_tolerance, int window)
void restoreCertifiedClimb (NEBPath &path, const BandForceStall &stall)
 Put the certified climb back and make it the climbing image.
OieBandTraceRecord captureOieBandTrace (const NEBPath &path, GaussianProcessRegression &gp, int outer, const std::vector< double > &acquisition_variance, bool con_geometry, bool global_snapshot, int oracle_calls)
EndpointSymmetry endpointSymmetryFromPermutation (const std::vector< int > &permutation, const Eigen::VectorXd &reactant, const Eigen::VectorXd &product, const std::vector< int > &atomic_numbers)
EndpointSymmetry requireEndpointSymmetry (const std::vector< int > &permutation, const Eigen::VectorXd &reactant, const Eigen::VectorXd &product, const std::vector< int > &atomic_numbers, double radius)
int gprMeanSurfaceCallback (void *user, eon_relax_surface_request_t *req) noexcept
double forceComponentRmsForNorm (double component_rms, Eigen::Index degrees_of_freedom, ConvergenceNormType norm) noexcept
bool oracleContextRequestsAdaptiveSo3 (const NEBOracleEvaluationContext &context)
static double bandPairCutoff (const GPNEBConfig &config)
void applyConfigToGP (const GPNEBConfig &config, gpr::GaussianProcessRegression &gp)
GPNEBResult gpNEBUngated (NEBOracle oracle, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int n_images, const GPNEBConfig &config, ActiveLearningSession *session)
GPNEBResult gpNEB (NEBOracle oracle, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int n_images, const GPNEBConfig &config={}, ActiveLearningSession *session=nullptr)
 Run GP-accelerated NEB.
NEBOracle makeLazyPotentialOracle (std::function< pot::PotentialWrapper()> potential_factory, std::vector< int > atomic_numbers, std::array< double, 9 > box, int &oracle_call_counter, double *oracle_seconds=nullptr, double *oracle_energy_noise_rms=nullptr, const bool *oracle_variance_updates_enabled=nullptr, double *oracle_force_noise_rms=nullptr, std::shared_ptr< detail::LazyPotentialOracleState > *state_out=nullptr, std::shared_ptr< const gpr::WallClockLimit > wall_clock_limit=nullptr)
NEBBatchOracle makeLazyPotentialBatchOracle (std::shared_ptr< detail::LazyPotentialOracleState > state)
pot::PotentialWrapper makePotentialWrapperFromOracle (NEBOracle oracle)
double saddleForceMagnitude (const Eigen::VectorXd &gradient)
double testingHelpedModeCurvature ()
void runOciNebOuterIteration (const std::shared_ptr< OCINEBController > &controller, NEBOracle &oracle, const GPNEBConfig &neb_config, int &total_oracle_calls, int &bursts_fired, int &dimer_saddle_image_idx, const std::shared_ptr< OciMmfHandoffTrapState > &handoff_trap_state, const GPNEBConfig::OuterIterHook &caller_hook, NEBPath &path, int ci_image_idx, int outer_iter, ActiveLearningSession &sess, bool &converged, bool trap_detected)
OCINEBResult runOCINEB (NEBOracle oracle, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int n_images, const GPNEBConfig &neb_config, const OCINEBConfig &oci_config_in, ActiveLearningSession &session)
IndexEscapeResult runIndexEscapeGpDimer (const OCINEBConfig &oci_config, const GPNEBConfig &neb_config, ActiveLearningSession &session, NEBOracle &oracle, const Eigen::VectorXd &x_seed, double e_seed, const Eigen::VectorXd &g_seed, const Eigen::VectorXd &mode_seed, double energy_ceiling)
OCINEBResult runOCINEBRefined (NEBOracle oracle, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int n_images, GPNEBConfig neb_config, const OCINEBConfig &oci_config, ActiveLearningSession &session)
void certifyOCINEBResult (OCINEBResult &result, NEBOracle oracle, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int active_n_images, const GPNEBConfig &neb_config, const OCINEBConfig &oci_config, ActiveLearningSession &session)
int reduceOracleProviderCalls (int local_calls)
bool ciIndexCertificateRefuted (const OCINEBResult &result)
bool ocinebReportsConverged (const OCINEBResult &result)
template<typename Oracle>
CartesianOracleStencil evaluateCartesianOracleStencil (const Eigen::VectorXd &center, double displacement, const Eigen::MatrixXd &directions, const Oracle &oracle, const NEBBatchOracle *batch_oracle=nullptr, Eigen::Index batch_chunk=0)
template<typename Oracle>
CartesianOracleStencil evaluateCartesianOracleStencil (const Eigen::VectorXd &center, double displacement, const Eigen::MatrixXd &directions, const Oracle &oracle, const CartesianOracleCenter &measured_center, const NEBBatchOracle *batch_oracle=nullptr, Eigen::Index batch_chunk=0)
Eigen::MatrixXd stencilDirectionalActions (const CartesianOracleStencil &stencil)
Eigen::MatrixXd stencilHessianColumns (const CartesianOracleStencil &stencil)
std::string oracleStencilDestination (const std::string &requested, const std::string &anchor)
SaddleCertificateReport saddleCertificateReport (bool otherwise_certified, bool stencil_measured, bool force_stop_certified, bool inconclusive)
const char * stencilIndexLabel (bool first_order, bool higher_order)
void writeCartesianOracleStencil (const std::string &path, const CartesianOracleStencil &stencil, const std::vector< int > &atomic_numbers, const std::array< double, 9 > &cell, int oracle_calls, const CartesianStencilRefinement *refinement=nullptr)
std::string formatCompositionTrace (const std::vector< OuterIterCompositionTraceRecord > &records)
 Canonical text serialization used by golden files and exact-match asserts.
bool parseCompositionTrace (const std::string &text, std::vector< OuterIterCompositionTraceRecord > &out, std::string *error)
bool writeCompositionTraceFile (const std::string &path, const std::vector< OuterIterCompositionTraceRecord > &records)
bool readCompositionTraceFile (const std::string &path, std::vector< OuterIterCompositionTraceRecord > &out, std::string *error)
bool compositionTracesTextuallyEqual (const std::vector< OuterIterCompositionTraceRecord > &a, const std::vector< OuterIterCompositionTraceRecord > &b)
 True when canonical serializations are identical (golden check).
bool compositionTracesNumericallyClose (const std::vector< OuterIterCompositionTraceRecord > &got, const std::vector< OuterIterCompositionTraceRecord > &expected, double rtol, double atol, std::string *mismatch)
GPNEBConfig periodicBandConfig ()
 GPNEBConfig of a periodic local band before the geometry is attached.
rgsaddle_status_t activeGpRgsaddleSurface (void *user, rgsaddle_surface_request_t *req)
rgsaddle_status_t gprRgsaddleSurface (void *user, rgsaddle_surface_request_t *req)
BandMidpointCertificate certifyBandMidpoints (ActiveLearningSession &session, const NEBPath &path, double force_tol)
BandMidpointCertificate certifyBandMidpointsMeasured (ActiveLearningSession &session, const NEBPath &path, double force_tol, NEBOracle &oracle, int max_measurements, int *oracle_calls)
ClimbingImageIndexCertificate certifyClimbingImageIndex (const NEBOracle &oracle, ActiveLearningSession &session, const Eigen::VectorXd &x_ci, double e_ci, const Eigen::VectorXd &g_ci, double hessian_fd_step, double max_move, double force_tol, const NEBBatchOracle *batch_oracle, Eigen::Index batch_chunk)
SaddlePolishResult polishSaddleOnSurrogate (const NEBOracle &oracle, ActiveLearningSession &session, const Eigen::VectorXd &x0, double e0, const Eigen::VectorXd &g0, double force_tol, int max_steps, double max_move, double hessian_fd_step)
Eigen::LLT< Eigen::MatrixXd > factorSubstrate (const Eigen::MatrixXd &hessian)
Eigen::VectorXd substrateStep (const Eigen::MatrixXd &hessian, const Eigen::VectorXd &force)
 One substrate step, H^{-1} force, from that factor.
int rejectUntrustedStep (NEBPath &path, const std::vector< Eigen::VectorXd > &accepted_positions, const gpr::TrustRadius &trust, double trust_threshold)
 Reject a simultaneous inner-loop NEB step outside the GP trust set.
Eigen::MatrixXd oracleStencilDirections (const Eigen::VectorXd &positions, const gpr::AtomsConfiguration *atoms, gpr::optim::VibrationalStencil stencil)
VibrationalIndexDecision decideVibrationalIndex (const Eigen::VectorXd &positions, const Eigen::VectorXd &gradient, const gpr::AtomsConfiguration *atoms, gpr::GaussianProcessRegression *gp, double variance, double variance_threshold, double move, double stencil_step, const NEBOracle *oracle, const NEBBatchOracle *batch, Eigen::Index batch_chunk, gpr::optim::VibrationalStencil stencil)
void applyVibrationalIndexDecision (GPNEBResult &result, const VibrationalIndexDecision &decision, int outer_budget)
void resetForceStopStencilCache ()
void writeForceStopHandoff (const std::string &archive_dir, const GPNEBResult &result)
std::optional< ForceStopHandoffStencil > readForceStopHandoff (const std::string &archive_dir, const Eigen::VectorXd &center)
int appendForceStopObservations (gpr::Observation &observations, const ForceStopHandoffStencil &handoff)
bool seedDimerModeFromForceStop (gpr::Coord &orient, const ForceStopHandoffStencil &handoff)
void certifyForceStoppedNeb (GPNEBResult &result, NEBOracle &oracle, const GPNEBConfig &config, const gpr::AtomsConfiguration *atoms)
int vibrationalIndexOuterBudget (const GPNEBConfig &config, int n_images)
 Outer-iteration cap, including the per-image reading.
IndexGateAction decideIndexGate (bool pass, bool cap_remains)
VibrationalIndexClass classifyVibrationalIndex (const Eigen::VectorXd &curvatures, double resolution)
VibrationalIndexMeasurement indexFromCartesianColumns (const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double move, const Eigen::VectorXd *center_gradient=nullptr, const Eigen::VectorXi *frozen=nullptr, bool anchored=false, const Eigen::MatrixXd *measured=nullptr)
template<typename Force>
VibrationalIndexMeasurement measureVibrationalIndex (const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, double move, const Force &force, const Eigen::VectorXd *center_gradient=nullptr, const Eigen::VectorXi *frozen=nullptr, gpr::optim::VibrationalStencil stencil=gpr::optim::VibrationalStencil::Full, bool periodic=false)
constexpr double indexGateVarianceToNoise () noexcept
constexpr double indexGateNoiseFloor () noexcept
 Noise variance a noise-free fit is credited with in that comparison.
double indexGateVarianceThreshold (double noise_variance) noexcept

Variables

constexpr int kMaxConsecutiveOracleFailures = 8
constexpr int kCompositionTraceFormatVersion = 1
 Bump when the on-disk golden format changes incompatibly.
constexpr int kPeriodicBandImages = 8
 Images between the endpoints. GPLocalBand's constructor default.
constexpr double kPeriodicBandFmax = 0.05
 Force tolerance of GPLocalBand.run, eV/Angstrom.
constexpr int kPeriodicBandSteps = 1000
 Outer-iteration budget of GPLocalBand.run.
constexpr double kPeriodicBandMaxMove = 0.2

Detailed Description

The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition, IDPP start.

Typedef Documentation

◆ NEBBatchOracle

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

Whole-band oracle: evaluates every geometry in one call (an AOTI band package runs one graph call per chunk). Same contract per element as ~NEBOracle~; falls back internally when the potential has no batch surface.

Definition at line 89 of file GPNEB.h.

◆ NEBOracle

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

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

Definition at line 82 of file GPNEB.h.

◆ ObservationVarianceEstimator

Initial value:
std::function<ObservationVariance(const Eigen::VectorXd& positions)>
Predictive variance of one joint energy-and-gradient observation.

Posterior variance estimator for one joint oracle observation.

The returned record contains the energy variance and every gradient variance. OIE acquisition projects that complete record onto the quantity resolved by each strategy.

Definition at line 100 of file GPNEB.h.

Enumeration Type Documentation

◆ AcquisitionType

enum class gpr::neb::AcquisitionType
strong

Available acquisition strategies for image selection.

Enumerator
MaxVariance 
MaxForce 
UCB 
ThompsonSampling 
IMSPE 
ExpectedImprovement 
PriorityCascade 
TPE 
PSBAX 

Definition at line 31 of file AcquisitionStrategy.h.

31 {
32 MaxVariance, // Select image with highest posterior force variance
33 MaxForce, // Select image with highest NEB force
34 UCB, // Upper confidence bound: force magnitude + kappa * sigma_perp
35 ThompsonSampling, // Sample from GP posterior, select maximum force
36 // magnitude
37 IMSPE, // GP-OIE chain IMSPE (Sacks 1989, R&W 5.4.2).
38 // selectNextImage scores joint energy+gradient
39 // variance, not the chain IMSPE reduction.
40 ExpectedImprovement, // EI for argmax-E saddle finding (R&W 5.4.1).
41 // selectNextImage scores energy variance.
42 PriorityCascade, // GP-OIE outer-loop cascade selector.
43 // selectNextImage scores joint energy+gradient
44 // variance.
45 TPE, // GP-OIE interior-index TPE
46 // (oie::selectTpeOracleTarget). selectNextImage
47 // scores joint energy+gradient variance and
48 // does not use kappa.
49 PSBAX, // GP-OIE chain PS-BAX (Cheng et al. NeurIPS
50 // 2024; InfoBAX, Neiswanger et al. ICML 2021).
51 // selectNextImage scores joint energy+gradient
52 // variance.
53};

◆ AdaptiveSo3EvaluationMode

Enumerator
Raw 
ScatterProbe 
Averaged 

Definition at line 161 of file GPNEB.h.

◆ BandStallAction

enum class gpr::neb::BandStallAction
strong

What to do when the max band force stops falling.

Enumerator
Continue 
Restore 
Stop 

Definition at line 17 of file BandStall.h.

◆ GPNEBConvergenceStatus

Enumerator
NotConverged 
ForceTolerance 
ModelNoiseFloor 

Definition at line 228 of file GPNEB.h.

228 {
229 NotConverged = 0,
230 ForceTolerance = 1,
231 ModelNoiseFloor = 2,
232};

◆ GPNEBStopReason

enum class gpr::neb::GPNEBStopReason
strong

Result of GP-NEB optimization.

Enumerator
Unspecified 

No terminal condition has been assigned.

Converged 

The requested force and certificate conditions were satisfied.

IterationBudget 

The configured outer-iteration budget was exhausted.

WallClockLimit 

The shared monotonic wall-clock deadline was reached.

Definition at line 3670 of file GPNEB.h.

3670 {
3674 Converged,
3679};
@ WallClockLimit
The shared monotonic wall-clock deadline was reached.
@ Converged
The requested force and certificate conditions were satisfied.
Definition GPNEB.h:3674

◆ IndexGateAction

enum class gpr::neb::IndexGateAction
strong

What a force-quiet climbing image may do. Accept only an index-1 point. Continue steps along the soft mode while the search caps remain. Exhausted means those caps are spent and the point must not be reported as a saddle.

Enumerator
Accept 
Continue 
Exhausted 

Definition at line 26 of file VibrationalIndexGate.h.

◆ MetatomicSO3Policy

enum class gpr::neb::MetatomicSO3Policy
strong

Rotational averaging policy shared by file and command-line configuration.

Enumerator
Raw 
Adaptive 
Always 

Definition at line 10 of file MetatomicSO3Policy.h.

◆ MmfHandoffPolicy

enum class gpr::neb::MmfHandoffPolicy : std::uint8_t
strong

Scheduler that owns the first MMF lease. Classical OCINEB follows the adaptive force handoff directly. A GP-assisted band retains ownership until its information/optimization state certifies that local MMF is the next useful action.

Enumerator
Auto 
ClassicalAdaptive 
GpBandFallback 

Definition at line 70 of file OCINEBController.h.

◆ MMFRejectKind

enum class gpr::neb::MMFRejectKind
strong
Enumerator
None 
UncertifiedPath 
ForceOnlyBelowEndpoint 
SeedEnergyDescent 
Displacement 
RecoveryPortfolioExhausted 

Recovery portfolio had negative-curvature phases but none accepted after true-PES certification (Baker 05 freeze).

Definition at line 55 of file OCINEBController.h.

◆ MMFStatus

enum class gpr::neb::MMFStatus : int
strong

Outcome of one MMF burst, mirroring eOn's enum class.

Enumerator
Helped 

Mode converged, alignment in tol.

MaxIterations 

Hit dimer iter cap; usable but no signal.

Skipped 

Invalid input or mode drifted outside tol.

PositiveCurvature 

CI was a minimum; restore position.

Definition at line 48 of file OCINEBController.h.

48 : int {
49 Helped = 0,
50 MaxIterations = 1,
51 Skipped = -1,
53};
@ Helped
Mode converged, alignment in tol.
@ MaxIterations
Hit dimer iter cap; usable but no signal.
@ Skipped
Invalid input or mode drifted outside tol.
@ PositiveCurvature
CI was a minimum; restore position.

◆ NEBMode

enum class gpr::neb::NEBMode
strong

NEB evaluation mode.

Enumerator
Standard 
AIE 
OIE 
GP_AIE 
GP_OIE 
GP_LOCAL 

Definition at line 68 of file GPNEB.h.

68 {
69 Standard, // All images evaluated every iteration (no GP)
70 AIE, // All images evaluated on the true potential.
71 OIE, // One Image Evaluated per iteration (GP-accelerated)
72 GP_AIE, // GP inner relaxation, then oracle every interior image.
73 GP_OIE, // GP inner relaxation, then one oracle eval at the selected image.
74 GP_LOCAL, // Band relaxed on a pair-additive spline baseline of the
75 // whole system plus a Cartesian GP residual over the atoms
76 // that carry the path motion; one image measured per round.
77};

◆ ObservationRetention

enum class gpr::neb::ObservationRetention
strong

Whether an acquisition still needs a ledger entry when admitted to a model.

Enumerator
RecordAcquisition 
AlreadyRecorded 

Definition at line 61 of file Session.h.

◆ PeriodicBandInitial

enum class gpr::neb::PeriodicBandInitial
strong

How the initial path is built.

Enumerator
Linear 
Idpp 
Sidpp 

Definition at line 38 of file PeriodicBand.h.

Function Documentation

◆ activeGpRgsaddleSurface()

rgsaddle_status_t gpr::neb::activeGpRgsaddleSurface ( void * user,
rgsaddle_surface_request_t * req )

Definition at line 317 of file RgsaddleClient.cpp.

319{
320 if (user == nullptr || req == nullptr || req->positions == nullptr ||
321 req->energies == nullptr || req->gradients == nullptr ||
322 req->n_images <= 0 || req->n_atoms <= 0) {
323 return RGSADDLE_NULL_SESSION;
324 }
325 if (req->version.major != RGSADDLE_ABI_MAJOR) return RGSADDLE_NULL_SESSION;
326 auto* ctx = static_cast<ActiveGpRgsaddleUser*>(user);
327 if (ctx->gp == nullptr || ctx->atomic_nrs == nullptr)
328 return RGSADDLE_NULL_SESSION;
329 const long n_images = static_cast<long>(req->n_images);
330 const long n_atoms = static_cast<long>(req->n_atoms);
331 const long dof = 3 * n_atoms;
332 std::vector<double> forces(static_cast<std::size_t>(dof));
333 for (long im = 0; im < n_images; ++im) {
334 const double* p = req->positions + im * dof;
335 double* g = req->gradients + im * dof;
336 double e = 0.0;
337 double var = 0.0;
338 const int rc = ctx->gp->force(n_atoms, p, ctx->atomic_nrs,
339 forces.data(), &e, &var, ctx->box);
340 if (rc != 0) return RGSADDLE_SURFACE_FAILED;
341 req->energies[im] = e;
342 for (long k = 0; k < dof; ++k)
343 g[k] = -forces[static_cast<std::size_t>(k)];
344 }
345 return RGSADDLE_OK;
346}
eon_relax_band_t eon_relax_surface_fn void * user

◆ appendForceStopObservations()

int gpr::neb::appendForceStopObservations ( gpr::Observation & observations,
const ForceStopHandoffStencil & handoff )

Append stencil rows the saddle has not already stored. Returns the number of rows added. An empty observation takes its width from the handoff.

Definition at line 436 of file VibrationalIndexGate.cpp.

438{
439 if (handoff.positions.cols() == 0 || handoff.gradients.rows() == 0)
440 return 0;
441 const Eigen::Index dof = handoff.positions.rows();
442 if (handoff.gradients.cols() != dof) return 0;
443 if (observations.R.cols() != 0 && observations.R.cols() != dof) return 0;
444 int added = 0;
445 for (Eigen::Index col = 0; col < handoff.positions.cols(); ++col) {
446 if (col >= handoff.gradients.rows()) break;
447 const Eigen::VectorXd position = handoff.positions.col(col);
448 const Eigen::VectorXd gradient = handoff.gradients.row(col).transpose();
449 if (!position.allFinite() || !gradient.allFinite()) continue;
450 if (gpr::optim::forceStopHeldColumn(observations.R.transpose(),
451 position) >= 0)
452 continue;
453 const Eigen::Index row = observations.R.rows();
454 observations.R.conservativeResize(row + 1, dof);
455 observations.E.conservativeResize(row + 1, 1);
456 observations.G.conservativeResize(row + 1, dof);
457 observations.R.row(row) = position.transpose();
458 observations.E(row, 0) =
459 col < static_cast<Eigen::Index>(handoff.energies.size())
460 ? handoff.energies[static_cast<std::size_t>(col)]
461 : 0.0;
462 observations.G.row(row) = gradient.transpose();
463 ++added;
464 }
465 return added;
466}
Eigen::Index forceStopHeldColumn(const Eigen::MatrixXd &held, const Eigen::VectorXd &query, double relative=1e-6)
FieldMatrixd E

◆ applyConfigToGP()

void gpr::neb::applyConfigToGP ( const GPNEBConfig & config,
gpr::GaussianProcessRegression & gp )

Push a GPNEBConfig onto a GP: profile first, then the explicit objective and every switch keyed on the effective objective.

Definition at line 8296 of file GPNEB.cpp.

8298{
8300 const double pair_cutoff = bandPairCutoff(config);
8301 const gpr::PairCutoff validate_cutoff(pair_cutoff,
8302 config.pair_cutoff_width);
8303 if (gp.getAtomsConfig().pair_cutoff != pair_cutoff ||
8305 auto atoms = gp.getAtomsConfig();
8306 atoms.pair_cutoff = pair_cutoff;
8307 atoms.pair_cutoff_width = config.pair_cutoff_width;
8308 gp.updateConfiguration(atoms);
8309 }
8310 // Covering energy/gradient layouts reuse pair derivatives in curvature
8311 // assembly, including an open boundary. The cutoff selected above is
8312 // left as it is. A configuration-pair tile has one owner across MPI
8313 // ranks; a layout that does not cover falls back to the channel blocks.
8315 const bool objective_requires_hssvd = config.hyperparameter_objective ==
8317 if (config.rgmin_method_set)
8318 gp.setRgminMethod(static_cast<rgmin_method_t>(config.rgmin_method));
8324 gp.setHssvdBackend(config.use_hssvd_solver || objective_requires_hssvd);
8326 objective_requires_hssvd);
8336 gpr::detail::validateRigidNullDeflationConfiguration(
8338 if (!config.principled_nugget) gp.setPrincipledNugget(false);
8339 if (!config.use_rigid_null_deflation) gp.setRigidNullDeflation(false);
8342 gp.setUseLsPrior(config.use_ls_prior);
8344 if (!config.gp_population_prior.empty()) {
8345 std::ifstream table(config.gp_population_prior);
8347 if (!table || !population.read(table))
8348 throw std::runtime_error("population prior table unreadable: " +
8349 config.gp_population_prior);
8350 gp.setPopulationPrior(std::move(population));
8351 }
8360 gp.setKappaMax(config.kappa_max);
8367 if (config.scalapack_block_size > 0)
8369 if (config.scalapack_nprow > 0)
8371 if (config.theta_shift_skip_tol > 0.0)
8376 gp.setAnnealStage(
8377 config.gp_anneal_stage,
8378 static_cast<std::size_t>(std::max(0, config.gp_anneal_budget)),
8379 static_cast<std::size_t>(std::max(1, config.gp_anneal_replicas)),
8380 static_cast<std::size_t>(std::max(0, config.gp_anneal_every)),
8381 static_cast<std::uint64_t>(config.seed));
8386 }
8387 // RFF request is uncertainty-mode-agnostic: the cutoff-gated
8388 // RFF-replace path (updateModelWithFullData) serves mean AND variance
8389 // from the RFF posterior for every mode (MAP included), so enable it
8390 // unconditionally. Above the design cutoff it replaces the exact
8391 // dual-kernel eigensolve; below it, it leaves the exact path active.
8392 if (config.rff_features == -1) {
8394 } else if (config.rff_features < -1) {
8395 throw std::invalid_argument(
8396 "rff_features must be -1 (auto), 0, or positive");
8397 } else {
8399 }
8400
8401 // Classic profiles select the joint prior, objective and normalization.
8402 // The configured solver optimizes that objective independently.
8403 gp.setModelProfile(config.model_profile);
8404 if (config.rff_features == -1) {
8406 }
8412 // The classic profiles reset the objective to NLML. An objective named
8413 // on the command line is a decision, not a default: re-apply it after
8414 // the profile so `--hyperparameter-objective loo` fits LOO under
8415 // gprd_zbl instead of silently fitting NLML (every downstream switch
8416 // below keys on the effective mode, so it must be settled here).
8419 config.hyperparameter_objective) {
8421 }
8422 {
8423 const auto effective = gp.getHyperparameterObjectiveMode();
8424 const char* name =
8425 effective == gpr::HyperparameterObjectiveMode::LOO ? "loo"
8427 ? "local_loo"
8428 : "nlml";
8429 neb_log() << "GP objective: " << name
8431 ? " (command line)"
8432 : " (model profile default)")
8433 << "\n";
8434 }
8437 }
8438
8439 // Noise fitting follows the effective objective, including an explicit
8440 // command-line choice. The trailing-noise gradient lives in the NLML
8441 // paths; the LOO direction loop has no branch for it.
8443 config.learn_likelihood_noise &&
8446 gp.setRobustNu(config.robust_nu);
8447 gp.setFitStepStop(config.fit_step_stop);
8448
8449 // LOO requires the dual basis. Other objectives honor the requested
8450 // HS-SVD setting independently of the model profile.
8451 const bool effective_objective_requires_hssvd =
8455 effective_objective_requires_hssvd);
8457 effective_objective_requires_hssvd);
8460}
void setObjectiveStationaritySkipAuto(bool use) noexcept
void setOptimizationSubsetHistory(int rows) noexcept
void setOutputScaleFloor(bool enabled) noexcept
void setHssvdDualRandomizedSketch(int sketch_size) noexcept
void setHyperparameterObjectiveMode(HyperparameterObjectiveMode mode) noexcept
void setUncertaintyMode(UncertaintyMode mode)
void setFitStepStop(bool use) noexcept
Whether the auto stationarity mode also ends each fit at its scale.
HyperparameterOptimizationMode getHyperparameterOptimizationMode() const noexcept
void setHssvdLocalPosteriorActiveSetSize(int size) noexcept
void setUsePsisDeterministicGrid(bool use) noexcept
void setHutchinsonProbes(int num_probes) noexcept
void setSubsetFailureEscalation(bool enabled) noexcept
void setHssvdDualChopTolerance(double tol) noexcept
void setAtomicEnvironmentModel(bool enabled)
void setKappaMax(double kappa_max) noexcept
void setScalapackBlockSize(int block_size) noexcept
void setWallClockLimit(std::shared_ptr< const WallClockLimit > limit)
void setVarianceConvention(VarianceConvention convention) noexcept
void setDisableOutputNormalization(bool d) noexcept
void setRigidNullDeflation(bool enabled)
Opt-in rigid-motion nullspace deflation for free systems.
void setChemFactorizedHyperparameters(bool enabled) noexcept
void setPriorMeanStatistic(PriorMeanStatistic statistic) noexcept
void setVarianceSubsetConfigurations(int configurations) noexcept
void setModelProfile(GPModelProfile profile)
void setRgminInitialLogMove(double distance) noexcept
void setHyperparameterOptimizationMode(HyperparameterOptimizationMode mode) noexcept
void setPopulationPrior(priors::PopulationPrior prior)
void setRgminMethod(rgmin_method_t m) noexcept
void setPairLocalDirectionalTiles(bool enabled) noexcept
void setUseLogNormalMagnPrior(bool use) noexcept
void setHssvdBackend(bool enabled) noexcept
void setHssvdDualLapackRrr(bool enabled) noexcept
void setHssvdObjectiveContractions(bool enabled) noexcept
void enableRFFFeatureSelection(double force_tol_fraction=0.0)
void setLengthScaleSeedChemicalFloor(bool enabled) noexcept
void setActivePosteriorRefits(bool enabled) noexcept
void updateConfiguration(const AtomsConfiguration &conf_info)
Update the internal atoms configuration. Use this when the set of active/frozen atoms changes dynamic...
void setRgminInitialLogMoveWholeSession(bool whole_session) noexcept
void setEnvironmentResiduals(bool enabled)
void setAdditivePairResiduals(bool enabled) noexcept
void setSkipUnchangedSubsetFit(bool enabled) noexcept
void setHssvdLocalActiveSetSize(int size) noexcept
void setObjectiveStationaritySkipThreshold(double threshold) noexcept
const AtomsConfiguration & getAtomsConfig() const
void setAnnealStage(bool enabled, std::size_t budget, std::size_t replicas, std::size_t every, std::uint64_t seed)
HyperparameterObjectiveMode getHyperparameterObjectiveMode() const noexcept
void setOptimizeSigma2(bool optimize) noexcept
Definition LikGaussian.h:82
bool read(std::istream &input)
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40
void configureStablePosteriorVariance(bool enabled) noexcept
Turn stable posterior variance reductions on or off for the process.
Definition ExactSchur.h:34
DistributedFactorization distributedFactorization() noexcept
Process-wide selection; Reproducible unless configured otherwise.
void configureDistributedFactorization(DistributedFactorization mode)
static double bandPairCutoff(const GPNEBConfig &config)
Definition GPNEB.cpp:8289
double theta_shift_skip_tol
Definition GPNEB.h:790
gpr::HyperparameterOptimizationMode hyperparameter_mode
Definition GPNEB.h:800
gpr::linalg::DistributedFactorization linalg_mode
Definition GPNEB.h:782
gpr::GaussianProcessRegression::VarianceConvention variance_convention
Definition GPNEB.h:562
gpr::UncertaintyMode uncertainty_mode
Definition GPNEB.h:559
bool disable_output_normalization
Definition GPNEB.h:569
bool hssvd_dual_lapack_rrr
Definition GPNEB.h:766
bool active_posterior_refits
Definition GPNEB.h:690
bool ls_seed_chemical_floor
Definition GPNEB.h:726
double rgmin_initial_log_move
Definition GPNEB.h:736
unsigned int seed
Definition GPNEB.h:505
bool hyperparameter_objective_explicit
Definition GPNEB.h:808
int hssvd_local_active_set_size
Definition GPNEB.h:767
bool environment_residuals
Definition GPNEB.h:691
double rff_force_tol_fraction
Definition GPNEB.h:754
double pair_cutoff_width
Definition GPNEB.h:428
bool subset_failure_escalation
Definition GPNEB.h:733
bool additive_pair_residuals
Definition GPNEB.h:695
bool use_psis_deterministic
Definition GPNEB.h:565
GPModelProfile model_profile
Definition GPNEB.h:689
int hssvd_local_posterior_active_set_size
Definition GPNEB.h:768
bool skip_unchanged_subset_fit
Definition GPNEB.h:746
bool theta_shift_skip_auto
Definition GPNEB.h:793
gpr::HyperparameterObjectiveMode hyperparameter_objective
Definition GPNEB.h:802
std::shared_ptr< const gpr::WallClockLimit > wall_clock_limit
Definition GPNEB.h:485
bool learn_likelihood_noise
Definition GPNEB.h:582
bool stable_posterior_variance
Definition GPNEB.h:786
bool rgmin_initial_log_move_whole_session
Definition GPNEB.h:739
bool use_rigid_null_deflation
Definition GPNEB.h:730
std::string gp_population_prior
Population prior table (gpr/prior/PopulationPrior.h); empty is none.
Definition GPNEB.h:722
int hssvd_dual_randomized_sketch
Definition GPNEB.h:765
PriorMeanStatistic prior_mean_statistic
Definition GPNEB.h:697
bool use_chem_factorized_hyper
Definition GPNEB.h:684
bool use_hssvd_objective_contractions
Definition GPNEB.h:760
bool use_lognormal_magn_prior
Definition GPNEB.h:720
double hssvd_dual_chop_tol
Definition GPNEB.h:764

◆ applyVibrationalIndexDecision()

void gpr::neb::applyVibrationalIndexDecision ( GPNEBResult & result,
const VibrationalIndexDecision & decision,
int outer_budget )

Apply decision to a force-converged result. A refusal with outer iterations still below outer_budget steps the climbing image and asks the caller to resume. A refusal with the budget spent clears convergence and sets index_refused.

Definition at line 262 of file VibrationalIndexGate.cpp.

265{
266 if (!result.converged || !result.path) return;
267 result.index_checked = decision.checked;
268 result.index_negative = decision.negative;
269 result.index_unresolved = decision.unresolved;
270 result.index_resolution = decision.resolution;
271 result.index_gate_true_calls += decision.true_calls;
272 result.oracle_calls += decision.true_calls;
273 result.oracle_calls_outer += decision.true_calls;
274 result.index_continue = false;
275 if (!decision.checked) return;
276 if (decision.accept) return;
277 const int image = result.max_energy_image;
278 auto& path = *result.path;
279 const bool interior = image > 0 && image < path.numImages() - 1;
280 const bool budget_left =
281 result.outer_iterations < outer_budget && interior &&
282 decision.step.size() == path.image(image).positions.size() &&
283 decision.step.allFinite();
284 result.converged = false;
286 if (!budget_left) {
287 result.index_refused = true;
288 std::cout << "[neb] vibrational index: action=refuse"
289 << " negative=" << decision.negative
290 << " unresolved=" << decision.unresolved
291 << " outer=" << result.outer_iterations
292 << " budget=" << outer_budget << "\n";
293 return;
294 }
295 path.image(image).positions += decision.step;
296 path.image(image).evaluated = false;
297 result.index_continue = true;
298 std::cout << "[neb] vibrational index: action=continue"
299 << " negative=" << decision.negative
300 << " unresolved=" << decision.unresolved
301 << " step=" << decision.step.norm()
302 << " outer=" << result.outer_iterations
303 << " budget=" << outer_budget << "\n";
304}
bool index_refused
A force-quiet point failed the index-1 gate and no budget remains.
Definition GPNEB.h:3690
bool index_checked
The vibrational-index gate ran on this result.
Definition GPNEB.h:3688
GPNEBConvergenceStatus convergence_status
Definition GPNEB.h:3685
bool index_continue
The gate stepped the climbing image; the caller resumes the search.
Definition GPNEB.h:3692
double index_resolution
Definition GPNEB.h:3695
std::unique_ptr< NEBPath > path
Definition GPNEB.h:3682

◆ bandPairCutoff()

double gpr::neb::bandPairCutoff ( const GPNEBConfig & config)
static

Definition at line 8289 of file GPNEB.cpp.

8290{
8291 return config.pair_cutoff > 0.0
8292 ? config.pair_cutoff
8294}
double uniqueImageRadius(const double cell[9]) noexcept
Definition MinImage.h:112
std::array< double, 9 > cell
Definition GPNEB.h:426

◆ bandStallWindow()

int gpr::neb::bandStallWindow ( int n_images,
int polished_dofs )
inlinenoexcept

Outers the max force may sit still before the climb is stalled.

The window is the longer of two band sizes. Every ordered pair of images is one step, since the worst force can sit on any image and be handed to any other. A polished subspace that is longer than that waits one step per polished coordinate instead.

Definition at line 39 of file BandStall.h.

40{
41 const int images = n_images > 1 ? n_images : 1;
42 const int pairs = images * (images - 1);
43 const int polished = polished_dofs > 0 ? polished_dofs : 0;
44 return std::max(pairs, std::max(polished, 1));
45}

◆ captureOieBandTrace()

OieBandTraceRecord gpr::neb::captureOieBandTrace ( const NEBPath & path,
GaussianProcessRegression & gp,
int outer,
const std::vector< double > & acquisition_variance,
bool con_geometry,
bool global_snapshot = true,
int oracle_calls = -1 )
nodiscard

Record what the outer iteration already holds (band energies, the measured mask, NEB force norms, the acquisition variance, hyperparameters, the oracle-call count). With global_snapshot the fitted global model is also queried at every image, without updating the band or refitting.

Definition at line 13 of file BandTrace.cpp.

17{
19 rec.outer = outer;
20 rec.oracle_calls = oracle_calls;
21 const int count = path.numImages();
22 rec.energies.resize(count);
23 rec.posterior_energy_variance.assign(count, 0.0);
24 rec.neb_force_norm.assign(count, 0.0);
25 rec.measured.resize(count);
26 if (global_snapshot)
27 rec.global_posterior_mean.R.resize(count,
28 path.image(0).positions.size());
29 if (con_geometry) rec.positions.resize(count);
30 for (int i = 0; i < count; ++i) {
31 const auto& image = path.image(i);
32 rec.energies[i] = image.energy;
33 rec.measured[i] = image.evaluated ? 1.0 : 0.0;
34 if (global_snapshot)
35 rec.global_posterior_mean.R.row(i) = image.positions.transpose();
36 if (i > 0 && i < count - 1) {
37 if (i < static_cast<int>(acquisition_variance.size()))
38 rec.posterior_energy_variance[i] = acquisition_variance[i];
39 const double force = path.nebForce(i).norm();
40 rec.neb_force_norm[i] = std::isfinite(force) ? force : 0.0;
41 }
42 if (con_geometry) {
43 rec.positions[i].assign(
44 image.positions.data(),
45 image.positions.data() + image.positions.size());
46 rec.gradients.resize(count);
47 rec.gradients[i].assign(
48 image.gradient.data(),
49 image.gradient.data() + image.gradient.size());
50 }
51 }
52 if (global_snapshot) {
56 }
58 rec.sigma2_noise = gp.getSigma2();
59 const auto& lengths = gp.getSexpAtCovarianceFunction().getLengthScaleRef();
60 rec.length_scales.assign(lengths.data(), lengths.data() + lengths.size());
61 return rec;
62}
void calculateVarianceDispatched(Observation &image1)
void calculatePotentialDispatched(Observation &image1)
Definition Predict.cpp:982
double getMagnSigma2()
Definition SexpatCF.inl:53
FieldMatrixd & getLengthScaleRef()
Definition SexpatCF.inl:58
int numImages() const
Definition NEBPath.h:338
const Eigen::VectorXd & nebForce(int i) const
Get the NEB force for image i.
Definition NEBPath.h:257
Image & image(int i)
Access image i.
Definition NEBPath.h:329
Eigen::VectorXd positions
Definition NEBPath.h:40
std::vector< double > energies
Definition BandTrace.h:19
int oracle_calls
Oracle calls made by the end of this outer iteration.
Definition BandTrace.h:26
std::vector< std::vector< double > > positions
Definition BandTrace.h:28
Observation global_posterior_variance
Definition BandTrace.h:36
std::vector< double > length_scales
Definition BandTrace.h:27
std::vector< double > posterior_energy_variance
Definition BandTrace.h:20
std::vector< double > measured
Definition BandTrace.h:22
Observation global_posterior_mean
Definition BandTrace.h:35
std::vector< double > neb_force_norm
Definition BandTrace.h:21
std::vector< std::vector< double > > gradients
Definition BandTrace.h:31

◆ certifyBandMidpoints()

BandMidpointCertificate gpr::neb::certifyBandMidpoints ( ActiveLearningSession & session,
const NEBPath & path,
double force_tol )
nodiscard

The chord midpoint of every segment is relaxed on the surrogate in the hyperplane perpendicular to the chord (no oracle call) until its in-plane force is below force_tol, and that valley-floor energy upper bound must not exceed the climbing image. force_tol <= 0 checks raw chord midpoints.

Definition at line 199 of file SaddlePolish.cpp.

202{
203 // The chord midpoint of two images on a curved path cuts the corner of
204 // the valley and climbs its wall, so its surrogate energy exceeds both
205 // images with no ridge between them (04_ch3o: four refinement passes
206 // and 72 oracle rows spent on such corner cuts). The question is whether
207 // the surrogate minimum-energy path between the images rises above the
208 // climbing image, so the midpoint is relaxed on the surrogate in the
209 // hyperplane perpendicular to the chord, descent with an Armijo
210 // backtracking line search and no oracle call, until the in-plane force
211 // is below the band tolerance. A ridge the band straddles keeps that
212 // valley-floor point above the climbing image; a corner cut drops it to
213 // the floor. The point may not wander further than one chord length
214 // from the midpoint, beyond which it no longer describes this segment,
215 // and a trial point is taken only where the surrogate is trusted: its
216 // posterior energy variance no larger than the model noise floor (the
217 // acquisition floor of the search) or than the variance at the chord
218 // midpoint it started from, so the descent never moves into territory
219 // the model knows less well than its starting point. Descent on an
220 // untrusted surrogate finds its holes (a synthetic valley fit dropped
221 // 250 eV within 0.1 A of the training grid). The descent stops as soon
222 // as the point is no higher than the climbing image: the question is
223 // answered there.
225 const int n = path.numImages();
226 const int ci = detail::climbingStopImage(path);
227 if (n < 3 || ci <= 0 || ci >= n - 1) return out;
228 const double e_ci = path.image(ci).energy;
229 if (!std::isfinite(e_ci)) return out;
230 const double tol =
231 (std::isfinite(force_tol) && force_tol > 0.0) ? force_tol : 0.0;
232 constexpr int kMaxRelaxSteps = 200;
233 constexpr int kMaxBacktracks = 24;
234 constexpr double kArmijo = 1e-4;
235 constexpr double kEnergyConfidence = 2.0;
236 const double variance_floor = std::max(0.0, session.gp.getSigma2());
237 out.evaluated = true;
238 out.holds = true;
239 out.excess = -std::numeric_limits<double>::infinity();
240 double worst_upper_excess = -std::numeric_limits<double>::infinity();
241 const double nan = std::numeric_limits<double>::quiet_NaN();
242 out.segment_excess.assign(static_cast<std::size_t>(n - 1), nan);
243 out.segment_raw_excess.assign(static_cast<std::size_t>(n - 1), nan);
244 out.segment_variance.assign(static_cast<std::size_t>(n - 1), nan);
245 out.segment_position.assign(static_cast<std::size_t>(n - 1),
246 Eigen::VectorXd());
247 for (int i = 0; i + 1 < n; ++i) {
248 const Eigen::VectorXd& a = path.image(i).positions;
249 const Eigen::VectorXd& b = path.image(i + 1).positions;
250 if (a.size() != b.size() || a.size() == 0) continue;
251 Eigen::VectorXd tau = b - a;
252 const double chord = tau.norm();
253 if (!(chord > 0.0) || !std::isfinite(chord)) continue;
254 tau /= chord;
255 const Eigen::VectorXd mid = 0.5 * (a + b);
256 Eigen::VectorXd x = mid;
257 double e = surrogateEnergy(session, x);
258 if (!std::isfinite(e)) continue;
259 const double e_raw = e;
260 const double v_mid = surrogateEnergyVariance(session, mid);
261 const double trust_cap = std::isfinite(v_mid)
262 ? std::max(variance_floor, v_mid)
263 : variance_floor;
264 double step = 0.5 * chord;
265 const auto descend_from_observed_rows = [&]() {
266 // A short-range posterior can be flat between its observations.
267 // Project nearby observed geometries into the segment plane to
268 // propose a descent where the local mean gradient is uninformative.
269 const auto& rows = session.training_obs.R;
270 if (rows.cols() != x.size()) return false;
271 std::vector<std::pair<double, Eigen::Index>> candidates;
272 const auto projected = [&](Eigen::Index row) -> Eigen::VectorXd {
273 const Eigen::VectorXd offset = rows.row(row).transpose() - mid;
274 return mid + offset - tau.dot(offset) * tau;
275 };
276 for (Eigen::Index row = 0; row < rows.rows(); ++row) {
277 const Eigen::VectorXd trial = projected(row);
278 if (trial.allFinite() && (trial - mid).norm() <= chord &&
279 !(trial.array() == x.array()).all())
280 candidates.emplace_back((trial - x).squaredNorm(), row);
281 }
282 std::sort(candidates.begin(), candidates.end());
283 for (const auto& candidate: candidates) {
284 const Eigen::VectorXd trial = projected(candidate.second);
285 const double trial_energy = surrogateEnergy(session, trial);
286 if (!std::isfinite(trial_energy) || !(trial_energy < e))
287 continue;
288 const double variance = surrogateEnergyVariance(session, trial);
289 if (!std::isfinite(variance) || variance > trust_cap) continue;
290 x = trial;
291 e = trial_energy;
292 step = 0.5 * chord;
293 return true;
294 }
295 return false;
296 };
297 for (int it = 0; it < kMaxRelaxSteps && tol > 0.0 && e > e_ci; ++it) {
298 const Eigen::VectorXd g = surrogateGradient(session, x);
299 if (g.size() != x.size() || !g.allFinite()) break;
300 Eigen::VectorXd f = -(g - g.dot(tau) * tau);
301 const double fn = f.norm();
302 if (!(fn > tol)) {
303 if (descend_from_observed_rows()) continue;
304 break;
305 }
306 f /= fn;
307 bool accepted = false;
308 const double initial_step = step;
309 bool rejected_by_variance = false;
310 for (int direction = 0; direction < 2 && !accepted; ++direction) {
311 if (direction == 1) {
312 if (!rejected_by_variance) break;
313 Eigen::VectorXd normal =
314 surrogateEnergyVarianceGradient(session, x);
315 if (normal.size() != x.size() || !normal.allFinite()) break;
316 normal -= normal.dot(tau) * tau;
317 const double normal_norm = normal.norm();
318 if (std::getenv("GPR_MIDPOINT_DEBUG"))
319 std::cerr << "[midpoint] seg=" << i
320 << " energy_direction=" << f.transpose()
321 << " variance_gradient=" << normal.transpose()
322 << " cap=" << trust_cap << std::endl;
323 if (!(normal_norm > 0.0)) break;
324 normal /= normal_norm;
325 // The bisector of energy descent and variance descent
326 // decreases both functions to first order. At an active
327 // variance boundary, reducing the length of an outward
328 // energy gradient alone cannot produce a feasible step.
329 f -= normal;
330 const double feasible_norm = f.norm();
331 if (!(feasible_norm >
332 std::sqrt(std::numeric_limits<double>::epsilon())))
333 break;
334 f /= feasible_norm;
335 step = initial_step;
336 }
337 const double descent = -g.dot(f);
338 if (!(descent > 0.0)) break;
339 for (int ls = 0; ls < kMaxBacktracks; ++ls) {
340 const Eigen::VectorXd xt = x + step * f;
341 if ((xt.array() == x.array()).all()) break;
342 if ((xt - mid).norm() > chord) {
343 step *= 0.5;
344 continue;
345 }
346 const double et = surrogateEnergy(session, xt);
347 const double vt = surrogateEnergyVariance(session, xt);
348 const bool trusted = std::isfinite(vt) && vt <= trust_cap;
349 if (std::getenv("GPR_MIDPOINT_DEBUG") &&
350 (ls == 0 || ls + 1 == kMaxBacktracks))
351 std::cerr << "[midpoint] seg=" << i
352 << " direction=" << direction << " ls=" << ls
353 << " step=" << step << " e=" << e
354 << " trial=" << et << " variance=" << vt
355 << " cap=" << trust_cap
356 << " descent=" << descent << std::endl;
357 rejected_by_variance = rejected_by_variance || !trusted;
358 if (trusted && std::isfinite(et) && et < e &&
359 et <= e - kArmijo * step * descent) {
360 x = xt;
361 e = et;
362 accepted = true;
363 step = std::min(2.0 * step, chord);
364 break;
365 }
366 step *= 0.5;
367 }
368 }
369 if (!accepted) {
370 if (descend_from_observed_rows()) continue;
371 break;
372 }
373 if (std::getenv("GPR_MIDPOINT_DEBUG")) {
374 std::cerr << "[midpoint] seg=" << i << " it=" << it
375 << " e=" << e << " fn=" << fn << " step=" << step
376 << " disp=" << (x - mid).norm() << " chord=" << chord
377 << std::endl;
378 }
379 }
380 if (std::getenv("GPR_MIDPOINT_DEBUG")) {
381 std::cerr
382 << "[midpoint] seg=" << i << " final e=" << e
383 << " e_ci=" << e_ci
384 << " e_raw=" << surrogateEnergy(session, mid)
385 << " variance=" << surrogateEnergyVariance(session, x)
386 << " magn="
388 << " lengths="
390 << std::endl;
391 }
392 const double excess = e - e_ci;
393 const double v_x = surrogateEnergyVariance(session, x);
394 // A mean below the climbing image cannot certify an unsampled gap
395 // whose posterior still permits a higher barrier. The measured
396 // certificate resolves these two-standard-deviation upper bounds.
397 const double uncertainty =
398 std::isfinite(v_x)
399 ? kEnergyConfidence *
400 std::sqrt(std::max(0.0, v_x - variance_floor))
401 : std::numeric_limits<double>::infinity();
402 const double upper_excess = excess + uncertainty;
403 out.segment_excess[static_cast<std::size_t>(i)] = excess;
404 out.segment_raw_excess[static_cast<std::size_t>(i)] = e_raw - e_ci;
405 out.segment_variance[static_cast<std::size_t>(i)] = v_x;
406 out.segment_position[static_cast<std::size_t>(i)] = x;
407 if (upper_excess > worst_upper_excess) {
408 worst_upper_excess = upper_excess;
409 out.excess = excess;
410 out.raw_excess = e_raw - e_ci;
411 out.worst_segment = i;
412 out.worst_position = x;
413 out.worst_variance = v_x;
414 }
415 if (upper_excess > 0.0) out.holds = false;
416 }
417 if (!std::isfinite(out.excess)) out.excess = 0.0;
418 return out;
419}
@ x
Definition Enums.h:28
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
gpr::Observation training_obs
Definition Session.h:246
gpr::GaussianProcessRegression gp
Definition Session.h:471
double energy
Definition NEBPath.h:41

◆ certifyBandMidpointsMeasured()

BandMidpointCertificate gpr::neb::certifyBandMidpointsMeasured ( ActiveLearningSession & session,
const NEBPath & path,
double force_tol,
NEBOracle & oracle,
int max_measurements,
int * oracle_calls )
nodiscard

The surrogate certificate, with a refused midpoint measured before it is believed: a refusal rests on the surrogate at a point no row has sampled (16_h2po4_anion: chord midpoints of a proton-transfer band sit where the ZBL prior mean rises 0.13 to 0.56 eV above the climbing image, and each refusal bought a refinement pass of 100+ rows). One oracle row at the relaxed midpoint either corrects the surrogate, and the certificate is re-run, or confirms a ridge above the climbing image (true_ridge), which is the refusal the refinement is for. A hump the relaxation slid off into an unsampled valley is verified the same way (17_claisen: the chord between two images crossed 1.16 eV, the relaxed midpoint sat in a surrogate valley no row had seen, and the band kept a 0.28 eV conformational saddle for the 1.3 eV rearrangement). At most max_measurements rows; oracle_calls counts them when non-null.

Definition at line 421 of file SaddlePolish.cpp.

424{
426 certifyBandMidpoints(session, path, force_tol);
427 int measured = 0;
428 // A measured energy above the climbing image does not prove a ridge:
429 // the surrogate-relaxed point need not be the true in-plane minimum.
430 // The row corrects the surrogate and the certificate is re-run; the
431 // refusal stands only when the corrected surrogate still shows the
432 // ridge (04_ch3o: one measured excess of 0.097 eV read as a ridge
433 // would have bought a refinement pass the certificate did not need).
434 // Each row carries the true gradient at the relaxed point, so the
435 // loop is a measured in-plane descent: the corrected surrogate relaxes
436 // to a new point and that is measured next, up to max_measurements
437 // rows (one per segment). Only an exactly repeated position is stuck
438 // (04_ch3o: a 1e-3 A radius stopped the descent after two rows 0.1 eV
439 // above the climbing image and bought a refinement pass instead).
440 std::vector<Eigen::VectorXd> measured_at;
441 auto already_measured = [&](const Eigen::VectorXd& x) {
442 for (const auto& m: measured_at)
443 if (m.size() == x.size() && (m - x).norm() < 1e-6) return true;
444 return false;
445 };
446 bool any_measured_above = false;
447 Eigen::VectorXd measured_above_position;
448 while (mid.evaluated && !mid.holds && measured < max_measurements &&
449 mid.worst_segment >= 0 && mid.worst_position.size() > 0 &&
450 mid.worst_position.allFinite() &&
451 !already_measured(mid.worst_position)) {
452 const int ci = detail::climbingStopImage(path);
453 const double e_ci = path.image(ci).energy;
454 const auto [e_true, g_true] =
455 detail::evaluateOieOraclePosition(mid.worst_position, oracle);
456 ++measured;
457 if (oracle_calls != nullptr) ++(*oracle_calls);
458 if (!std::isfinite(e_true) ||
459 g_true.size() != mid.worst_position.size() || !g_true.allFinite())
460 break;
461 measured_at.push_back(mid.worst_position);
462 session.appendObservation(mid.worst_position, e_true, g_true);
463 (void)session.refitGPIfTrainingChanged(/*reinit_seeds=*/false);
464 std::cout << "[ocineb] midpoint measured: seg=" << mid.worst_segment
465 << " e_true-e_ci=" << (e_true - e_ci)
466 << " surrogate_excess=" << mid.excess
467 << " variance=" << mid.worst_variance << std::endl;
468 if (e_true > e_ci) {
469 // A true-surface point above the climbing image is conclusive:
470 // the band missed the pass in this segment. Relaxing and
471 // measuring the midpoint again only spends the budget (dacp2:
472 // the certificate's own loop ran out the cell).
473 any_measured_above = true;
474 measured_above_position = mid.worst_position;
475 break;
476 }
477 mid = certifyBandMidpoints(session, path, force_tol);
478 }
479 if (mid.evaluated && !mid.holds) {
480 mid.true_ridge = any_measured_above;
481 mid.measured_position = measured_above_position;
483 return mid;
484 }
485 // A hump the relaxation slid off: the raw chord midpoint lay above the
486 // climbing image and the relaxed point below it, in a region the
487 // surrogate has no row for. Verify the valley before trusting it.
488 const double noise_floor = std::max(0.0, session.gp.getSigma2());
489 std::vector<char> verified(mid.segment_excess.size(), 0);
490 while (mid.evaluated && mid.holds && measured < max_measurements) {
491 int target = -1;
492 double worst_raw = 0.0;
493 for (std::size_t i = 0; i < mid.segment_excess.size(); ++i) {
494 if (verified[i]) continue;
495 const double raw = mid.segment_raw_excess[i];
496 const double rel = mid.segment_excess[i];
497 const double var = mid.segment_variance[i];
498 if (!std::isfinite(raw) || !std::isfinite(rel) || !(raw > 0.0) ||
499 !(rel <= 0.0) || mid.segment_position[i].size() == 0)
500 continue;
501 if (std::isfinite(var) && var <= noise_floor) continue;
502 if (raw > worst_raw) {
503 worst_raw = raw;
504 target = static_cast<int>(i);
505 }
506 }
507 if (target < 0) break;
508 verified[static_cast<std::size_t>(target)] = 1;
509 const int ci = detail::climbingStopImage(path);
510 const double e_ci = path.image(ci).energy;
511 const Eigen::VectorXd x =
512 mid.segment_position[static_cast<std::size_t>(target)];
513 const auto [e_true, g_true] =
514 detail::evaluateOieOraclePosition(x, oracle);
515 ++measured;
516 if (oracle_calls != nullptr) ++(*oracle_calls);
517 if (!std::isfinite(e_true) || g_true.size() != x.size() ||
518 !g_true.allFinite())
519 break;
520 session.appendObservation(x, e_true, g_true);
521 (void)session.refitGPIfTrainingChanged(/*reinit_seeds=*/false);
522 std::cout << "[ocineb] midpoint verified: seg=" << target
523 << " raw_excess=" << worst_raw
524 << " e_true-e_ci=" << (e_true - e_ci) << " variance="
525 << mid.segment_variance[static_cast<std::size_t>(target)]
526 << std::endl;
527 if (e_true > e_ci) any_measured_above = true;
528 // The row corrects the surrogate; the certificate decides again.
529 const BandMidpointCertificate again =
530 certifyBandMidpoints(session, path, force_tol);
531 if (again.evaluated) {
532 mid = again;
533 if (mid.segment_excess.size() != verified.size())
534 verified.assign(mid.segment_excess.size(), 0);
535 }
536 if (!mid.holds) {
537 // A corrected surrogate that now refuses goes back through the
538 // refusal loop above only via the caller's next certificate
539 // call; report the refusal as measured.
540 mid.true_ridge = any_measured_above;
541 break;
542 }
543 }
545 return mid;
546}
Half measured(const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &options)
Full central difference of the oracle gradient: 2 d calls.
BandMidpointCertificate certifyBandMidpoints(ActiveLearningSession &session, const NEBPath &path, double force_tol)
bool refitGPIfTrainingChanged(bool reinit_seeds)
Definition Session.h:3301
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
double worst_variance
posterior variance there
int measurements
oracle rows bought by the measured variant
std::vector< double > segment_raw_excess
std::vector< Eigen::VectorXd > segment_position
std::vector< double > segment_variance
int worst_segment
segment with the highest energy upper bound
std::vector< double > segment_excess
Eigen::VectorXd worst_position
the relaxed midpoint of worst_segment
double excess
mean E_mid - E_ci for that segment (eV)

◆ certifyClimbingImageIndex()

ClimbingImageIndexCertificate gpr::neb::certifyClimbingImageIndex ( const NEBOracle & oracle,
ActiveLearningSession & session,
const Eigen::VectorXd & x_ci,
double e_ci,
const Eigen::VectorXd & g_ci,
double hessian_fd_step,
double max_move,
double force_tol,
const NEBBatchOracle * batch_oracle = nullptr,
Eigen::Index batch_chunk = 0 )
nodiscard

The stencil and the refinement pairs are oracle steps whose points are shared out over the ranks; a rank's points go through batch_oracle in one call when one is given (GPNEBConfig::batch_oracle and GPNEBConfig::oracle_batch_chunk).

Definition at line 559 of file SaddlePolish.cpp.

564{
566 const Eigen::Index n = x_ci.size();
567 if (n < 3 || g_ci.size() != n || !(hessian_fd_step > 0.0) ||
568 !std::isfinite(hessian_fd_step) || !(force_tol > 0.0)) {
569 out.reason = "invalid input";
570 return out;
571 }
572 const Eigen::VectorXd x = detail::broadcastRootVector(x_ci);
573 const gpr::Coord positions_row = x.transpose();
574 const Eigen::MatrixXd Q =
575 gpr::optim::physicalCurvatureBasis(positions_row, session.atoms_config);
576 const Eigen::Index dimension = Q.cols();
577 if (dimension < 2) {
578 out.reason = "fewer than two non-rigid modes";
579 return out;
580 }
581
582 const double h = hessian_fd_step;
583 const Eigen::MatrixXd H = surrogateHessian(session, x);
584 if (H.rows() != n || !H.allFinite()) {
585 out.reason =
586 "surrogate Hessian unavailable (rows=" + std::to_string(H.rows()) +
587 ")";
588 return out;
589 }
590 const Eigen::MatrixXd surrogate = Q.transpose() * H * Q;
591 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(surrogate);
592 if (es.info() != Eigen::Success) {
593 out.reason = "eigensolver failed";
594 return out;
595 }
596 out.evaluated = true;
597 out.surrogate_lambda1 = es.eigenvalues()(0);
598 out.surrogate_lambda2 = es.eigenvalues()(1);
599
600 // The complete coarse stencil: two calls along every physical direction.
601 const int probes = 2 * static_cast<int>(dimension);
602 Eigen::MatrixXd positions(n, probes);
603 for (Eigen::Index j = 0; j < dimension; ++j) {
604 positions.col(2 * j) = x + h * Q.col(j);
605 positions.col(2 * j + 1) = x - h * Q.col(j);
606 }
607 const auto observations = detail::evaluateOwnedOraclePositions(
608 positions, oracle, batch_oracle, batch_chunk);
609 out.oracle_calls = probes;
610 bool valid = true;
611 for (int i = 0; i < probes; ++i) {
612 if (observations.valid[i]) {
613 session.appendObservation(positions.col(i), observations.energy[i],
614 observations.gradient.row(i).transpose());
615 } else {
616 valid = false;
617 }
618 }
619 if (!valid) {
620 out.reason = "oracle probe failed";
621 (void)session.refitGPIfTrainingChanged(false);
622 return out;
623 }
624 out.rounds = static_cast<int>(dimension);
625 out.verified = true;
626
627 // The measured columns carry the same error model as the dimer's index
628 // certificate: entry by entry, the even stencil residual over the step
629 // (the cubic force term the central difference cannot see) above the
630 // roundoff of the two gradients, mapped into the physical basis. The
631 // surrogate Hessian is the prior of the smoothed spectrum, and the
632 // stationarity floor of a mode, sqrt(2 max(b f, 0)) with b its cubic
633 // coefficient and f the residual gradient along it, is the curvature
634 // below which no stationary point of the measured sign exists.
635 const Eigen::MatrixXd Q_sq = Q.array().square().matrix();
636 const auto physical_variance =
637 [&](const Eigen::VectorXd& cartesian_error) -> Eigen::VectorXd {
638 return Q_sq.transpose() * cartesian_error.array().square().matrix();
639 };
640 const double eps = std::numeric_limits<double>::epsilon();
641 // The roundoff floor of a column, as in the dimer's certificate: the
642 // scale of the measured actions and of the gradient at the point.
643 double action_scale = g_ci.norm();
644 for (Eigen::Index j = 0; j < dimension; ++j)
645 action_scale =
646 std::max(action_scale, (observations.gradient.row(2 * j) -
647 observations.gradient.row(2 * j + 1))
648 .norm() /
649 (2.0 * h));
650 const double roundoff_scale = eps * action_scale;
651 const auto roundoff_error = [&](const Eigen::VectorXd& g_plus,
652 const Eigen::VectorXd& g_minus,
653 double step) -> Eigen::VectorXd {
654 if (!(step > 0.0) || !std::isfinite(step) ||
655 g_plus.size() != g_minus.size() || !g_plus.allFinite() ||
656 !g_minus.allFinite()) {
657 return Eigen::VectorXd::Zero(g_plus.size());
658 }
659 return (eps * (g_plus.array().abs() + g_minus.array().abs()) /
660 (2.0 * step))
661 .max(roundoff_scale)
662 .matrix()
663 .eval();
664 };
665 struct ColumnStencil {
666 Eigen::VectorXd coarse_action; // Cartesian central difference
667 Eigen::VectorXd even_residual;
668 };
669 std::vector<gpr::optim::MeasuredHessianColumn> columns;
670 std::vector<ColumnStencil> stencils;
671 Eigen::MatrixXd second_differences = Eigen::MatrixXd::Zero(n, dimension);
672 columns.reserve(static_cast<std::size_t>(dimension));
673 for (Eigen::Index j = 0; j < dimension; ++j) {
674 const Eigen::VectorXd g_plus =
675 observations.gradient.row(2 * j).transpose();
676 const Eigen::VectorXd g_minus =
677 observations.gradient.row(2 * j + 1).transpose();
678 const Eigen::VectorXd coarse = (g_plus - g_minus) / (2.0 * h);
679 const Eigen::VectorXd even = 0.5 * (g_plus + g_minus) - g_ci;
680 const Eigen::VectorXd roundoff = roundoff_error(g_plus, g_minus, h);
681 Eigen::VectorXd error;
682 if (!even.allFinite() || !(h > 0.0) || !std::isfinite(h)) {
683 error = Eigen::VectorXd::Zero(even.size());
684 } else {
685 error = (even.array().abs() / h).max(roundoff.array()).matrix();
686 }
687 columns.push_back({Eigen::VectorXd::Unit(dimension, j),
688 Q.transpose() * coarse, physical_variance(error),
689 false});
690 stencils.push_back({coarse, even});
691 second_differences.col(j) = (2.0 / (h * h)) * even;
692 }
693 // Refinement of a coarse column: two calls at half the step; the
694 // Richardson combination is exact through the quartic force term and
695 // the difference of the two stencils is the truncation the coarse
696 // column carried, entry by entry.
697 const auto refine_column = [&](Eigen::Index j) {
698 auto& column = columns[static_cast<std::size_t>(j)];
699 const auto& stencil = stencils[static_cast<std::size_t>(j)];
700 Eigen::MatrixXd pair(n, 2);
701 pair.col(0) = x + 0.5 * h * Q.col(j);
702 pair.col(1) = x - 0.5 * h * Q.col(j);
703 const auto probed = detail::evaluateOwnedOraclePositions(
704 pair, oracle, batch_oracle, batch_chunk);
705 out.oracle_calls += 2;
706 bool probed_valid = true;
707 for (int i = 0; i < 2; ++i) {
708 if (probed.valid[i])
709 session.appendObservation(pair.col(i), probed.energy[i],
710 probed.gradient.row(i).transpose());
711 else
712 probed_valid = false;
713 }
714 if (!probed_valid) return false;
715 const Eigen::VectorXd g_plus = probed.gradient.row(0).transpose();
716 const Eigen::VectorXd g_minus = probed.gradient.row(1).transpose();
717 const Eigen::VectorXd fine = (g_plus - g_minus) / h;
718 const Eigen::VectorXd refined =
719 (4.0 * fine - stencil.coarse_action) / 3.0;
720 const Eigen::VectorXd truncation = (stencil.coarse_action - fine) / 3.0;
721 column.action = Q.transpose() * refined;
722 column.variance = physical_variance(
723 truncation.array()
724 .abs()
725 .max(roundoff_error(g_plus, g_minus, 0.5 * h).array())
726 .matrix());
727 column.refined = true;
728 std::cout << "[ocineb] index certificate refined column " << j << ": "
729 << Q.col(j).dot(stencil.coarse_action) << " coarse, "
730 << Q.col(j).dot(refined) << " extrapolated, truncation "
731 << Q.col(j).dot(truncation) << std::endl;
732 return true;
733 };
734 const Eigen::VectorXd gradient_physical = Q.transpose() * g_ci;
735 gpr::optim::SmoothedCurvatureSpectrum smoothed;
736 const auto stationarity_floor = [&](Eigen::Index k) {
738 Q, second_differences, Q * smoothed.modes.col(k));
739 const double f = gradient_physical.dot(smoothed.modes.col(k));
740 return std::sqrt(2.0 * std::max(b * f, 0.0));
741 };
742 // The resolution of an eigenvalue of the Hessian at this point is its
743 // posterior spread: what the validation stencil measures and accepts
744 // on. The stationarity floor is reported, not applied (see the
745 // dimer's certificate). The irreducible resolution is the best
746 // precision a fully refined stencil reaches; a sign inside it is
747 // undecidable and no column is refined for it.
748 const auto resolution = [&](Eigen::Index k) { return smoothed.spreads(k); };
749 const auto irreducible = [&](Eigen::Index k) { return smoothed.floors(k); };
750 const auto decidable = [&](Eigen::Index k) {
751 const double curvature = smoothed.mean_curvatures(k);
752 return curvature * curvature > irreducible(k) * irreducible(k);
753 };
754 // The verdict on the point: index one; a resolved minimum or a
755 // resolved higher-index point, each with the mode to leave along; or
756 // a lowest curvature no stencil resolves.
757 enum class IndexVerdict {
758 Undecided,
759 IndexOne,
760 Minimum,
761 HigherIndex,
762 Unresolved,
763 Polish
764 };
765 IndexVerdict verdict = IndexVerdict::Undecided;
766 double resolution1 = std::numeric_limits<double>::infinity();
767 double resolution2 = std::numeric_limits<double>::infinity();
768 while (verdict == IndexVerdict::Undecided) {
770 surrogate, columns, smoothed.valid ? &smoothed : nullptr,
771 session.gp.mpiContext());
772 out.local_spectrum_samples = smoothed.local_samples;
773 if (!smoothed.valid) {
774 out.reason = "projected eigensolver failed";
775 (void)session.refitGPIfTrainingChanged(false);
776 return out;
777 }
778 resolution1 = resolution(0);
779 resolution2 = resolution(1);
780 // The eigenvalues of the posterior mean Hessian: deterministic,
781 // exact for an exact stencil, and within the sampled spread of
782 // the sorted-eigenvalue posterior's mean, which the resolution
783 // already covers.
784 out.oracle_curvature1 = smoothed.mean_curvatures(0);
785 out.oracle_curvature2 = smoothed.mean_curvatures(1);
786 out.mode1 = Q * smoothed.modes.col(0);
787 out.mode2 = Q * smoothed.modes.col(1);
788 out.residual1 = h * resolution1;
789 out.residual2 = h * resolution2;
790 std::cout << "[ocineb] index certificate at energy " << e_ci
791 << ": lowest curvature " << out.oracle_curvature1
792 << " (resolution " << resolution1 << "), second "
793 << out.oracle_curvature2 << " (resolution " << resolution2
794 << ", spread " << smoothed.spreads(1)
795 << ", stationarity floor " << stationarity_floor(1)
796 << ", irreducible " << irreducible(1) << "), calls "
797 << out.oracle_calls << std::endl;
798 if (!(out.oracle_curvature1 + resolution1 < 0.0)) {
799 if (out.oracle_curvature1 - resolution1 > 0.0) {
800 out.reason = "resolved minimum";
801 verdict = IndexVerdict::Minimum;
802 break;
803 }
804 // The lowest curvature is not resolved negative: refine the
805 // coarse column it overlaps most, when a stencil can decide it.
806 const Eigen::Index coarse =
807 decidable(0)
808 ? gpr::optim::coarseColumnToRefine(smoothed, columns, 0)
809 : -1;
810 if (coarse >= 0 && refine_column(coarse)) continue;
811 out.reason = "lowest curvature is unresolved";
812 verdict = IndexVerdict::Unresolved;
813 break;
814 }
815 if (out.oracle_curvature2 - resolution2 > 0.0) {
816 out.reason = "resolved positive second curvature";
817 out.positive_complement_lower_bound =
818 out.oracle_curvature2 - resolution2;
819 verdict = IndexVerdict::IndexOne;
820 break;
821 }
822 if (out.oracle_curvature2 + resolution2 < 0.0) {
823 // Index two at the point; the escape is worth its calls only
824 // when the stationary point has index two as well (the
825 // cubic model along the mode, see the dimer's certificate).
827 Q, second_differences, Q * smoothed.modes.col(1));
828 const double f = gradient_physical.dot(smoothed.modes.col(1));
829 const double sigma_f = h * smoothed.measured_spreads(1);
830 const double sigma_b = 2.0 * sigma_f / (h * h);
831 const auto stationary = gpr::optim::stationaryCurvaturePosterior(
832 out.oracle_curvature2, resolution2, f, sigma_f, b, sigma_b);
833 std::cout << "[ocineb] index certificate: second curvature at the "
834 "stationary point in ["
835 << stationary.lower << ", " << stationary.upper
836 << "], undetermined fraction " << stationary.undetermined
837 << ", force target " << stationary.force_target
838 << std::endl;
839 if (stationary.valid && !(stationary.upper < 0.0) &&
840 stationary.force_decidable &&
841 stationary.force_target < force_tol) {
842 out.polish_force_target = stationary.force_target;
843 out.reason =
844 "second curvature negative at the point, "
845 "undetermined at the stationary point";
846 verdict = IndexVerdict::Polish;
847 break;
848 }
849 out.reason = "resolved negative second curvature";
850 verdict = IndexVerdict::HigherIndex;
851 break;
852 }
853 // A refinement decides the sign only when the stencil error, not
854 // the irreducible resolution, hides it.
855 const Eigen::Index coarse =
856 decidable(1)
857 ? gpr::optim::coarseColumnToRefine(smoothed, columns, 1)
858 : -1;
859 if (coarse >= 0 && refine_column(coarse)) continue;
860 // Within the irreducible resolution of zero the second curvature's
861 // sign is beyond every affordable stencil: no certificate and no
862 // escape, as the validation stencil refuses an unresolved mode.
863 out.reason = "second curvature unresolved within " +
864 std::to_string(resolution2) + " of zero";
865 verdict = IndexVerdict::Unresolved;
866 }
867 out.certified = verdict == IndexVerdict::IndexOne;
868 // A certified index ends the search at this point: no query follows that
869 // the stencil rows could inform, and conditioning on them factors a
870 // covariance of the band's rows plus two per physical direction. The
871 // session's training revision records the appended rows, so a caller
872 // that continues conditions or refits before its next query. A refused
873 // index continues from this posterior and needs it now.
874 if (!out.certified) (void)session.refitGPIfTrainingChanged(false);
875 const bool escape = verdict == IndexVerdict::Minimum ||
876 verdict == IndexVerdict::HigherIndex;
877 if (out.certified || !(max_move > 0.0) || !escape) return out;
878
879 // Leave the higher-index stationary point along the offending mode
880 // (mode 2 when the second curvature is negative, mode 1 when the image
881 // is not even a saddle along its lowest mode), toward the side the
882 // surrogate ranks lower.
883 const Eigen::VectorXd& mode =
884 verdict == IndexVerdict::HigherIndex ? out.mode2 : out.mode1;
885 const Eigen::VectorXd xa = x + max_move * mode;
886 const Eigen::VectorXd xb = x - max_move * mode;
887 const double ea = surrogateEnergy(session, xa);
888 const double eb = surrogateEnergy(session, xb);
889 // The side the surrogate ranks lower; a side without a finite energy
890 // is never chosen over one with.
891 const bool prefer_b = std::isfinite(eb) && (!std::isfinite(ea) || eb < ea);
892 out.displaced_positions = prefer_b ? xb : xa;
893 return out;
894}
DoubleDouble abs(DoubleDouble a)
Half surrogate(GaussianProcessRegression &gp, const Eigen::VectorXd &x, Kind kind, const Options &options)
Half refined(GaussianProcessRegression &gp, const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &raw_options)
Eigen::MatrixXd physicalCurvatureBasis(const gpr::Coord &positions, const gpr::AtomsConfiguration &config, bool exclude_rotations=true, RigidMotionMetric metric=RigidMotionMetric::MassWeighted)
double axisStencilDirectionalCubic(const Eigen::MatrixXd &axes, const Eigen::MatrixXd &second_differences, const Eigen::VectorXd &mode)
Eigen::Index coarseColumnToRefine(const SmoothedCurvatureSpectrum &spectrum, const std::vector< MeasuredHessianColumn > &columns, Eigen::Index k)
SmoothedCurvatureSpectrum smoothMeasuredCurvature(const Eigen::MatrixXd &prior, const std::vector< MeasuredHessianColumn > &columns, const SmoothedCurvatureSpectrum *previous=nullptr, const linalg::MpiContext &context=linalg::MpiContext::local())
StationaryCurvaturePosterior stationaryCurvaturePosterior(double c, double c_spread, double f, double f_spread, double b, double b_spread, Eigen::Index samples=detail::kSpectrumSamples)
FieldMatrixd Coord
Definition Macros.h:35
gpr::AtomsConfiguration atoms_config
Definition Session.h:1129
Eigen::Index local_samples
Spectrum samples evaluated by this process.

◆ certifyForceStoppedNeb()

void gpr::neb::certifyForceStoppedNeb ( GPNEBResult & result,
NEBOracle & oracle,
const GPNEBConfig & config,
const gpr::AtomsConfiguration * atoms )

The force loop has already stopped. Measure one Cartesian stencil, certify a first-order saddle, and refine only along a soft mode when the stencil has more than one negative mode. Does not resume the band.

Definition at line 481 of file VibrationalIndexGate.cpp.

484{
485 if (!config.force_stop_certificate) return;
486 if (!result.converged || !result.path) return;
487 const int image = result.max_energy_image;
488 NEBPath& path = *result.path;
489 if (image <= 0 || image >= path.numImages() - 1) return;
490 auto& climbing = path.image(image);
491 if (!climbing.evaluated || !std::isfinite(path.saddleForce(image)) ||
492 !(path.saddleForce(image) < config.conv_tol))
493 return;
494 const double step =
496 const gpr::optim::VibrationalStencil stencil_mode =
497 config.vibrational_stencil;
498 const Frame frame = frameFor(climbing.positions, atoms);
499 if (!frame.usable) return;
502 query.requested = config.force_stop_certificate;
505 stencil_cache.find(geometryKey(climbing.positions, stencil_mode)) !=
506 stencil_cache.end();
509 if (plan.defer_certificate) {
510 const auto outcome = gpr::optim::runForceStopCertificate(
511 [] { return gpr::optim::ForceStopMeasurement{}; },
512 [] { return -1; }, plan);
513 result.force_stop_certificate_calls = outcome.calls;
514 result.force_stop_certified = false;
515 result.force_stop_hand_off = outcome.hand_off;
516 result.force_stop_deferred = outcome.deferred_to_following_stage;
517 result.index_checked = false;
518 result.index_continue = false;
519 result.index_refused = false;
520 std::cout << "[neb] force-stop stencil: deferred to the saddle stage\n";
521 return;
522 }
525 const Eigen::VectorXd stopped_at = climbing.positions;
526 // A resumed band arrives with the calls of its earlier certificates.
527 const int earlier_calls = result.force_stop_certificate_calls;
528 const auto measure_once = [&]() {
529 gpr::optim::ForceStopMeasurement measured;
530 const Eigen::VectorXd center = climbing.positions;
531 const std::string key = geometryKey(center, stencil_mode);
532 const auto cached = stencil_cache.find(key);
533 if (cached != stencil_cache.end()) {
534 latest = cached->second.index;
535 stencil = cached->second.stencil;
536 measured = cached->second.measurement;
537 measured.calls = 0;
538 std::cout << "[neb] force-stop stencil: cached geometry"
539 << " negative=" << latest.negative
540 << " first_order=" << measured.first_order
541 << " higher_order=" << measured.higher_order << "\n";
542 return measured;
543 }
544 const bool reuse = climbing.gradient.size() == center.size() &&
545 climbing.gradient.allFinite() &&
546 std::isfinite(climbing.energy);
547 const Eigen::MatrixXd directions =
548 stencilDirections(frame, center, stencil_mode);
549 if (reuse) {
550 const CartesianOracleCenter held{center, climbing.energy,
551 climbing.gradient};
553 center, step, directions, oracle, held, &config.batch_oracle,
554 config.oracle_batch_chunk);
555 } else {
557 center, step, directions, oracle, &config.batch_oracle,
558 config.oracle_batch_chunk);
559 }
560 measured.calls = stencil.complete()
561 ? static_cast<int>(stencil.positions.cols() -
562 (stencil.center_reused ? 1 : 0))
563 : 0;
564 const Eigen::MatrixXd columns = stencilHessianColumns(stencil);
565 if (columns.rows() == center.size() && frame.usable) {
566 const Eigen::VectorXd* gradient =
567 reuse ? &climbing.gradient : nullptr;
569 columns, center, frame.masses, step, gradient, frame.frozen_ptr,
570 frame.anchored, &stencil.directions);
571 measured.measured = latest.measured;
572 measured.first_order = latest.pass;
573 measured.higher_order = latest.negative > 1;
574 }
575 std::cout << "[neb] force-stop stencil: negative=" << latest.negative
576 << " unresolved=" << latest.unresolved
577 << " calls=" << measured.calls
578 << " first_order=" << measured.first_order
579 << " higher_order=" << measured.higher_order << "\n";
580 stencil_cache[key] = StencilRecord{measured, latest, stencil};
581 return measured;
582 };
583 // A following saddle owns an inconclusive or higher-order stencil.
584 // The columns were already paid for: hand them over and do not
585 // measure again. The final stage still refines, then certifies.
586 gpr::optim::ForceStopCertificateResult outcome;
587 if (config.saddle_stage_follows) {
588 const auto cached =
589 stencil_cache.find(geometryKey(climbing.positions, stencil_mode));
590 gpr::optim::ForceStopMeasurement prior;
591 if (cached != stencil_cache.end()) {
592 prior = cached->second.measurement;
593 prior.calls = 0;
594 stencil = cached->second.stencil;
595 latest = cached->second.index;
596 const Eigen::MatrixXd columns = stencilHessianColumns(stencil);
597 if (columns.rows() == climbing.positions.size() &&
598 frame.masses.size() * 3 == climbing.positions.size()) {
599 prior.hessian = columns;
601 columns, climbing.positions, frame.masses, 4,
602 &stencil.directions);
603 prior.positions = stencil.positions;
604 prior.gradients = stencil.observations.gradient;
605 prior.center = climbing.positions;
606 prior.step = step;
607 }
608 }
610 measure_once, [] { return -1; }, plan, &prior);
611 } else {
613 measure_once,
614 [&]() {
615 if (latest.step.size() != climbing.positions.size() ||
616 !latest.step.allFinite())
617 return -1;
618 climbing.positions += latest.step;
619 const auto sample = oracle(climbing.positions);
620 if (!std::isfinite(sample.first) ||
621 sample.second.size() != climbing.positions.size() ||
622 !sample.second.allFinite())
623 return -1;
624 climbing.energy = sample.first;
625 climbing.gradient = sample.second;
626 climbing.evaluated = true;
627 std::cout << "[neb] force-stop stencil: one soft-mode step\n";
628 return 1;
629 },
630 plan);
631 // The soft-mode steps stay inside the negative well. Leave along
632 // the extra negative mode, doubling the displacement, and certify
633 // the point that is reached. A following saddle does this itself.
634 double length = latest.step.norm();
635 Eigen::VectorXd direction =
636 latest.step.size() == climbing.positions.size() && length > 0.0
637 ? latest.step / length
638 : Eigen::VectorXd();
639 for (int escape = 0; outcome.needs_min_mode_escape &&
641 direction.size() == climbing.positions.size();
642 ++escape) {
643 length *= 2.0;
644 const Eigen::VectorXd trial =
645 climbing.positions + length * direction;
646 const auto sample = oracle(trial);
647 if (!std::isfinite(sample.first) ||
648 sample.second.size() != trial.size() ||
649 !sample.second.allFinite())
650 break;
651 climbing.positions = trial;
652 climbing.energy = sample.first;
653 climbing.gradient = sample.second;
654 climbing.evaluated = true;
655 std::cout << "[neb] force-stop stencil: min-mode escape\n";
656 const gpr::optim::ForceStopMeasurement measured = measure_once();
657 outcome.calls += measured.calls + 1;
658 outcome.measurements += 1;
659 outcome.measured = measured.measured;
660 outcome.higher_order = measured.higher_order;
661 outcome.first_order = measured.measured && measured.first_order &&
662 !measured.higher_order;
664 measured.measured, outcome.first_order);
666 measured.higher_order &&
667 !outcome.certified;
668 // Keep the grown length. The new stencil's step is one finite
669 // difference, and resetting to it walks in place.
670 if (latest.step.size() == direction.size() &&
671 latest.step.norm() > 0.0)
672 direction = latest.step / latest.step.norm();
673 }
674 }
675 result.force_stop_certificate_calls = earlier_calls + outcome.calls;
676 result.oracle_calls += outcome.calls;
677 result.oracle_calls_validation += outcome.calls;
678 // The soft-mode and escape steps move the climbing image and measure
679 // it. The force stop held at the geometry the band stopped on, not at
680 // the one those steps reached: a first-order index there does not make
681 // it stationary. Report its measured force, and when that is above the
682 // tolerance give the stepped band back to the search.
683 if (!config.saddle_stage_follows && climbing.evaluated &&
684 (climbing.positions - stopped_at).norm() > 0.0) {
685 const double force = path.saddleForce(image);
686 result.returned_true_force = force;
687 if (!(std::isfinite(force) && force < config.conv_tol)) {
688 std::cout << "[neb] force-stop stencil: the stepped image has"
689 << " force=" << force
690 << " above tolerance=" << config.conv_tol
691 << "; the band resumes\n";
692 result.force_stop_certified = false;
693 result.index_checked = outcome.measured;
694 result.index_negative = latest.negative;
695 result.index_unresolved = latest.unresolved;
696 result.index_resolution = latest.resolution;
697 result.index_refused = false;
698 result.index_continue = true;
699 result.converged = false;
701 return;
702 }
703 }
704 result.force_stop_certified = outcome.certified;
705 result.force_stop_positions = stencil.positions;
706 result.force_stop_directions = stencil.directions;
707 result.force_stop_gradients = stencil.observations.gradient;
708 result.force_stop_energies = Eigen::Map<const Eigen::VectorXd>(
709 stencil.observations.energy.data(),
710 static_cast<Eigen::Index>(stencil.observations.energy.size()));
711 result.force_stop_displacement = stencil.displacement;
712 result.force_stop_center_reused = stencil.center_reused;
713 result.force_stop_wall_s = stencil.wall_seconds;
714 result.force_stop_modes = outcome.handed.lowest_modes;
716 outcome.measured && !outcome.first_order && !outcome.higher_order;
717 result.index_checked = outcome.measured;
718 result.index_negative = latest.negative;
719 result.index_unresolved = latest.unresolved;
720 result.index_resolution = latest.resolution;
721 result.index_continue = false;
722 result.force_stop_hand_off = outcome.hand_off;
723 if (config.saddle_stage_follows && outcome.measured && !outcome.certified &&
724 (outcome.higher_order || result.force_stop_inconclusive))
725 result.force_stop_hand_off = true;
726 // The band is the final stage. A higher-order stencil that the soft
727 // refinement did not repair is not a saddle. Zero negatives is not
728 // that refusal. A following saddle keeps the force stop and receives
729 // the climbing image instead.
730 result.index_refused = !result.force_stop_hand_off && outcome.measured &&
731 outcome.higher_order && !outcome.certified;
732 if (result.index_refused) {
733 result.converged = false;
735 }
736 // The same adaptive certificate the dimer uses. A final-stage band
737 // records its probes so the written stencil carries the index evidence.
738 // A following saddle owns that measurement and must not repeat it.
739 const Eigen::MatrixXd final_columns =
740 !config.saddle_stage_follows && !result.force_stop_deferred &&
741 frame.usable &&
742 frame.masses.size() * 3 == climbing.positions.size()
743 ? stencilHessianColumns(stencil)
744 : Eigen::MatrixXd();
745 if (final_columns.rows() == climbing.positions.size()) {
746 const Eigen::MatrixXd& columns = final_columns;
747 const auto index = gpr::optim::analyzeStencilIndex(
748 columns, climbing.positions, frame.masses, &stencil.directions);
749 int probes = 0;
750 const auto gradients = [&](const Eigen::MatrixXd& points) {
751 probes += static_cast<int>(points.cols());
752 Eigen::MatrixXd measured(points.cols(), points.rows());
753 for (Eigen::Index j = 0; j < points.cols(); ++j) {
754 const auto sample = oracle(points.col(j));
755 if (!std::isfinite(sample.first) ||
756 sample.second.size() != points.rows() ||
757 !sample.second.allFinite())
758 return Eigen::MatrixXd();
759 measured.row(j) = sample.second.transpose();
760 }
761 return measured;
762 };
763 const auto certificate = gpr::optim::certifyAdaptiveStencilIndex(
764 index, climbing.positions, frame.masses, step, gradients);
765 result.force_stop_certificate_calls += probes;
766 result.oracle_calls += probes;
767 result.oracle_calls_validation += probes;
768 if (certificate.refinement_points.cols() > 0 &&
769 certificate.refinement_gradients.rows() ==
770 certificate.refinement_points.cols()) {
771 result.force_stop_refinement_positions =
772 certificate.refinement_points.transpose();
773 result.force_stop_refinement_gradients =
774 certificate.refinement_gradients;
775 result.force_stop_negative_upper = certificate.negative_upper;
776 result.force_stop_positive_lower = certificate.positive_lower;
777 result.force_stop_negative_pair_upper =
778 certificate.negative_pair_upper;
779 result.force_stop_refinement_recorded = true;
780 result.force_stop_refinement_higher_order =
781 certificate.higher_order;
782 result.force_stop_certified =
783 certificate.first_order && !certificate.higher_order;
784 // The coarse stencil may be unresolved. A later bound that
785 // fixes the index replaces that flag, so the summary and the
786 // file do not keep calling a resolved saddle unresolved.
787 if (result.force_stop_certified || certificate.higher_order)
788 result.force_stop_inconclusive = false;
789 if (certificate.higher_order && !certificate.first_order &&
790 !result.force_stop_hand_off) {
791 result.index_refused = true;
792 result.converged = false;
793 result.convergence_status =
794 GPNEBConvergenceStatus::NotConverged;
795 }
796 }
797 }
798}
NEB path: chain of images between two endpoints.
Definition NEBPath.h:57
double saddleForce(int i) const
Definition NEBPath.h:263
CartesianOracleStencil evaluateCartesianOracleStencil(const Eigen::VectorXd &center, double displacement, const Eigen::MatrixXd &directions, const Oracle &oracle, const NEBBatchOracle *batch_oracle=nullptr, Eigen::Index batch_chunk=0)
VibrationalIndexMeasurement indexFromCartesianColumns(const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double move, const Eigen::VectorXd *center_gradient=nullptr, const Eigen::VectorXi *frozen=nullptr, bool anchored=false, const Eigen::MatrixXd *measured=nullptr)
Eigen::MatrixXd stencilHessianColumns(const CartesianOracleStencil &stencil)
constexpr double stencilStepOrDefault(double requested) noexcept
The requested stencil step, or the default when none was requested.
StencilIndexCertificate certifyAdaptiveStencilIndex(const StencilIndex &index, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const Gradients &gradients, double noise_multiplier=0.0)
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
ForceStopStencilPlan planForceStopStencil(ForceStopStencilQuery query)
constexpr int forceStopMinModeEscapes() noexcept
Min-mode escapes after a higher-order certificate, for every search.
ForceStopCertificateResult runForceStopCertificate(Measure measure, Refine refine, ForceStopStencilPlan plan, const ForceStopMeasurement *prior=nullptr)
std::vector< int > measured
1 for a mode at least 99% inside the measured directions.
Eigen::Index oracle_batch_chunk
Definition GPNEB.h:259
NEBBatchOracle batch_oracle
Definition GPNEB.h:253
bool force_stop_certificate
Definition GPNEB.h:847
gpr::optim::VibrationalStencil vibrational_stencil
Definition GPNEB.h:852
bool saddle_stage_follows
Definition GPNEB.h:863
double ci_stencil_step
Definition GPNEB.h:856
Eigen::MatrixXd force_stop_positions
Definition GPNEB.h:3768
Eigen::MatrixXd force_stop_modes
Lowest Cartesian modes of the measured Hessian, lowest first.
Definition GPNEB.h:3774
Eigen::VectorXd force_stop_energies
Definition GPNEB.h:3772
double returned_true_force
Definition GPNEB.h:3730
bool force_stop_center_reused
Definition GPNEB.h:3776
Eigen::MatrixXd force_stop_gradients
Definition GPNEB.h:3771
bool force_stop_deferred
The saddle owns the index. This stage did not measure a stencil.
Definition GPNEB.h:3765
double force_stop_wall_s
Definition GPNEB.h:3777
int force_stop_certificate_calls
Definition GPNEB.h:3759
Eigen::MatrixXd force_stop_directions
Orthonormal Cartesian directions of that stencil, one column each.
Definition GPNEB.h:3770
double force_stop_displacement
Definition GPNEB.h:3775
bool force_stop_inconclusive
The stencil was measured and did not resolve an index.
Definition GPNEB.h:3767
Float64 central-difference index of one geometry.
bool hand_off
A following saddle receives handed.
Eigen::VectorXd center
Stencil geometries (columns) and gradients (rows) already paid for.
bool defer_certificate
Do not measure. The following saddle certifies the point it reaches.
bool columns_already_measured
Finite-difference columns at this geometry were already paid for.

◆ certifyOCINEBResult()

void gpr::neb::certifyOCINEBResult ( OCINEBResult & result,
NEBOracle oracle,
const Eigen::VectorXd & initial,
const Eigen::VectorXd & final_state,
int n_images,
const GPNEBConfig & neb_config,
const OCINEBConfig & oci_config,
ActiveLearningSession & session )

Measure the returned band's certificates and recover an invalid saddle through the shared GP and oracle. The result retains every certificate measurement and recovery call.

Definition at line 5395 of file OCINEBController.cpp.

5401{
5402 const auto markWallClockStop = [&]() {
5403 result.neb_result.converged = false;
5407 result.dimer_converged = false;
5408 };
5410 markWallClockStop();
5411 return;
5412 }
5413 const double band_scale = neb_config.band_certificate_force_scale;
5414 // Index-1 certificate on the converged climbing image. A stationary
5415 // point of any index is a fixed point of the CI-NEB force, so the band
5416 // certificate alone accepts higher-index saddles; measure the two
5417 // lowest curvatures on the oracle and, on failure, warm-start the band
5418 // with the image displaced along the offending mode. Each attempt can
5419 // remove at most one negative direction, so 3N attempts bound the loop.
5420 auto record_band_certificate = [&]() {
5421 if (!result.neb_result.path) return;
5422 const auto report = detail::bandDiscretizationCertificateReport(
5423 *result.neb_result.path, neb_config.conv_tol,
5424 neb_config.band_leak_bound);
5425 result.band_certificate_evaluated = report.evaluated;
5426 result.band_certificate_holds =
5427 band_scale > 0.0 ? detail::bandPathCertificateHolds(
5428 *result.neb_result.path, band_scale)
5429 : report.holds;
5430 result.band_certificate_leak = report.leak_max;
5431 result.band_certificate_residual = report.residual_max;
5432 result.band_midpoint_evaluated = false;
5433 result.band_midpoint_holds = false;
5434 result.band_midpoint_excess = 0.0;
5435 result.band_midpoint_segment = -1;
5436 if (!neb_config.band_midpoint_certificate) return;
5437 int midpoint_calls = 0;
5438 BandMidpointCertificate mid;
5439 try {
5441 session, *result.neb_result.path, neb_config.conv_tol, oracle,
5442 result.neb_result.path->numImages() - 1, &midpoint_calls);
5443 } catch (const OracleSessionRestartRequested&) {
5444 throw;
5445 } catch (const gpr::WallClockLimitReached&) {
5446 markWallClockStop();
5447 return;
5448 } catch (const std::exception& error) {
5449 // A refused midpoint leaves the certificate unevaluated.
5450 std::cout << "[ocineb] band midpoint certificate refused by the "
5451 "oracle: "
5452 << error.what() << std::endl;
5453 }
5454 result.neb_result.oracle_calls += midpoint_calls;
5455 result.neb_result.oracle_calls_outer += midpoint_calls;
5456 result.band_midpoint_evaluated = mid.evaluated;
5457 result.band_midpoint_holds = mid.holds;
5458 result.band_midpoint_excess = mid.excess;
5459 result.band_midpoint_segment = mid.worst_segment;
5460 };
5461 record_band_certificate();
5463 return;
5464 if (neb_config.ci_index_certificate && neb_config.climbing_image) {
5465 const int max_attempts = std::max(1, 3 * neb_config.n_atoms);
5466 int certificate_calls = 0;
5467 Eigen::VectorXd previous_escape;
5468 for (int attempt = 0; attempt < max_attempts; ++attempt) {
5469 // A Hessian index is local to the stationary image. Band
5470 // resolution cannot withhold the measurements that identify an
5471 // invalid stationary point and supply its escape direction.
5472 const bool converged = result.dimer_ran
5473 ? result.dimer_converged
5474 : result.neb_result.converged;
5475 if (!converged || !result.neb_result.path) break;
5476 NEBPath& path = *result.neb_result.path;
5477 const int ci = result.neb_result.max_energy_image;
5478 if (ci <= 0 || ci >= path.numImages() - 1) break;
5479 auto& image = path.image(ci);
5480 if (!image.evaluated ||
5481 image.gradient.size() != image.positions.size())
5482 break;
5484 try {
5486 oracle, session, image.positions, image.energy,
5487 image.gradient,
5489 neb_config.ci_stencil_step),
5490 neb_config.lbfgs_max_move, neb_config.conv_tol,
5491 &neb_config.batch_oracle, neb_config.oracle_batch_chunk);
5492 } catch (const OracleSessionRestartRequested&) {
5493 throw;
5494 } catch (const gpr::WallClockLimitReached&) {
5495 markWallClockStop();
5496 return;
5497 } catch (const std::exception& error) {
5498 // A refused stencil leaves the index unmeasured; the
5499 // image is not certified.
5500 std::cout << "[ocineb] index certificate refused by the "
5501 "oracle: "
5502 << error.what() << std::endl;
5503 result.ci_index_evaluated = false;
5504 result.ci_index_certified = false;
5505 result.ci_index_attempts = attempt + 1;
5506 break;
5507 }
5508 gpr::PhaseTimers::notePeak("after_certificate");
5509 certificate_calls += cert.oracle_calls;
5510 result.ci_index_evaluated = cert.evaluated;
5511 result.ci_index_certified = cert.certified;
5512 result.ci_index_attempts = attempt + 1;
5513 // Certificate calls plus the calls of every earlier attempt: the
5514 // driver's ledger records them (recordPolish) next to the final
5515 // run's own breakdown, so the provider count reconciles.
5516 result.ci_index_oracle_calls = certificate_calls;
5517 result.ci_index_curvature1 = cert.oracle_curvature1;
5518 result.ci_index_curvature2 = cert.oracle_curvature2;
5519 result.ci_index_verified = cert.verified;
5520 result.ci_index_residual1 = cert.residual1;
5521 result.ci_index_residual2 = cert.residual2;
5522 if (auto* tracker = gpr::track::activeRun()) {
5523 // The oracle's verdict on the climbing image's index: the
5524 // two lowest curvatures with the resolution of the
5525 // measurement, the modes, and the point that was probed.
5526 gpr::track::JsonRecord record;
5527 record.add("attempt", static_cast<long>(attempt + 1))
5528 .add("evaluated", cert.evaluated)
5529 .add("verified", cert.verified)
5530 .add("certified", cert.certified)
5531 .add("reason", cert.reason)
5532 .add("oracle_calls", static_cast<long>(cert.oracle_calls))
5533 .add("rounds", static_cast<long>(cert.rounds))
5534 .add("surrogate_lambda1", cert.surrogate_lambda1)
5535 .add("surrogate_lambda2", cert.surrogate_lambda2)
5536 .add("oracle_curvature1", cert.oracle_curvature1)
5537 .add("oracle_curvature2", cert.oracle_curvature2)
5538 .add("residual1", cert.residual1)
5539 .add("residual2", cert.residual2)
5540 .add("energy", image.energy)
5541 .add("positions", image.positions)
5542 .add("gradient", image.gradient)
5543 .add("mode1", cert.mode1)
5544 .add("mode2", cert.mode2);
5545 tracker->appendRecord("certificate/index", record);
5546 const long step = static_cast<long>(attempt + 1);
5547 tracker->logMetric("certificate.oracle_curvature1",
5548 cert.oracle_curvature1, step);
5549 tracker->logMetric("certificate.oracle_curvature2",
5550 cert.oracle_curvature2, step);
5551 tracker->logMetric("certificate.surrogate_lambda1",
5552 cert.surrogate_lambda1, step);
5553 tracker->logMetric("certificate.surrogate_lambda2",
5554 cert.surrogate_lambda2, step);
5555 tracker->logMetric("certificate.residual1", cert.residual1,
5556 step);
5557 tracker->logMetric("certificate.residual2", cert.residual2,
5558 step);
5559 tracker->logMetric("certificate.oracle_calls",
5560 static_cast<double>(cert.oracle_calls),
5561 step);
5562 tracker->logMetric("certificate.certified",
5563 cert.certified ? 1.0 : 0.0, step);
5564 tracker->logMetric("certificate.verified",
5565 cert.verified ? 1.0 : 0.0, step);
5566 tracker->flush();
5567 }
5568 if (!cert.evaluated || !cert.verified || cert.certified) break;
5569 if (std::isfinite(cert.polish_force_target)) {
5570 // The point's index is two but the stationary point's is
5571 // undetermined: converge the image to the certificate's
5572 // force target on the surrogate and certify again.
5573 SaddlePolishResult polished;
5574 try {
5575 polished = polishSaddleOnSurrogate(
5576 oracle, session, image.positions, image.energy,
5577 image.gradient, cert.polish_force_target,
5578 std::max(1, neb_config.n_atoms),
5579 neb_config.lbfgs_max_move,
5581 neb_config.ci_stencil_step));
5582 } catch (const OracleSessionRestartRequested&) {
5583 throw;
5584 } catch (const gpr::WallClockLimitReached&) {
5585 markWallClockStop();
5586 return;
5587 } catch (const std::exception& error) {
5588 std::cout << "[ocineb] index certificate polish refused "
5589 "by the oracle: "
5590 << error.what() << std::endl;
5591 break;
5592 }
5593 certificate_calls += polished.oracle_calls;
5594 std::cout << "[ocineb] index certificate polish: force "
5595 << polished.initial_max_atom_force << " -> "
5596 << polished.final_max_atom_force << " (target "
5597 << cert.polish_force_target << ") in "
5598 << polished.steps << " steps, "
5599 << polished.oracle_calls << " calls" << std::endl;
5600 if (polished.steps == 0) break;
5601 image.positions = polished.positions;
5602 image.energy = polished.energy;
5603 image.gradient = polished.gradient;
5604 image.evaluated = true;
5605 path.computeNEBForces();
5606 continue;
5607 }
5608 if (cert.displaced_positions.size() != image.positions.size())
5609 break;
5610 // A higher-index point can descend along another unstable mode;
5611 // a minimum requires an uphill escape. The dimer uses the shared
5612 // measured rows and the lowest mode, and its result undergoes
5613 // the same independent index certificate. A failed recovery or
5614 // midpoint certificate restarts the band from the measured seed.
5615 const double e_refused = image.energy;
5616 double e_d = std::numeric_limits<double>::quiet_NaN();
5617 Eigen::VectorXd g_d;
5618 ++certificate_calls;
5619 try {
5620 std::tie(e_d, g_d) = detail::evaluateOieOraclePosition(
5621 cert.displaced_positions, oracle);
5622 } catch (const OracleSessionRestartRequested&) {
5623 throw;
5624 } catch (const gpr::WallClockLimitReached&) {
5625 markWallClockStop();
5626 return;
5627 } catch (const std::exception& error) {
5628 // The escape geometry was refused: the certificate stays
5629 // failed and the band keeps its measured climbing image.
5630 std::cout << "[ocineb] index escape refused by the oracle: "
5631 << error.what() << std::endl;
5632 break;
5633 }
5634 if (!std::isfinite(e_d) || g_d.size() != image.positions.size() ||
5635 !g_d.allFinite())
5636 break;
5637 session.appendObservation(cert.displaced_positions, e_d, g_d);
5638 image.positions = cert.displaced_positions;
5639 image.energy = e_d;
5640 image.gradient = g_d;
5641 image.evaluated = true;
5642 path.computeNEBForces();
5643 const Eigen::VectorXd escape_mode =
5644 cert.mode1.size() == image.positions.size()
5645 ? cert.mode1
5646 : path.tangentAt(ci);
5648 try {
5650 oci_config, neb_config, session, oracle,
5651 cert.displaced_positions, e_d, g_d, escape_mode,
5652 cert.escapeEnergyCeiling(e_refused));
5653 } catch (const OracleSessionRestartRequested&) {
5654 throw;
5655 } catch (const std::runtime_error& error) {
5656 // The escape dimer stopped on oracle failures: the escape
5657 // is unconverged and the certificate stays failed.
5658 std::cout << "[ocineb] index escape dimer stopped by oracle "
5659 "failures: "
5660 << error.what() << std::endl;
5661 }
5662 certificate_calls += esc.oracle_calls;
5663 std::cout << "[ocineb] index escape (gprd): converged="
5664 << (esc.converged ? 1 : 0) << " force=" << esc.force
5665 << " curvature=" << esc.curvature
5666 << " phases=" << esc.phases
5667 << " calls=" << esc.oracle_calls
5668 << " energy=" << esc.energy << std::endl;
5669 if (esc.wall_clock_limit) {
5670 result.neb_result.converged = false;
5674 return;
5675 }
5676 if (esc.converged &&
5677 esc.positions.size() == image.positions.size() &&
5678 esc.gradient.size() == image.positions.size() &&
5679 std::isfinite(esc.energy)) {
5680 // An escape that converges where the previous one did has
5681 // no other saddle to offer: the refused point is where the
5682 // dimer's own certificate stands, and another attempt buys
5683 // the same stencil again (12_ethane: eleven rounds at one
5684 // point until the wall).
5685 if (previous_escape.size() == esc.positions.size() &&
5686 (esc.positions - previous_escape).norm() <=
5687 1e-8 * (1.0 + previous_escape.norm())) {
5688 std::cout << "[ocineb] index escape returned to its "
5689 "previous point; no further attempt."
5690 << std::endl;
5691 break;
5692 }
5693 previous_escape = esc.positions;
5694 image.positions = esc.positions;
5695 image.energy = esc.energy;
5696 image.gradient = esc.gradient;
5697 image.evaluated = true;
5698 path.computeNEBForces();
5699 record_band_certificate();
5700 if (!result.band_midpoint_evaluated ||
5701 result.band_midpoint_holds)
5702 continue;
5703 std::cout << "[ocineb] index escape: band midpoint "
5704 "certificate fails around the dimer saddle "
5705 "(excess="
5706 << result.band_midpoint_excess
5707 << " segment=" << result.band_midpoint_segment
5708 << "); relaxing the band from it" << std::endl;
5709 }
5710 // Warm start from the converged band with the climbing image
5711 // moved off the higher-index point (as far as the dimer got).
5712 GPNEBConfig warm = neb_config;
5713 warm.has_initial_path = true;
5714 warm.initial_path.resize(path.numImages(), image.positions.size());
5715 for (int i = 0; i < path.numImages(); ++i)
5716 warm.initial_path.row(i) = path.image(i).positions.transpose();
5717 certificate_calls += result.neb_result.oracle_calls;
5718 result = runOCINEB(oracle, initial, final_state, active_n_images,
5719 warm, oci_config, session);
5720 result.ci_index_evaluated = cert.evaluated;
5721 result.ci_index_certified = false;
5722 result.ci_index_attempts = attempt + 1;
5723 result.ci_index_oracle_calls = certificate_calls;
5724 result.ci_index_curvature1 = cert.oracle_curvature1;
5725 result.ci_index_curvature2 = cert.oracle_curvature2;
5726 result.ci_index_verified = cert.verified;
5727 result.ci_index_residual1 = cert.residual1;
5728 result.ci_index_residual2 = cert.residual2;
5729 }
5730 result.ci_index_oracle_calls = certificate_calls;
5731 }
5732 record_band_certificate();
5733 const bool index_required =
5734 neb_config.ci_index_certificate && neb_config.climbing_image;
5735 const bool index_holds = !index_required || (result.ci_index_evaluated &&
5736 result.ci_index_verified &&
5737 result.ci_index_certified);
5738 const bool discretization_required =
5739 band_scale > 0.0 || neb_config.band_leak_bound;
5740 const bool discretization_holds = !discretization_required ||
5743 const bool midpoint_holds =
5744 !neb_config.band_midpoint_certificate ||
5746 if (!index_holds || !discretization_holds || !midpoint_holds) {
5747 result.neb_result.converged = false;
5750 result.dimer_converged = false;
5751 }
5752}
JsonRecord & add(std::string_view key, double value)
SaddlePolishResult polishSaddleOnSurrogate(const NEBOracle &oracle, ActiveLearningSession &session, const Eigen::VectorXd &x0, double e0, const Eigen::VectorXd &g0, double force_tol, int max_steps, double max_move, double hessian_fd_step)
@ WallClockLimit
The shared monotonic wall-clock deadline was reached.
Definition GPNEB.h:3678
OCINEBResult runOCINEB(NEBOracle oracle, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int n_images, const GPNEBConfig &neb_config, const OCINEBConfig &oci_config_in, ActiveLearningSession &session)
ClimbingImageIndexCertificate certifyClimbingImageIndex(const NEBOracle &oracle, ActiveLearningSession &session, const Eigen::VectorXd &x_ci, double e_ci, const Eigen::VectorXd &g_ci, double hessian_fd_step, double max_move, double force_tol, const NEBBatchOracle *batch_oracle, Eigen::Index batch_chunk)
BandMidpointCertificate certifyBandMidpointsMeasured(ActiveLearningSession &session, const NEBPath &path, double force_tol, NEBOracle &oracle, int max_measurements, int *oracle_calls)
IndexEscapeResult runIndexEscapeGpDimer(const OCINEBConfig &oci_config, const GPNEBConfig &neb_config, ActiveLearningSession &session, NEBOracle &oracle, const Eigen::VectorXd &x_seed, double e_seed, const Eigen::VectorXd &g_seed, const Eigen::VectorXd &mode_seed, double energy_ceiling)
MlflowRun * activeRun() noexcept
bool collectiveWallClockLimitReached(const std::shared_ptr< const WallClockLimit > &limit, const linalg::MpiContext &context)
Definition PhaseTimers.h:81
static void notePeak(const char *phase) noexcept
Configuration for GP-NEB.
Definition GPNEB.h:246
double lbfgs_max_move
Definition GPNEB.h:960
bool band_midpoint_certificate
Definition GPNEB.h:866
double band_certificate_force_scale
Definition GPNEB.h:494
bool ci_index_certificate
Definition GPNEB.h:839
GPNEBStopReason stop_reason
Definition GPNEB.h:3684
int oracle_calls
oracle rows the search paid
bool ci_index_evaluated
Climbing-image index certificate (see certifyClimbingImageIndex).
bool band_midpoint_evaluated
Surrogate midpoint check of the returned band (certifyBandMidpoints).
Outcome of a saddle polish (see polishSaddleOnSurrogate).
int oracle_calls
true-PES evaluations spent

◆ ciIndexCertificateRefuted()

bool gpr::neb::ciIndexCertificateRefuted ( const OCINEBResult & result)
inline

The opt-in climbing-image index certificate measured this point and refused it. An unevaluated or unverified certificate is not a refutation: the curvature was not established.

Definition at line 1373 of file OCINEBController.h.

1374{
1375 return result.ci_index_evaluated && result.ci_index_verified &&
1376 !result.ci_index_certified;
1377}

◆ classifyVibrationalIndex()

VibrationalIndexClass gpr::neb::classifyVibrationalIndex ( const Eigen::VectorXd & curvatures,
double resolution )
inline

Definition at line 47 of file VibrationalIndexGate.h.

49{
51 if (curvatures.size() == 0 || !curvatures.allFinite() ||
52 !std::isfinite(resolution) || resolution < 0.0) {
53 if (curvatures.size() > 0 && curvatures.allFinite()) {
54 out.unresolved = static_cast<int>(curvatures.size());
55 out.soft_mode = 0;
56 }
57 return out;
58 }
59 int soft = -1;
60 double soft_abs = std::numeric_limits<double>::infinity();
61 bool kept_primary = false;
62 for (Eigen::Index i = 0; i < curvatures.size(); ++i) {
63 const double curvature = curvatures(i);
64 if (curvature < -resolution) {
65 ++out.negative;
66 // The most negative mode is the one a first-order saddle is
67 // allowed to keep. Any further negative mode is an escape.
68 if (!kept_primary) {
69 kept_primary = true;
70 continue;
71 }
72 } else if (curvature > resolution) {
73 ++out.positive;
74 continue;
75 } else {
76 ++out.unresolved;
77 }
78 const double magnitude = std::abs(curvature);
79 if (magnitude < soft_abs) {
80 soft_abs = magnitude;
81 soft = static_cast<int>(i);
82 }
83 }
84 out.pass = out.negative == 1 && out.unresolved == 0;
85 if (!out.pass) {
86 if (soft < 0) soft = 0;
87 out.soft_mode = soft;
88 }
89 return out;
90}

◆ compositionTracesNumericallyClose()

bool gpr::neb::compositionTracesNumericallyClose ( const std::vector< OuterIterCompositionTraceRecord > & got,
const std::vector< OuterIterCompositionTraceRecord > & expected,
double rtol,
double atol,
std::string * mismatch = nullptr )
nodiscard

Golden check tolerant to last-ULP floating-point drift. The structural and decision fields (indices, counts, ci_active, every certificate flag, and the theta length) must match exactly; the continuous fields (barrier_estimate, max_oracle_force, each theta value) match within atol plus rtol times the magnitude of the expected value. Exact string equality is too strict for a trace that carries 17-significant-figure reductions whose ordering drifts (e.g. a cuSOLVER GPU/CPU-fallback path), where a decision-identical run differs only in the trailing digits. mismatch, when non-null, receives a human-readable description of the first divergence.

Definition at line 271 of file OuterIterCompositionTrace.cpp.

275{
276 auto fail = [&](const std::string& why) {
277 if (mismatch != nullptr) *mismatch = why;
278 return false;
279 };
280 if (got.size() != expected.size()) {
281 return fail("record count " + std::to_string(got.size()) + " vs " +
282 std::to_string(expected.size()));
283 }
284 auto close = [&](double g, double e, const char* field, std::size_t i) {
285 const double diff = std::abs(g - e);
286 const double bound = atol + rtol * std::abs(e);
287 if (diff <= bound) return true;
288 std::ostringstream os;
289 os << "record " << i << " field " << field << ": "
290 << std::setprecision(17) << g << " vs " << e << " (|diff|=" << diff
291 << " > " << bound << ")";
292 return fail(os.str());
293 };
294 for (std::size_t i = 0; i < got.size(); ++i) {
295 const auto& g = got[i];
296 const auto& e = expected[i];
297 // Structural / decision fields: exact.
298 auto eq_int = [&](long long a, long long b, const char* field) {
299 if (a == b) return true;
300 return fail("record " + std::to_string(i) + " field " + field +
301 ": " + std::to_string(a) + " vs " + std::to_string(b));
302 };
303 if (!eq_int(g.outer_idx, e.outer_idx, "outer_idx")) return false;
304 if (!eq_int(g.oracle_target_image, e.oracle_target_image,
305 "oracle_target_image"))
306 return false;
307 if (!eq_int(g.ci_index, e.ci_index, "ci_index")) return false;
308 if (!eq_int(g.n_uneval, e.n_uneval, "n_uneval")) return false;
309 if (!eq_int(g.ci_active, e.ci_active, "ci_active")) return false;
310 const auto& gc = g.certificates;
311 const auto& ec = e.certificates;
312 if (!eq_int(gc.n_uneval_zero, ec.n_uneval_zero, "cert.n_uneval_zero") ||
313 !eq_int(gc.mep_force_ok, ec.mep_force_ok, "cert.mep_force_ok") ||
314 !eq_int(gc.ci_force_ok, ec.ci_force_ok, "cert.ci_force_ok") ||
315 !eq_int(gc.true_saddle_energy, ec.true_saddle_energy,
316 "cert.true_saddle_energy") ||
317 !eq_int(gc.ci_adjacent_perp, ec.ci_adjacent_perp,
318 "cert.ci_adjacent_perp") ||
319 !eq_int(gc.force_tolerance, ec.force_tolerance,
320 "cert.force_tolerance") ||
321 !eq_int(gc.certified_ci_only_branch, ec.certified_ci_only_branch,
322 "cert.certified_ci_only_branch") ||
323 !eq_int(gc.certified_full_band_branch,
324 ec.certified_full_band_branch,
325 "cert.certified_full_band_branch") ||
326 !eq_int(gc.certified_hook_branch, ec.certified_hook_branch,
327 "cert.certified_hook_branch")) {
328 return false;
329 }
330 if (!eq_int(static_cast<long long>(g.theta.size()),
331 static_cast<long long>(e.theta.size()), "theta_n"))
332 return false;
333 // Continuous fields: tolerant.
334 if (!close(g.barrier_estimate, e.barrier_estimate, "barrier_estimate",
335 i))
336 return false;
337 if (!close(g.max_oracle_force, e.max_oracle_force, "max_oracle_force",
338 i))
339 return false;
340 for (std::size_t k = 0; k < g.theta.size(); ++k) {
341 if (!close(g.theta[k], e.theta[k], "theta", i)) return false;
342 }
343 }
344 return true;
345}

◆ compositionTracesTextuallyEqual()

bool gpr::neb::compositionTracesTextuallyEqual ( const std::vector< OuterIterCompositionTraceRecord > & a,
const std::vector< OuterIterCompositionTraceRecord > & b )
nodiscard

True when canonical serializations are identical (golden check).

Definition at line 264 of file OuterIterCompositionTrace.cpp.

267{
269}
std::string formatCompositionTrace(const std::vector< OuterIterCompositionTraceRecord > &records)
Canonical text serialization used by golden files and exact-match asserts.

◆ decideIndexGate()

IndexGateAction gpr::neb::decideIndexGate ( bool pass,
bool cap_remains )
inline

◆ decideVibrationalIndex()

VibrationalIndexDecision gpr::neb::decideVibrationalIndex ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & gradient,
const gpr::AtomsConfiguration * atoms,
gpr::GaussianProcessRegression * gp,
double variance,
double variance_threshold,
double move,
double stencil_step,
const NEBOracle * oracle,
const NEBBatchOracle * batch = nullptr,
Eigen::Index batch_chunk = 0,
gpr::optim::VibrationalStencil stencil = gpr::optim::VibrationalStencil::Full )
nodiscard

One index decision for a climbing image. The GP mean Hessian is read first and costs no true call. Posterior energy variance is compared with variance_threshold (indexGateVarianceThreshold of the fitted noise). A resolved index-1 surrogate accepts. The true stencil runs only when that variance is above the threshold or the surrogate reports three or more negative modes. Full, the default, is two force evaluations per Cartesian coordinate and a resolution that includes the rigid columns. Vibrational displaces only the complement; its resolution is the measured block and can call a borderline mode resolved where full leaves it unresolved. A resolved surrogate with fewer negatives than that does not spend true calls and does not refuse: the mean Hessian on the hollow adatom reports two negatives, or none, at a true index-1 saddle.

Definition at line 142 of file VibrationalIndexGate.cpp.

148{
150 const Frame frame = frameFor(positions, atoms);
151 if (!frame.usable) return decision;
152 const Eigen::VectorXd* gradient_ptr =
153 gradient.size() == positions.size() && gradient.allFinite() ? &gradient
154 : nullptr;
155 auto classify = [&](const Eigen::MatrixXd& columns, const char* source,
156 int true_calls,
157 const Eigen::MatrixXd* measured = nullptr) {
158 return fromMeasurement(
159 indexFromCartesianColumns(columns, positions, frame.masses, move,
160 gradient_ptr, frame.frozen_ptr,
161 frame.anchored, measured),
162 source, true_calls, variance, variance_threshold);
163 };
164
165 // The mean Hessian screens the point. Posterior energy variance above
166 // the caller's threshold, or three or more negative surrogate modes,
167 // is the only reason to buy a true stencil. A resolved index-1
168 // surrogate accepts. Two surrogate negatives, or none, are the hollow
169 // adatom's false reading of a true index-1 saddle: they neither spend
170 // true calls nor withdraw the converged claim.
171 //
172 // The band row is every atom in file order. The kernel reads that row
173 // as atoms_mov. A session that never loaded a geometry (standard and
174 // AIE leave the GP uninitialised) has an empty moving set, and a
175 // derivative channel then indexes past it. Skip the surrogate and
176 // screen on the true surface instead of throwing.
177 const bool surrogate_geometry =
178 gp != nullptr && atoms != nullptr && atoms->atoms_mov.type.size() > 0 &&
179 3 * atoms->atoms_mov.type.size() == positions.size();
180 if (surrogate_geometry) {
181 if (!std::isfinite(variance)) variance = energyVariance(*gp, positions);
182 const bool uncertain =
183 !std::isfinite(variance) || variance > variance_threshold;
184 const Eigen::MatrixXd hessian = surrogateHessian(*gp, positions);
185 if (hessian.rows() == positions.size() && hessian.allFinite()) {
186 auto surrogate = classify(hessian, "surrogate", 0);
187 std::cout << "[neb] vibrational index: source=surrogate"
188 << " negative=" << surrogate.negative
189 << " unresolved=" << surrogate.unresolved
190 << " resolution=" << surrogate.resolution
191 << " variance=" << variance
192 << " threshold=" << variance_threshold << " true_calls=0"
193 << " pass=" << (surrogate.accept ? "yes" : "no") << "\n";
194 if (surrogate.checked && !uncertain && surrogate.unresolved == 0 &&
195 surrogate.negative <= 2) {
196 // A resolved index-1 surrogate is the decision. Zero, one,
197 // or two negatives under the variance threshold are not a
198 // refutation: the hollow adatom's mean Hessian reports two
199 // or none at a true index-1 saddle. Leave the converged
200 // claim in place and spend no true calls.
201 surrogate.checked = true;
202 surrogate.accept = true;
203 return surrogate;
204 }
205 }
206 }
207
208 if (oracle == nullptr || !(stencil_step > 0.0) ||
209 !std::isfinite(stencil_step)) {
210 decision.checked = false;
211 return decision;
212 }
213 // A free molecule whose coordinates are pure rigid motion has no
214 // vibrational index. Leave the caller's convergence claim unchanged
215 // and spend no true evaluations. Full still measures every coordinate.
217 !frame.anchored && frame.frozen_ptr == nullptr &&
218 gpr::optim::vibrationalComplement(positions, frame.masses).cols() ==
219 0) {
220 decision.checked = false;
221 return decision;
222 }
223 const Eigen::MatrixXd directions =
224 stencilDirections(frame, positions, stencil);
225 CartesianOracleStencil oracle_stencil;
226 if (gradient_ptr != nullptr) {
227 const CartesianOracleCenter center{positions, 0.0, gradient};
228 oracle_stencil =
229 evaluateCartesianOracleStencil(positions, stencil_step, directions,
230 *oracle, center, batch, batch_chunk);
231 } else {
232 oracle_stencil = evaluateCartesianOracleStencil(
233 positions, stencil_step, directions, *oracle, batch, batch_chunk);
234 }
235 int true_calls = 0;
236 if (!oracle_stencil.complete()) return decision;
237 // The center column is reused when a gradient was supplied. Every
238 // other column is one displaced force evaluation.
239 true_calls = static_cast<int>(oracle_stencil.positions.cols() -
240 (gradient_ptr ? 1 : 0));
241 const Eigen::MatrixXd columns = stencilHessianColumns(oracle_stencil);
242 if (columns.rows() != positions.size()) return decision;
244 columns, positions, frame.masses, move, gradient_ptr, frame.frozen_ptr,
245 frame.anchored, &oracle_stencil.directions);
246 auto truth = fromMeasurement(measured, "true", true_calls, variance,
247 variance_threshold);
248 std::cout << "[neb] vibrational index: source=true"
249 << " negative=" << truth.negative
250 << " unresolved=" << truth.unresolved
251 << " resolution=" << truth.resolution
252 << " true_calls=" << truth.true_calls
253 << " pass=" << (truth.accept ? "yes" : "no") << " eigenvalues=[";
254 for (Eigen::Index i = 0; i < measured.curvatures.size(); ++i) {
255 if (i > 0) std::cout << ",";
256 std::cout << measured.curvatures(i);
257 }
258 std::cout << "]\n";
259 return truth;
260}
Eigen::MatrixXd vibrationalComplement(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses)
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844

◆ endpointSymmetryFromPermutation()

EndpointSymmetry gpr::neb::endpointSymmetryFromPermutation ( const std::vector< int > & permutation,
const Eigen::VectorXd & reactant,
const Eigen::VectorXd & product,
const std::vector< int > & atomic_numbers )
inline

The endpoint-exchanging symmetry with permutation permutation (slot a of the mapped geometry takes atom permutation[a]). Q and t are the orthogonal Procrustes fit of the permuted reactant onto the product, which is optimal over proper and improper rotations alike; the fit is exact for a degenerate reaction whose endpoints are symmetry images. Throws when the permutation is not a non-identity bijection of like atoms.

Definition at line 119 of file EndpointSymmetry.h.

122{
123 const std::size_t nat = atomic_numbers.size();
124 if (nat < 2 || permutation.size() != nat ||
125 reactant.size() != static_cast<Eigen::Index>(3 * nat) ||
126 product.size() != reactant.size())
127 throw std::invalid_argument(
128 "endpoint symmetry: the permutation, the atomic numbers and both "
129 "endpoints must describe the same atoms");
130 std::vector<char> seen(nat, 0);
131 bool identity = true;
132 for (std::size_t a = 0; a < nat; ++a) {
133 const int source = permutation[a];
134 if (source < 0 || static_cast<std::size_t>(source) >= nat ||
135 seen[static_cast<std::size_t>(source)])
136 throw std::invalid_argument(
137 "endpoint symmetry: the permutation is not a bijection");
138 seen[static_cast<std::size_t>(source)] = 1;
139 if (atomic_numbers[static_cast<std::size_t>(source)] !=
140 atomic_numbers[a])
141 throw std::invalid_argument(
142 "endpoint symmetry: the permutation exchanges unlike atoms");
143 identity = identity && static_cast<std::size_t>(source) == a;
144 }
145 if (identity)
146 throw std::invalid_argument(
147 "endpoint symmetry: the identity permutation exchanges nothing");
148
149 EndpointSymmetry symmetry;
150 symmetry.permutation = permutation;
151 Eigen::Matrix<double, 3, Eigen::Dynamic> source(3, nat);
152 Eigen::Matrix<double, 3, Eigen::Dynamic> target(3, nat);
153 for (std::size_t a = 0; a < nat; ++a) {
154 source.col(static_cast<Eigen::Index>(a)) =
155 reactant.segment<3>(3 * permutation[a]);
156 target.col(static_cast<Eigen::Index>(a)) =
157 product.segment<3>(static_cast<Eigen::Index>(3 * a));
158 }
159 const Eigen::Vector3d source_centroid = source.rowwise().mean();
160 const Eigen::Vector3d target_centroid = target.rowwise().mean();
161 const Eigen::Matrix3d covariance =
162 (source.colwise() - source_centroid) *
163 (target.colwise() - target_centroid).transpose();
164 const Eigen::JacobiSVD<Eigen::Matrix3d> svd(
165 covariance, Eigen::ComputeFullU | Eigen::ComputeFullV);
166 symmetry.orthogonal = svd.matrixV() * svd.matrixU().transpose();
167 symmetry.translation =
168 target_centroid - symmetry.orthogonal * source_centroid;
169 symmetry.forward_residual = detail::labelledElementDisplacement(
170 symmetry.mapPositions(reactant), product, atomic_numbers);
171 symmetry.reverse_residual = detail::labelledElementDisplacement(
172 symmetry.mapPositions(product), reactant, atomic_numbers);
173 return symmetry;
174}

◆ evaluateCartesianOracleStencil() [1/2]

template<typename Oracle>
CartesianOracleStencil gpr::neb::evaluateCartesianOracleStencil ( const Eigen::VectorXd & center,
double displacement,
const Eigen::MatrixXd & directions,
const Oracle & oracle,
const CartesianOracleCenter & measured_center,
const NEBBatchOracle * batch_oracle = nullptr,
Eigen::Index batch_chunk = 0 )

Reuse rank zero's exact measured center, retaining all 2*K+1 rows and their original owners. An invalid, stale or partial root measurement falls back to measuring the full stencil. Other ranks need not supply a measurement.

Definition at line 128 of file OracleStencil.h.

133{
134 return detail::evaluateCartesianOracleStencilImpl(
135 center, displacement, directions, oracle, &measured_center,
136 batch_oracle, batch_chunk);
137}

◆ evaluateCartesianOracleStencil() [2/2]

template<typename Oracle>
CartesianOracleStencil gpr::neb::evaluateCartesianOracleStencil ( const Eigen::VectorXd & center,
double displacement,
const Eigen::MatrixXd & directions,
const Oracle & oracle,
const NEBBatchOracle * batch_oracle = nullptr,
Eigen::Index batch_chunk = 0 )

Every displacement of the stencil is one point of one oracle step: the points are shared out over the ranks and each rank's points go through batch_oracle in one call when one is given. directions are the stencil's orthonormal Cartesian directions, normally gpr::optim::vibrationalStencilDirections at center.

Definition at line 114 of file OracleStencil.h.

118{
119 return detail::evaluateCartesianOracleStencilImpl(
120 center, displacement, directions, oracle, nullptr, batch_oracle,
121 batch_chunk);
122}

◆ expandToTriplet()

std::vector< int > gpr::neb::expandToTriplet ( int center,
int n_total )

Expand a single image index to a triplet {i-1, i, i+1}.

Triplet evaluation ensures the improved tangent at the center image uses ground-truth neighbors.

Parameters
centerCenter image index
n_totalTotal number of images (including endpoints)
Returns
Vector of image indices to evaluate

Definition at line 134 of file AcquisitionStrategy.cpp.

135{
136 std::vector<int> triplet;
137 int lo = std::max(1, center - 1);
138 int hi = std::min(n_total - 2, center + 1);
139 for (int i = lo; i <= hi; ++i) {
140 triplet.push_back(i);
141 }
142 return triplet;
143}

◆ factorSubstrate()

Eigen::LLT< Eigen::MatrixXd > gpr::neb::factorSubstrate ( const Eigen::MatrixXd & hessian)
inline

Cholesky factor of a substrate Hessian.

The factor is double. A float factor rounds every entry onto a boundary a one-ulp force can cross, and the quasi-Newton step then leaves the basin.

Definition at line 16 of file SubstrateFactor.h.

18{
19 return Eigen::LLT<Eigen::MatrixXd>(hessian);
20}

◆ forceComponentRmsForNorm()

double gpr::neb::forceComponentRmsForNorm ( double component_rms,
Eigen::Index degrees_of_freedom,
ConvergenceNormType norm )
nodiscardnoexcept

Convert per-Cartesian-component force RMS to the selected force norm.

Definition at line 147 of file GPNEB.cpp.

148 {
149 std::vector<char> grown = picked;
150 for (Eigen::Index g = 0; g < groups; ++g) {
151 if (!picked[static_cast<std::size_t>(g)]) continue;
152 for (Eigen::Index h = 0; h < groups; ++h) {
153 if (grown[static_cast<std::size_t>(h)]) continue;
154 const double distance =
155 (initial.segment(g * 3, 3) - initial.segment(h * 3, 3))
156 .norm();
157 if (distance <= radius) grown[static_cast<std::size_t>(h)] = 1;
158 }
159 }
160 picked.swap(grown);
161 }
162 for (Eigen::Index g = 0; g < groups; ++g) {
163 if (!picked[static_cast<std::size_t>(g)]) continue;
164 for (Eigen::Index k = 0; k < per; ++k)
165 dofs.push_back(g * per + k);
166 }
167 return dofs;

◆ formatCompositionTrace()

std::string gpr::neb::formatCompositionTrace ( const std::vector< OuterIterCompositionTraceRecord > & records)
nodiscard

Canonical text serialization used by golden files and exact-match asserts.

Definition at line 183 of file OuterIterCompositionTrace.cpp.

185{
186 std::ostringstream os;
187 os << "# gpridge outer-iter composition trace v"
189 os << "# Deterministic; no timestamps/pointers. Regenerate with "
190 "GPR_REGEN_GOLDEN=1.\n";
191 writeInt(os, "version", kCompositionTraceFormatVersion);
192 writeInt(os, "n_records", static_cast<int>(records.size()));
193 for (const auto& rec: records)
194 writeRecord(os, rec);
195 return os.str();
196}
constexpr int kCompositionTraceFormatVersion
Bump when the on-disk golden format changes incompatibly.

◆ gpNEB()

GPNEBResult gpr::neb::gpNEB ( NEBOracle oracle,
const Eigen::VectorXd & initial,
const Eigen::VectorXd & final_state,
int n_images,
const GPNEBConfig & config = {},
ActiveLearningSession * session = nullptr )

Run GP-accelerated NEB.

Parameters
oracleEnergy/gradient evaluation function
initialInitial state positions (flat)
final_stateFinal state positions (flat)
n_imagesNumber of intermediate images
configNEB configuration
sessionOptional active-learning session used to share observations and restore session state
Returns
GPNEBResult

Definition at line 21110 of file GPNEB.cpp.

21113{
21114 GPNEBConfig cfg = config;
21115 // A band the force-stop certificate resumes continues the search that
21116 // measured it. Without a session each pass builds an empty model: the
21117 // resumed band re-measures its endpoints and fits three rows, the tied
21118 // endpoint minima and the stepped image, so the prior alone sets its
21119 // hyperparameters. One session carries every row across the passes.
21120 std::optional<ActiveLearningSession> resumable;
21121 if (session == nullptr && config.force_stop_certificate &&
21122 isGpOieMode(config.mode) && config.gp_setup) {
21123 resumable.emplace();
21124 resumable->gp_setup = config.gp_setup;
21125 session = &*resumable;
21126 }
21127 if (n_images > 1 && cfg.secant_hessian.quadratic_prior_mean) {
21128 // Band observations and MMF leases cross image histories. A single
21129 // quadratic extrapolated through those displacements is not a local
21130 // curvature model, so keep the independently safe consistency and
21131 // seed features but gate the quadratic for the whole band driver.
21133 std::cout << "[secant-quadratic] mean disabled across band images; "
21134 "consistency and curvature seeds remain enabled\n";
21135 }
21136 if (session != nullptr) session->setSecantHessianConfig(cfg.secant_hessian);
21137 if (cfg.wall_clock_limit) {
21138 auto unguarded_oracle = std::move(oracle);
21139 const auto limit = cfg.wall_clock_limit;
21140 oracle = [unguarded = std::move(unguarded_oracle),
21141 limit](const Eigen::VectorXd& positions) mutable {
21142 gpr::requireWallClock(limit);
21143 return unguarded(positions);
21144 };
21145 if (cfg.batch_oracle) {
21146 auto unguarded_batch = std::move(cfg.batch_oracle);
21147 cfg.batch_oracle =
21148 [unguarded = std::move(unguarded_batch),
21149 limit](const std::vector<Eigen::VectorXd>& points) mutable {
21150 gpr::requireWallClock(limit);
21151 return unguarded(points);
21152 };
21153 }
21154 }
21155 long spent = 0;
21156 long cap = -1;
21157 int carried_oracle = 0;
21158 int carried_true = 0;
21159 int carried_validation = 0;
21160 int carried_certificate = 0;
21161 Eigen::VectorXd refused_at;
21162 GPNEBResult result;
21163 const auto finish = [&](GPNEBResult done) {
21164 if (session) done.prior_observations = session->priorObservations();
21165 return done;
21166 };
21167 for (int guard = 0; guard < gpr::optim::forceStopMinModeEscapes();
21168 ++guard) {
21169 result =
21170 gpNEBUngated(oracle, initial, final_state, n_images, cfg, session);
21171 result.oracle_calls += carried_oracle;
21172 // Certificate calls of an earlier pass stay validation calls.
21173 result.oracle_calls_outer += carried_oracle - carried_validation;
21174 result.oracle_calls_validation += carried_validation;
21175 result.force_stop_certificate_calls += carried_certificate;
21176 result.index_gate_true_calls += carried_true;
21177 spent += result.outer_iterations;
21178 if (config.force_stop_certificate && result.converged &&
21179 !result.index_checked && result.path) {
21180 const int image = result.max_energy_image;
21181 NEBPath& path = *result.path;
21182 const bool force_under = image > 0 &&
21183 image < path.numImages() - 1 &&
21184 path.image(image).evaluated &&
21185 std::isfinite(path.saddleForce(image)) &&
21186 path.saddleForce(image) < config.conv_tol;
21187 if (force_under) {
21189 result, oracle, cfg,
21190 session != nullptr ? &session->atoms_config : nullptr);
21191 } else if (image > 0 && image < path.numImages() - 1) {
21192 const double move = config.lbfgs_max_move > 0.0
21193 ? config.lbfgs_max_move
21194 : config.ci_stencil_step;
21195 const int images = path.numImages();
21196 const int budget = vibrationalIndexOuterBudget(config, images);
21197 const double threshold =
21198 session != nullptr
21200 : std::numeric_limits<double>::infinity();
21201 const auto decision = decideVibrationalIndex(
21202 path.image(image).positions, path.image(image).gradient,
21203 session != nullptr ? &session->atoms_config : nullptr,
21204 session != nullptr ? &session->gp : nullptr,
21205 path.image(image).posterior_variance, threshold, move,
21207 &oracle, &cfg.batch_oracle, config.oracle_batch_chunk,
21208 config.vibrational_stencil);
21209 applyVibrationalIndexDecision(result, decision, budget);
21210 }
21211 }
21212 if (!result.index_continue || !result.path)
21213 return finish(std::move(result));
21214 if (cap < 0)
21215 cap = vibrationalIndexOuterBudget(config, result.path->numImages());
21216 const int image = result.max_energy_image;
21217 const Eigen::VectorXd& claimed = result.path->image(image).positions;
21218 const bool repeated =
21219 refused_at.size() == claimed.size() &&
21220 (claimed - refused_at).norm() <= 1e-8 * (1.0 + refused_at.norm());
21221 if (spent >= cap || repeated) {
21222 result.converged = false;
21223 result.convergence_status = GPNEBConvergenceStatus::NotConverged;
21224 result.index_refused = true;
21225 result.index_continue = false;
21226 return finish(std::move(result));
21227 }
21228 refused_at = claimed;
21229 carried_oracle = result.oracle_calls;
21230 carried_true = result.index_gate_true_calls;
21231 carried_validation = result.oracle_calls_validation;
21232 carried_certificate = result.force_stop_certificate_calls;
21233 resumeFromSteppedPath(cfg, config, result, cap, spent);
21234 }
21235 result.converged = false;
21236 result.convergence_status = GPNEBConvergenceStatus::NotConverged;
21237 result.index_refused = true;
21238 result.index_continue = false;
21239 return finish(std::move(result));
21240}
int vibrationalIndexOuterBudget(const GPNEBConfig &config, int n_images)
Outer-iteration cap, including the per-image reading.
VibrationalIndexDecision decideVibrationalIndex(const Eigen::VectorXd &positions, const Eigen::VectorXd &gradient, const gpr::AtomsConfiguration *atoms, gpr::GaussianProcessRegression *gp, double variance, double variance_threshold, double move, double stencil_step, const NEBOracle *oracle, const NEBBatchOracle *batch, Eigen::Index batch_chunk, gpr::optim::VibrationalStencil stencil)
GPNEBResult gpNEBUngated(NEBOracle oracle, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int n_images, const GPNEBConfig &config, ActiveLearningSession *session)
Definition GPNEB.cpp:19834
double indexGateVarianceThreshold(double noise_variance) noexcept
void applyVibrationalIndexDecision(GPNEBResult &result, const VibrationalIndexDecision &decision, int outer_budget)
void certifyForceStoppedNeb(GPNEBResult &result, NEBOracle &oracle, const GPNEBConfig &config, const gpr::AtomsConfiguration *atoms)
void requireWallClock(const std::shared_ptr< const WallClockLimit > &limit)
Definition PhaseTimers.h:73
Panel finish(Real left, Real right, const Value &k, const Value &g, const Value &absolute)
void setSecantHessianConfig(const optim::SecantHessianConfig &config)
Definition Session.h:253
int priorObservations() const noexcept
Rows loaded from a seed file. Not an oracle-call count.
Definition Session.h:1288
gpr::optim::SecantHessianConfig secant_hessian
Definition GPNEB.h:536
std::function< void(gpr::InputParameters &, gpr::AtomsConfiguration &)> gp_setup
Definition GPNEB.h:1204

◆ gpNEBUngated()

GPNEBResult gpr::neb::gpNEBUngated ( NEBOracle oracle,
const Eigen::VectorXd & initial,
const Eigen::VectorXd & final_state,
int n_images,
const GPNEBConfig & config,
ActiveLearningSession * session )

Definition at line 19834 of file GPNEB.cpp.

19838{
19839 const NebVerboseGuard verbose_guard(config.verbose);
19840 GPNEBResult result;
19841 const auto wallClockReached = [&]() {
19843 return false;
19844 result.converged = false;
19847 return true;
19848 };
19849
19850 // The GP modes train their surrogate through gp_setup. Without it the
19851 // run would fall through to the oracle-only branches and report a GP
19852 // search that never built a GP, so refuse it.
19853 if (isGpOieMode(config.mode) && !config.gp_setup) {
19854 throw std::invalid_argument(
19855 std::string("GPNEBConfig: mode ") +
19856 (config.mode == NEBMode::GP_OIE ? "GP_OIE" : "GP_AIE") +
19857 " needs gp_setup to build its Gaussian process; set gp_setup, "
19858 "or choose NEBMode::OIE, AIE or Standard to run without one");
19859 }
19860
19861 // Initialize path
19862 std::unique_ptr<NEBPath> path_ptr;
19863 if (config.has_initial_path) {
19864 path_ptr = std::make_unique<NEBPath>(config.initial_path,
19865 config.spring_constant);
19866 path_ptr->setSpringBounds(config.spring_constant,
19867 config.spring_constant_min);
19868 // A warm-started band holds the spacing it was given (a local
19869 // refinement at the ridge) for the whole attempt; the rest lengths
19870 // are a fixed target, never refreshed under the relaxation.
19871 if (config.hold_refined_spacing &&
19872 static_cast<int>(config.initial_rest_lengths.size()) ==
19873 path_ptr->numImages() - 1) {
19874 path_ptr->setSpringRestLengths(config.initial_rest_lengths);
19875 }
19876 } else {
19877 path_ptr = std::make_unique<NEBPath>(initial, final_state, n_images,
19878 config.spring_constant);
19879 path_ptr->setSpringBounds(config.spring_constant,
19880 config.spring_constant_min);
19881 }
19882 NEBPath& path = *path_ptr;
19883 path.setConvergenceForceNorm(config.convergence_force_norm);
19884 path.setPeriodicCell(config.cell);
19885 if (!config.moving_atoms.empty()) path.setMovingAtoms(config.moving_atoms);
19886 path.setExternalFixedAtoms(config.frozen_positions.size() > 0);
19887 path.setMolecularRigidMotion(config.remove_molecular_rigid_motion &&
19888 config.n_atoms >= 2 &&
19889 config.frozen_positions.size() == 0);
19890 path.alignMolecularFrames();
19891 if (!config.has_initial_path) path.interpolateFromEndpoints();
19892 if (!config.rgsaddle_library.empty())
19894 if (!config.has_initial_path && config.use_idpp && config.n_atoms > 0) {
19895 std::cout << "[startup] path_seed engine=rgsaddle\n";
19896 if (config.use_sidpp) {
19897 if (config.sidpp_geodesic) {
19898 path.initializeSIDPPGeodesic(
19899 config.n_atoms, config.moving_atoms, config.sidpp_alpha);
19900 } else {
19901 path.initializeSIDPP(config.n_atoms, config.moving_atoms,
19902 config.sidpp_alpha);
19903 }
19904 } else {
19905 path.initializeIDPP(config.n_atoms, config.moving_atoms, false);
19906 }
19907 }
19908 path.setGeometricSpring(config.use_geometric_spring);
19909 // The surrogate bands relax with a predicted interior and are certified
19910 // on measured rows at the same geometry; one spring law serves both.
19911 path.setEnergyWeightedSprings(config.mode != NEBMode::GP_AIE &&
19912 config.mode != NEBMode::GP_OIE &&
19913 config.mode != NEBMode::OIE);
19914 path.alignMolecularFrames();
19915 (void)detail::publishOracleSessionPathCheckpoint(config, path);
19916 EndpointSymmetry endpoint_symmetry;
19917 if (!config.symmetry_permutation.empty())
19918 endpoint_symmetry = bandEndpointSymmetry(config, path, session);
19919
19920 result.oracle_calls = 0;
19921 std::mt19937 rng(config.seed);
19922 bool ci_active = false;
19923 const bool had_preexisting_session_rows =
19924 session != nullptr && session->training_obs.R.rows() > 0;
19925
19926 try {
19927 // Evaluate endpoints (always needed) - parallelized to avoid
19928 // replication. Wall-budget restarts restore the session's endpoint
19929 // rows instead of re-purchasing them.
19930 {
19931 const bool endpoints_restored =
19932 session &&
19933 detail::restoreObservedImageIfPresent(session->training_obs,
19934 path.image(0)) &&
19935 detail::restoreObservedImageIfPresent(
19936 session->training_obs, path.image(path.numImages() - 1));
19937 if (!endpoints_restored) {
19938 // Sample the band endpoints. A warm start can carry a
19939 // geometry other than the initial/final arguments; writing
19940 // that sample onto the other geometry poisons the endpoint
19941 // rows. A matching warm start has the same positions.
19942 std::vector<Eigen::VectorXd> endpoints = {
19943 path.image(0).positions,
19944 path.image(path.numImages() - 1).positions};
19945 // The endpoints are the given minima the band hangs from; a
19946 // band has no accepted state without them, so a failure there
19947 // ends the run.
19948 std::vector<EvalResult> res;
19949 try {
19950 res = parallelEvaluate(
19951 endpoints, oracle, nullptr, {},
19953 &config.batch_oracle, config.oracle_batch_chunk);
19954 } catch (const OracleSessionRestartRequested&) {
19955 throw;
19956 } catch (const gpr::WallClockLimitReached&) {
19957 throw;
19958 } catch (const std::exception& error) {
19959 throw std::runtime_error(
19960 std::string("the oracle failed at a band endpoint (the "
19961 "given reactant or product): ") +
19962 error.what());
19963 }
19964
19965 path.image(0).energy = res[0].energy;
19966 path.image(0).gradient = res[0].gradient;
19967 path.image(0).evaluated = true;
19968
19969 path.image(path.numImages() - 1).energy = res[1].energy;
19970 path.image(path.numImages() - 1).gradient = res[1].gradient;
19971 path.image(path.numImages() - 1).evaluated = true;
19972 if (session) {
19973 session->appendObservation(0, path.image(0).positions,
19974 res[0].energy, res[0].gradient);
19975 session->appendObservation(
19976 path.numImages() - 1,
19977 path.image(path.numImages() - 1).positions,
19978 res[1].energy, res[1].gradient);
19979 }
19980
19981 // Oracle calls are distributed; we increment by the number of
19982 // points evaluated across all ranks.
19983 result.oracle_calls += 2;
19984 result.oracle_calls_endpoints += 2;
19985 }
19986 }
19987 if (!endpoint_symmetry.empty())
19988 session->setEndpointSymmetry(std::move(endpoint_symmetry));
19989
19990 const bool uses_one_image_eval =
19991 config.mode == NEBMode::OIE || config.mode == NEBMode::GP_OIE;
19992
19993 // Initial-design: oracle every intermediate image once before the
19994 // outer loop. Standard / AIE modes always do this. GP-OIE does it
19995 // when config.seed_full_chain is true (ChemGP's gp_neb_oie default,
19996 // neb_oie.rs:648-664). Without it the GP starts knowing only the 2
19997 // endpoints and any chain-relaxation step is on a path-blind
19998 // surrogate; the chain settles into a wrong basin.
19999 const bool do_initial_design =
20000 config.mode == NEBMode::GP_LOCAL
20001 ? config.gp_local_initial_sweep
20002 : (!uses_one_image_eval ||
20003 (isGpOieMode(config.mode) && config.seed_full_chain));
20004
20005 if (do_initial_design) {
20006 // Bayesian continuation across wall-budget restarts: rows the
20007 // session already holds at these exact positions are restored,
20008 // not re-purchased -- the deterministic band reset makes every
20009 // restart's initial design identical, and re-oracling it would
20010 // pay the full design again on each attempt.
20011 std::vector<Eigen::VectorXd> intermediates;
20012 std::vector<int> pending_idx;
20013 for (int i = 1; i < path.numImages() - 1; ++i) {
20014 if (session && detail::restoreObservedImageIfPresent(
20015 session->training_obs, path.image(i))) {
20016 continue;
20017 }
20018 intermediates.push_back(path.image(i).positions);
20019 pending_idx.push_back(i);
20020 }
20021 if (!intermediates.empty()) {
20022 // A GP band can start without a failed image's row; a band
20023 // relaxed on the true forces cannot move an image it has no
20024 // force for, so there a failure ends the run.
20025 std::vector<char> measured;
20026 std::string failure;
20027 auto res = evaluateTrialPoints(
20028 intermediates, oracle, nullptr, {},
20030 &config.batch_oracle, config.oracle_batch_chunk, measured,
20031 failure);
20032 for (int k = 0; k < static_cast<int>(pending_idx.size()); ++k) {
20033 const int i = pending_idx[k];
20034 if (!measured[static_cast<std::size_t>(k)]) {
20035 if (!isGpOieMode(config.mode))
20036 throw std::runtime_error(
20037 "the oracle failed at image " +
20038 std::to_string(i) +
20039 " of the initial band: " + failure);
20040 if (config.verbose)
20041 neb_log() << "[oracle-refused] initial image=" << i
20042 << " what=" << failure << std::endl;
20043 continue;
20044 }
20045 path.image(i).energy = res[k].energy;
20046 path.image(i).gradient = res[k].gradient;
20047 path.image(i).evaluated = true;
20048 if (session)
20049 session->appendObservation(i, path.image(i).positions,
20050 res[k].energy,
20051 res[k].gradient);
20052 }
20053 result.oracle_calls += static_cast<int>(intermediates.size());
20054 result.oracle_calls_initial +=
20055 static_cast<int>(intermediates.size());
20056 }
20057 }
20058
20059 // Sampled energies do not bound the maximum between images. Only an
20060 // externally supplied energy limit can constrain the accepted saddle.
20061 const double connecting_path_energy_ceiling =
20062 session ? session->path_energy_ceiling
20063 : std::numeric_limits<double>::infinity();
20064 // Retain the initial geometry as a restart target for an explicit
20065 // limit.
20066 std::vector<Eigen::VectorXd> ceiling_witness_positions;
20067 if (std::isfinite(connecting_path_energy_ceiling)) {
20068 ceiling_witness_positions.reserve(path.numImages());
20069 for (int i = 0; i < path.numImages(); ++i) {
20070 ceiling_witness_positions.push_back(path.image(i).positions);
20071 }
20072 }
20073 // Fully measured fallback anchor: initially the seeded band and
20074 // replaced only by a lower-force band whose interior gradients all come
20075 // from the oracle. The restart selector prefers retained trust-bounded
20076 // path/climb snapshots and uses this anchor when none exists; an
20077 // unconverged result also restores it so a surrogate-only excursion is
20078 // never returned as the physical band.
20079 std::vector<Eigen::VectorXd> anchor_positions =
20080 ceiling_witness_positions;
20081 if (anchor_positions.empty()) {
20082 anchor_positions.reserve(path.numImages());
20083 for (int i = 0; i < path.numImages(); ++i) {
20084 anchor_positions.push_back(path.image(i).positions);
20085 }
20086 }
20087 // Descending true-force residuals refine the usual max-force merit:
20088 // equal maxima compare the next-largest residual. The anchor moves only
20089 // to a lexicographically better, fully measured band.
20090 std::vector<double> anchor_true_force_profile =
20091 detail::measuredBandForceProfile(path);
20092 double anchor_true_max_force =
20093 anchor_true_force_profile.empty()
20094 ? std::numeric_limits<double>::infinity()
20095 : anchor_true_force_profile.front();
20096
20097 // Compute initial NEB forces
20098 path.computeNEBForces();
20099 OracleForceProgressTracker oracle_force_progress(path.numImages());
20100 for (int i = 0; i < path.numImages(); ++i) {
20101 const Image& image = path.image(i);
20102 if (image.evaluated && image.gradient.size() > 0 &&
20103 image.gradient.allFinite()) {
20104 (void)oracle_force_progress.observe(i, image.gradient.norm());
20105 }
20106 }
20107
20108 // ------------------------------------------------------------------
20109 // GP-OIE branch: GP inner relaxation with one oracle acquisition.
20110 //
20111 // Outer iter:
20112 // 1. Build a GP with no across-iteration cache state; apply
20113 // layered-chain knobs;
20114 // train on accumulated obs.
20115 // 2. Inner GP-relaxation loop: predict (E, G) at each
20116 // intermediate image's current position from the GP, recompute
20117 // NEB forces, take a clipped global L-BFGS step. Break on
20118 // a condition certificate or an explicit positive inner budget.
20119 // 3. Pick the worst image (max variance with non-MAP modes, max
20120 // GP force otherwise), oracle-eval it, append to the training
20121 // set, then check the oracle-force convergence condition.
20122 //
20123 // Callers without gp_setup use the acquisition branch below.
20124 // ------------------------------------------------------------------
20125 if (config.mode == NEBMode::GP_LOCAL && !config.gp_local_sweep) {
20126 result = runGpLocalOie(oracle, config, path_ptr, path, result,
20127 ci_active, session);
20128 if (result.converged ||
20130 return result;
20131 // A zero outer budget asks for the initial band only; the retries
20132 // below would relax it, so hand it back as built.
20133 if (config.max_outer_iter == 0) return result;
20134 // The surrogate stopped above the force tolerance. Its springs
20135 // followed only the atoms that move between the endpoints, so a
20136 // substrate atom the pair model says is loaded by that motion was
20137 // left free. Search the same chord once more with those atoms
20138 // sprung. A search that already carried them, and still stopped,
20139 // finishes on the plain band.
20140 if (!config.gp_local_carry_springs) {
20141 GPNEBConfig carried = config;
20142 carried.gp_local_carry_springs = true;
20143 carried.has_initial_path = false;
20144 GPNEBResult second = gpNEBUngated(oracle, initial, final_state,
20145 n_images, carried, session);
20146 second.oracle_calls_endpoints += result.oracle_calls_endpoints;
20147 second.oracle_calls_initial += result.oracle_calls_initial;
20148 second.oracle_calls_outer += result.oracle_calls_outer;
20149 second.oracle_calls_validation +=
20151 second.oracle_calls = second.oracle_calls_endpoints +
20152 second.oracle_calls_initial +
20153 second.oracle_calls_outer +
20154 second.oracle_calls_validation;
20155 return second;
20156 }
20157 // The plain band on the same chord springs every atom. Finish
20158 // there and keep the surrogate's calls.
20159 GPNEBConfig plain = config;
20160 plain.mode = NEBMode::Standard;
20161 plain.has_initial_path = false;
20162 GPNEBResult finished = gpNEBUngated(oracle, initial, final_state,
20163 n_images, plain, session);
20164 finished.oracle_calls_endpoints += result.oracle_calls_endpoints;
20165 finished.oracle_calls_initial += result.oracle_calls_initial;
20166 finished.oracle_calls_outer += result.oracle_calls_outer;
20167 finished.oracle_calls_validation += result.oracle_calls_validation;
20168 finished.oracle_calls = finished.oracle_calls_endpoints +
20169 finished.oracle_calls_initial +
20170 finished.oracle_calls_outer +
20171 finished.oracle_calls_validation;
20172 return finished;
20173 }
20174 if (isGpOieMode(config.mode) && config.gp_setup) {
20175 return runGpOieNeb(oracle, config, session, path_ptr, path, result,
20176 oracle_force_progress, anchor_positions,
20177 anchor_true_force_profile, anchor_true_max_force,
20178 ceiling_witness_positions, ci_active,
20179 connecting_path_energy_ceiling,
20180 had_preexisting_session_rows);
20181 }
20182 // ------------------------------------------------------------------
20183 // Standard / AIE / OIE branches.
20184 // Allocate a band-L-BFGS chain optimizer once for these branches.
20185 // refresh() does NOT touch the GP -- the chain image gradients
20186 // come from the oracle (in AIE/Standard via re-evaluate after each
20187 // step; in OIE via the worst-image oracle). NEB forces are
20188 // recomputed from the stored gradients each refresh.
20189 detail::GlobalLBFGSOptions ndl_band_options;
20190 ndl_band_options.memory = config.lbfgs_memory;
20191 ndl_band_options.inverse_curvature = config.lbfgs_inverse_curvature;
20192 ndl_band_options.finite_difference = config.lbfgs_finite_difference;
20193 ndl_band_options.auto_scale = config.lbfgs_auto_scale;
20194 ndl_band_options.angle_reset = config.lbfgs_angle_reset;
20195 ndl_band_options.distance_reset = config.lbfgs_distance_reset;
20196 ndl_band_options.newton_agreement = config.lbfgs_newton_agreement;
20197 ndl_band_options.sketch_history = config.lbfgs_sketch_history;
20198 ndl_band_options.sketch_seed = config.lbfgs_sketch_seed;
20199 ndl_band_options.sketch_h0_rank = config.lbfgs_sketch_h0_rank;
20200 // GP_LOCAL never buys an oracle sweep inside a band step, so the
20201 // finite-difference curvature probe, which would read stale gradients
20202 // at the probed geometry, stays off and H0 comes from the scalar seed.
20203 if (config.mode == NEBMode::GP_LOCAL)
20204 ndl_band_options.finite_difference = 0.0;
20205 detail::GlobalLBFGSOptimizer ndl_band_optimizer(ndl_band_options);
20206 // Consecutive refused band evaluations; past the bound the run stops.
20207 OracleFailureBudget oracle_failures;
20208 auto ndl_refresh = [&]() {
20209 if (wallClockReached()) return false;
20210 // Standard / AIE relax the band on the TRUE potential. The L-BFGS
20211 // chain optimizer probes the objective at perturbed band geometries
20212 // (finite-difference curvature + trial steps); without a GP to
20213 // supply forces there, the image gradients must be re-evaluated on
20214 // the oracle at the current positions, else computeNEBForces() runs
20215 // on stale gradients, the curvature model degenerates, and the band
20216 // freezes (max NEB force constant across outer iters). The
20217 // post-step re-eval (the mode switch below) still runs; the extra
20218 // evals here are what make the chain L-BFGS see a consistent
20219 // true-force surface.
20220 if (config.mode == NEBMode::Standard ||
20221 config.mode == NEBMode::AIE) {
20222 std::vector<Eigen::VectorXd> pts;
20223 for (int i = 1; i < path.numImages() - 1; ++i) {
20224 pts.push_back(path.image(i).positions);
20225 }
20226 if (!pts.empty()) {
20227 // A refused image keeps its last measured state, and the
20228 // refresh reports failure so the optimizer rejects the
20229 // probe that led there.
20230 std::vector<char> measured;
20231 std::string failure;
20232 auto res = evaluateTrialPoints(
20233 pts, oracle, nullptr, {},
20235 &config.batch_oracle, config.oracle_batch_chunk,
20236 measured, failure);
20237 bool all_measured = true;
20238 for (int i = 0; i < static_cast<int>(pts.size()); ++i) {
20239 if (!measured[static_cast<std::size_t>(i)]) {
20240 all_measured = false;
20241 continue;
20242 }
20243 path.image(i + 1).energy = res[i].energy;
20244 path.image(i + 1).gradient = res[i].gradient;
20245 noteMeasuredSecant(session, config, i + 1,
20246 path.image(i + 1).positions,
20247 res[i].energy, res[i].gradient);
20248 }
20249 result.oracle_calls += static_cast<int>(pts.size());
20250 result.oracle_calls_outer += static_cast<int>(pts.size());
20251 if (!all_measured) {
20252 oracle_failures.failed("band", failure);
20253 if (config.verbose)
20254 neb_log() << "[oracle-refused] band refresh what="
20255 << failure << std::endl;
20256 detail::installSecantClimbingDirection(path, session,
20257 config);
20258 path.computeNEBForces();
20259 return false;
20260 }
20261 oracle_failures.measured();
20262 }
20263 }
20264 detail::installSecantClimbingDirection(path, session, config);
20265 path.computeNEBForces();
20266 return true;
20267 };
20268 detail::NEBBandObjective ndl_band_objective(path, ndl_refresh);
20269 // Halved after a band step whose geometry the oracle refused.
20270 double ndl_band_max_step = config.lbfgs_max_move;
20271 // Running maximum of the initial NEB force across the band. eOn's
20272 // relative CI activation rule fires once the current max NEB
20273 // force drops below ci_activation_factor * initial_max_force,
20274 // capped from below by ci_activation_tol.
20275 double initial_max_force = 0.0;
20276 // ------------------------------------------------------------------
20277
20278 // Main outer loop
20279 // Outer budget, optionally per image. The acquisition oracles about
20280 // one image per outer iteration, so a band of n images needs n outers
20281 // to be covered once; read absolutely, the same number gives a longer
20282 // band less chance per image, and a setting tuned at one image count
20283 // is silently wrong at another.
20284 const int outer_budget =
20285 (config.outer_budget_per_image && path.numImages() > 0)
20286 ? static_cast<int>(
20287 std::min<long>(static_cast<long>(config.max_outer_iter) *
20288 path.numImages(),
20289 std::numeric_limits<int>::max()))
20290 : config.max_outer_iter;
20291 // This loop is the model-free driver for OIE and for GP-OIE with
20292 // no gp_setup. Unevaluated interiors still hold energy 0.
20293 const bool model_free_one_image =
20294 config.mode == NEBMode::OIE || config.mode == NEBMode::GP_OIE;
20295 // ------------------------------------------------------------------
20296 // GP_LOCAL: the atoms that carry the endpoint motion form a Cartesian
20297 // subspace; a gradient GP over that subspace polishes every interior
20298 // image after each true-force band step, with the other coordinates
20299 // held at the stepped geometry. The oracle then measures the polished
20300 // band once, so each outer costs one sweep, and the band L-BFGS keeps
20301 // every measured secant pair, including the polish displacement.
20302 // ------------------------------------------------------------------
20303 const bool local_polish = config.mode == NEBMode::GP_LOCAL;
20304 std::vector<Eigen::Index> local_dofs;
20305 std::unique_ptr<LocalCartesianGP> local_gp;
20306 double local_trust = config.gp_local_trust;
20307 std::vector<double> local_predicted_energy;
20308 double local_fit_seconds = 0.0;
20309 double local_polish_seconds = 0.0;
20310 int local_polish_steps = 0;
20311 const Eigen::Index band_dof = path.numImages() > 0
20312 ? path.image(0).positions.size()
20313 : Eigen::Index(0);
20314 if (local_polish && band_dof > 0) {
20315 local_dofs = detail::selectLocalPolishDofs(
20316 path.image(0).positions,
20317 path.image(path.numImages() - 1).positions,
20318 config.gp_local_fraction, config.gp_local_radius);
20319 if (!local_dofs.empty()) {
20320 local_gp =
20321 std::make_unique<LocalCartesianGP>(band_dof, local_dofs);
20322 local_gp->setWindow(config.gp_local_window);
20323 local_gp->setNoise(config.gp_local_noise,
20324 config.gp_local_noise);
20325 local_gp->setLengthScaleBounds(0.05, 50.0);
20326 local_gp->setHyperparameters(1.0, 1.0);
20327 }
20328 if (config.verbose) {
20329 neb_log() << "[gp_local] subspace dofs=" << local_dofs.size()
20330 << " of " << band_dof
20331 << " fraction=" << config.gp_local_fraction
20332 << " radius=" << config.gp_local_radius
20333 << " window=" << config.gp_local_window
20334 << " trust=" << local_trust << "\n";
20335 }
20336 }
20337 auto local_gather = [&](const Eigen::VectorXd& v) {
20338 Eigen::VectorXd out(static_cast<Eigen::Index>(local_dofs.size()));
20339 for (std::size_t k = 0; k < local_dofs.size(); ++k)
20340 out(static_cast<Eigen::Index>(k)) = v(local_dofs[k]);
20341 return out;
20342 };
20343 // Every measured image feeds the local model; a repeated geometry
20344 // replaces its earlier row.
20345 auto local_observe = [&](const Image& image) {
20346 if (!local_gp || !image.evaluated) return;
20347 if (image.gradient.size() != band_dof ||
20348 !std::isfinite(image.energy))
20349 return;
20350 local_gp->add(image.positions, image.energy,
20351 local_gather(image.gradient));
20352 };
20353 if (local_gp) {
20354 for (int i = 0; i < path.numImages(); ++i)
20355 local_observe(path.image(i));
20356 }
20357 // Relax the local subspace of every interior image on the GP mean
20358 // under the band projection, the other coordinates fixed. Returns the
20359 // number of inner iterations taken.
20360 auto local_polish_band = [&](int outer) -> int {
20361 if (!local_gp || wallClockReached()) return 0;
20362 const auto t_fit = std::chrono::steady_clock::now();
20363 if (local_gp->size() >= 2 && !local_gp->ready() &&
20364 result.hyperparameter_refits == 0) {
20365 local_gp->setHyperparametersFromData(3.0);
20366 (void)local_gp->fit(config.gp_local_refit_iters);
20367 ++result.hyperparameter_refits;
20368 } else if (config.gp_local_refit_every > 0 &&
20369 outer % config.gp_local_refit_every == 0) {
20370 (void)local_gp->fit(config.gp_local_refit_iters);
20371 ++result.hyperparameter_refits;
20372 } else {
20373 local_gp->condition();
20374 ++result.fixed_theta_refreshes;
20375 }
20376 const auto t_polish = std::chrono::steady_clock::now();
20377 local_fit_seconds +=
20378 std::chrono::duration<double>(t_polish - t_fit).count();
20379 if (!local_gp->ready()) return 0;
20380 const int n_int = path.numImages() - 2;
20381 const Eigen::Index d = static_cast<Eigen::Index>(local_dofs.size());
20382 const Eigen::Index per = (band_dof % 3 == 0) ? 3 : 1;
20383 if (n_int <= 0 || d <= 0) return 0;
20384 std::vector<Eigen::VectorXd> start(static_cast<std::size_t>(n_int));
20385 std::vector<Image> before(static_cast<std::size_t>(n_int));
20386 for (int i = 0; i < n_int; ++i) {
20387 before[static_cast<std::size_t>(i)] = path.image(i + 1);
20388 start[static_cast<std::size_t>(i)] =
20389 local_gather(path.image(i + 1).positions);
20390 }
20391 auto refresh = [&]() {
20392 for (int i = 1; i < path.numImages() - 1; ++i) {
20393 Image& image = path.image(i);
20394 double energy = 0.0;
20395 Eigen::VectorXd grad;
20396 local_gp->predict(image.positions, energy, grad);
20397 gpr::numerics::perturbPosterior(energy, grad);
20398 image.energy = energy;
20399 image.gradient.setZero(band_dof);
20400 for (std::size_t k = 0; k < local_dofs.size(); ++k)
20401 image.gradient(local_dofs[k]) =
20402 grad(static_cast<Eigen::Index>(k));
20403 image.evaluated = false;
20404 }
20405 path.computeNEBForces();
20406 };
20407 auto band_force = [&]() {
20408 Eigen::VectorXd f(static_cast<Eigen::Index>(n_int) * d);
20409 for (int i = 0; i < n_int; ++i)
20410 f.segment(static_cast<Eigen::Index>(i) * d, d) =
20411 local_gather(path.nebForce(i + 1));
20412 return f;
20413 };
20414 auto band_positions = [&]() {
20415 Eigen::VectorXd z(static_cast<Eigen::Index>(n_int) * d);
20416 for (int i = 0; i < n_int; ++i)
20417 z.segment(static_cast<Eigen::Index>(i) * d, d) =
20418 local_gather(path.image(i + 1).positions);
20419 return z;
20420 };
20421 const double inner_tol =
20422 config.gp_local_inner_tol_factor * config.conv_tol;
20423 const double max_move =
20424 config.lbfgs_max_move > 0.0 ? config.lbfgs_max_move : 0.2;
20425 std::deque<Eigen::VectorXd> s_hist, y_hist;
20426 std::deque<double> rho_hist;
20427 Eigen::VectorXd z_prev, f_prev;
20428 double H0 = 0.05;
20429 int steps = 0;
20430 for (; steps < config.gp_local_inner_max; ++steps) {
20431 if (wallClockReached()) break;
20432 refresh();
20433 const Eigen::VectorXd f = band_force();
20434 double worst = 0.0;
20435 for (int i = 0; i < n_int; ++i)
20436 worst = std::max(
20437 worst,
20438 f.segment(static_cast<Eigen::Index>(i) * d, d).norm());
20439 if (!(worst > inner_tol) || !f.allFinite()) break;
20440 const Eigen::VectorXd z = band_positions();
20441 if (steps > 0) {
20442 const Eigen::VectorXd sv = z - z_prev;
20443 const Eigen::VectorXd yv = f_prev - f;
20444 const double sy = sv.dot(yv);
20445 if (sy > 1e-14 && std::isfinite(sy)) {
20446 s_hist.push_back(sv);
20447 y_hist.push_back(yv);
20448 rho_hist.push_back(1.0 / sy);
20449 while (static_cast<int>(s_hist.size()) > 20) {
20450 s_hist.pop_front();
20451 y_hist.pop_front();
20452 rho_hist.pop_front();
20453 }
20454 H0 =
20456 } else {
20457 s_hist.clear();
20458 y_hist.clear();
20459 rho_hist.clear();
20460 }
20461 }
20462 Eigen::VectorXd step = -gpr::optim::twoLoopRecursion(
20463 s_hist, y_hist, rho_hist, f, H0);
20464 if (step.dot(f) <= 0.0) {
20465 s_hist.clear();
20466 y_hist.clear();
20467 rho_hist.clear();
20468 step = H0 * f;
20469 }
20470 // Per-atom move bound, then the per-image trust sphere about
20471 // the stepped geometry.
20472 double largest = 0.0;
20473 for (Eigen::Index g = 0; g + per <= step.size(); g += per)
20474 largest = std::max(largest, step.segment(g, per).norm());
20475 if (largest > max_move) step *= max_move / largest;
20476 for (int i = 0; i < n_int; ++i) {
20477 const Eigen::Index off = static_cast<Eigen::Index>(i) * d;
20478 Eigen::VectorXd target =
20479 z.segment(off, d) + step.segment(off, d);
20480 Eigen::VectorXd disp =
20481 target - start[static_cast<std::size_t>(i)];
20482 const double dn = disp.norm();
20483 if (dn > local_trust && dn > 0.0) {
20484 target = start[static_cast<std::size_t>(i)] +
20485 disp * (local_trust / dn);
20486 }
20487 Image& image = path.image(i + 1);
20488 for (std::size_t k = 0; k < local_dofs.size(); ++k)
20489 image.positions(local_dofs[k]) =
20490 target(static_cast<Eigen::Index>(k));
20491 path.pinFixedAtoms(image.positions);
20492 }
20493 z_prev = z;
20494 f_prev = f;
20495 }
20496 refresh();
20497 local_predicted_energy.assign(static_cast<std::size_t>(n_int), 0.0);
20498 for (int i = 0; i < n_int; ++i)
20499 local_predicted_energy[static_cast<std::size_t>(i)] =
20500 path.image(i + 1).energy;
20501 local_polish_steps += steps;
20502 local_polish_seconds +=
20503 std::chrono::duration<double>(std::chrono::steady_clock::now() -
20504 t_polish)
20505 .count();
20506 if (config.verbose) {
20507 double moved = 0.0;
20508 for (int i = 0; i < n_int; ++i)
20509 moved = std::max(
20510 moved, (local_gather(path.image(i + 1).positions) -
20511 start[static_cast<std::size_t>(i)])
20512 .norm());
20513 neb_log() << "[gp_local] outer=" << outer
20514 << " polish_steps=" << steps << " moved=" << moved
20515 << " trust=" << local_trust
20516 << " n_obs=" << local_gp->size()
20517 << " ell=" << local_gp->lengthScale()
20518 << " sf=" << std::sqrt(local_gp->signalVariance())
20519 << "\n";
20520 }
20521 return steps;
20522 };
20523 BandForceStall band_stall;
20524 const int stall_window = bandStallWindow(
20525 path.numImages(), static_cast<int>(local_dofs.size()));
20526 for (int outer = 0; outer < outer_budget; ++outer) {
20527 if (wallClockReached()) break;
20528 if (local_gp) {
20529 for (int i = 1; i < path.numImages() - 1; ++i)
20530 local_observe(path.image(i));
20531 }
20532 if (session) {
20533 session->ci_active_at_outer_start = ci_active;
20534 if (ci_active)
20535 ++session->ci_stable_outer_count;
20536 else
20537 session->ci_stable_outer_count = 0;
20538 }
20539 // Check convergence
20540 double max_force = 0.0;
20541 for (int i = 1; i < path.numImages() - 1; ++i) {
20542 double f = path.nebForceMagnitude(i);
20543 max_force = std::max(max_force, f);
20544 }
20545 // CI-converged-only semantics. eOn (neb_loose default) checks
20546 // only the climbing image's NEB-force norm once CI is active;
20547 // the off-saddle band can remain slack since the saddle is the
20548 // physically meaningful target. Mirrors
20549 // NudgedElasticBand::convergenceForce() in eOn:399-422. Without
20550 // this gate the Standard/AIE branch needs ~2x more outer iters
20551 // (gpr AIE 03_h2co: 626 calls vs eOn 298 at conv_tol=0.5).
20552 double convergence_force = max_force;
20553 const bool climb_only =
20554 config.climbing_image_converged_only && ci_active;
20555 // The installed marker, not the current energy maximum. The
20556 // maximum can move onto a quieter neighbour while the bead that
20557 // is climbing is still above --converged-force.
20558 const int climbing_image =
20559 climb_only ? detail::activeClimbingMarkerIndex(path) : -1;
20560 const int measured_candidate =
20561 climb_only
20562 ? climbing_image
20563 : (ci_active ? path.highestEnergyImageIndex()
20564 : detail::bestEvaluatedSaddleCandidate(path));
20565 if (detail::evaluatedTrueForceBelowFinalTolerance(
20566 path, measured_candidate, config.conv_tol, !ci_active)) {
20567 // The climbing bead's true force is already the final
20568 // tolerance. Do not spend another outer on the rest of the
20569 // band.
20570 result.converged = true;
20571 result.convergence_status =
20573 convergence_force = path.saddleForce(measured_candidate);
20574 }
20575 if (climb_only) {
20576 if (climbing_image > 0 &&
20577 climbing_image < path.numImages() - 1) {
20578 convergence_force = path.saddleForce(climbing_image);
20579 } else {
20580 convergence_force = std::numeric_limits<double>::infinity();
20581 }
20582 }
20583 result.max_force_history.push_back(convergence_force);
20584
20585 if (detail::outerConvergenceCertifiedByTolerance(
20586 config, path, ci_active, convergence_force)) {
20587 result.converged = true;
20588 result.convergence_status =
20589 detail::convergenceStatusForCurrentTolerance(config);
20590 // Fall through to the composition-trace write below, then
20591 // break.
20592 }
20593
20594 // Climbing image activation. eOn (neb_loose) uses
20595 // activate when max_force <= max(ci_after,
20596 // ci_after_rel *
20597 // initial_max_force)
20598 // with ci_after = 0.5 eV/A and ci_after_rel = 0.8. The relative
20599 // trigger fires much earlier than the absolute one for runs
20600 // starting with max_force >> 1 eV/A; the absolute floor caps
20601 // it so converged_force=0.5 runs still activate CI before
20602 // reaching the band-wide convergence threshold (otherwise
20603 // ci_converged_only never kicks in and the convergence
20604 // criterion is max-over-band, which costs ~2x more outer
20605 // iterations than eOn).
20606 if (result.converged) {
20607 // Count the accepting outer (parity with the GP-OIE branch,
20608 // which sets outer_iterations before its convergence gate).
20609 result.outer_iterations = outer + 1;
20610 // Still emit one composition snapshot for the accepting outer
20611 // before leaving the loop (no further band step / re-eval).
20612 if (config.record_composition_trace) {
20614 rec.outer_idx = outer;
20615 rec.oracle_target_image = -1;
20616 rec.max_oracle_force = max_force;
20617 rec.n_uneval = 0;
20618 rec.ci_active = ci_active;
20619 rec.ci_index = ci_active
20620 ? (climbing_image > 0
20621 ? climbing_image
20622 : path.highestEnergyImageIndex())
20623 : -1;
20624 {
20625 const int hi = path.highestEnergyImageIndex();
20626 rec.barrier_estimate =
20627 detail::forwardBarrierEnergy(path, hi);
20628 }
20629 rec.certificates.force_tolerance = true;
20630 rec.certificates.mep_force_ok =
20631 (max_force <
20632 detail::effectiveModelNoiseTolerance(config));
20633 rec.certificates.ci_force_ok =
20634 (!ci_active ||
20635 convergence_force <
20636 detail::effectiveModelNoiseTolerance(config));
20637 rec.certificates.n_uneval_zero = true;
20638 rec.certificates.certified_full_band_branch = true;
20639 result.composition_trace.push_back(std::move(rec));
20640 }
20641 break;
20642 }
20643 if (initial_max_force <= 0.0 && std::isfinite(max_force)) {
20644 initial_max_force = max_force;
20645 }
20646 const double ci_relative_trigger =
20647 (initial_max_force > 0.0 && config.ci_activation_factor > 0.0)
20648 ? config.ci_activation_factor * initial_max_force
20649 : 0.0;
20650 const double ci_activation_threshold =
20651 std::max(config.ci_activation_tol, ci_relative_trigger);
20652 if (config.climbing_image && !ci_active &&
20653 max_force < ci_activation_threshold) {
20654 ci_active = true;
20655 }
20656 if (config.climbing_image && ci_active) {
20657 if (model_free_one_image &&
20658 detail::hasUnevaluatedInterior(path)) {
20659 detail::assignClimbingImageFromEvaluatedEnergies(path);
20660 } else {
20661 path.enableClimbingImage();
20662 }
20663 }
20664
20665 // Band L-BFGS step. Same chain optimizer the GP-OIE branch uses
20666 // (gpr::neb::detail::GlobalLBFGSOptimizer with Nocedal two-loop
20667 // recursion and per-atom maxMove clip), matching eOn/ChemGP
20668 // NEB chain optimization. Per-image steepest descent
20669 // (step = inner_step_size * nebForce, clipped to 0.1 A) can
20670 // park the barrier near the saddle while leaving max force
20671 // above conv_tol; L-BFGS is the force-reducing step.
20672 detail::installSecantClimbingDirection(path, session, config);
20673 path.computeNEBForces();
20674 // The measured band before the step, restored when the oracle
20675 // refuses a geometry the step moved an image to.
20676 std::vector<Image> band_before_step;
20677 band_before_step.reserve(
20678 static_cast<std::size_t>(path.numImages()));
20679 for (int i = 0; i < path.numImages(); ++i)
20680 band_before_step.push_back(path.image(i));
20681 const int prev_hist = ndl_band_optimizer.historySize();
20682 const std::optional<double> secant_inverse_curvature =
20683 secantBandInverseCurvature(session, config);
20684 (void)ndl_band_optimizer.step(ndl_band_objective, ndl_band_max_step,
20685 secant_inverse_curvature);
20686 if (wallClockReached()) {
20687 for (int i = 0; i < path.numImages(); ++i)
20688 path.image(i) =
20689 band_before_step[static_cast<std::size_t>(i)];
20690 path.computeNEBForces();
20691 break;
20692 }
20693 const int post_hist = ndl_band_optimizer.historySize();
20694 const bool hist_reset = post_hist <= prev_hist && prev_hist > 0;
20695 // Per-outer AIE trace (one line per outer iter). Mirrors the
20696 // [gp_oie] line emitted by the GP-OIE branch so smokes can
20697 // diff iteration-by-iteration against eOn / OIE for the same
20698 // cell. Includes the chain L-BFGS history size and a
20699 // history-reset flag so angle_reset cascades
20700 // are visible without recompiling for verbose mode.
20701 if (config.verbose) {
20702 const int hi_now = path.highestEnergyImageIndex();
20703 const double bar_now =
20704 detail::forwardBarrierEnergy(path, hi_now);
20705 neb_log() << "[aie] outer=" << outer << " max_F=" << max_force
20706 << " conv_F=" << convergence_force
20707 << " ci=" << (ci_active ? 1 : 0) << " hi=" << hi_now
20708 << " bar=" << bar_now << " hist=" << post_hist
20709 << (hist_reset ? " (LBFGS_RESET)" : "")
20710 << " noracle=" << result.oracle_calls << "\n";
20711 }
20712
20713 // Re-evaluate based on mode
20714 switch (config.mode) {
20715 case NEBMode::Standard:
20716 case NEBMode::AIE:
20717 case NEBMode::GP_LOCAL: {
20718 if (local_polish) (void)local_polish_band(outer);
20719 std::vector<Eigen::VectorXd> pts;
20720 for (int i = 1; i < path.numImages() - 1; ++i) {
20721 pts.push_back(path.image(i).positions);
20722 }
20723 std::vector<char> measured;
20724 std::string failure;
20725 auto res = evaluateTrialPoints(
20726 pts, oracle, nullptr, {},
20728 &config.batch_oracle, config.oracle_batch_chunk,
20729 measured, failure);
20730 result.oracle_calls += static_cast<int>(pts.size());
20731 result.oracle_calls_outer += static_cast<int>(pts.size());
20732 if (std::find(measured.begin(), measured.end(), 0) !=
20733 measured.end()) {
20734 // A rejected band step: the measured band comes back,
20735 // the step bound halves, and the curvature pairs that
20736 // aimed at the refused geometry are dropped.
20737 oracle_failures.failed("band", failure);
20738 for (int i = 0; i < path.numImages(); ++i)
20739 path.image(i) =
20740 band_before_step[static_cast<std::size_t>(i)];
20741 path.computeNEBForces();
20742 ndl_band_max_step *= 0.5;
20743 ndl_band_optimizer.reset();
20744 if (config.verbose)
20745 neb_log() << "[oracle-refused] band step rejected, "
20746 "max move "
20747 << ndl_band_max_step
20748 << " what=" << failure << std::endl;
20749 break;
20750 }
20751 oracle_failures.measured();
20752 for (int i = 0; i < static_cast<int>(pts.size()); ++i) {
20753 path.image(i + 1).energy = res[i].energy;
20754 path.image(i + 1).gradient = res[i].gradient;
20755 path.image(i + 1).evaluated = true;
20756 noteMeasuredSecant(session, config, i + 1,
20757 path.image(i + 1).positions,
20758 res[i].energy, res[i].gradient);
20759 }
20760 if (local_polish && local_gp &&
20761 local_predicted_energy.size() == pts.size()) {
20762 // The measured energies grade the polish: a surprise
20763 // halves the trust sphere, agreement widens it.
20764 double surprise = 0.0;
20765 for (std::size_t i = 0; i < pts.size(); ++i)
20766 surprise = std::max(
20767 surprise, std::abs(res[i].energy -
20768 local_predicted_energy[i]));
20769 if (surprise > 0.1) {
20770 local_trust = std::max(0.5 * local_trust, 0.02);
20771 } else if (surprise < 0.01) {
20772 local_trust =
20773 std::min(1.5 * local_trust,
20774 std::max(1.0, config.gp_local_trust));
20775 }
20776 if (config.verbose)
20777 neb_log() << "[gp_local] outer=" << outer
20778 << " surprise=" << surprise
20779 << " trust=" << local_trust << "\n";
20780 }
20781 // OCINEB MMF on the climbing image, true-potential dimer.
20782 // Standard/AIE relax the band but otherwise never run the
20783 // minimum-mode-following step, so they were plain CI-NEB
20784 // and climbed a higher saddle than the eOn OCINEB
20785 // reference. Drive the SAME outer_iter_hook the GP-OIE
20786 // branch uses (the OCINEB controller): it gates triggering
20787 // via stability + adaptive threshold and writes the
20788 // dimer-refined saddle back to the CI.
20789 if (config.outer_iter_hook && session && ci_active) {
20790 const int hook_ci_idx =
20791 detail::activeClimbingMarkerIndex(path);
20792 if (hook_ci_idx > 0 &&
20793 hook_ci_idx < path.numImages() - 1) {
20794 path.computeNEBForces();
20795 bool hook_converged = false;
20796 config.outer_iter_hook(path, hook_ci_idx, outer,
20797 *session, hook_converged,
20798 /*trap_detected=*/false);
20799 if (hook_converged) {
20800 result.converged = true;
20801 result.convergence_status = detail::
20802 convergenceStatusForCurrentTolerance(
20803 config);
20804 }
20805 }
20806 }
20807 break;
20808 }
20809
20810 case NEBMode::GP_AIE:
20811 case NEBMode::GP_OIE:
20812 case NEBMode::OIE: {
20813 // Select image(s) to evaluate via acquisition strategy.
20814 int n_int = path.numIntermediate();
20815 std::vector<Eigen::VectorXd> forces(n_int);
20816 std::vector<ObservationVariance> variances(n_int);
20817 const bool have_variance_estimator = static_cast<bool>(
20819 std::vector<Eigen::VectorXd> tangents(n_int);
20820 std::vector<bool> evaluated(n_int, false);
20821
20822 for (int i = 0; i < n_int; ++i) {
20823 forces[i] = path.nebForce(i + 1);
20824 // Tangent at image i+1
20825 Eigen::VectorXd tau = path.image(i + 2).positions -
20826 path.image(i).positions;
20827 double tn = tau.norm();
20828 if (tn > 1e-10) tau /= tn;
20829 tangents[i] = tau;
20830
20831 if (have_variance_estimator) {
20832 variances[i] =
20834 path.image(i + 1).positions);
20835 } else {
20836 variances[i].gradient = Eigen::VectorXd::Zero(
20837 path.image(i + 1).positions.size());
20838 }
20839 }
20840
20841 // Select images to evaluate
20842 std::vector<int> to_eval;
20843 for (int ev = 0; ev < config.evals_per_iter; ++ev) {
20844 int sel = selectNextImage(forces, variances, tangents,
20845 evaluated, config.acquisition,
20846 config.ucb_kappa, &rng);
20847 if (sel >= 0) {
20848 if (config.use_triplet) {
20849 auto triplet =
20850 expandToTriplet(sel + 1, path.numImages());
20851 for (int idx: triplet) {
20852 if (idx > 0 && idx < path.numImages() - 1) {
20853 to_eval.push_back(idx);
20854 evaluated[idx - 1] = true;
20855 }
20856 }
20857 } else {
20858 to_eval.push_back(sel + 1);
20859 evaluated[sel] = true;
20860 }
20861 }
20862 }
20863
20864 // Evaluate selected images
20865 std::vector<Eigen::VectorXd> pts_to_eval;
20866 for (int idx: to_eval) {
20867 pts_to_eval.push_back(path.image(idx).positions);
20868 }
20869 std::vector<char> measured;
20870 std::string failure;
20871 auto res = evaluateTrialPoints(
20872 pts_to_eval, oracle, nullptr, {},
20874 &config.batch_oracle, config.oracle_batch_chunk,
20875 measured, failure);
20876 if (std::find(measured.begin(), measured.end(), 0) !=
20877 measured.end()) {
20878 // As for the full-band modes: the step that moved the
20879 // image onto the refused geometry is rejected.
20880 result.oracle_calls += static_cast<int>(to_eval.size());
20881 result.oracle_calls_outer +=
20882 static_cast<int>(to_eval.size());
20883 oracle_failures.failed("band", failure);
20884 for (int i = 0; i < path.numImages(); ++i)
20885 path.image(i) =
20886 band_before_step[static_cast<std::size_t>(i)];
20887 path.computeNEBForces();
20888 ndl_band_max_step *= 0.5;
20889 ndl_band_optimizer.reset();
20890 if (config.verbose)
20891 neb_log() << "[oracle-refused] band step rejected, "
20892 "max move "
20893 << ndl_band_max_step
20894 << " what=" << failure << std::endl;
20895 break;
20896 }
20897 oracle_failures.measured();
20898 for (int i = 0; i < static_cast<int>(to_eval.size()); ++i) {
20899 int idx = to_eval[i];
20900 path.image(idx).energy = res[i].energy;
20901 path.image(idx).gradient = res[i].gradient;
20902 path.image(idx).evaluated = true;
20903 }
20904 if (model_free_one_image && config.climbing_image &&
20905 ci_active && detail::hasUnevaluatedInterior(path)) {
20906 detail::assignClimbingImageFromEvaluatedEnergies(path);
20907 }
20908 result.oracle_calls += static_cast<int>(to_eval.size());
20909 result.oracle_calls_outer +=
20910 static_cast<int>(to_eval.size());
20911 break;
20912 }
20913 }
20914
20915 if (wallClockReached()) break;
20916 // Recompute NEB forces with updated energies/gradients
20917 path.computeNEBForces();
20918 result.outer_iterations = outer + 1;
20919 if (config.band_stall) {
20920 noteLowestCertifiedClimb(band_stall, path,
20921 path.highestEnergyImageIndex());
20922 double measured_max = 0.0;
20923 for (int i = 1; i < path.numImages() - 1; ++i)
20924 measured_max =
20925 std::max(measured_max, path.nebForceMagnitude(i));
20926 const BandStallAction action = observeMaxBandForce(
20927 band_stall, measured_max, config.conv_tol, stall_window);
20928 if (action != BandStallAction::Continue) {
20929 restoreCertifiedClimb(path, band_stall);
20930 ndl_band_optimizer.reset();
20931 double restored_max = 0.0;
20932 for (int i = 1; i < path.numImages() - 1; ++i)
20933 restored_max =
20934 std::max(restored_max, path.nebForceMagnitude(i));
20935 band_stall.best_force = restored_max;
20936 if (config.verbose)
20937 neb_log()
20938 << "[band] stall outer=" << outer << " action="
20939 << (action == BandStallAction::Stop ? "stop"
20940 : "restore")
20941 << " image=" << band_stall.image
20942 << " E=" << band_stall.energy
20943 << " F=" << restored_max
20944 << " window=" << stall_window << "\n";
20945 if (action == BandStallAction::Stop) {
20946 if (detail::evaluatedTrueForceBelowFinalTolerance(
20947 path, band_stall.image, config.conv_tol,
20948 !ci_active)) {
20949 result.converged = true;
20950 result.convergence_status =
20952 } else if (session && config.outer_iter_hook &&
20953 ci_active) {
20954 session->stagnation_handoff = true;
20955 const int handoff_ci =
20956 detail::activeClimbingMarkerIndex(path);
20957 if (handoff_ci > 0 &&
20958 handoff_ci < path.numImages() - 1) {
20959 bool handoff_converged = false;
20960 config.outer_iter_hook(path, handoff_ci, outer,
20961 *session,
20962 handoff_converged,
20963 /*trap_detected=*/false);
20964 if (handoff_converged) {
20965 result.converged = true;
20966 result.convergence_status = detail::
20967 convergenceStatusForCurrentTolerance(
20968 config);
20969 }
20970 }
20971 }
20972 break;
20973 }
20974 }
20975 }
20976
20977 // Composition-level snapshot for Standard / AIE / model-free OIE.
20978 // Captures post-step decision state for this outer. (The accepting
20979 // outer is recorded on the early-exit path above.)
20980 if (config.record_composition_trace) {
20981 double post_max_force = 0.0;
20982 for (int i = 1; i < path.numImages() - 1; ++i) {
20983 const double f = path.nebForceMagnitude(i);
20984 post_max_force = std::max(post_max_force, f);
20985 }
20987 rec.outer_idx = outer;
20988 // Standard/AIE re-eval the full band; OIE uses acquisition.
20989 // This composition branch does not retain the primary target,
20990 // so -1 means "band-wide / acquisition-driven".
20991 rec.oracle_target_image = -1;
20992 rec.max_oracle_force = post_max_force;
20993 rec.n_uneval = 0;
20994 rec.ci_active = ci_active;
20995 const int trace_ci =
20996 ci_active ? detail::activeClimbingMarkerIndex(path) : -1;
20997 rec.ci_index = trace_ci;
20998 {
20999 const int hi = path.highestEnergyImageIndex();
21000 rec.barrier_estimate =
21001 detail::forwardBarrierEnergy(path, hi);
21002 }
21003 const double model_tol =
21004 detail::effectiveModelNoiseTolerance(config);
21005 rec.certificates.n_uneval_zero = true;
21006 rec.certificates.mep_force_ok = (post_max_force < model_tol);
21007 rec.certificates.ci_force_ok =
21008 (!ci_active ||
21009 (trace_ci > 0 && path.saddleForce(trace_ci) < model_tol));
21010 const double trace_stop_force =
21011 (config.climbing_image_converged_only && ci_active)
21012 ? (trace_ci > 0
21013 ? path.saddleForce(trace_ci)
21014 : std::numeric_limits<double>::infinity())
21015 : post_max_force;
21016 rec.certificates.force_tolerance =
21017 detail::outerConvergenceCertifiedByTolerance(
21018 config, path, ci_active, trace_stop_force);
21019 result.composition_trace.push_back(std::move(rec));
21020 }
21021 }
21022
21023 if (local_polish && config.verbose) {
21024 neb_log() << "[gp_local] summary dofs=" << local_dofs.size()
21025 << " polish_steps=" << local_polish_steps
21026 << " fit_seconds=" << local_fit_seconds
21027 << " polish_seconds=" << local_polish_seconds << "\n";
21028 }
21029 // Find barrier (forward convention: E_saddle - E_reactant, matching
21030 // the eOn results.dat extremum convention consumed downstream).
21031 // Energy 0 on an image the oracle has not touched is not a saddle.
21032 if (model_free_one_image && detail::hasUnevaluatedInterior(path)) {
21033 const int evaluated_hi =
21034 detail::highestEvaluatedInteriorImageIndex(path);
21035 result.max_energy_image = evaluated_hi > 0
21036 ? evaluated_hi
21037 : path.highestEnergyImageIndex();
21038 } else if (config.climbing_image_converged_only && ci_active) {
21039 const int climbing = detail::activeClimbingMarkerIndex(path);
21040 result.max_energy_image =
21041 climbing > 0 ? climbing : path.highestEnergyImageIndex();
21042 } else {
21043 result.max_energy_image = path.highestEnergyImageIndex();
21044 }
21045 result.returned_true_force =
21046 detail::evaluatedTrueForce(path, result.max_energy_image);
21047 result.barrier_energy =
21048 detail::forwardBarrierEnergy(path, result.max_energy_image);
21049 result.reverse_barrier_energy =
21050 detail::reverseBarrierEnergy(path, result.max_energy_image);
21051 result.path = std::move(path_ptr);
21053 result.stop_reason = result.converged
21056
21057 return result;
21058 } catch (const gpr::WallClockLimitReached&) {
21059 result.converged = false;
21062 if (session) {
21063 for (int image = 0; image < path.numImages(); ++image)
21064 (void)detail::restoreObservedImageIfPresent(
21065 session->training_obs, path.image(image));
21066 }
21067 result.max_energy_image =
21068 detail::highestEvaluatedInteriorImageIndex(path);
21069 const bool measured_saddle = result.max_energy_image > 0;
21070 if (result.max_energy_image <= 0)
21071 result.max_energy_image = path.highestEnergyImageIndex();
21072 result.returned_true_force =
21073 detail::evaluatedTrueForce(path, result.max_energy_image);
21074 if (measured_saddle && path.image(0).evaluated &&
21075 path.image(path.numImages() - 1).evaluated) {
21076 result.barrier_energy =
21077 detail::forwardBarrierEnergy(path, result.max_energy_image);
21078 result.reverse_barrier_energy =
21079 path.image(result.max_energy_image).energy -
21080 path.image(path.numImages() - 1).energy;
21081 } else {
21082 result.barrier_energy = std::numeric_limits<double>::quiet_NaN();
21083 result.reverse_barrier_energy =
21084 std::numeric_limits<double>::quiet_NaN();
21085 }
21086 result.path = std::move(path_ptr);
21087 return result;
21088 }
21089}
@ z
Definition Enums.h:28
int selectNextImage(const std::vector< Eigen::VectorXd > &neb_forces, const std::vector< ObservationVariance > &variances, const std::vector< Eigen::VectorXd > &tangents, const std::vector< bool > &evaluated, AcquisitionType strategy, double kappa, std::mt19937 *rng)
Select the next unevaluated intermediate image by a per-image score.
void restoreCertifiedClimb(NEBPath &path, const BandForceStall &stall)
Put the certified climb back and make it the climbing image.
Definition BandStall.h:100
@ IterationBudget
The configured outer-iteration budget was exhausted.
Definition GPNEB.h:3676
@ Unspecified
No terminal condition has been assigned.
Definition GPNEB.h:3672
BandStallAction observeMaxBandForce(BandForceStall &stall, double max_force, double force_tolerance, int window)
Definition BandStall.h:80
BandStallAction
What to do when the max band force stops falling.
Definition BandStall.h:17
void noteLowestCertifiedClimb(BandForceStall &stall, const NEBPath &path, int image)
Definition BandStall.h:50
std::vector< int > expandToTriplet(int center, int n_total)
Expand a single image index to a triplet {i-1, i, i+1}.
int bandStallWindow(int n_images, int polished_dofs) noexcept
Definition BandStall.h:39
void perturbPosterior(double &energy, Eigen::VectorXd &gradient)
double barzilaiBorweinInverseScale(const Eigen::VectorXd &s, const Eigen::VectorXd &y, double fallback)
Scalar BB2 inverse-curvature seed for L-BFGS H0.
Definition LBFGS.cpp:39
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
void setBofillRgsaddleLibrary(const char *path)
void setEndpointSymmetry(EndpointSymmetry symmetry)
Definition Session.h:1601
bool remove_molecular_rigid_motion
Definition GPNEB.h:379
std::vector< char > moving_atoms
Definition GPNEB.h:422
double gp_local_inner_tol_factor
Definition GPNEB.h:900
double gp_local_radius
Definition GPNEB.h:889
OuterIterHook outer_iter_hook
Definition GPNEB.h:1225
std::vector< int > symmetry_permutation
Definition GPNEB.h:670
bool outer_budget_per_image
Definition GPNEB.h:300
std::optional< ConvergenceNormType > convergence_force_norm
Definition GPNEB.h:263
double lbfgs_inverse_curvature
Definition GPNEB.h:1010
std::vector< double > initial_rest_lengths
Definition GPNEB.h:542
double lbfgs_finite_difference
Definition GPNEB.h:1011
ObservationVarianceEstimator observation_variance_estimator
Definition GPNEB.h:1209
double ci_activation_tol
Definition GPNEB.h:354
AcquisitionType acquisition
Definition GPNEB.h:445
Eigen::VectorXd frozen_positions
Definition GPNEB.h:387
bool gp_local_initial_sweep
Definition GPNEB.h:921
uint64_t lbfgs_sketch_seed
Definition GPNEB.h:1088
double lbfgs_newton_agreement
Definition GPNEB.h:1020
bool gp_local_carry_springs
Definition GPNEB.h:959
std::string rgsaddle_library
Definition GPNEB.h:711
double gp_local_trust
Definition GPNEB.h:894
bool hold_refined_spacing
Definition GPNEB.h:873
bool record_composition_trace
Definition GPNEB.h:525
bool use_geometric_spring
Definition GPNEB.h:434
double ci_activation_factor
Definition GPNEB.h:355
bool climbing_image_converged_only
Definition GPNEB.h:328
double gp_local_fraction
Definition GPNEB.h:886
double gp_local_noise
Definition GPNEB.h:909
double spring_constant
Definition GPNEB.h:313
EigenMatrix initial_path
Definition GPNEB.h:538
double spring_constant_min
Definition GPNEB.h:315
std::function< bool()> oracle_session_restart_requested
Definition GPNEB.h:279
std::vector< OuterIterCompositionTraceRecord > composition_trace
Definition GPNEB.h:3756
double reverse_barrier_energy
Definition GPNEB.h:3739
std::vector< double > max_force_history
Definition GPNEB.h:3748
A single image on the NEB path.
Definition NEBPath.h:39
One outer-iteration composition snapshot.

◆ gprMeanSurfaceCallback()

int gpr::neb::gprMeanSurfaceCallback ( void * user,
eon_relax_surface_request_t * req )
noexcept

Surface trampoline: the frozen-or-live GP surface behind the eon_relax_surface_fn contract. user is a GprMeanPotential*. Every image is evaluated through the cached-factor force path; the request's epoch_out carries surfaceEpoch() so eOn's Matter cache keys on the model generation. A request whose version major is unknown is refused.

Definition at line 167 of file EonRelaxClient.cpp.

169{
170 if (user == nullptr || req == nullptr || req->positions == nullptr ||
171 req->atomic_nrs == nullptr || req->boxes == nullptr ||
172 req->energies == nullptr || req->forces == nullptr ||
173 req->n_images <= 0 || req->n_atoms <= 0) {
174 return -1;
175 }
176 if (req->version.major != EON_RELAX_ABI_MAJOR) {
177 return -1;
178 }
179 try {
180 auto* surface = static_cast<pot::GprMeanPotential*>(user);
181 const long n_images = static_cast<long>(req->n_images);
182 const long n_atoms = static_cast<long>(req->n_atoms);
183 const long dof = 3 * n_atoms;
184 std::vector<int> atomic_nrs(req->atomic_nrs, req->atomic_nrs + n_atoms);
185 // Publish nothing until every image succeeds. A later failure
186 // must leave the caller buffers as they were.
187 std::vector<double> scratch_energies(
188 static_cast<std::size_t>(n_images));
189 std::vector<double> scratch_forces(static_cast<std::size_t>(n_images) *
190 static_cast<std::size_t>(dof));
191 std::vector<double> scratch_variances;
192 if (req->variances != nullptr)
193 scratch_variances.resize(static_cast<std::size_t>(n_images));
194 for (long i = 0; i < n_images; ++i) {
195 double variance = 0.0;
196 surface->force(n_atoms, req->positions + i * dof, atomic_nrs.data(),
197 scratch_forces.data() + i * dof,
198 &scratch_energies[static_cast<std::size_t>(i)],
199 req->variances != nullptr ? &variance : nullptr,
200 req->boxes + i * 9);
201 // Same acceptance rule as energyVarianceToRms. A rejected
202 // raw variance must fail before any caller buffer or the
203 // epoch is written. A tiny negative value may stay raw.
204 if (req->variances != nullptr &&
206 return -1;
207 if (req->variances != nullptr)
208 scratch_variances[static_cast<std::size_t>(i)] = variance;
209 }
210 std::copy_n(scratch_energies.data(), n_images, req->energies);
211 std::copy_n(
212 scratch_forces.data(),
213 static_cast<std::size_t>(n_images) * static_cast<std::size_t>(dof),
214 req->forces);
215 if (req->variances != nullptr)
216 std::copy_n(scratch_variances.data(), n_images, req->variances);
217 if (req->epoch_out != nullptr)
218 *req->epoch_out = surface->surfaceEpoch();
219 return 0;
220 } catch (...) {
221 return -1;
222 }
223}
#define EON_RELAX_ABI_MAJOR
eon_relax_band_t eon_relax_surface_fn surface
bool energyVarianceAccepted(const double variance) noexcept

◆ gprRgsaddleSurface()

rgsaddle_status_t gpr::neb::gprRgsaddleSurface ( void * user,
rgsaddle_surface_request_t * req )

Definition at line 348 of file RgsaddleClient.cpp.

350{
351 if (user == nullptr || req == nullptr || req->positions == nullptr ||
352 req->energies == nullptr || req->gradients == nullptr ||
353 req->n_images <= 0 || req->n_atoms <= 0) {
354 return RGSADDLE_NULL_SESSION;
355 }
356 if (req->version.major != RGSADDLE_ABI_MAJOR) return RGSADDLE_NULL_SESSION;
357 auto* ctx = static_cast<GprRgsaddleUser*>(user);
358 if (ctx->gp == nullptr) return RGSADDLE_NULL_SESSION;
359 const long n_images = static_cast<long>(req->n_images);
360 const long n_atoms = static_cast<long>(req->n_atoms);
361 const long dof = 3 * n_atoms;
362 for (long im = 0; im < n_images; ++im) {
363 const double* p = req->positions + im * dof;
364 Observation probe;
365 probe.R.resize(1, dof);
366 for (long k = 0; k < dof; ++k)
367 probe.R(0, k) = p[k];
368 ctx->gp->calculatePotentialDispatched(probe);
369 if (probe.E.size() < 1 || probe.G.cols() < dof)
370 return RGSADDLE_NULL_SESSION;
371 req->energies[im] = probe.E(0, 0);
372 double* g = req->gradients + im * dof;
373 for (long k = 0; k < dof; ++k)
374 g[k] = probe.G(0, k);
375 }
376 return RGSADDLE_OK;
377}
Observation data: energy, gradient and positions.

◆ indexFromCartesianColumns()

VibrationalIndexMeasurement gpr::neb::indexFromCartesianColumns ( const Eigen::MatrixXd & columns,
const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
double move,
const Eigen::VectorXd * center_gradient = nullptr,
const Eigen::VectorXi * frozen = nullptr,
bool anchored = false,
const Eigen::MatrixXd * measured = nullptr )
inline

Classify a float64 Cartesian central-difference Hessian. Column j of columns is (g(x + h e_j) - g(x - h e_j)) / (2h). With no frozen atoms the spectrum is the mass-weighted vibrational complement from analyzeStencilIndex, and the resolution is that stencil's resolution. Frozen atoms fix the frame: the spectrum is the mass-weighted moving block, and rigid motion is not removed again. frozen is one flag per atom, nonzero when that atom is frozen. measured names the stencil directions when the other columns were rebuilt (gpr::optim::analyzeStencilIndex).

Definition at line 174 of file VibrationalIndexGate.h.

180{
182 const Eigen::Index dof = positions.size();
183 if (dof == 0 || dof % 3 != 0 || columns.rows() != dof ||
184 columns.cols() != dof || masses.size() * 3 != dof ||
185 !columns.allFinite() || !positions.allFinite() || !masses.allFinite() ||
186 (masses.array() <= 0.0).any()) {
187 out.reason = "invalid Hessian";
188 return out;
189 }
190 std::vector<Eigen::Index> moving;
191 moving.reserve(static_cast<std::size_t>(dof));
192 bool any_frozen = anchored;
193 if (anchored) {
194 for (Eigen::Index j = 0; j < dof; ++j)
195 moving.push_back(j);
196 }
197 if (frozen != nullptr && !anchored) {
198 if (frozen->size() != masses.size()) {
199 out.reason = "frozen flags do not match the atoms";
200 return out;
201 }
202 for (Eigen::Index atom = 0; atom < masses.size(); ++atom) {
203 if ((*frozen)(atom) != 0) {
204 any_frozen = true;
205 continue;
206 }
207 for (int axis = 0; axis < 3; ++axis)
208 moving.push_back(3 * atom + axis);
209 }
210 }
211 if (!any_frozen) {
212 if (gpr::optim::vibrationalComplement(positions, masses).cols() == 0) {
213 out.reason = "no vibrational coordinates";
214 return out;
215 }
216 const auto index = gpr::optim::analyzeStencilIndex(columns, positions,
217 masses, measured);
218 if (!index.valid) {
219 out.reason = "stencil index is not valid";
220 return out;
221 }
222 Eigen::VectorXd root(dof);
223 for (Eigen::Index k = 0; k < dof; ++k)
224 root(k) = std::sqrt(masses(k / 3));
225 Eigen::MatrixXd cartesian = index.modes;
226 for (Eigen::Index j = 0; j < cartesian.cols(); ++j)
227 cartesian.col(j) = index.modes.col(j).cwiseQuotient(root);
228 return detail::measurementFromSpectrum(
229 classifyVibrationalIndex(index.curvatures, index.resolution),
230 index.curvatures, index.resolution, cartesian, move,
231 center_gradient);
232 }
233 if (moving.empty()) {
234 out.reason = "no moving coordinates";
235 return out;
236 }
237 const Eigen::Index n = static_cast<Eigen::Index>(moving.size());
238 Eigen::MatrixXd block(n, n);
239 Eigen::VectorXd inv_root(n);
240 for (Eigen::Index a = 0; a < n; ++a) {
241 inv_root(a) =
242 1.0 / std::sqrt(masses(moving[static_cast<std::size_t>(a)] / 3));
243 for (Eigen::Index b = 0; b < n; ++b)
244 block(a, b) = columns(moving[static_cast<std::size_t>(a)],
245 moving[static_cast<std::size_t>(b)]);
246 }
247 const Eigen::MatrixXd weight = inv_root * inv_root.transpose();
248 const Eigen::MatrixXd antisym =
249 (0.5 * (block - block.transpose())).cwiseProduct(weight);
250 const Eigen::MatrixXd sym =
251 (0.5 * (block + block.transpose())).cwiseProduct(weight);
252 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(sym);
253 if (spectrum.info() != Eigen::Success) {
254 out.reason = "moving-block eigensolver failed";
255 return out;
256 }
257 const double antisymmetry =
258 antisym.size() == 0
259 ? 0.0
260 : Eigen::JacobiSVD<Eigen::MatrixXd>(antisym).singularValues()(0);
261 const double scale = spectrum.eigenvalues().cwiseAbs().maxCoeff();
262 const double resolution =
263 detail::stencilResolutionFloor(antisymmetry, scale, n);
264 Eigen::MatrixXd cartesian = Eigen::MatrixXd::Zero(dof, n);
265 for (Eigen::Index j = 0; j < n; ++j) {
266 for (Eigen::Index a = 0; a < n; ++a) {
267 const Eigen::Index coord = moving[static_cast<std::size_t>(a)];
268 cartesian(coord, j) = spectrum.eigenvectors()(a, j) * inv_root(a);
269 }
270 }
271 return detail::measurementFromSpectrum(
272 classifyVibrationalIndex(spectrum.eigenvalues(), resolution),
273 spectrum.eigenvalues(), resolution, cartesian, move, center_gradient);
274}
VibrationalIndexClass classifyVibrationalIndex(const Eigen::VectorXd &curvatures, double resolution)
StencilIndex analyzeStencilIndex(const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, const Eigen::MatrixXd *measured=nullptr)

◆ indexGateNoiseFloor()

double gpr::neb::indexGateNoiseFloor ( )
inlineconstexprnoexcept

Noise variance a noise-free fit is credited with in that comparison.

Definition at line 380 of file VibrationalIndexGate.h.

381{
382 return 1e-12;
383}

◆ indexGateVarianceThreshold()

double gpr::neb::indexGateVarianceThreshold ( double noise_variance)
inlinenodiscardnoexcept

Posterior energy variance above which decideVibrationalIndex measures the true stencil: an order of magnitude over the fitted noise.

Definition at line 387 of file VibrationalIndexGate.h.

389{
390 return indexGateVarianceToNoise() *
391 std::max(noise_variance, indexGateNoiseFloor());
392}
constexpr double indexGateVarianceToNoise() noexcept
constexpr double indexGateNoiseFloor() noexcept
Noise variance a noise-free fit is credited with in that comparison.

◆ indexGateVarianceToNoise()

double gpr::neb::indexGateVarianceToNoise ( )
inlineconstexprnoexcept

Ratio of posterior energy variance to fitted noise variance above which the surrogate index of a climbing image is not trusted.

Definition at line 374 of file VibrationalIndexGate.h.

375{
376 return 10.0;
377}

◆ makeLazyPotentialBatchOracle()

NEBBatchOracle gpr::neb::makeLazyPotentialBatchOracle ( std::shared_ptr< detail::LazyPotentialOracleState > state)
inline

Whole-batch companion to ~makeLazyPotentialOracle~ over the same state: one potential call per batch when the wrapped source has a batch surface (a UMA band package runs one graph call per chunk), a per-point walk through the same wrapper otherwise.

Definition at line 237 of file LazyPotentialOracle.h.

239{
240 if (!state) {
241 throw std::invalid_argument(
242 "lazy potential batch oracle requires the single oracle's state");
243 }
244 return
245 [state = std::move(state)](const std::vector<Eigen::VectorXd>& points)
246 -> std::vector<std::pair<double, Eigen::VectorXd>> {
247 return state->evaluate(points);
248 };
249}

◆ makeLazyPotentialOracle()

NEBOracle gpr::neb::makeLazyPotentialOracle ( std::function< pot::PotentialWrapper()> potential_factory,
std::vector< int > atomic_numbers,
std::array< double, 9 > box,
int & oracle_call_counter,
double * oracle_seconds = nullptr,
double * oracle_energy_noise_rms = nullptr,
const bool * oracle_variance_updates_enabled = nullptr,
double * oracle_force_noise_rms = nullptr,
std::shared_ptr< detail::LazyPotentialOracleState > * state_out = nullptr,
std::shared_ptr< const gpr::WallClockLimit > wall_clock_limit = nullptr )
inline

The single-point oracle of a run. The potential is built on the first call; state_out receives the shared state so that the whole-batch oracle of the same run (makeLazyPotentialBatchOracle) measures through the same instance and the same accounting.

Definition at line 211 of file LazyPotentialOracle.h.

220{
221 auto state = std::make_shared<detail::LazyPotentialOracleState>(
222 std::move(potential_factory), std::move(atomic_numbers), box,
223 oracle_call_counter, oracle_seconds, oracle_energy_noise_rms,
224 oracle_variance_updates_enabled, oracle_force_noise_rms,
225 std::move(wall_clock_limit));
226 if (state_out) *state_out = state;
227 return [state](const Eigen::VectorXd& positions)
228 -> std::pair<double, Eigen::VectorXd> {
229 return state->evaluate({positions}).front();
230 };
231}

◆ makePotentialWrapperFromOracle()

pot::PotentialWrapper gpr::neb::makePotentialWrapperFromOracle ( NEBOracle oracle)
inline

Build a ~pot::PotentialWrapper~ that calls through to a ~NEBOracle~ lambda. Drop the atomicNrs / box / variance arguments (the NEB oracle's backing potential already owns those).

Definition at line 37 of file NEBOraclePotential.h.

38{
40 [oracle = std::move(oracle)](
41 long N, const double* R, const int* /*atomicNrs*/, double* F,
42 double* U, double* variance, const double* /*box*/) mutable {
43 Eigen::VectorXd positions(3 * N);
44 for (long i = 0; i < 3 * N; ++i)
45 positions(i) = R[i];
46
47 auto [energy, gradient] = oracle(positions);
48
49 if (U) *U = energy;
50 // Force = -gradient. Dimer reads from F.
51 for (long i = 0; i < 3 * N; ++i)
52 F[i] = -gradient(i);
53 // The dimer's variance arm is left unfilled (the NEB oracle
54 // is the true PES, no surrogate variance to report).
55 if (variance) *variance = 0.0;
56 };
57 return pot::PotentialWrapper(std::move(fn));
58}
Type-erased wrapper around any potential that provides a force() interface.
std::function< void( long N, const double *R, const int *atomicNrs, double *F, double *U, double *energy_noise_rms, const double *box)> ForceFn

◆ measureVibrationalIndex()

template<typename Force>
VibrationalIndexMeasurement gpr::neb::measureVibrationalIndex ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
double step,
double move,
const Force & force,
const Eigen::VectorXd * center_gradient = nullptr,
const Eigen::VectorXi * frozen = nullptr,
gpr::optim::VibrationalStencil stencil = gpr::optim::VibrationalStencil::Full,
bool periodic = false )

Float64 central differences of force at positions. force maps a Cartesian geometry to its Cartesian gradient. Two evaluations per stencil direction, and one at the center when the directions are not the coordinate axes and center_gradient is not supplied: the removed rigid columns are rebuilt about it. Full measures all 3 coordinates for N=1, and measureVibrationalIndex(frozen, Full) probes all 3N. Vibrational uses gpr::optim::vibrationalStencilDirections: frozen atoms, when flagged, are not displaced. periodic keeps the rotations, which are not symmetries of a cell: a free molecule measures 3N-6 directions (3N-5 when linear) and a periodic cell measures 3N-3.

Definition at line 287 of file VibrationalIndexGate.h.

294{
296 const Eigen::Index dof = positions.size();
297 if (dof == 0 || dof % 3 != 0 || masses.size() * 3 != dof || !(step > 0.0) ||
298 !std::isfinite(step) || !positions.allFinite() || !masses.allFinite() ||
299 (masses.array() <= 0.0).any()) {
300 out.reason = "invalid geometry";
301 return out;
302 }
303 if (frozen != nullptr && frozen->size() != masses.size()) {
304 out.reason = "frozen flags do not match the atoms";
305 return out;
306 }
307 const Eigen::MatrixXd directions = gpr::optim::stencilDirectionsForMode(
308 stencil, positions, masses, periodic, /*anchored=*/false, frozen);
309 if (directions.cols() == 0) {
310 out.reason = "no vibrational coordinates";
311 return out;
312 }
313 const Eigen::MatrixXd points =
314 gpr::optim::centralDifferencePoints(positions, step, directions);
315 Eigen::MatrixXd actions(dof, directions.cols());
316 for (Eigen::Index k = 0; k < directions.cols(); ++k) {
317 const Eigen::VectorXd g_plus =
318 force(Eigen::VectorXd(points.col(2 * k)));
319 const Eigen::VectorXd g_minus =
320 force(Eigen::VectorXd(points.col(2 * k + 1)));
321 out.force_calls += 2;
322 if (g_plus.size() != dof || g_minus.size() != dof ||
323 !g_plus.allFinite() || !g_minus.allFinite()) {
324 out.reason = "force evaluation failed";
325 out.measured = false;
326 return out;
327 }
328 actions.col(k) = (g_plus - g_minus) / (2.0 * step);
329 }
330 Eigen::VectorXd center;
331 if (directions.cols() < dof &&
333 if (center_gradient != nullptr && center_gradient->size() == dof &&
334 center_gradient->allFinite()) {
335 center = *center_gradient;
336 } else {
337 center = force(positions);
338 out.force_calls += 1;
339 }
340 }
341 const Eigen::MatrixXd columns = gpr::optim::hessianColumnsFromDirections(
342 positions, center, directions, actions);
343 if (columns.rows() != dof) {
344 out.reason = "Hessian columns cannot be formed";
345 return out;
346 }
347 auto measured =
348 indexFromCartesianColumns(columns, positions, masses, move,
349 center_gradient, frozen, false, &directions);
350 measured.force_calls = out.force_calls;
351 return measured;
352}
Eigen::MatrixXd hessianColumnsFromDirections(const Eigen::VectorXd &center, const Eigen::VectorXd &center_gradient, const Eigen::MatrixXd &directions, const Eigen::MatrixXd &actions)
bool directionsAreCoordinateAxes(const Eigen::MatrixXd &directions)
Eigen::MatrixXd stencilDirectionsForMode(VibrationalStencil mode, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, bool periodic, bool anchored, const Eigen::VectorXi *frozen=nullptr)
Eigen::MatrixXd centralDifferencePoints(const Eigen::VectorXd &center, double step, const Eigen::MatrixXd &directions)

◆ noteLowestCertifiedClimb()

void gpr::neb::noteLowestCertifiedClimb ( BandForceStall & stall,
const NEBPath & path,
int image )
inline

Remember image when it is the highest on the band and lower than the climb already kept. The whole band is stored so a later restore climbs that image in the geometry that certified it.

Definition at line 50 of file BandStall.h.

52{
53 if (image <= 0 || image >= path.numImages() - 1) return;
54 const Image& img = path.image(image);
55 const Image& prev = path.image(image - 1);
56 const Image& next = path.image(image + 1);
57 if (!img.evaluated || !prev.evaluated || !next.evaluated) return;
58 if (!std::isfinite(img.energy) || !std::isfinite(prev.energy) ||
59 !std::isfinite(next.energy))
60 return;
61 // A certified climb is a measured local maximum, not a placeholder zero
62 // left on an image the oracle has not touched.
63 if (!(img.energy > prev.energy && img.energy > next.energy)) return;
64 if (stall.have && !(img.energy < stall.energy)) return;
65 stall.have = true;
66 stall.image = image;
67 stall.energy = img.energy;
68 stall.band.clear();
69 stall.band.reserve(static_cast<std::size_t>(path.numImages()));
70 for (int i = 0; i < path.numImages(); ++i)
71 stall.band.push_back(path.image(i));
72}
std::vector< Image > band
Definition BandStall.h:30

◆ observeMaxBandForce()

BandStallAction gpr::neb::observeMaxBandForce ( BandForceStall & stall,
double max_force,
double force_tolerance,
int window )
inline

max_force is the max NEB force on the band. Progress is a drop of one force tolerance. A quiet window with a certified climb restores it once; a second quiet window stops on that climb instead of wandering. Stop leaves the certified climb in place. When that climb's force is still above the tolerance the band driver sets the session stagnation handoff so the dimer, not another capped band step, continues it.

Definition at line 80 of file BandStall.h.

83{
84 if (!(force_tolerance > 0.0) || window < 1 || !std::isfinite(max_force)) {
86 }
87 if (max_force < stall.best_force - force_tolerance) {
88 stall.best_force = max_force;
89 stall.quiet = 0;
91 }
92 if (++stall.quiet < window || !stall.have) return BandStallAction::Continue;
93 stall.quiet = 0;
94 if (stall.restores >= 1) return BandStallAction::Stop;
95 ++stall.restores;
97}

◆ ocinebReportsConverged()

bool gpr::neb::ocinebReportsConverged ( const OCINEBResult & result)
inline

Whether a finished OCINEB attempt may be called converged. A refuted index certificate is not a saddle, and neither is a vibrational-index refusal. The band or dimer flag alone does not settle the run.

Definition at line 1382 of file OCINEBController.h.

1383{
1384 const bool converged =
1385 result.dimer_ran ? result.dimer_converged : result.neb_result.converged;
1386 return converged && !ciIndexCertificateRefuted(result) &&
1387 !result.neb_result.index_refused;
1388}
bool ciIndexCertificateRefuted(const OCINEBResult &result)

◆ oracleContextRequestsAdaptiveSo3()

bool gpr::neb::oracleContextRequestsAdaptiveSo3 ( const NEBOracleEvaluationContext & context)
nodiscard

Definition at line 333 of file GPNEB.cpp.

◆ oracleStencilDestination()

std::string gpr::neb::oracleStencilDestination ( const std::string & requested,
const std::string & anchor )
inline

Explicit –oracle-stencil path, or oracle-stencil.json beside the run's output (the HDF5 path for a band, the geometry for a dimer). The parent directory is created by the writer, so a search persists the stencil without a directory prepared ahead of time.

Definition at line 189 of file OracleStencil.h.

191{
192 if (!requested.empty()) return requested;
193 std::filesystem::path directory = ".";
194 if (!anchor.empty()) {
195 const std::filesystem::path file(anchor);
196 if (file.has_parent_path() && !file.parent_path().empty())
197 directory = file.parent_path();
198 }
199 return (directory / "oracle-stencil.json").string();
200}

◆ oracleStencilDirections()

Eigen::MatrixXd gpr::neb::oracleStencilDirections ( const Eigen::VectorXd & positions,
const gpr::AtomsConfiguration * atoms,
gpr::optim::VibrationalStencil stencil = gpr::optim::VibrationalStencil::Full )
nodiscard

Directions of a true-oracle Hessian stencil of a band geometry in the frame of atoms (masses, frozen atoms, cell), the same frame decideVibrationalIndex and certifyForceStoppedNeb measure in. Null atoms is a free molecule with unit masses. Full is every coordinate.

Definition at line 132 of file VibrationalIndexGate.cpp.

135{
136 const Frame frame = frameFor(positions, atoms);
137 if (!frame.usable)
138 throw std::invalid_argument("invalid geometry for an oracle stencil");
139 return stencilDirections(frame, positions, stencil);
140}

◆ parseCompositionTrace()

bool gpr::neb::parseCompositionTrace ( const std::string & text,
std::vector< OuterIterCompositionTraceRecord > & out,
std::string * error )
nodiscard

Definition at line 198 of file OuterIterCompositionTrace.cpp.

201{
202 out.clear();
203 std::istringstream is(text);
204 // Skip comment lines.
205 std::string line;
206 std::string body;
207 while (std::getline(is, line)) {
208 std::size_t i = 0;
209 while (i < line.size() &&
210 std::isspace(static_cast<unsigned char>(line[i])))
211 ++i;
212 if (i < line.size() && line[i] == '#') continue;
213 body += line;
214 body += '\n';
215 }
216 std::istringstream bs(body);
217 int version = 0;
218 int n_records = 0;
219 if (!readInt(bs, "version", version, error)) return false;
220 if (version != kCompositionTraceFormatVersion) {
221 if (error)
222 *error = "unsupported composition trace version " +
223 std::to_string(version);
224 return false;
225 }
226 if (!readInt(bs, "n_records", n_records, error)) return false;
227 if (n_records < 0 || n_records > 1'000'000) {
228 if (error) *error = "n_records out of range";
229 return false;
230 }
231 out.reserve(static_cast<std::size_t>(n_records));
232 for (int i = 0; i < n_records; ++i) {
234 if (!readRecord(bs, rec, error)) return false;
235 out.push_back(std::move(rec));
236 }
237 return true;
238}

◆ periodicBandConfig()

GPNEBConfig gpr::neb::periodicBandConfig ( )
inline

GPNEBConfig of a periodic local band before the geometry is attached.

Definition at line 41 of file PeriodicBand.h.

42{
43 GPNEBConfig cfg;
48 cfg.climbing_image = true;
51 cfg.use_idpp = false;
52 cfg.use_sidpp = false;
54 cfg.verbose = false;
55 cfg.force_stop_certificate = false;
56 return cfg;
57}
constexpr int kPeriodicBandSteps
Outer-iteration budget of GPLocalBand.run.
constexpr double kPeriodicBandMaxMove
constexpr double kPeriodicBandFmax
Force tolerance of GPLocalBand.run, eV/Angstrom.

◆ perpendicularSigma()

double gpr::neb::perpendicularSigma ( const Eigen::VectorXd & gradient_variance,
const Eigen::VectorXd & tangent )

Compute perpendicular GP variance (variance orthogonal to path tangent).

sigma_perp = sqrt(sum_d sigma_d^2 * (1 - tau_d^2))

Parameters
gradient_variancePer-component gradient variance
tangentUnit tangent vector
Returns
Perpendicular standard deviation

Definition at line 41 of file AcquisitionStrategy.cpp.

43{
44 // sigma_perp = sqrt(sum_d sigma_d^2 * (1 - tau_d^2))
45 double sum = 0.0;
46 for (Eigen::Index d = 0; d < gradient_variance.size(); ++d) {
47 double tau_d = (d < tangent.size()) ? tangent(d) : 0.0;
48 const double perpendicular_weight = std::max(0.0, 1.0 - tau_d * tau_d);
49 sum += nonNegativeFinite(gradient_variance(d)) * perpendicular_weight;
50 }
51 return std::sqrt(std::max(0.0, sum));
52}

◆ polishSaddleOnSurrogate()

SaddlePolishResult gpr::neb::polishSaddleOnSurrogate ( const NEBOracle & oracle,
ActiveLearningSession & session,
const Eigen::VectorXd & x0,
double e0,
const Eigen::VectorXd & g0,
double force_tol,
int max_steps,
double max_move,
double hessian_fd_step )
nodiscard

Newton polish driven by measured gradients and the surrogate Hessian. Each step solves d = -H^+ g on the allowed coordinate subspace, keeping fixed atoms immobile and removing only rigid motions that are symmetries of the system. Cartesian components are capped at max_move. Acceptance and convergence use the maximum per-atom norm of the true gradient projected into the allowed step space. A rejected trial is halved once; every measured row joins the session. The result retains component infinity norms as additional diagnostics. Termination occurs at force_tol, a failed halving, or max_steps accepted steps. The returned gradient is measured at the returned positions.

Definition at line 896 of file SaddlePolish.cpp.

900{
902 out.positions = x0;
903 out.energy = e0;
904 out.gradient = g0;
905 if (x0.size() == 0 || g0.size() != x0.size() || !g0.allFinite() ||
906 !(force_tol > 0.0) || !(hessian_fd_step > 0.0)) {
907 return out;
908 }
909 out.initial_force_inf = g0.lpNorm<Eigen::Infinity>();
910 out.final_force_inf = out.initial_force_inf;
911 out.initial_max_atom_force =
912 detail::saddlePolishForceMagnitude(x0, g0, session.atoms_config);
913 out.final_max_atom_force = out.initial_max_atom_force;
914 out.converged = out.final_max_atom_force <= force_tol;
915 if (out.converged) return out;
916
917 Eigen::VectorXd x = x0, g = g0;
918 double e = e0;
919 for (int step = 0; step < max_steps; ++step) {
920 const Eigen::MatrixXd H = surrogateHessian(session, x);
921 if (H.size() == 0 || !H.allFinite()) break;
922 double correction = 0.0;
923 Eigen::VectorXd d =
924 newtonSaddleStep(H, g, x, session.atoms_config, &correction);
925 out.quadratic_correction = correction;
926 const double dmax = d.lpNorm<Eigen::Infinity>();
927 if (!(dmax > 0.0) || !std::isfinite(dmax)) break;
928 if (max_move > 0.0 && dmax > max_move) d *= max_move / dmax;
929
930 bool accepted = false;
931 const double f_before =
932 detail::saddlePolishForceMagnitude(x, g, session.atoms_config);
933 for (int halving = 0; halving < 2 && !accepted; ++halving) {
934 const Eigen::VectorXd x_try = x + d;
935 const auto [e_try, g_try] =
936 detail::evaluateOieOraclePosition(x_try, oracle);
937 ++out.oracle_calls;
938 if (g_try.size() == x.size() && g_try.allFinite()) {
939 session.appendObservation(x_try, e_try, g_try);
940 (void)session.refitGPIfTrainingChanged(false);
941 if (detail::saddlePolishForceMagnitude(
942 x_try, g_try, session.atoms_config) < f_before) {
943 x = x_try;
944 e = e_try;
945 g = g_try;
946 accepted = true;
947 }
948 }
949 if (!accepted) d *= 0.5;
950 }
951 if (!accepted) break;
952 ++out.steps;
953 out.positions = x;
954 out.energy = e;
955 out.gradient = g;
956 out.final_force_inf = g.lpNorm<Eigen::Infinity>();
957 out.final_max_atom_force =
958 detail::saddlePolishForceMagnitude(x, g, session.atoms_config);
959 if (out.final_max_atom_force <= force_tol) {
960 out.converged = true;
961 break;
962 }
963 }
964 // Report the correction the remaining force still hides at the final
965 // point, from the surrogate curvature there.
966 if (out.steps > 0 || out.oracle_calls > 0) {
967 const Eigen::MatrixXd H = surrogateHessian(session, out.positions);
968 if (H.size() > 0 && H.allFinite()) {
969 double correction = 0.0;
970 (void)newtonSaddleStep(H, out.gradient, out.positions,
971 session.atoms_config, &correction);
972 out.quadratic_correction = correction;
973 }
974 }
975 return out;
976}

◆ readCompositionTraceFile()

bool gpr::neb::readCompositionTraceFile ( const std::string & path,
std::vector< OuterIterCompositionTraceRecord > & out,
std::string * error )
nodiscard

Definition at line 250 of file OuterIterCompositionTrace.cpp.

253{
254 std::ifstream ifs(path, std::ios::binary);
255 if (!ifs) {
256 if (error) *error = "cannot open " + path;
257 return false;
258 }
259 std::ostringstream ss;
260 ss << ifs.rdbuf();
261 return parseCompositionTrace(ss.str(), out, error);
262}
bool parseCompositionTrace(const std::string &text, std::vector< OuterIterCompositionTraceRecord > &out, std::string *error)

◆ readForceStopHandoff()

std::optional< ForceStopHandoffStencil > gpr::neb::readForceStopHandoff ( const std::string & archive_dir,
const Eigen::VectorXd & center )
nodiscard

Definition at line 385 of file VibrationalIndexGate.cpp.

387{
388 if (archive_dir.empty() || center.size() == 0) return std::nullopt;
389 std::ifstream in(archive_dir + "/force-stop-handoff.bin", std::ios::binary);
390 if (!in) return std::nullopt;
391 int magic = 0, dof = 0, npts = 0, flags = 0, nenergy = 0, nmodes = 0;
392 double step = 0.0;
393 in.read(reinterpret_cast<char*>(&magic), sizeof magic);
394 in.read(reinterpret_cast<char*>(&dof), sizeof dof);
395 in.read(reinterpret_cast<char*>(&npts), sizeof npts);
396 const bool version2 = magic == 0x46534832;
397 if (version2) in.read(reinterpret_cast<char*>(&nmodes), sizeof nmodes);
398 in.read(reinterpret_cast<char*>(&step), sizeof step);
399 in.read(reinterpret_cast<char*>(&flags), sizeof flags);
400 if (!in || (magic != 0x46534831 && magic != 0x46534832) || dof < 0 ||
401 npts < 0 || nmodes < 0)
402 return std::nullopt;
404 stencil.step = step;
405 stencil.higher_order = (flags & 1) != 0;
406 stencil.inconclusive = (flags & 2) != 0;
407 stencil.deferred = version2 && (flags & 4) != 0;
408 if (stencil.deferred && npts == 0) return stencil;
409 if (dof != center.size() || npts <= 0 || dof <= 0) return std::nullopt;
410 stencil.positions.resize(dof, npts);
411 stencil.gradients.resize(npts, dof);
412 in.read(reinterpret_cast<char*>(stencil.positions.data()),
413 sizeof(double) * stencil.positions.size());
414 in.read(reinterpret_cast<char*>(stencil.gradients.data()),
415 sizeof(double) * stencil.gradients.size());
416 in.read(reinterpret_cast<char*>(&nenergy), sizeof nenergy);
417 if (nenergy > 0) {
418 stencil.energies.resize(static_cast<std::size_t>(nenergy));
419 in.read(reinterpret_cast<char*>(stencil.energies.data()),
420 sizeof(double) * static_cast<std::size_t>(nenergy));
421 }
422 if (version2 && nmodes > 0) {
423 stencil.lowest_modes.resize(dof, nmodes);
424 in.read(reinterpret_cast<char*>(stencil.lowest_modes.data()),
425 sizeof(double) * stencil.lowest_modes.size());
426 }
427 if (!in || stencil.positions.cols() < 1) return std::nullopt;
428 stencil.center = stencil.positions.col(0);
429 Eigen::MatrixXd held_center(stencil.center.size(), 1);
430 held_center.col(0) = stencil.center;
431 if (gpr::optim::forceStopHeldColumn(held_center, center) < 0)
432 return std::nullopt;
433 return stencil;
434}
Eigen::MatrixXd lowest_modes
Lowest Cartesian modes, lowest curvature first.

◆ reduceOracleProviderCalls()

int gpr::neb::reduceOracleProviderCalls ( int local_calls)

Aggregates completed OCINEB attempts while the provider counter remains authoritative for calls made by aborted oracle-surface sessions.

provider_calls must be the communicator-wide count. parallelEvaluate shards the PES (point i on rank i % nprocs), so a rank-local increment is a slice of the ledger and fails the invariant below.

Definition at line 5754 of file OCINEBController.cpp.

5755{
5756#ifdef GPR_HAVE_MPI
5757 int mpi_up = 0;
5758 MPI_Initialized(&mpi_up);
5759 if (mpi_up) {
5760 int nprocs = 1;
5761 MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
5762 if (nprocs > 1) {
5763 int global_calls = 0;
5764 MPI_Allreduce(&local_calls, &global_calls, 1, MPI_INT, MPI_SUM,
5765 MPI_COMM_WORLD);
5766 return global_calls;
5767 }
5768 }
5769#endif
5770 return local_calls;
5771}

◆ rejectUntrustedStep()

int gpr::neb::rejectUntrustedStep ( NEBPath & path,
const std::vector< Eigen::VectorXd > & accepted_positions,
const gpr::TrustRadius & trust,
double trust_threshold )

Reject a simultaneous inner-loop NEB step outside the GP trust set.

Returns
First offending image index, or -1 when all intermediate images remain within the trust threshold.

Definition at line 12 of file TrustGuard.cpp.

15{
16 if (static_cast<int>(accepted_positions.size()) != path.numImages()) {
17 throw std::invalid_argument(
18 "rejectUntrustedStep requires one accepted position per image");
19 }
20
21 int offending = -1;
22 for (int i = 1; i < path.numImages() - 1; ++i) {
23 const double d = trust.distanceToTraining(path.image(i).positions);
24 if (d > trust_threshold) {
25 offending = i;
26 break;
27 }
28 }
29
30 if (offending > 0) {
31 for (int i = 1; i < path.numImages() - 1; ++i) {
32 path.image(i).positions = accepted_positions[i];
33 }
34 }
35 return offending;
36}
double distanceToTraining(const Eigen::VectorXd &x_new) const
Minimum Euclidean distance from x_new to any training point.

◆ requireEndpointSymmetry()

EndpointSymmetry gpr::neb::requireEndpointSymmetry ( const std::vector< int > & permutation,
const Eigen::VectorXd & reactant,
const Eigen::VectorXd & product,
const std::vector< int > & atomic_numbers,
double radius )
inline

endpointSymmetryFromPermutation, refused unless the operation carries each endpoint to within radius of the other: only then do the mirrored rows of one basin sit inside the trust region of the other's images.

Definition at line 179 of file EndpointSymmetry.h.

183{
185 permutation, reactant, product, atomic_numbers);
186 if (!(symmetry.forward_residual <= radius) ||
187 !(symmetry.reverse_residual <= radius)) {
188 std::ostringstream message;
189 message << "endpoint symmetry: the operation maps the reactant "
190 << symmetry.forward_residual << " A and the product "
191 << symmetry.reverse_residual
192 << " A from the other endpoint, beyond the trust radius "
193 << radius << " A";
194 throw std::invalid_argument(message.str());
195 }
196 return symmetry;
197}
EndpointSymmetry endpointSymmetryFromPermutation(const std::vector< int > &permutation, const Eigen::VectorXd &reactant, const Eigen::VectorXd &product, const std::vector< int > &atomic_numbers)
double reverse_residual
Labelled displacement between the mapped product and the reactant.
double forward_residual
Labelled displacement between the mapped reactant and the product.

◆ resetForceStopStencilCache()

void gpr::neb::resetForceStopStencilCache ( )

Drop the in-process stencil cache. Tests use this so a previous geometry cannot satisfy a later count.

Definition at line 332 of file VibrationalIndexGate.cpp.

333{
334 stencil_cache.clear();
335}

◆ restoreCertifiedClimb()

void gpr::neb::restoreCertifiedClimb ( NEBPath & path,
const BandForceStall & stall )
inline

Put the certified climb back and make it the climbing image.

Definition at line 100 of file BandStall.h.

101{
102 if (!stall.have) return;
103 const int n =
104 std::min(path.numImages(), static_cast<int>(stall.band.size()));
105 for (int i = 0; i < n; ++i)
106 path.image(i) = stall.band[static_cast<std::size_t>(i)];
107 path.computeNEBForces();
108 path.enableClimbingImage();
109}
void enableClimbingImage()
Enable climbing image on the highest-energy intermediate image.
Definition NEBPath.cpp:1121
void computeNEBForces()
Compute NEB forces for all intermediate images.
Definition NEBPath.cpp:880

◆ runIndexEscapeGpDimer()

IndexEscapeResult gpr::neb::runIndexEscapeGpDimer ( const OCINEBConfig & oci_config,
const GPNEBConfig & neb_config,
ActiveLearningSession & session,
NEBOracle & oracle,
const Eigen::VectorXd & x_seed,
double e_seed,
const Eigen::VectorXd & g_seed,
const Eigen::VectorXd & mode_seed,
double energy_ceiling )

Run the standalone GP dimer from the measured seed ~x_seed~, ~e_seed~, ~g_seed~ in the shared session, oriented along ~mode_seed~. A finite ~energy_ceiling~ requests a downhill recovery from a verified higher-index point. A minimum escape uses infinity to allow an uphill search. The dimer checks measured forces and rotation before stopping; its caller certifies the complete Hessian index. A measured interatomic distance below ratio_at_limit times the seed's minimum aborts the search.

Definition at line 4947 of file OCINEBController.cpp.

4952{
4954 if (x_seed.size() == 0 || g_seed.size() != x_seed.size() ||
4955 mode_seed.size() != x_seed.size() || !std::isfinite(e_seed))
4956 return out;
4957 // The seed row was appended by the caller; the surrogate (and its
4958 // HS-SVD basis) must cover it before the dimer reads curvature there.
4959 (void)session.refitGPIfTrainingChanged(/*reinit_seeds=*/false);
4961 auto restore_model = model.scopedParameterRestore();
4962 {
4963 // The surrogate at its own newest row: a residual above the
4964 // tolerance here means the search cannot converge on this model
4965 // (it reports convergence where the oracle disagrees).
4966 gpr::Observation probe;
4967 probe.R = flatToCoord1xD(x_seed);
4968 model.gp().calculatePotentialDispatched(probe);
4969 double resid = std::numeric_limits<double>::quiet_NaN();
4970 double e_gp = std::numeric_limits<double>::quiet_NaN();
4971 if (probe.G.rows() > 0 && probe.G.cols() == x_seed.size()) {
4972 Eigen::VectorXd g_gp(x_seed.size());
4973 for (Eigen::Index j = 0; j < x_seed.size(); ++j)
4974 g_gp(j) = probe.G(0, j);
4975 resid = (g_gp - g_seed).norm();
4976 }
4977 if (probe.E.size() > 0) e_gp = probe.E(0, 0);
4978 // The dimer predicts the midpoint and image 1 in one two-row batch;
4979 // compare that batch's row 0 with the single-row prediction.
4980 double batch_resid = std::numeric_limits<double>::quiet_NaN();
4981 {
4982 gpr::Observation batch;
4983 batch.R.resize(2, x_seed.size());
4984 batch.R.row(0) = x_seed.transpose();
4985 Eigen::VectorXd shifted = x_seed;
4986 Eigen::VectorXd dir = mode_seed;
4987 if (dir.norm() > 0.0) shifted += 0.01 * dir.normalized();
4988 batch.R.row(1) = shifted.transpose();
4989 model.gp().calculatePotentialDispatched(batch);
4990 if (batch.G.rows() > 1 && batch.G.cols() == x_seed.size()) {
4991 Eigen::VectorXd g0(x_seed.size());
4992 for (Eigen::Index j = 0; j < x_seed.size(); ++j)
4993 g0(j) = batch.G(0, j);
4994 batch_resid = (g0 - g_seed).norm();
4995 }
4996 }
4997 gpr::Observation vprobe;
4998 vprobe.R = flatToCoord1xD(x_seed);
4999 vprobe.E.resize(1, 1);
5000 vprobe.G.resize(1, x_seed.size());
5001 model.gp().calculateVarianceDispatched(vprobe);
5002 std::cout << "[ocineb] index escape seed: rows="
5003 << model.observations().E.rows()
5004 << " gp_force_residual=" << resid
5005 << " batch_row0_force_residual=" << batch_resid
5006 << " gp_energy_error=" << (e_gp - e_seed)
5007 << " energy_variance="
5008 << (vprobe.E.size() > 0
5009 ? vprobe.E(0, 0)
5010 : std::numeric_limits<double>::quiet_NaN())
5011 << " sigma2=" << model.gp().getSigma2()
5012 << " true_force=" << saddleForceMagnitude(g_seed)
5013 << " ceiling=" << energy_ceiling << std::endl;
5014 }
5015
5016 gpr::Observation init_observations = model.observations();
5017 gpr::Observation middle_point;
5018 middle_point.R = flatToCoord1xD(x_seed);
5019 middle_point.E.resize(1, 1);
5020 middle_point.E(0, 0) = e_seed;
5021 middle_point.G = flatToCoord1xD(g_seed);
5022
5023 gpr::AtomsConfiguration tmp;
5024 const bool use_analytic_hssvd =
5025 detail::shouldUseHssvdAnalyticDimerCurvature(
5026 neb_config, model.gp().hasReusableHssvdPosterior());
5027 gpr::InputParameters parameters = detail::buildDimerParameters(
5028 neb_config, oci_config, tmp, use_analytic_hssvd);
5029 // The standalone search takes gprd's phase budget, not the burst's
5030 // condition-driven one: the burst stops on its path-leash contract,
5031 // the escape stops on true-force convergence.
5032 if (parameters.num_bigiter.value <= 0) {
5033 gpr::InputParameters canonical;
5034 gpr::CanonicalDimerDefaultOptions dd;
5036 parameters.num_bigiter.value = canonical.num_bigiter.value;
5037 }
5038
5039 atmd::AtomicDimer dimer;
5040 if (neb_config.training_policy != nullptr)
5041 dimer.setTrainingPolicy(neb_config.training_policy);
5043 // The band index certificate decides the saddle claim.
5044 dimer.setForceStopCertificateStep(0.0);
5045 dimer.attachExternalGP(&model.gp());
5046 dimer.setWallClockLimit(neb_config.wall_clock_limit);
5047 Eigen::VectorXd orient = mode_seed;
5048 if (orient.norm() > 0.0) orient.normalize();
5049 dimer.initialize(parameters, init_observations, middle_point,
5050 flatToCoord1xD(orient), session.atoms_config);
5051 dimer.setKappaDimer(oci_config.dimer_kappa_beta);
5052 dimer.setUseHssvdAnalyticCurvature(use_analytic_hssvd);
5056 dimer.setAlignmentAbortTol(0.0);
5057 dimer.setAbortOnDegenerateProbes(true);
5058 dimer.setMeasuredEnergyCeiling(energy_ceiling);
5061 {
5062 atmd::AtomicDimer::VarianceGateConfig vg =
5063 dimer.getVarianceGateConfig();
5064 vg.accept_tau = oci_config.dimer_variance_tau_abs;
5066 detail::resolveDimerVarianceTauRelative(neb_config, oci_config);
5069 std::max(1, oci_config.dimer_imspe_history_size);
5070 dimer.setVarianceGateConfig(vg);
5071 }
5072#ifdef USE_READCON_DB
5073 dimer.setObservationArchive(session.observationArchive());
5074#endif
5075 pot::PotentialWrapper potential = makePotentialWrapperFromOracle(oracle);
5076 detail::configureBurstDimerSecant(dimer, neb_config.secant_hessian);
5077 const gpr::optim::SecantCurvatureCounts replayed_secants =
5078 dimer.secantLedger();
5079 dimer.execute(potential);
5080 gpr::optim::SecantCurvatureCounts fresh_secants = dimer.secantLedger();
5081 fresh_secants.pairs_accepted -= replayed_secants.pairs_accepted;
5082 fresh_secants.pairs_rejected -= replayed_secants.pairs_rejected;
5083 fresh_secants.hvp_calls -= replayed_secants.hvp_calls;
5084 fresh_secants.consistency_rejections -=
5085 replayed_secants.consistency_rejections;
5086 session.addSecantCounts(fresh_secants);
5087
5088 out.oracle_calls = static_cast<int>(dimer.getTotalForceCalls());
5089 out.phases = static_cast<int>(dimer.getPhaseHistory().size());
5090 const gpr::FieldMatrixd e_zero = dimer.getEnergyZeroLevel();
5091 const double e0 = (e_zero.size() > 0) ? e_zero(0, 0) : 0.0;
5092 {
5093 gpr::Coord& dimer_R =
5095 gpr::FieldMatrixd& dimer_E =
5098 for (const auto& staged: detail::stageDimerObservationUpdates(
5099 init_observations, dimer_R, dimer_E, dimer_G, e0)) {
5100 session.appendObservation(staged.positions, staged.energy,
5101 staged.gradient,
5104 }
5105 }
5106 out.converged = dimer.getConverged();
5107 out.wall_clock_limit =
5110 out.force = dimer.getFinalForceNormForConvergence();
5111 out.curvature = dimer.getFinalCurvature();
5113 out.gradient = dimer.getFinalGradientAtMidPoint();
5114 out.energy = dimer.getFinalEnergy() + e0;
5115 restore_model.restore();
5116 return out;
5117}
void initialize(const gpr::InputParameters &parameters, const gpr::Observation &initial_data, const gpr::Observation &middle_point, const gpr::Coord &initial_orientation, const gpr::AtomsConfiguration &init_atom_config)
Initilalize with initial data.
void setVarianceGateConfig(const VarianceGateConfig &cfg) noexcept
void setWallClockLimit(std::shared_ptr< const gpr::WallClockLimit > limit)
Share an enclosing deadline (used by OCI-NEB and deterministic tests).
const VarianceGateConfig & getVarianceGateConfig() const noexcept
Eigen::VectorXd getFinalCoordOfMidPoint() const
Return final coordinates of the middle point.
gpr::optim::SecantCurvatureCounts secantLedger() const noexcept
Pair, probe and rejection counts, without the GP's quadratic-mean uses.
void setForceStopCertificateStep(double step) noexcept
gpr::Coord & getGradientForAllObservationPointsRef()
Return gradients for all observed points.
void setAlignmentAbortTol(double tol) noexcept
gpr::FieldMatrixd & getEnergyForAllObservationPointsRef()
Return energies for all observed points.
void setUseHssvdAnalyticCurvature(bool enabled) noexcept
Eigen::VectorXd getFinalGradientAtMidPoint() const
Return the final gradient dE/dR at the middle point.
void setPreserveInitialAlignmentReference(bool enabled) noexcept
void setKappaDimer(double beta)
void setHssvdModeSelectionPolicy(HssvdModeSelectionPolicy policy) noexcept
void setTrainingPolicy(const gpr::policy::TrainingPolicy *policy)
Not owned. The pointer must outlive execute(). Null is the engine.
gpr::FieldMatrixd getEnergyZeroLevel() const
Internal E_zero_level used by the dimer's cutOffEnergy bookkeeping. The energies returned by ~getEner...
gpr::Index_t getTotalForceCalls() const
Return the total number of force calls.
double getFinalForceNormForConvergence() const
Return final force in the configured convergence norm.
void attachExternalGP(gpr::GaussianProcessRegression *external_gp) noexcept
Attach an externally-owned GPR model. Must be called BEFORE ~initialize~. The dimer will use this GP ...
double getFinalEnergy() const
Return final energy.
void setMeasuredEnergyCeiling(double ceiling) noexcept
void setAbortOnDegenerateProbes(bool enabled) noexcept
void setRejectHigherIndexSurrogateConvergence(bool enabled) noexcept
See want_second_negative_mode_.
DimerRelaxationTerminationReason getRelaxationTerminationReason() const noexcept
void setProjectRigidModesForConvergence(bool enabled) noexcept
double getFinalCurvature() const
Return final curvature.
bool getConverged() const
Return true when the final force convergence criterion is met.
gpr::Coord & getMidPointCoordForAllObservationPointsRef()
Return gpr::Coordinates of all observed points.
const std::vector< DimerPhaseRecord > & getPhaseHistory() const noexcept
Return the per-phase dimer trajectory history.
void execute(pot::PotentialWrapper &general_potential)
This function uses the atomic GP-dimer method to converge to a saddle point, starting from somewhere ...
void setAbortOnInteratomicCollapse(bool enabled) noexcept
ScopedParameterRestore scopedParameterRestore() &
Definition Session.h:2775
gpr::GaussianProcessRegression & gp() const
Definition Session.h:2642
const gpr::Observation & observations() const
Definition Session.h:2647
pot::PotentialWrapper makePotentialWrapperFromOracle(NEBOracle oracle)
double saddleForceMagnitude(const Eigen::VectorXd &gradient)
Definition NEBPath.cpp:25
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
void applyCanonicalReadconDimerDefaults(InputParameters &parameters, const CanonicalDimerDefaultOptions &options)
Apply the canonical readcon dimer defaults to parameters.
KeyValuePair< int > num_bigiter
Definition Structures.h:532
void addSecantCounts(const optim::SecantCurvatureCounts &extra)
Definition Session.h:406
const policy::TrainingPolicy * training_policy
Definition GPNEB.h:1269
int dimer_imspe_history_size
EMD-filtered ring-buffer size for the dimer IMSPE soft-skip.
double dimer_kappa_beta
Xiao contour curvature restraint; zero disables, paper uses 5 Angstrom.

◆ runOCINEB()

OCINEBResult gpr::neb::runOCINEB ( NEBOracle oracle,
const Eigen::VectorXd & initial,
const Eigen::VectorXd & final_state,
int n_images,
const GPNEBConfig & neb_config,
const OCINEBConfig & oci_config,
ActiveLearningSession & session )

Entry point. Builds a stateful ~OCINEBController~, installs its run-method as the NEB's per-outer-iter hook, then calls ~gpNEB~ with the session. The hook fires after every NEB outer iter once CI is active, drives MMF bursts via the controller, and writes results back into the chain.

Definition at line 4673 of file OCINEBController.cpp.

4678{
4679 OCINEBResult result;
4680
4681 if (!detail::shouldInstallOciMmfHook(neb_config, oci_config_in)) {
4682 if (neb_config.training_policy != nullptr &&
4684 GPNEBConfig tagged = neb_config;
4686 result.neb_result =
4687 gpNEB(oracle, initial, final_state, n_images, tagged, &session);
4688 } else {
4689 result.neb_result = gpNEB(oracle, initial, final_state, n_images,
4690 neb_config, &session);
4691 }
4693 // No saddle is max_energy_image -1. Leave ci_final_position empty,
4694 // the same as a run that returned no path.
4695 if (result.neb_result.path) {
4696 const int image = result.neb_result.max_energy_image;
4697 if (image >= 0 && image < result.neb_result.path->numImages()) {
4698 result.ci_final_position =
4699 result.neb_result.path->image(image).positions;
4700 }
4701 }
4702 return result;
4703 }
4704
4705 // Wire force_tolerance to neb conv_tol if caller did not set
4706 // it. Mirrors eOn: force_tolerance is the NEB's convergence
4707 // criterion, NOT a separate MMF setting.
4708 OCINEBConfig oci_config = oci_config_in;
4709 oci_config.handoff_policy = detail::resolveMmfHandoffPolicy(
4710 oci_config.handoff_policy, neb_config.mode);
4711 // Unified convergence: the dimer-refined climbing image is accepted under
4712 // the SAME force criterion as the NEB band, so the OCI dimer always
4713 // inherits the NEB conv_tol rather than carrying a separate MMF tolerance.
4714 // (Avoids the two-criterion mismatch where the band converges at conv_tol
4715 // but the dimer chases a different threshold.)
4716 oci_config.force_tolerance = neb_config.conv_tol;
4717 auto caller_force_tolerance_provider =
4718 std::move(oci_config.effective_force_tolerance);
4719 oci_config.effective_force_tolerance =
4720 [&neb_config, caller_force_tolerance_provider =
4721 std::move(caller_force_tolerance_provider)]() {
4722 double tol = detail::effectiveModelNoiseTolerance(neb_config);
4723 if (caller_force_tolerance_provider) {
4724 const double caller_tol = caller_force_tolerance_provider();
4725 if (std::isfinite(caller_tol) && caller_tol > tol) {
4726 tol = caller_tol;
4727 }
4728 }
4729 return tol;
4730 };
4731
4732 auto controller = std::make_shared<OCINEBController>(oci_config);
4733 auto handoff_trap_state = std::make_shared<OciMmfHandoffTrapState>();
4734 int total_oracle_calls = 0;
4735 int bursts_fired = 0;
4736 int dimer_saddle_image_idx = -1;
4737
4738 GPNEBConfig neb_cfg_with_hook = neb_config;
4739 if (neb_cfg_with_hook.training_search_kind == policy::SearchKind::Neb)
4741 neb_cfg_with_hook.current_ci_oracle_priority =
4742 [controller, handoff_trap_state, kappa = neb_config.ucb_kappa](
4743 const NEBPath& path, int ci_image_idx, int outer_iter,
4744 double ci_force) {
4745 const bool ci_is_energy_max =
4746 path.highestEnergyImageIndex() == ci_image_idx;
4747 const bool wants_current_ci = controller->wantsCurrentCiOracle(
4748 ci_force, /*ci_active=*/true, static_cast<long>(ci_image_idx),
4749 static_cast<long>(path.numImages() - 2), outer_iter,
4750 detail::ciPosteriorConfident(path, ci_image_idx, kappa),
4751 /*trap_detected=*/false, /*ntrain_now=*/0, ci_is_energy_max);
4752 if (detail::shouldRefreshCurrentCiHandoffPrediction(
4753 handoff_trap_state->requested_current_ci,
4754 handoff_trap_state->ci_image_idx, wants_current_ci,
4755 ci_image_idx)) {
4756 handoff_trap_state->outer_iter = outer_iter;
4757 handoff_trap_state->ci_image_idx = ci_image_idx;
4758 handoff_trap_state->gp_force = ci_force;
4759 handoff_trap_state->threshold = controller->threshold();
4760 handoff_trap_state->requested_current_ci = wants_current_ci;
4761 }
4762 return wants_current_ci;
4763 };
4764 neb_cfg_with_hook.oie_inner_handoff_priority =
4765 [controller, kappa = neb_config.ucb_kappa,
4766 dimer_use_global_gp = neb_config.dimer_use_global_gp,
4767 inner_unc_relative = neb_config.inner_unc_relative](
4768 const NEBPath& path, int ci_image_idx, int outer_iter,
4769 double ci_force, double max_chain_energy_variance,
4770 double posterior_variance_threshold, bool current_chain_certificate,
4771 bool planned_current_chain_or_ci,
4772 const ActiveLearningSession* sess) {
4773 (void)outer_iter;
4774 (void)ci_force;
4775 if (!(ci_image_idx > 0 && ci_image_idx < path.numImages() - 1)) {
4776 return false;
4777 }
4778 const bool band_information_exhausted =
4779 sess != nullptr &&
4780 detail::isBandInformationExhaustedForMmf(
4781 max_chain_energy_variance, sess->gp.getSigma2(),
4782 posterior_variance_threshold, inner_unc_relative);
4783 if (!controller->shouldPrepareMmfHandoff(
4784 /*trap_detected=*/false, band_information_exhausted,
4785 current_chain_certificate)) {
4786 return false;
4787 }
4788 const auto diagnostics = controller->diagnostics();
4789 const detail::MmfSurrogateFingerprint surrogate =
4790 sess != nullptr ? sess->mmfSurrogateFingerprint(
4791 ci_image_idx, dimer_use_global_gp)
4793 detail::MmfPosteriorActionFingerprint action;
4794 action.surrogate = surrogate;
4795 const bool rejected_seed_replay = controller->rejectedMmfSeedReplay(
4796 path.image(ci_image_idx).positions, action,
4797 static_cast<long>(ci_image_idx),
4798 sess != nullptr ? &sess->atoms_config : nullptr);
4799 const bool trusted_retry_progress_pending =
4800 diagnostics.trusted_recovery_active &&
4801 std::isfinite(diagnostics.trusted_retry_reject_force) &&
4802 diagnostics.trusted_retry_reject_force > 0.0;
4803 const bool band_acquisition_quiet =
4804 detail::isOieAcquisitionQuietForMmf(
4805 max_chain_energy_variance, posterior_variance_threshold);
4806 const bool current_saddle_stencil_certificate =
4807 sess != nullptr &&
4808 detail::hasCurrentOciSaddleStencilCertificate(*sess, path,
4809 ci_image_idx);
4810 const bool ci_posterior_confident =
4811 detail::ciPosteriorConfident(path, ci_image_idx, kappa);
4812 const bool ci_is_energy_maximum =
4813 path.highestEnergyImageIndex() == ci_image_idx;
4814 detail::OieInnerHandoffPrecheck state;
4815 state.handoff_data_ready = detail::isOciMmfHandoffDataReady(
4816 band_acquisition_quiet, current_saddle_stencil_certificate,
4817 ci_posterior_confident, ci_is_energy_maximum);
4818 state.current_chain_certificate = current_chain_certificate;
4819 state.current_saddle_stencil_certificate =
4820 current_saddle_stencil_certificate;
4821 state.soft_quiet_blocked_after_reject =
4822 diagnostics.soft_quiet_blocked_after_reject;
4823 state.trusted_recovery_active = diagnostics.trusted_recovery_active;
4824 state.trusted_retry_progress_pending =
4825 trusted_retry_progress_pending;
4826 state.oie_quiet_handoff_stalled =
4827 diagnostics.oie_quiet_handoff_stalled;
4828 state.rejected_seed_replay = rejected_seed_replay;
4829 state.planned_current_chain_or_ci = planned_current_chain_or_ci;
4830 state.ci_force = ci_force;
4831 state.handoff_force_threshold = diagnostics.current_threshold;
4832 return detail::shouldBypassOieInnerForHandoff(
4833 state, /*accepted_inner_steps=*/0);
4834 };
4835 auto caller_oie_fixed_image = neb_config.oie_fixed_image;
4836 auto caller_oie_fixed_image_lease = neb_config.oie_fixed_image_lease;
4837 neb_cfg_with_hook.oie_fixed_image_lease = [controller,
4838 caller_oie_fixed_image,
4839 caller_oie_fixed_image_lease](
4840 const NEBPath& path,
4841 int ci_image_idx,
4842 int outer_iter) {
4843 const auto diagnostics_before_stability = controller->diagnostics();
4844 const int owner_before_stability = detail::activeOieRecoveryOwnerImage(
4845 diagnostics_before_stability.recovery_owner_image, ci_image_idx,
4846 diagnostics_before_stability.force_improving_recovery_active,
4847 diagnostics_before_stability.trusted_recovery_active);
4848 controller->updateStabilityForOuter(
4849 static_cast<long>(owner_before_stability > 0
4850 ? owner_before_stability
4851 : ci_image_idx),
4852 outer_iter);
4853 const auto diagnostics = controller->diagnostics();
4854 const int recovery_owner = detail::activeOieRecoveryOwnerImage(
4855 diagnostics.recovery_owner_image, ci_image_idx,
4856 diagnostics.force_improving_recovery_active,
4857 diagnostics.trusted_recovery_active);
4858 const bool rejected_recovery_seed =
4859 diagnostics.trusted_recovery_active &&
4860 diagnostics.mmf_reject_climbing_image == recovery_owner;
4861 const OieFixedImageLease recovery_lease =
4862 detail::makeOieRecoveryFixedImageLease(
4863 recovery_owner, diagnostics.force_improving_recovery_active,
4864 diagnostics.trusted_recovery_active, rejected_recovery_seed,
4865 diagnostics.info_gate,
4866 diagnostics.pure_reject_lock ||
4867 diagnostics.soft_quiet_blocked_after_reject);
4868 if (recovery_lease.image_index > 0) {
4869 return recovery_lease;
4870 }
4871 const OieFixedImageLease exhausted_recovery_lease =
4872 detail::makeOieExhaustedRecoveryEvidenceLease(
4873 ci_image_idx, diagnostics.exhausted_recovery_reject_active,
4874 diagnostics.mmf_reject_climbing_image,
4875 path.highestEnergyImageIndexPreferring(ci_image_idx));
4876 if (exhausted_recovery_lease.image_index > 0) {
4877 return exhausted_recovery_lease;
4878 }
4879 if (caller_oie_fixed_image_lease) {
4880 return caller_oie_fixed_image_lease(path, ci_image_idx, outer_iter);
4881 }
4882 OieFixedImageLease caller_lease;
4883 if (caller_oie_fixed_image) {
4884 caller_lease.image_index =
4885 caller_oie_fixed_image(path, ci_image_idx, outer_iter);
4886 }
4887 return caller_lease;
4888 };
4889 auto caller_hook_reject = neb_config.outer_iter_hook_reject;
4890 neb_cfg_with_hook.outer_iter_hook_reject =
4891 [controller, caller_hook_reject, &neb_config](
4892 const NEBPath& path, int ci_image_idx, int outer_iter,
4893 ActiveLearningSession& sess) {
4894 if (caller_hook_reject) {
4895 caller_hook_reject(path, ci_image_idx, outer_iter, sess);
4896 }
4897 if (!(ci_image_idx > 0 && ci_image_idx < path.numImages() - 1)) {
4898 return;
4899 }
4900 const double ci_force = path.nebForce(ci_image_idx).norm();
4901 detail::MmfPosteriorActionFingerprint action =
4902 controller->previewMmfAction(sess, path, ci_image_idx,
4903 neb_config);
4904 controller->recordUncertifiedMmfHookReject(
4905 ci_force, path.image(ci_image_idx).positions, std::move(action),
4906 static_cast<long>(ci_image_idx));
4907 };
4908 // Preserve a caller-installed hook (e.g. gprn's --midrun-realign
4909 // chain re-alignment): it runs first, then the MMF controller sees
4910 // the updated path.
4911 auto caller_hook = neb_config.outer_iter_hook;
4912 neb_cfg_with_hook.outer_iter_hook =
4913 [controller, &oracle, &neb_config, &total_oracle_calls, &bursts_fired,
4914 &dimer_saddle_image_idx, handoff_trap_state, caller_hook](
4915 NEBPath& path, int ci_image_idx, int outer_iter,
4916 ActiveLearningSession& sess, bool& converged, bool trap_detected) {
4917 runOciNebOuterIteration(controller, oracle, neb_config,
4918 total_oracle_calls, bursts_fired,
4919 dimer_saddle_image_idx, handoff_trap_state,
4920 caller_hook, path, ci_image_idx, outer_iter,
4921 sess, converged, trap_detected);
4922 };
4923
4924 result.neb_result = gpNEB(oracle, initial, final_state, n_images,
4925 neb_cfg_with_hook, &session);
4926 const bool dimer_summary_applied = detail::applyDimerSaddleSummary(
4927 result.neb_result, dimer_saddle_image_idx);
4928 (void)dimer_summary_applied;
4930 result.dimer_ran = (bursts_fired > 0);
4931 result.dimer_oracle_calls = total_oracle_calls;
4932 result.mmf_bursts = bursts_fired;
4933 result.dimer_converged = result.neb_result.converged;
4934
4935 // No saddle is max_energy_image -1. Leave ci_final_position empty,
4936 // the same as a run that returned no path.
4937 if (result.neb_result.path) {
4938 const int image = result.neb_result.max_energy_image;
4939 if (image >= 0 && image < result.neb_result.path->numImages()) {
4940 result.ci_final_position =
4941 result.neb_result.path->image(image).positions;
4942 }
4943 }
4944 return result;
4945}
GPNEBResult gpNEB(NEBOracle oracle, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int n_images, const GPNEBConfig &config, ActiveLearningSession *session)
Run GP-accelerated NEB.
Definition GPNEB.cpp:21110
void runOciNebOuterIteration(const std::shared_ptr< OCINEBController > &controller, NEBOracle &oracle, const GPNEBConfig &neb_config, int &total_oracle_calls, int &bursts_fired, int &dimer_saddle_image_idx, const std::shared_ptr< OciMmfHandoffTrapState > &handoff_trap_state, const GPNEBConfig::OuterIterHook &caller_hook, NEBPath &path, int ci_image_idx, int outer_iter, ActiveLearningSession &sess, bool &converged, bool trap_detected)
static SurrogateFingerprint global(std::uint64_t revision)
Definition Session.h:211
OieFixedImageLeaseProvider oie_fixed_image_lease
Definition GPNEB.h:1265
OuterIterHookReject outer_iter_hook_reject
Definition GPNEB.h:1233
double inner_unc_relative
Definition GPNEB.h:1140
policy::SearchKind training_search_kind
Label published to the policy. runOCINEB sets OciNeb.
Definition GPNEB.h:1271
OieFixedImage oie_fixed_image
Definition GPNEB.h:1259
MmfHandoffPolicy handoff_policy
Eigen::VectorXd ci_final_position

◆ runOciNebOuterIteration()

void gpr::neb::runOciNebOuterIteration ( const std::shared_ptr< OCINEBController > & controller,
NEBOracle & oracle,
const GPNEBConfig & neb_config,
int & total_oracle_calls,
int & bursts_fired,
int & dimer_saddle_image_idx,
const std::shared_ptr< OciMmfHandoffTrapState > & handoff_trap_state,
const GPNEBConfig::OuterIterHook & caller_hook,
NEBPath & path,
int ci_image_idx,
int outer_iter,
ActiveLearningSession & sess,
bool & converged,
bool trap_detected )

Definition at line 4175 of file OCINEBController.cpp.

4183{
4184 if (caller_hook)
4185 caller_hook(path, ci_image_idx, outer_iter, sess, converged,
4186 trap_detected);
4187 path.computeNEBForces();
4188 const double conv_force = path.nebForce(ci_image_idx).norm();
4189 // The adaptive MMF branch compares the band convergence force
4190 // against its learned threshold. An exact current saddle stencil
4191 // is a separate handoff proof because the dimer consumes that
4192 // local true-PES geometry directly.
4193 double band_conv_force = conv_force;
4194 for (int i = 1; i < path.numImages() - 1; ++i) {
4195 band_conv_force = std::max(band_conv_force, path.nebForce(i).norm());
4196 }
4197
4198 // Track stability (mirrors eOn).
4199 controller->updateStabilityForOuter(static_cast<long>(ci_image_idx),
4200 outer_iter);
4201
4202 const std::size_t ntrain_now =
4203 static_cast<std::size_t>(sess.training_obs.R.rows());
4204 const auto diagnostics_before_growth = controller->diagnostics();
4205 const bool active_recovery = detail::activeMmfRecoveryOwnsClimbingImage(
4206 diagnostics_before_growth.force_improving_recovery_active,
4207 diagnostics_before_growth.trusted_recovery_active);
4208 const bool exhausted_recovery_applies =
4209 detail::exhaustedRecoveryRejectAppliesToCi(
4210 diagnostics_before_growth.exhausted_recovery_reject_active,
4211 diagnostics_before_growth.mmf_reject_climbing_image, ci_image_idx);
4212 const int active_recovery_owner = detail::activeOieRecoveryOwnerImage(
4213 diagnostics_before_growth.recovery_owner_image, ci_image_idx,
4214 diagnostics_before_growth.force_improving_recovery_active,
4215 diagnostics_before_growth.trusted_recovery_active);
4216 const int recovery_owner = active_recovery_owner > 0 ? active_recovery_owner
4217 : exhausted_recovery_applies ? ci_image_idx
4218 : -1;
4219 const int candidate_image =
4220 path.highestEnergyImageIndexPreferring(ci_image_idx);
4221 const int recovery_model_image =
4222 recovery_owner > 0 ? recovery_owner : ci_image_idx;
4223 const detail::MmfSurrogateFingerprint mmf_surrogate_now =
4224 sess.mmfSurrogateFingerprint(recovery_model_image,
4225 neb_config.dimer_use_global_gp);
4226 detail::MmfPosteriorActionFingerprint mmf_action_now;
4227 mmf_action_now.surrogate = mmf_surrogate_now;
4228 const bool rejected_position_matches =
4229 controller->rejectedMmfSeedPositionMatches(
4230 path.image(ci_image_idx).positions, &sess.atoms_config,
4231 static_cast<long>(ci_image_idx));
4232 if (diagnostics_before_growth.info_gate !=
4233 detail::MmfInformationGate::Open ||
4234 rejected_position_matches) {
4235 mmf_action_now =
4236 controller->previewMmfAction(sess, path, ci_image_idx, neb_config);
4237 }
4238 const bool rejected_seed_replay = controller->rejectedMmfSeedReplay(
4239 path.image(ci_image_idx).positions, mmf_action_now,
4240 static_cast<long>(ci_image_idx), &sess.atoms_config);
4241 const bool exhausted_owner_model_growth_requested =
4242 exhausted_recovery_applies && candidate_image == recovery_owner;
4243 const bool recovery_model_growth_requested =
4244 detail::shouldRequestOieRecoveryModelGrowth(
4245 diagnostics_before_growth.force_improving_recovery_active,
4246 diagnostics_before_growth.trusted_recovery_active,
4247 rejected_seed_replay, diagnostics_before_growth.info_gate) ||
4248 exhausted_owner_model_growth_requested;
4249 const bool recovery_model_growth_ready =
4250 detail::isOieRecoveryOwnerModelGrowthReady(
4251 recovery_model_growth_requested, mmf_surrogate_now,
4252 diagnostics_before_growth.mmf_surrogate_at_last_reject);
4253 // Noise-floor exhaustion voids adaptive threshold; soft OIE-quiet
4254 // (chain var under the active OIE posterior scale) leases MMF
4255 // while keeping the near-saddle force bound.
4256 const double chain_var = sess.last_max_chain_energy_variance;
4257 const double noise_floor = sess.gp.getSigma2();
4258 const double magn_sigma2 =
4260 const double posterior_threshold =
4261 detail::effectivePosteriorVarianceThreshold(
4262 neb_config, std::optional<double>{magn_sigma2});
4263 const bool band_information_exhausted =
4264 detail::isBandInformationExhaustedForMmf(chain_var, noise_floor,
4265 posterior_threshold,
4266 neb_config.inner_unc_relative);
4267 const bool band_acquisition_quiet =
4268 detail::isOieAcquisitionQuietForMmf(chain_var, posterior_threshold);
4269 const bool ci_is_energy_max =
4270 path.highestEnergyImageIndex() == ci_image_idx;
4271 const bool ci_posterior_confident =
4272 detail::ciPosteriorConfident(path, ci_image_idx, neb_config.ucb_kappa);
4273 const bool current_chain_certificate = sess.hasCurrentChainCertificate(
4274 ci_image_idx, path.image(ci_image_idx).positions);
4275 const bool current_saddle_stencil_certificate =
4276 detail::hasCurrentOciSaddleStencilCertificate(sess, path, ci_image_idx);
4277 const bool candidate_posterior_confident =
4278 candidate_image > 0 && detail::ciPosteriorConfident(
4279 path, candidate_image, neb_config.ucb_kappa);
4280 const bool candidate_chain_certificate =
4281 candidate_image > 0 &&
4282 sess.hasCurrentChainCertificate(candidate_image,
4283 path.image(candidate_image).positions);
4284 const bool candidate_saddle_stencil_certificate =
4285 candidate_image > 0 && detail::hasCurrentOciSaddleStencilCertificate(
4286 sess, path, candidate_image);
4287 const bool band_force_converged =
4288 std::isfinite(band_conv_force) &&
4289 band_conv_force < detail::effectiveModelNoiseTolerance(neb_config);
4290 const bool release_exhausted_recovery =
4291 detail::shouldReleaseOieExhaustedRecoveryForCertifiedHandover(
4292 diagnostics_before_growth.exhausted_recovery_reject_active,
4293 diagnostics_before_growth.mmf_reject_climbing_image,
4294 candidate_image, candidate_posterior_confident,
4295 candidate_chain_certificate, candidate_saddle_stencil_certificate);
4296 if (release_exhausted_recovery) {
4297 controller->releaseExhaustedRecoveryForCertifiedHandover();
4298 if (neb_config.verbose && isRank0()) {
4299 std::cout << "[ocineb] exhausted-recovery-handover outer="
4300 << outer_iter << " owner="
4301 << diagnostics_before_growth.mmf_reject_climbing_image
4302 << " candidate=" << candidate_image
4303 << " candidate_confident="
4304 << candidate_posterior_confident
4305 << " candidate_chain_cert=" << candidate_chain_certificate
4306 << " candidate_stencil_cert="
4307 << candidate_saddle_stencil_certificate << std::endl;
4308 }
4309 return;
4310 }
4311 const bool release_recovery_owner =
4312 detail::shouldReleaseOieRecoveryForCertifiedHandover(
4313 active_recovery, recovery_owner, candidate_image,
4314 candidate_posterior_confident, candidate_chain_certificate,
4315 candidate_saddle_stencil_certificate);
4316 if (release_recovery_owner) {
4317 controller->releaseRecoveryOwnerForCertifiedHandover(
4318 path.image(recovery_owner).positions,
4319 static_cast<long>(recovery_owner));
4320 if (neb_config.verbose && isRank0()) {
4321 std::cout << "[ocineb] recovery-handover outer=" << outer_iter
4322 << " owner=" << recovery_owner
4323 << " candidate=" << candidate_image
4324 << " candidate_confident="
4325 << candidate_posterior_confident
4326 << " band_force_cert=" << band_force_converged
4327 << " candidate_chain_cert=" << candidate_chain_certificate
4328 << " candidate_stencil_cert="
4329 << candidate_saddle_stencil_certificate
4330 << " mmf_surrogate_owner=" << mmf_surrogate_now.owner
4331 << " mmf_surrogate_revision="
4332 << mmf_surrogate_now.revision << std::endl;
4333 }
4334 return;
4335 }
4336 const bool release_invalidated_owner =
4337 detail::shouldReleaseOieRecoveryForInvalidatedOwner(
4338 active_recovery, recovery_owner, ci_image_idx,
4339 recovery_model_growth_ready, band_force_converged,
4340 current_chain_certificate, current_saddle_stencil_certificate,
4341 ci_posterior_confident, ci_is_energy_max);
4342 if (release_invalidated_owner) {
4343 controller->releaseRecoveryOwnerForCertifiedHandover(
4344 path.image(recovery_owner).positions,
4345 static_cast<long>(recovery_owner));
4346 if (neb_config.verbose && isRank0()) {
4347 std::cout << "[ocineb] recovery-owner-invalidated outer="
4348 << outer_iter << " owner=" << recovery_owner
4349 << " retry=" << ci_image_idx
4350 << " band_force_cert=" << band_force_converged
4351 << " owner_chain_cert=" << current_chain_certificate
4352 << " owner_stencil_cert="
4353 << current_saddle_stencil_certificate
4354 << " owner_confident=" << ci_posterior_confident
4355 << " owner_energy_max=" << ci_is_energy_max
4356 << " mmf_surrogate_owner=" << mmf_surrogate_now.owner
4357 << " mmf_surrogate_revision="
4358 << mmf_surrogate_now.revision << std::endl;
4359 }
4360 return;
4361 }
4362 const bool retry_matches_recovery_owner =
4363 detail::shouldAdvanceOieRecoveryInformationGate(
4364 active_recovery, recovery_owner, ci_image_idx);
4365 if (!retry_matches_recovery_owner) {
4366 if (neb_config.verbose && isRank0()) {
4367 std::cout << "[ocineb] recovery-owner-wait outer=" << outer_iter
4368 << " owner=" << recovery_owner
4369 << " retry=" << ci_image_idx
4370 << " candidate=" << candidate_image
4371 << " candidate_confident="
4372 << candidate_posterior_confident
4373 << " candidate_chain_cert=" << candidate_chain_certificate
4374 << " candidate_stencil_cert="
4375 << candidate_saddle_stencil_certificate << std::endl;
4376 }
4377 return;
4378 }
4379 controller->noteMmfActionChange(std::move(mmf_action_now));
4380 const bool certified_active_recovery_model_growth =
4381 active_recovery &&
4382 detail::isOieRecoveryModelGrowthCertified(
4383 recovery_owner, ci_image_idx, recovery_model_growth_ready,
4384 current_chain_certificate, current_saddle_stencil_certificate,
4385 ci_is_energy_max);
4386 const bool certified_exhausted_recovery_model_growth =
4387 exhausted_owner_model_growth_requested &&
4388 detail::isOieExhaustedRecoveryModelGrowthCertified(
4389 recovery_owner, ci_image_idx, recovery_model_growth_ready,
4390 current_chain_certificate, current_saddle_stencil_certificate,
4391 ci_is_energy_max, rejected_seed_replay);
4392 const bool certified_recovery_model_growth =
4393 certified_active_recovery_model_growth ||
4394 certified_exhausted_recovery_model_growth;
4395 const bool transition_focal_handoff =
4396 detail::isOracleTransitionFocalHandoff(
4397 neb_config.oracle_transition_focal_image, ci_image_idx,
4398 current_chain_certificate, current_saddle_stencil_certificate);
4399 const bool handoff_ci_posterior_confident = ci_posterior_confident ||
4400 transition_focal_handoff ||
4401 certified_recovery_model_growth;
4402 const bool handoff_ci_is_energy_max = ci_is_energy_max ||
4403 transition_focal_handoff ||
4404 certified_recovery_model_growth;
4405 const bool handoff_data_ready = detail::isOciMmfHandoffDataReady(
4406 band_acquisition_quiet, current_saddle_stencil_certificate,
4407 handoff_ci_posterior_confident, handoff_ci_is_energy_max);
4408 if (band_information_exhausted) {
4409 controller->openInformationGateAtNoiseFloor(
4410 path.image(ci_image_idx).positions, mmf_surrogate_now,
4411 static_cast<long>(ci_image_idx));
4412 }
4413 // Adaptive handoff trap: GP residual under the MMF bar while the
4414 // true CI force remains above it (same predicate as
4415 // GPNEB::detail::shouldFlagMmfHandoffTrap). The pick callback and
4416 // outer hook can observe the same climbing image under different
4417 // outer bookkeeping, so CI identity is the stable match key.
4418 const bool adaptive_handoff_trap =
4419 handoff_trap_state && handoff_trap_state->requested_current_ci &&
4420 handoff_trap_state->ci_image_idx == ci_image_idx &&
4421 detail::shouldPromoteCurrentCiHandoffMismatchToTrap(
4422 handoff_trap_state->outer_iter, outer_iter,
4423 handoff_trap_state->gp_force, conv_force,
4424 handoff_trap_state->threshold);
4425 const bool effective_trap = trap_detected || adaptive_handoff_trap ||
4426 certified_recovery_model_growth;
4427
4428 // Lease residual: when handoff data is ready (quiet band or exact
4429 // saddle stencil + confident energy-max CI), use the CI force —
4430 // that is the residual the dimer acts on. Otherwise keep the
4431 // band-max force so early non-ready bands do not fire MMF on a
4432 // soft CI while the rest of the path is still hot (Baker 01).
4433 // Baker 05 needed the CI residual under thr with handoff_ready
4434 // while band F stayed ~6 and starved every lease.
4435 const bool stagnation_handoff = sess.stagnation_handoff;
4436 // Keep the grant until the dimer lease is taken or the certified
4437 // handoff declines. Clearing it before shouldTrigger lets a closed
4438 // information gate spend the fixed-point grant without a lease.
4439 // A stopped climb leases on its own residual. The band-max stand-in
4440 // is only for a walk that is still descending and not yet ready.
4441 const double lease_force = (handoff_data_ready || stagnation_handoff)
4442 ? conv_force
4443 : band_conv_force;
4444 // Quiet-stall tracks the residual MMF would lease on. Band-max
4445 // thrash can keep "improving" while the CI residual is flat above
4446 // thr (Baker 05), so stall must not use band_force once handoff is
4447 // ready. Threshold seed still uses band scale when unset so thr is
4448 // not pinned to a soft CI on first contact.
4449 const double quiet_track_force =
4450 controller->baselineSet() ? lease_force : band_conv_force;
4451 controller->recordMmfHandoffForce(quiet_track_force, handoff_data_ready);
4452 if (stagnation_handoff && neb_config.verbose && isRank0()) {
4453 std::cout << "[band] stagnation-handoff outer=" << outer_iter
4454 << " image=" << ci_image_idx << " F=" << lease_force
4455 << std::endl;
4456 }
4457 const bool trigger =
4458 (handoff_data_ready || stagnation_handoff) &&
4459 controller->shouldTrigger(
4460 lease_force, /*ci_active=*/true, static_cast<long>(ci_image_idx),
4461 static_cast<long>(path.numImages() - 2),
4462 handoff_ci_posterior_confident, effective_trap, ntrain_now,
4463 handoff_ci_is_energy_max, band_information_exhausted,
4464 band_acquisition_quiet, rejected_seed_replay,
4465 current_chain_certificate, current_saddle_stencil_certificate,
4466 rejected_position_matches, stagnation_handoff);
4467 if (stagnation_handoff && !trigger) {
4468 // Certified handoff declined: residual already at the force
4469 // tolerance, MMF off, or no climbing image. A closed information
4470 // gate is not a decline.
4471 sess.stagnation_handoff = false;
4472 }
4473 if (!trigger) {
4474 if (neb_config.verbose && isRank0()) {
4475 const auto diagnostics = controller->diagnostics();
4476 const bool exhausted_recovery_gate =
4477 detail::exhaustedRecoveryRejectAppliesToCi(
4478 diagnostics.exhausted_recovery_reject_active,
4479 diagnostics.mmf_reject_climbing_image,
4480 static_cast<long>(ci_image_idx));
4481 std::cout
4482 << "[ocineb] gate-skip outer=" << outer_iter
4483 << " ci=" << ci_image_idx << " force=" << conv_force
4484 << " band_force=" << band_conv_force
4485 << " threshold=" << diagnostics.current_threshold
4486 << " baseline=" << diagnostics.baseline_force
4487 << " pure_lock=" << diagnostics.pure_reject_lock
4488 << " soft_block=" << diagnostics.soft_quiet_blocked_after_reject
4489 << " quiet_stalled=" << diagnostics.oie_quiet_handoff_stalled
4490 << " force_recovery="
4491 << diagnostics.force_improving_recovery_active
4492 << " trusted_recovery=" << diagnostics.trusted_recovery_active
4493 << " recovery_owner=" << diagnostics.recovery_owner_image
4494 << " exhausted_recovery_reject="
4495 << diagnostics.exhausted_recovery_reject_active
4496 << " exhausted_recovery_gate=" << exhausted_recovery_gate
4497 << " trusted_retry_force="
4498 << diagnostics.trusted_retry_reject_force
4499 << " uncert_hook=" << diagnostics.uncertified_hook_reject_active
4500 << " info_gate="
4501 << mmfInformationGateName(diagnostics.info_gate)
4502 << " mmf_surrogate=" << mmfSurrogateOwnerName(mmf_surrogate_now)
4503 << " reject_ci=" << diagnostics.mmf_reject_climbing_image
4504 << " rejected_seed=" << rejected_seed_replay
4505 << " rejected_position=" << rejected_position_matches
4506 << " current_cert=" << current_chain_certificate
4507 << " local_stencil=" << current_saddle_stencil_certificate
4508 << " handoff_ready=" << handoff_data_ready
4509 << " quiet=" << band_acquisition_quiet
4510 << " band_quiet=" << band_acquisition_quiet
4511 << " exhausted=" << band_information_exhausted
4512 << " confident=" << ci_posterior_confident
4513 << " transition_focal=" << transition_focal_handoff
4514 << " recovery_growth_requested="
4515 << recovery_model_growth_requested
4516 << " recovery_growth_ready=" << recovery_model_growth_ready
4517 << " recovery_growth_certified="
4518 << certified_recovery_model_growth << " trap=" << effective_trap
4519 << " adaptive_trap=" << adaptive_handoff_trap
4520 << " gp_handoff_force="
4521 << (handoff_trap_state
4522 ? handoff_trap_state->gp_force
4523 : std::numeric_limits<double>::infinity())
4524 << " gp_handoff_threshold="
4525 << (handoff_trap_state
4526 ? handoff_trap_state->threshold
4527 : std::numeric_limits<double>::quiet_NaN())
4528 << " energy_max=" << ci_is_energy_max
4529 << " ntrain=" << ntrain_now
4530 << " mmf_surrogate_owner=" << mmf_surrogate_now.owner
4531 << " mmf_surrogate_revision=" << mmf_surrogate_now.revision
4532 << " reject_mmf_surrogate_owner="
4533 << diagnostics.mmf_surrogate_at_last_reject.owner
4534 << " reject_mmf_surrogate_revision="
4535 << diagnostics.mmf_surrogate_at_last_reject.revision
4536 << " chain_var=" << chain_var << " noise_floor=" << noise_floor
4537 << " posterior_threshold=" << posterior_threshold << std::endl;
4538 }
4539 return;
4540 }
4541 if (neb_config.verbose && isRank0()) {
4542 const auto diagnostics = controller->diagnostics();
4543 const bool exhausted_recovery_gate =
4544 detail::exhaustedRecoveryRejectAppliesToCi(
4545 diagnostics.exhausted_recovery_reject_active,
4546 diagnostics.mmf_reject_climbing_image,
4547 static_cast<long>(ci_image_idx));
4548 std::cout
4549 << "[ocineb] gate-fire outer=" << outer_iter
4550 << " ci=" << ci_image_idx << " force=" << conv_force
4551 << " band_force=" << band_conv_force
4552 << " threshold=" << diagnostics.current_threshold
4553 << " baseline=" << diagnostics.baseline_force
4554 << " pure_lock=" << diagnostics.pure_reject_lock
4555 << " soft_block=" << diagnostics.soft_quiet_blocked_after_reject
4556 << " quiet_stalled=" << diagnostics.oie_quiet_handoff_stalled
4557 << " force_recovery=" << diagnostics.force_improving_recovery_active
4558 << " trusted_recovery=" << diagnostics.trusted_recovery_active
4559 << " recovery_owner=" << diagnostics.recovery_owner_image
4560 << " exhausted_recovery_reject="
4561 << diagnostics.exhausted_recovery_reject_active
4562 << " exhausted_recovery_gate=" << exhausted_recovery_gate
4563 << " trusted_retry_force=" << diagnostics.trusted_retry_reject_force
4564 << " uncert_hook=" << diagnostics.uncertified_hook_reject_active
4565 << " info_gate=" << mmfInformationGateName(diagnostics.info_gate)
4566 << " mmf_surrogate=" << mmfSurrogateOwnerName(mmf_surrogate_now)
4567 << " reject_ci=" << diagnostics.mmf_reject_climbing_image
4568 << " rejected_seed=" << rejected_seed_replay
4569 << " rejected_position=" << rejected_position_matches
4570 << " current_cert=" << current_chain_certificate
4571 << " local_stencil=" << current_saddle_stencil_certificate
4572 << " handoff_ready=" << handoff_data_ready
4573 << " quiet=" << band_acquisition_quiet
4574 << " band_quiet=" << band_acquisition_quiet
4575 << " exhausted=" << band_information_exhausted
4576 << " confident=" << ci_posterior_confident
4577 << " transition_focal=" << transition_focal_handoff
4578 << " recovery_growth_requested=" << recovery_model_growth_requested
4579 << " recovery_growth_ready=" << recovery_model_growth_ready
4580 << " recovery_growth_certified=" << certified_recovery_model_growth
4581 << " trap=" << effective_trap
4582 << " adaptive_trap=" << adaptive_handoff_trap
4583 << " gp_handoff_force="
4584 << (handoff_trap_state ? handoff_trap_state->gp_force
4585 : std::numeric_limits<double>::infinity())
4586 << " gp_handoff_threshold="
4587 << (handoff_trap_state ? handoff_trap_state->threshold
4588 : std::numeric_limits<double>::quiet_NaN())
4589 << " energy_max=" << ci_is_energy_max << " ntrain=" << ntrain_now
4590 << " mmf_surrogate_owner=" << mmf_surrogate_now.owner
4591 << " mmf_surrogate_revision=" << mmf_surrogate_now.revision
4592 << " reject_mmf_surrogate_owner="
4593 << diagnostics.mmf_surrogate_at_last_reject.owner
4594 << " reject_mmf_surrogate_revision="
4595 << diagnostics.mmf_surrogate_at_last_reject.revision
4596 << " chain_var=" << chain_var << " noise_floor=" << noise_floor
4597 << " posterior_threshold=" << posterior_threshold << std::endl;
4598 }
4599
4600 if (handoff_trap_state) {
4601 handoff_trap_state->requested_current_ci = false;
4602 }
4603 detail::OracleNoiseUpdatePause noise_pause(
4604 neb_config.oracle_noise_updates_enabled);
4605 if (stagnation_handoff) sess.stagnation_handoff = false;
4606 auto burst = controller->run(path, ci_image_idx, oracle, neb_config, sess,
4607 effective_trap);
4608 gpr::PhaseTimers::notePeak("after_burst");
4609 total_oracle_calls += burst.oracle_calls;
4610 ++bursts_fired;
4611 (void)detail::publishOracleSessionPathCheckpoint(neb_config, path,
4612 ci_image_idx);
4613 const auto observe_oracle_outcome =
4614 [&neb_config, ci_image_idx](const MMFRunResult& current) {
4615 if (!neb_config.oracle_optimization_outcome) return;
4617 outcome.image_index = ci_image_idx;
4618 outcome.force_before = current.previousForce;
4619 outcome.force_after = current.newForce;
4620 outcome.comparable_true_pes_forces =
4621 std::isfinite(current.previousForce) &&
4622 std::isfinite(current.newForce);
4623 outcome.certified_lower_saddle =
4624 current.certified_lower_saddle_advanced;
4625 outcome.converged = current.convergedAfterMMF;
4626 neb_config.oracle_optimization_outcome(outcome);
4627 };
4628 observe_oracle_outcome(burst);
4629 // FI recovery can land under thr without Helped. Non-trusted FI
4630 // retains the same CI while each burst makes measured progress.
4631 // Trusted recovery additionally requires a fresh exact saddle
4632 // stencil, which each accepted true-PES row can renew.
4633 const double rerelease_force_tolerance =
4634 detail::effectiveModelNoiseTolerance(neb_config);
4635 burst = detail::continueImmediateOciRecovery(
4636 burst, rerelease_force_tolerance,
4637 [controller] { return controller->diagnostics().current_threshold; },
4638 [&sess, &path, ci_image_idx] {
4639 return detail::hasCurrentOciSaddleStencilCertificate(sess, path,
4640 ci_image_idx);
4641 },
4643 [&](const MMFRunResult& accepted, double threshold) {
4644 if (neb_config.verbose && isRank0()) {
4645 std::cout << "[ocineb] immediate recovery re-lease outer="
4646 << outer_iter << " ci=" << ci_image_idx
4647 << " force=" << accepted.newForce
4648 << " thr=" << threshold
4649 << " tol=" << rerelease_force_tolerance
4650 << " trusted=" << accepted.trusted_recovery_advanced
4651 << " force_progress="
4652 << accepted.force_improving_recovery_advanced
4653 << " lower_saddle_progress="
4654 << accepted.certified_lower_saddle_advanced
4655 << " saddle_cert="
4656 << accepted.recovery_saddle_certified << std::endl;
4657 }
4658 auto next = controller->run(path, ci_image_idx, oracle, neb_config,
4659 sess, effective_trap);
4660 total_oracle_calls += next.oracle_calls;
4661 ++bursts_fired;
4662 (void)detail::publishOracleSessionPathCheckpoint(neb_config, path,
4663 ci_image_idx);
4664 observe_oracle_outcome(next);
4665 return next;
4666 });
4667 if (burst.convergedAfterMMF) {
4668 dimer_saddle_image_idx = ci_image_idx;
4669 converged = true;
4670 }
4671}
int highestEnergyImageIndex() const
Highest finite interior energy, or -1 when none exists.
Definition NEBPath.cpp:1132
int highestEnergyImageIndexPreferring(int preferred) const
Definition NEBPath.cpp:1165
bool hasCurrentChainCertificate(int image_idx, const Eigen::VectorXd &positions) const
Definition Session.h:2081
SurrogateFingerprint mmfSurrogateFingerprint(int image_idx, bool dimer_use_global_gp) const
Definition Session.h:1093
std::function< void(const NEBOracleOptimizationOutcome &)> oracle_optimization_outcome
Definition GPNEB.h:275
bool * oracle_noise_updates_enabled
Definition GPNEB.h:271
int oracle_transition_focal_image
Definition GPNEB.h:546
Result of one ~OCINEBControllerrun~ invocation.

◆ runOCINEBRefined()

OCINEBResult gpr::neb::runOCINEBRefined ( NEBOracle oracle,
const Eigen::VectorXd & initial,
const Eigen::VectorXd & final_state,
int n_images,
GPNEBConfig neb_config,
const OCINEBConfig & oci_config,
ActiveLearningSession & session )

runOCINEB with certificate-driven band refinement (GPNEBConfig:: band_refinement_max, band_certificate_force_scale, first_attempt_wall_seconds). The first attempt uses session; each refinement doubles the image count and runs on a fresh session rebuilt from neb_config.gp_setup, since the per-image models are indexed to the image count. With band_refinement_max == 0 this is exactly runOCINEB. Shared by the gprn CLI and the Python bindings so both get the same acceptance behaviour.

Definition at line 5119 of file OCINEBController.cpp.

5124{
5125 const int max_refinements = std::max(0, neb_config.band_refinement_max);
5126
5127 // Give the first (coarsest) attempt a wall budget so a band that grinds
5128 // without converging at the requested resolution yields to refinement
5129 // instead of consuming the whole cell. 17_claisen is the case: it does not
5130 // converge at 8 images in any budget but converges at 16, and each coarse
5131 // outer is expensive, so the yield must be wall-based, not outer-count
5132 // based.
5133 const double saved_attempt_wall = neb_config.attempt_wall_seconds;
5134 if (max_refinements > 0 && neb_config.first_attempt_wall_seconds > 0.0) {
5135 neb_config.attempt_wall_seconds =
5136 (saved_attempt_wall > 0.0)
5137 ? std::min(saved_attempt_wall,
5138 neb_config.first_attempt_wall_seconds)
5139 : neb_config.first_attempt_wall_seconds;
5140 }
5141
5142 OCINEBResult result = runOCINEB(oracle, initial, final_state, n_images,
5143 neb_config, oci_config, session);
5144 neb_config.attempt_wall_seconds = saved_attempt_wall;
5145
5146 const double band_scale = neb_config.band_certificate_force_scale;
5147 int active_n_images = n_images;
5148 for (int refinement = 0; refinement < max_refinements; ++refinement) {
5149 if (result.neb_result.stop_reason == GPNEBStopReason::WallClockLimit)
5150 break;
5151 const bool converged = result.dimer_ran ? result.dimer_converged
5152 : result.neb_result.converged;
5153 // band_scale > 0 keeps the measured tier; a non-positive scale
5154 // selects the derived chord-discretization certificate, which has no
5155 // free constant beyond the band's own convergence tolerance.
5156 const bool discretization_holds =
5157 result.neb_result.path == nullptr ||
5158 (band_scale > 0.0
5159 ? detail::bandPathCertificateHolds(*result.neb_result.path,
5160 band_scale)
5161 : detail::bandDiscretizationCertificateHolds(
5162 *result.neb_result.path, neb_config.conv_tol,
5163 neb_config.band_leak_bound));
5164 // The climbing image must top every segment midpoint on the
5165 // surrogate; a ridge hidden between two images fails here, and
5166 // h-refinement at the ridge is its remedy. The chord-discretization
5167 // report (leak, residual) is recorded for the verdict but drives a
5168 // refinement pass only when the caller bounds the leak or selected
5169 // the measured band tier: a pass costs a coarse search over again
5170 // (04_ch3o: 62 calls to the converged climbing image, then 137
5171 // more over four passes that left the band under-resolved).
5172 bool midpoint_holds = true;
5173 double midpoint_excess = 0.0;
5174 double midpoint_raw_excess = 0.0;
5175 int midpoint_segment = -1;
5176 Eigen::VectorXd midpoint_worst_position;
5177 if (neb_config.band_midpoint_certificate && result.neb_result.path) {
5178 int midpoint_calls = 0;
5179 const auto mid = certifyBandMidpointsMeasured(
5180 session, *result.neb_result.path, neb_config.conv_tol, oracle,
5181 result.neb_result.path->numImages() - 1, &midpoint_calls);
5182 result.neb_result.oracle_calls += midpoint_calls;
5183 result.neb_result.oracle_calls_outer += midpoint_calls;
5184 midpoint_holds = mid.evaluated && mid.holds;
5185 midpoint_excess = mid.excess;
5186 midpoint_raw_excess = mid.raw_excess;
5187 midpoint_segment = mid.worst_segment;
5188 midpoint_worst_position = mid.measured_position.size() > 0
5189 ? mid.measured_position
5190 : mid.worst_position;
5191 }
5192 const bool refine_for_discretization =
5193 !discretization_holds &&
5194 (band_scale > 0.0 || neb_config.band_leak_bound);
5195 std::cout << "[ocineb] attempt " << (refinement + 1)
5196 << " converged=" << (converged ? 1 : 0) << " status="
5197 << static_cast<int>(result.neb_result.convergence_status)
5198 << " midpoint=" << (midpoint_holds ? 1 : 0)
5199 << " midpoint_excess=" << midpoint_excess
5200 << " midpoint_raw=" << midpoint_raw_excess
5201 << " midpoint_segment=" << midpoint_segment
5202 << " discretization=" << (discretization_holds ? 1 : 0)
5203 << " refine_for_discretization="
5204 << (refine_for_discretization ? 1 : 0)
5205 << " calls=" << result.neb_result.oracle_calls << std::endl;
5206 if (converged && midpoint_holds && !refine_for_discretization) break;
5207
5208 // Local h-refinement at the ridge when a coarse band exists (the
5209 // certificate reads the two climbing-image neighbours, so those two
5210 // segments are halved and the spacing is held); a whole-band
5211 // doubling only when there is no band to refine.
5212 bool local_refined = false;
5213 // Refinement changes the image neighborhoods, while the fitted GP
5214 // and every measured row belong to the same session. GPNEB resets
5215 // per-image models when it installs the refined path size.
5216 // Warm-start the refined band from the converged coarse band: the
5217 // polyline is resampled at the doubled image count with new images
5218 // placed in proportion to the coarse rest lengths (the chord-leak
5219 // equidistribution measured on the coarse band), so the refinement
5220 // starts where its parent ended instead of from a fresh
5221 // interpolation that must be relaxed again over a training set of
5222 // hundreds of rows (elbBKH 03_hcn: 45 calls coarse, then 700 rows
5223 // and the hour on the re-interpolated refinement).
5224 // A measured midpoint above the climbing image is a true-surface
5225 // point the band's discretisation missed: by the mountain-pass
5226 // argument the pass lies in that segment. The point becomes an
5227 // image of the restarted band, which then climbs from it, instead
5228 // of a resample by rest lengths that spreads the images along the
5229 // same chord and can miss the segment again (dacp2: the same
5230 // midpoint measured 0.9 eV above the climbing image four times).
5231 if (!midpoint_holds && midpoint_segment >= 0 &&
5232 result.neb_result.path &&
5233 result.neb_result.path->numImages() >= 3 &&
5234 midpoint_worst_position.size() ==
5235 result.neb_result.path->image(0).positions.size()) {
5236 const NEBPath& coarse = *result.neb_result.path;
5237 const int n = coarse.numImages();
5238 const Eigen::Index dof = midpoint_worst_position.size();
5239 EigenMatrix refined(n + 1, dof);
5240 int row = 0;
5241 for (int k = 0; k < n; ++k) {
5242 refined.row(row++) = coarse.image(k).positions.transpose();
5243 if (k == midpoint_segment)
5244 refined.row(row++) = midpoint_worst_position.transpose();
5245 }
5246 if (row == n + 1) {
5247 neb_config.initial_path = refined;
5248 neb_config.has_initial_path = true;
5249 neb_config.initial_rest_lengths.clear();
5250 active_n_images = n - 1;
5251 local_refined = true;
5252 std::cout << "[ocineb] midpoint of segment " << midpoint_segment
5253 << " inserted as an image; the band restarts from "
5254 << n + 1 << " images" << std::endl;
5255 }
5256 }
5257 if (!local_refined && result.neb_result.path &&
5258 result.neb_result.path->numImages() >= 3) {
5259 const NEBPath& coarse = *result.neb_result.path;
5260 // Where the band needs images is where the chord leak is
5261 // measured: the equidistribution of the leak over the converged
5262 // band gives the segment rest lengths, and the image count grows
5263 // by the O(h^2) law so that the measured leak at the ridge comes
5264 // down to the tolerance in one step (at most a tripling).
5265 const auto leak_report =
5266 detail::bandDiscretizationCertificateReport(
5267 coarse, neb_config.conv_tol, neb_config.band_leak_bound);
5268 const double ratio =
5269 (neb_config.band_leak_bound &&
5270 std::isfinite(leak_report.leak_max) &&
5271 neb_config.conv_tol > 0.0)
5272 ? leak_report.leak_max / neb_config.conv_tol
5273 : 1.0;
5274 const double factor =
5275 std::clamp(std::sqrt(std::max(ratio, 1.0)), 1.0, 3.0);
5276 const int n_interior = coarse.numImages() - 2;
5277 const int n_new_interior = std::max(
5278 n_interior + 2, static_cast<int>(std::ceil(
5279 static_cast<double>(n_interior) * factor)));
5280 const std::vector<double> rest =
5281 detail::chordLeakSpringRestLengths(coarse, neb_config.conv_tol);
5282 const EigenMatrix refined = detail::resamplePathByRestLengths(
5283 coarse, n_new_interior + 2, rest);
5284 if (refined.rows() == n_new_interior + 2) {
5285 neb_config.initial_path = refined;
5286 neb_config.has_initial_path = true;
5287 std::vector<double> chord(
5288 static_cast<std::size_t>(n_new_interior + 1));
5289 for (int k = 0; k + 1 < refined.rows(); ++k)
5290 chord[static_cast<std::size_t>(k)] =
5291 (refined.row(k + 1) - refined.row(k)).norm();
5292 neb_config.initial_rest_lengths =
5293 neb_config.hold_refined_spacing ? chord
5294 : std::vector<double>{};
5295 active_n_images = n_new_interior;
5296 local_refined = true;
5297 }
5298 }
5299 if (!local_refined) active_n_images *= 2;
5300 session.ensureSingletonForGlobal();
5301 struct CoarseCounts {
5302 int oracle_calls, endpoints, initial, outer, validation;
5303 int outer_iterations, refits, refreshes, dimer_calls, refinements;
5304 } coarse{result.neb_result.oracle_calls,
5305 result.neb_result.oracle_calls_endpoints,
5306 result.neb_result.oracle_calls_initial,
5307 result.neb_result.oracle_calls_outer,
5308 result.neb_result.oracle_calls_validation,
5309 result.neb_result.outer_iterations,
5310 result.neb_result.hyperparameter_refits,
5311 result.neb_result.fixed_theta_refreshes,
5312 result.dimer_oracle_calls,
5313 result.refinements};
5314 result = runOCINEB(oracle, initial, final_state, active_n_images,
5315 neb_config, oci_config, session);
5316 // The coarse attempt's oracle calls and iterations are part of
5317 // this search: fold them into the refined result so the ledger
5318 // reports them as band work rather than as an unexplained
5319 // remainder.
5320 result.neb_result.oracle_calls += coarse.oracle_calls;
5321 result.neb_result.oracle_calls_endpoints += coarse.endpoints;
5322 result.neb_result.oracle_calls_initial += coarse.initial;
5323 result.neb_result.oracle_calls_outer += coarse.outer;
5324 result.neb_result.oracle_calls_validation += coarse.validation;
5325 result.neb_result.outer_iterations += coarse.outer_iterations;
5326 result.neb_result.hyperparameter_refits += coarse.refits;
5327 result.neb_result.fixed_theta_refreshes += coarse.refreshes;
5328 result.dimer_oracle_calls += coarse.dimer_calls;
5329 result.refinements = coarse.refinements + 1;
5330 }
5331
5332 if (result.neb_result.stop_reason == GPNEBStopReason::WallClockLimit)
5333 return result;
5334 certifyOCINEBResult(result, oracle, initial, final_state, active_n_images,
5335 neb_config, oci_config, session);
5336 const bool claims =
5337 result.dimer_ran ? result.dimer_converged : result.neb_result.converged;
5338 // A deferred force stop belongs to the saddle. Another true stencil
5339 // here is the band measurement the hand-off just declined.
5340 if (neb_config.force_stop_certificate && claims && result.neb_result.path &&
5341 !result.neb_result.index_refused && !result.neb_result.index_checked &&
5342 !result.neb_result.force_stop_hand_off) {
5343 const int image = result.neb_result.max_energy_image;
5344 NEBPath& path = *result.neb_result.path;
5345 if (image > 0 && image < path.numImages() - 1) {
5346 const double move = neb_config.lbfgs_max_move > 0.0
5347 ? neb_config.lbfgs_max_move
5348 : neb_config.ci_stencil_step;
5349 const int budget =
5350 vibrationalIndexOuterBudget(neb_config, path.numImages());
5351 const auto decision = decideVibrationalIndex(
5352 path.image(image).positions, path.image(image).gradient,
5353 &session.atoms_config, &session.gp,
5354 path.image(image).posterior_variance,
5355 indexGateVarianceThreshold(session.gp.getSigma2()), move,
5357 &oracle, &neb_config.batch_oracle,
5358 neb_config.oracle_batch_chunk, neb_config.vibrational_stencil);
5359 applyVibrationalIndexDecision(result.neb_result, decision, budget);
5360 if (result.neb_result.index_continue) {
5361 GPNEBConfig warm = neb_config;
5362 warm.has_initial_path = true;
5363 warm.initial_path.resize(path.numImages(),
5364 path.image(0).positions.size());
5365 for (int i = 0; i < path.numImages(); ++i)
5366 warm.initial_path.row(i) =
5367 path.image(i).positions.transpose();
5368 warm.initial_rest_lengths.clear();
5369 warm.outer_budget_per_image = false;
5370 warm.band_refinement_max = 0;
5371 warm.max_outer_iter =
5372 std::max(1, budget - result.neb_result.outer_iterations);
5373 const int kept_calls = result.neb_result.oracle_calls;
5374 const int kept_outers = result.neb_result.outer_iterations;
5375 auto resumed =
5376 runOCINEB(oracle, initial, final_state, active_n_images,
5377 warm, oci_config, session);
5378 resumed.neb_result.oracle_calls += kept_calls;
5379 resumed.neb_result.oracle_calls_outer += kept_calls;
5380 resumed.neb_result.outer_iterations += kept_outers;
5381 resumed.neb_result.index_gate_true_calls +=
5382 result.neb_result.index_gate_true_calls;
5383 result = std::move(resumed);
5384 }
5385 result.dimer_converged =
5386 result.neb_result.converged && result.dimer_ran
5387 ? result.dimer_converged
5388 : result.neb_result.converged;
5389 if (result.neb_result.index_refused) result.dimer_converged = false;
5390 }
5391 }
5392 return result;
5393}
void certifyOCINEBResult(OCINEBResult &result, NEBOracle oracle, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int active_n_images, const GPNEBConfig &neb_config, const OCINEBConfig &oci_config, ActiveLearningSession &session)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
double first_attempt_wall_seconds
Definition GPNEB.h:502
double attempt_wall_seconds
Definition GPNEB.h:482

◆ saddleCertificateReport()

SaddleCertificateReport gpr::neb::saddleCertificateReport ( bool otherwise_certified,
bool stencil_measured,
bool force_stop_certified,
bool inconclusive )
inline

Definition at line 209 of file OracleStencil.h.

212{
213 if (stencil_measured && inconclusive && !force_stop_certified)
214 return {"unresolved", false};
215 if (otherwise_certified) return {"yes", true};
216 return {"no", false};
217}

◆ saddleForceMagnitude()

double gpr::neb::saddleForceMagnitude ( const Eigen::VectorXd & gradient)

Maximum atomic force for Cartesian systems, Euclidean norm for toy PESs.

Definition at line 25 of file NEBPath.cpp.

26{
27 const auto norm = gradient.size() % 3 == 0
30 return gpr::forceNorm(gradient, norm);
31}
double forceNorm(const Eigen::MatrixBase< Derived > &force, ConvergenceNormType norm)
Definition ForceNorm.h:45

◆ seedDimerModeFromForceStop()

bool gpr::neb::seedDimerModeFromForceStop ( gpr::Coord & orient,
const ForceStopHandoffStencil & handoff )

Replace orient's single row with the lowest handed mode when that mode matches the row length. Returns false when there is no mode.

Definition at line 468 of file VibrationalIndexGate.cpp.

470{
471 if (orient.rows() != 1 || handoff.lowest_modes.cols() < 1 ||
472 handoff.lowest_modes.rows() != orient.cols())
473 return false;
474 Eigen::VectorXd mode = handoff.lowest_modes.col(0);
475 if (!mode.allFinite() || !(mode.norm() > 0.0)) return false;
476 mode.normalize();
477 orient.row(0) = mode.transpose();
478 return true;
479}

◆ selectNextImage()

int gpr::neb::selectNextImage ( const std::vector< Eigen::VectorXd > & neb_forces,
const std::vector< ObservationVariance > & variances,
const std::vector< Eigen::VectorXd > & tangents,
const std::vector< bool > & evaluated,
AcquisitionType strategy,
double kappa = 1.0,
std::mt19937 * rng = nullptr )

Select the next unevaluated intermediate image by a per-image score.

This helper scores each image independently. It does not run the chain-level TPE, PS-BAX, or IMSPE selectors used by the GP-OIE outer loop.

MaxVariance force-variance trace MaxForce ||F_NEB|| UCB ||F_NEB|| + kappa * sigma_perp ThompsonSampling N(||F_NEB||, sigma_perp) if rng is set ExpectedImprovement energy variance IMSPE, TPE, PSBAX, PriorityCascade joint energy+gradient variance trace

Parameters
neb_forcesNEB forces at each intermediate image
variancesJoint energy-and-gradient variance at each intermediate image
tangentsUnit tangent vectors at each intermediate image
evaluatedWhich images have been evaluated this iteration
strategyAcquisition strategy to use
kappaUCB exploration weight. Used only for AcquisitionType::UCB.
rngRandom number generator (for Thompson sampling)
Returns
Index into the intermediate-image arrays (0-based), or -1 if every image is already evaluated

Definition at line 54 of file AcquisitionStrategy.cpp.

59{
60 int n = static_cast<int>(neb_forces.size());
61 int best_idx = -1;
62 double best_score = -std::numeric_limits<double>::infinity();
63
64 for (int i = 0; i < n; ++i) {
65 if (evaluated[i]) continue;
66
67 double score = 0.0;
68 double f_norm = neb_forces[i].norm();
69 const double joint_variance = jointVarianceTrace(variances[i]);
70 const double force_sigma =
71 perpendicularSigma(variances[i].gradient, tangents[i]);
72
73 switch (strategy) {
75 score = forceVarianceTrace(variances[i]);
76 break;
77
82 // Per-image fallback: score the joint energy+gradient
83 // variance trace. This function does not run chain-level
84 // TPE, PS-BAX, or IMSPE.
85 score = joint_variance;
86 break;
87
89 // EI resolves saddle energy, but its variance is a projection
90 // of the same joint posterior used by every acquisition.
91 score = nonNegativeFinite(variances[i].energy);
92 break;
93
95 score = f_norm;
96 break;
97
99 score = f_norm + kappa * force_sigma;
100 break;
101 }
102
104 // Sample force from GP posterior
105 if (rng && force_sigma > 0.0) {
106 std::normal_distribution<double> dist(f_norm, force_sigma);
107 score = dist(*rng);
108 } else {
109 score = f_norm;
110 }
111 break;
112 }
113 }
114
115 if (score > best_score) {
116 best_score = score;
117 best_idx = i;
118 }
119 }
120
121 // Fallback: pick first unevaluated
122 if (best_idx < 0) {
123 for (int i = 0; i < n; ++i) {
124 if (!evaluated[i]) {
125 best_idx = i;
126 break;
127 }
128 }
129 }
130
131 return best_idx;
132}
double perpendicularSigma(const Eigen::VectorXd &gradient_variance, const Eigen::VectorXd &tangent)
Compute perpendicular GP variance (variance orthogonal to path tangent).

◆ stencilDirectionalActions()

Eigen::MatrixXd gpr::neb::stencilDirectionalActions ( const CartesianOracleStencil & stencil)
inline

Central differences of the gradient along each stencil direction, one column per direction. Empty for an incomplete stencil.

Definition at line 141 of file OracleStencil.h.

143{
144 const Eigen::Index count = stencil.directions.cols();
145 if (!stencil.complete() || count == 0 ||
146 stencil.positions.cols() != 2 * count + 1 ||
147 stencil.observations.gradient.rows() != stencil.positions.cols())
148 return {};
149 Eigen::MatrixXd actions(stencil.positions.rows(), count);
150 for (Eigen::Index k = 0; k < count; ++k)
151 actions.col(k) = (stencil.observations.gradient.row(2 * k + 1) -
152 stencil.observations.gradient.row(2 * k + 2))
153 .transpose() /
154 (2.0 * stencil.displacement);
155 return actions;
156}
detail::OwnedImageState observations

◆ stencilHessianColumns()

Eigen::MatrixXd gpr::neb::stencilHessianColumns ( const CartesianOracleStencil & stencil)
inline

The stencil's Cartesian Hessian columns, column j the action along coordinate j (gpr::optim::hessianColumnsFromDirections about the measured center gradient). Empty for an incomplete stencil.

Definition at line 161 of file OracleStencil.h.

163{
164 const Eigen::MatrixXd actions = stencilDirectionalActions(stencil);
165 if (actions.size() == 0) return {};
167 stencil.positions.col(0),
168 stencil.observations.gradient.row(0).transpose(), stencil.directions,
169 actions);
170}
Eigen::MatrixXd stencilDirectionalActions(const CartesianOracleStencil &stencil)

◆ stencilIndexLabel()

const char * gpr::neb::stencilIndexLabel ( bool first_order,
bool higher_order )
inline

Definition at line 219 of file OracleStencil.h.

220{
221 if (first_order && !higher_order) return "first_order";
222 if (higher_order && !first_order) return "higher_order";
223 return "unresolved";
224}

◆ substrateStep()

Eigen::VectorXd gpr::neb::substrateStep ( const Eigen::MatrixXd & hessian,
const Eigen::VectorXd & force )
inline

One substrate step, H^{-1} force, from that factor.

Definition at line 23 of file SubstrateFactor.h.

25{
26 auto factor = factorSubstrate(hessian);
27 if (factor.info() != Eigen::Success) return {};
28 return factor.solve(force);
29}
Eigen::LLT< Eigen::MatrixXd > factorSubstrate(const Eigen::MatrixXd &hessian)

◆ testingHelpedModeCurvature()

double gpr::neb::testingHelpedModeCurvature ( )

Measured min-mode curvature of the latest helped burst in this process. Quiet NaN until a burst converges to a saddle.

Definition at line 49 of file OCINEBController.cpp.

50{
51 return helpedModeCurvatureSlot();
52}

◆ vibrationalIndexOuterBudget()

int gpr::neb::vibrationalIndexOuterBudget ( const GPNEBConfig & config,
int n_images )
nodiscard

Outer-iteration cap, including the per-image reading.

Definition at line 800 of file VibrationalIndexGate.cpp.

801{
802 if (config.outer_budget_per_image && n_images > 0) {
803 const long cap = static_cast<long>(config.max_outer_iter) * n_images;
804 return static_cast<int>(
805 std::min<long>(cap, std::numeric_limits<int>::max()));
806 }
807 return config.max_outer_iter;
808}

◆ writeCartesianOracleStencil()

void gpr::neb::writeCartesianOracleStencil ( const std::string & path,
const CartesianOracleStencil & stencil,
const std::vector< int > & atomic_numbers,
const std::array< double, 9 > & cell,
int oracle_calls,
const CartesianStencilRefinement * refinement = nullptr )
inline

Write measured gradients in eV/A without Hessian projection or mass weighting. Schema 1 is the central-difference stencil along the Cartesian axes. Schema 2 is that stencil plus the refinement probes and the bounds they support, so a later reader can reach the same index without another oracle call. Schema 3 adds directions, one row per stencil direction (rows 2k+1 and 2k+2 of the positions displace along row k), and may carry the schema 2 refinement block; it is written whenever the directions are not the Cartesian axes. Parent directories of path are created.

Definition at line 235 of file OracleStencil.h.

239{
240 const std::filesystem::path destination(path);
241 if (destination.has_parent_path() && !destination.parent_path().empty()) {
242 std::error_code mkdir_error;
243 std::filesystem::create_directories(destination.parent_path(),
244 mkdir_error);
245 if (mkdir_error)
246 throw std::runtime_error("cannot write Cartesian oracle stencil: " +
247 path + ": " + mkdir_error.message());
248 }
249 std::ofstream output(path);
250 output << std::setprecision(17);
251 const auto write_array = [&](Eigen::Index count, auto value) {
252 output << '[';
253 for (Eigen::Index i = 0; i < count; ++i) {
254 if (i) output << ',';
255 output << value(i);
256 }
257 output << ']';
258 };
259 const auto write_rows = [&](const Eigen::MatrixXd& matrix) {
260 output << '[';
261 for (Eigen::Index row = 0; row < matrix.rows(); ++row) {
262 if (row) output << ',';
263 write_array(matrix.cols(),
264 [&](auto col) { return matrix(row, col); });
265 }
266 output << ']';
267 };
268 const bool write_refinement =
269 refinement != nullptr && refinement->positions.rows() > 0 &&
270 refinement->positions.cols() == refinement->gradients.cols() &&
271 refinement->positions.rows() == refinement->gradients.rows();
272 const bool write_directions =
273 stencil.directions.size() > 0 &&
274 !(stencil.directions.rows() == stencil.directions.cols() &&
275 stencil.directions.isIdentity(0.0));
276 output << "{\"schema_version\":"
277 << (write_directions ? 3 : (write_refinement ? 2 : 1))
278 << ",\"complete\":" << (stencil.complete() ? "true" : "false")
279 << ",\"displacement_A\":" << stencil.displacement
280 << ",\"wall_s\":" << stencil.wall_seconds
281 << ",\"oracle_calls\":" << oracle_calls;
282 if (stencil.center_reused) output << ",\"center_reused\":true";
283 output << ",\"atomic_numbers\":";
284 write_array(atomic_numbers.size(),
285 [&](auto i) { return atomic_numbers[i]; });
286 output << ",\"cell_A\":";
287 write_array(cell.size(), [&](auto i) { return cell[i]; });
288 output << ",\"positions_A\":";
289 write_rows(stencil.positions.transpose());
290 if (write_directions) {
291 output << ",\"directions\":";
292 write_rows(stencil.directions.transpose());
293 }
294 output << ",\"energies_eV\":";
295 write_array(stencil.observations.energy.size(),
296 [&](auto i) { return stencil.observations.energy[i]; });
297 output << ",\"gradients_eV_per_A\":";
298 write_rows(stencil.observations.gradient);
299 if (write_refinement) {
300 output << ",\"refinement\":{\"positions_A\":";
301 write_rows(refinement->positions);
302 output << ",\"gradients_eV_per_A\":";
303 write_rows(refinement->gradients);
304 const char* index = stencilIndexLabel(refinement->first_order,
305 refinement->higher_order);
306 // A bound the refinement did not establish is infinite, and JSON
307 // has no token for that: it is written as null.
308 const auto write_bound = [&](const char* key, double value) {
309 output << ",\"" << key << "\":";
310 if (std::isfinite(value))
311 output << value;
312 else
313 output << "null";
314 };
315 write_bound("negative_upper", refinement->negative_upper);
316 write_bound("positive_lower", refinement->positive_lower);
317 write_bound("negative_pair_upper", refinement->negative_pair_upper);
318 output << ",\"index\":\"" << index << "\",\"first_order\":"
319 << (std::strcmp(index, "first_order") == 0 ? "true" : "false")
320 << ",\"higher_order\":"
321 << (std::strcmp(index, "higher_order") == 0 ? "true" : "false")
322 << '}';
323 }
324 output << "}\n";
325 output.close();
326 if (!output)
327 throw std::runtime_error("cannot write Cartesian oracle stencil: " +
328 path);
329}
const char * stencilIndexLabel(bool first_order, bool higher_order)

◆ writeCompositionTraceFile()

bool gpr::neb::writeCompositionTraceFile ( const std::string & path,
const std::vector< OuterIterCompositionTraceRecord > & records )
nodiscard

Definition at line 240 of file OuterIterCompositionTrace.cpp.

243{
244 std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
245 if (!ofs) return false;
246 ofs << formatCompositionTrace(records);
247 return static_cast<bool>(ofs);
248}

◆ writeForceStopHandoff()

void gpr::neb::writeForceStopHandoff ( const std::string & archive_dir,
const GPNEBResult & result )

Write the handed stencil where a following saddle reads it: the observation archive the saddle opens as its seed archive.

Definition at line 337 of file VibrationalIndexGate.cpp.

339{
340 if (archive_dir.empty() || !result.force_stop_hand_off) return;
341 std::ofstream out(archive_dir + "/force-stop-handoff.bin",
342 std::ios::binary);
343 if (!out) return;
344 // 0x46534832 carries the deferred flag and the lowest modes.
345 // 0x46534831 was positions and gradients only.
346 const int magic = 0x46534832;
347 const int dof = static_cast<int>(result.force_stop_positions.rows());
348 const int npts = static_cast<int>(result.force_stop_positions.cols());
349 const int nmodes =
350 result.force_stop_modes.rows() == result.force_stop_positions.rows()
351 ? static_cast<int>(result.force_stop_modes.cols())
352 : 0;
353 int flags = 0;
354 if (!result.force_stop_deferred && !result.force_stop_inconclusive &&
355 !result.force_stop_certified)
356 flags |= 1;
357 if (result.force_stop_inconclusive) flags |= 2;
358 if (result.force_stop_deferred) flags |= 4;
359 out.write(reinterpret_cast<const char*>(&magic), sizeof magic);
360 out.write(reinterpret_cast<const char*>(&dof), sizeof dof);
361 out.write(reinterpret_cast<const char*>(&npts), sizeof npts);
362 out.write(reinterpret_cast<const char*>(&nmodes), sizeof nmodes);
363 out.write(reinterpret_cast<const char*>(&result.force_stop_displacement),
364 sizeof result.force_stop_displacement);
365 out.write(reinterpret_cast<const char*>(&flags), sizeof flags);
366 if (npts > 0 && dof > 0) {
367 out.write(
368 reinterpret_cast<const char*>(result.force_stop_positions.data()),
369 sizeof(double) * result.force_stop_positions.size());
370 out.write(
371 reinterpret_cast<const char*>(result.force_stop_gradients.data()),
372 sizeof(double) * result.force_stop_gradients.size());
373 }
374 const int nenergy = static_cast<int>(result.force_stop_energies.size());
375 out.write(reinterpret_cast<const char*>(&nenergy), sizeof nenergy);
376 if (nenergy > 0)
377 out.write(
378 reinterpret_cast<const char*>(result.force_stop_energies.data()),
379 sizeof(double) * nenergy);
380 if (nmodes > 0)
381 out.write(reinterpret_cast<const char*>(result.force_stop_modes.data()),
382 sizeof(double) * static_cast<std::size_t>(dof * nmodes));
383}

Variable Documentation

◆ kCompositionTraceFormatVersion

int gpr::neb::kCompositionTraceFormatVersion = 1
inlineconstexpr

Bump when the on-disk golden format changes incompatibly.

Definition at line 81 of file OuterIterCompositionTrace.h.

◆ kMaxConsecutiveOracleFailures

int gpr::neb::kMaxConsecutiveOracleFailures = 8
inlineconstexpr

Consecutive band geometries at which the oracle may fail (raise, or return a non-finite energy or force) before the search stops with an error. Each failure is a rejected trial: the image keeps its last measured state, no row is recorded, and the band step shrinks.

Definition at line 226 of file GPNEB.h.

◆ kPeriodicBandFmax

double gpr::neb::kPeriodicBandFmax = 0.05
inlineconstexpr

Force tolerance of GPLocalBand.run, eV/Angstrom.

Definition at line 28 of file PeriodicBand.h.

◆ kPeriodicBandImages

int gpr::neb::kPeriodicBandImages = 8
inlineconstexpr

Images between the endpoints. GPLocalBand's constructor default.

Definition at line 25 of file PeriodicBand.h.

◆ kPeriodicBandMaxMove

double gpr::neb::kPeriodicBandMaxMove = 0.2
inlineconstexpr

Largest per-atom step of one band move, Angstrom. GPLocalBand's constructor default, wider than the gprn L-BFGS cap.

Definition at line 35 of file PeriodicBand.h.

◆ kPeriodicBandSteps

int gpr::neb::kPeriodicBandSteps = 1000
inlineconstexpr

Outer-iteration budget of GPLocalBand.run.

Definition at line 31 of file PeriodicBand.h.