Loading...
Searching...
No Matches
OCINEBController.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "OCINEBController.h"
6
7#include <Eigen/Dense>
8#include <algorithm>
9#include <chrono>
10#include <cmath>
11#include <iostream>
12#include <limits>
13#include <optional>
14#include <sstream>
15#include <stdexcept>
16#include <tuple>
17#include <utility>
18
20#include "SaddlePolish.h"
22
23#ifdef GPR_HAVE_MPI
24#include <mpi.h>
25#endif
26
27#include "../ml/PhaseTimers.h"
28#include "NEBOraclePotential.h"
29#include "RgMinMode.h"
30#include "RgsaddleClient.h"
31#include "gpr/AtomicDimer.h"
37
38namespace gpr {
39namespace neb {
40
41namespace {
42double& helpedModeCurvatureSlot()
43{
44 static double value = std::numeric_limits<double>::quiet_NaN();
45 return value;
46}
47} // namespace
48
50{
51 return helpedModeCurvatureSlot();
52}
53
54namespace detail {
55
56struct OracleNoiseUpdatePause {
57 explicit OracleNoiseUpdatePause(bool* enabled_in)
58 : enabled(enabled_in), previous(enabled_in ? *enabled_in : true)
59 {
60 if (enabled) *enabled = false;
61 }
62
63 ~OracleNoiseUpdatePause()
64 {
65 if (enabled) *enabled = previous;
66 }
67
68 bool* enabled = nullptr;
69 bool previous = true;
70};
71
72bool isLowerValidSaddleEnergy(double reference_saddle_energy,
73 double candidate_saddle_energy,
74 double reactant_energy, double product_energy)
75{
76 return std::isfinite(reference_saddle_energy) &&
77 std::isfinite(candidate_saddle_energy) &&
78 candidate_saddle_energy < reference_saddle_energy &&
79 isTruePesSaddleEnergyCandidate(candidate_saddle_energy,
80 reactant_energy, product_energy);
81}
82
83MmfRecoveryPhaseEvidence recordedMmfRecoveryPhaseEvidence(
84 const atmd::AtomicDimer::DimerPhaseRecord& phase, double energy_zero,
85 Eigen::Index expected_dimension)
86{
87 MmfRecoveryPhaseEvidence evidence;
88 if (!phase.oracle_certified || phase.gradient.rows() != 1 ||
89 phase.gradient.cols() != expected_dimension ||
90 !phase.gradient.allFinite() || !std::isfinite(phase.energy) ||
91 !std::isfinite(energy_zero)) {
92 return evidence;
93 }
94 evidence.energy = phase.energy + energy_zero;
95 if (!std::isfinite(evidence.energy)) return evidence;
96 evidence.gradient = phase.gradient.row(0).transpose();
97 evidence.oracle_certified = true;
98 return evidence;
99}
100
101void appendAcceptedMmfRecoveryObservation(ActiveLearningSession& session,
102 int image_idx, const Image& accepted)
103{
104 if (image_idx < 0 || !accepted.evaluated ||
105 accepted.positions.size() == 0 || accepted.gradient.size() == 0 ||
106 accepted.positions.size() != accepted.gradient.size() ||
107 !accepted.positions.allFinite() || !accepted.gradient.allFinite() ||
108 !std::isfinite(accepted.energy)) {
109 return;
110 }
111 session.appendCurrentChainObservation(
112 image_idx, accepted.positions, accepted.energy, accepted.gradient,
115}
116
117MmfRecoveryAcceptanceDecision classifyMmfRecovery(
118 double pre_force, double recovery_force, double recovery_displacement,
119 double max_displacement, double acceptance_force_threshold,
120 bool keep_force_improving_burst, double reference_saddle_energy,
121 double candidate_saddle_energy, double reactant_energy,
122 double product_energy, bool candidate_saddle_certified,
123 bool candidate_path_mode_certified,
124 bool candidate_measured_descent_certified)
125{
126 MmfRecoveryAcceptanceDecision decision;
127 if (!std::isfinite(pre_force) || !std::isfinite(recovery_force)) {
128 return decision;
129 }
130 decision.finite_input = true;
131 decision.force_improves = recovery_force < pre_force;
132 decision.threshold_limited = acceptance_force_threshold > 0.0 &&
133 std::isfinite(acceptance_force_threshold);
134 decision.threshold_passed = decision.threshold_limited &&
135 recovery_force < acceptance_force_threshold;
136 // Recovery handbacks move the chain geometry, so they obey the same EMD
137 // trust ball used for committing dimer observations.
138 decision.has_displacement_trust =
139 std::isfinite(max_displacement) && max_displacement > 0.0;
140 if (decision.has_displacement_trust) {
141 decision.within_displacement_trust =
142 std::isfinite(recovery_displacement) &&
143 recovery_displacement <= max_displacement;
144 }
145 decision.uncertified_energy_descent =
146 !candidate_saddle_certified && std::isfinite(reference_saddle_energy) &&
147 std::isfinite(candidate_saddle_energy) &&
148 candidate_saddle_energy < reference_saddle_energy;
149 decision.measured_path_continuation = decision.force_improves &&
150 candidate_path_mode_certified &&
151 candidate_measured_descent_certified;
152 decision.measured_trust_bounded_progress =
153 decision.force_improves && candidate_measured_descent_certified &&
154 decision.has_displacement_trust && decision.within_displacement_trust;
155 // A lower-energy nonstationary phase is usable only as local continuation
156 // evidence: its true force improves, the dimer mode remains aligned with
157 // the path tangent, and either the geometry stays in the original EMD
158 // trust ball or every accepted measured descent renews the trust center.
159 // The outer path refreshes before another MMF lease consumes this shoulder.
160 const bool trusted_path_aligned_progress =
161 decision.force_improves && candidate_path_mode_certified &&
162 ((decision.has_displacement_trust &&
163 decision.within_displacement_trust) ||
164 decision.measured_path_continuation);
165 if (decision.uncertified_energy_descent && !trusted_path_aligned_progress &&
166 !decision.measured_trust_bounded_progress) {
167 return decision;
168 }
169 if (decision.has_displacement_trust) {
170 if (!decision.within_displacement_trust &&
171 !decision.measured_path_continuation) {
172 return decision;
173 }
174 decision.lower_valid_saddle_energy =
175 candidate_saddle_certified &&
176 isLowerValidSaddleEnergy(reference_saddle_energy,
177 candidate_saddle_energy, reactant_energy,
178 product_energy);
179 if (!decision.force_improves) {
180 // A dimer translation along a negative mode can raise the NEB
181 // force while staying on the ridge. That step is the dimer
182 // method. Uncertified energy descent (lower than the current
183 // saddle, not force-certified) is the off-ridge walk.
184 const bool on_ridge_min_mode =
185 !decision.uncertified_energy_descent &&
186 isTruePesSaddleEnergyCandidate(candidate_saddle_energy,
187 reactant_energy, product_energy);
188 decision.accepted =
189 decision.lower_valid_saddle_energy || on_ridge_min_mode;
190 return decision;
191 }
192 if (!keep_force_improving_burst && decision.threshold_limited &&
193 !decision.threshold_passed) {
194 decision.accepted = decision.lower_valid_saddle_energy;
195 return decision;
196 }
197 // A saddle on the minimum energy path lies above both connected
198 // minima; a recovery candidate whose energy has fallen below an
199 // endpoint has walked the climbing image off the ridge into a
200 // basin, not toward a transition state. Force improvement alone
201 // was admitting it (Baker 02 at np16: the alignment-termination
202 // recovery advanced the CI to energy -22.11 below the reactant,
203 // reporting a negative barrier, and one MPI rank aborted inside
204 // the descent). The endpoint floor is the same true-PES test the
205 // burst acceptance already applies; an unevaluated candidate
206 // energy (non-finite) is left to the force/trust gates.
207 if (std::isfinite(candidate_saddle_energy) &&
208 std::isfinite(reactant_energy) && std::isfinite(product_energy) &&
209 !isTruePesSaddleEnergyCandidate(candidate_saddle_energy,
210 reactant_energy, product_energy)) {
211 decision.accepted = false;
212 return decision;
213 }
214 decision.accepted = true;
215 return decision;
216 }
217 // Without a geometry trust bound, recovery must beat the adaptive
218 // near-saddle bar so partial force improvements cannot walk the CI
219 // off-ridge. keep_force_improving only relaxes the threshold gate inside
220 // an explicit EMD ball.
221 (void)keep_force_improving_burst;
222 if (!decision.force_improves) {
223 return decision;
224 }
225 if (!decision.threshold_limited) {
226 return decision;
227 }
228 // Same endpoint floor as the trust-bounded branch: a below-endpoint
229 // candidate is off the MEP, not a transition state.
230 if (std::isfinite(candidate_saddle_energy) &&
231 std::isfinite(reactant_energy) && std::isfinite(product_energy) &&
232 !isTruePesSaddleEnergyCandidate(candidate_saddle_energy,
233 reactant_energy, product_energy)) {
234 return decision;
235 }
236 decision.accepted = decision.threshold_passed;
237 return decision;
238}
239
240bool shouldAcceptMmfRecovery(
241 double pre_force, double recovery_force, double recovery_displacement,
242 double max_displacement, double acceptance_force_threshold,
243 bool keep_force_improving_burst, double reference_saddle_energy,
244 double candidate_saddle_energy, double reactant_energy,
245 double product_energy, bool candidate_saddle_certified,
246 bool candidate_path_mode_certified,
247 bool candidate_measured_descent_certified)
248{
249 return classifyMmfRecovery(
250 pre_force, recovery_force, recovery_displacement,
251 max_displacement, acceptance_force_threshold,
252 keep_force_improving_burst, reference_saddle_energy,
253 candidate_saddle_energy, reactant_energy, product_energy,
254 candidate_saddle_certified, candidate_path_mode_certified,
255 candidate_measured_descent_certified)
256 .accepted;
257}
258
259bool shouldRejectUncertifiedMmfRecoveryHandback(double recovery_force,
260 double recovery_displacement,
261 double max_displacement,
262 double force_tolerance)
263{
264 if (!std::isfinite(recovery_force) || recovery_force <= 0.0) {
265 return false;
266 }
267 if (!std::isfinite(force_tolerance) || force_tolerance <= 0.0) {
268 return false;
269 }
270 if (!std::isfinite(max_displacement) || max_displacement <= 0.0) {
271 return false;
272 }
273 if (!std::isfinite(recovery_displacement) ||
274 recovery_displacement <= max_displacement) {
275 return false;
276 }
277 // Outside the EMD trust ball a recovery phase is directional evidence, not
278 // a saddle certificate. At convergence-scale force it can anchor the chain
279 // to an off-path saddle without the dimer angle certificate.
280 return (recovery_force - force_tolerance) <= force_tolerance;
281}
282
283bool isConvergenceScaleForce(double force, double force_tolerance)
284{
285 if (!std::isfinite(force) || force <= 0.0) return false;
286 if (!std::isfinite(force_tolerance) || force_tolerance <= 0.0) {
287 return false;
288 }
289 return (force - force_tolerance) <= force_tolerance;
290}
291
292double effectiveMmfRecoveryDisplacementCap(double configured_cap,
293 double left_spacing,
294 double right_spacing)
295{
296 if (std::isfinite(configured_cap) && configured_cap > 0.0) {
297 return configured_cap;
298 }
299
300 double cap = std::numeric_limits<double>::infinity();
301 if (std::isfinite(left_spacing) && left_spacing > 0.0) {
302 cap = std::min(cap, left_spacing);
303 }
304 if (std::isfinite(right_spacing) && right_spacing > 0.0) {
305 cap = std::min(cap, right_spacing);
306 }
307 return std::isfinite(cap) ? cap : configured_cap;
308}
309
310bool shouldRejectUncertifiedHelpedDisplacement(bool dimer_converged,
311 bool helped_angle_certified,
312 double helped_displacement,
313 double max_displacement)
314{
315 if (!dimer_converged || helped_angle_certified) return false;
316 if (!std::isfinite(max_displacement) || max_displacement <= 0.0) {
317 return false;
318 }
319 return !std::isfinite(helped_displacement) ||
320 helped_displacement > max_displacement;
321}
322
323bool shouldRejectForceOnlyHelpedBelowEndpoints(bool dimer_converged,
324 bool helped_angle_certified,
325 double dimer_final_energy,
326 double reactant_energy,
327 double product_energy)
328{
329 // Force-only Helped with energy below either endpoint is a side saddle or
330 // below-endpoint stationary point. Angle-certified Helped is governed by
331 // its angle certificate and the downstream path certificate.
332 if (!dimer_converged || helped_angle_certified) return false;
333 return !isTruePesSaddleEnergyCandidate(dimer_final_energy, reactant_energy,
334 product_energy);
335}
336
337std::string forceOnlyHelpedBelowEndpointDiagnostic(double dimer_final_energy,
338 double reactant_energy,
339 double product_energy)
340{
341 std::ostringstream os;
342 const double endpoint_floor = std::max(reactant_energy, product_energy);
343 os << "force-only below path endpoints: E=" << dimer_final_energy
344 << ", reactant=" << reactant_energy << ", product=" << product_energy
345 << ", endpoint_floor=" << endpoint_floor
346 << ", forward_barrier=" << (dimer_final_energy - reactant_energy)
347 << ", reverse_barrier=" << (dimer_final_energy - product_energy);
348 return os.str();
349}
350
351std::string trustedRecoveryAdvanceDiagnostic(
353 int recovery_phase, std::size_t phase_count, double curvature,
354 double recovery_baseline, double recovery_force, double raw_pre_force,
355 double raw_force, double reference_energy, double candidate_energy,
356 double reactant_energy, double product_energy, bool saddle_certified)
357{
358 const bool lower_valid_energy =
359 std::isfinite(reference_energy) && std::isfinite(candidate_energy) &&
360 candidate_energy < reference_energy &&
361 isTruePesSaddleEnergyCandidate(candidate_energy, reactant_energy,
362 product_energy);
363 const char* termination = "relaxation handback";
364 switch (termination_reason) {
366 termination = "force-converged termination";
367 break;
369 termination = "true-PES non-descent handback";
370 break;
372 termination = "degenerate-probe handback";
373 break;
375 termination = "measured index-zero handback";
376 break;
378 termination = "uninformative-rotation handback";
379 break;
381 termination = "alignment termination";
382 break;
384 termination = "interatomic-collapse termination";
385 break;
387 termination = "invalid-atoms-configuration termination";
388 break;
390 termination = "oracle-budget termination";
391 break;
393 termination = "wall-clock limit termination";
394 break;
396 termination = "invalid-parameters termination";
397 break;
399 termination = "step-budget termination";
400 break;
402 termination = "uncertified-force termination";
403 break;
405 break;
406 }
407 std::ostringstream os;
408 os << termination << ", advanced CI to trusted negative-curvature phase "
409 << recovery_phase << "/" << phase_count << " (curv = " << curvature
410 << ", recovery force " << recovery_baseline << " -> " << recovery_force
411 << ", raw force " << raw_pre_force << " -> " << raw_force << ", "
412 << (saddle_certified ? "saddle energy " : "candidate energy ")
413 << reference_energy << " -> " << candidate_energy
414 << ", lower_valid_energy=" << (lower_valid_energy ? 1 : 0)
415 << ", saddle_certified=" << (saddle_certified ? 1 : 0) << ")";
416 return os.str();
417}
418
423double mmfRecoveryForceBaseline(double pre_neb_force, double pre_raw_force)
424{
425 double baseline = 0.0;
426 bool any = false;
427 if (std::isfinite(pre_neb_force) && pre_neb_force > 0.0) {
428 baseline = pre_neb_force;
429 any = true;
430 }
431 if (std::isfinite(pre_raw_force) && pre_raw_force > 0.0) {
432 baseline = any ? std::max(baseline, pre_raw_force) : pre_raw_force;
433 any = true;
434 }
435 return any ? baseline : std::numeric_limits<double>::infinity();
436}
437
438int chooseMmfRecoveryPhase(const std::vector<MmfRecoveryCandidate>& candidates,
439 double pre_force, double max_displacement,
440 double acceptance_force_threshold,
441 bool keep_force_improving_burst,
442 double reference_saddle_energy,
443 double reactant_energy, double product_energy,
444 MmfRecoverySelectionStats* stats,
445 bool allow_directional_out_of_trust_recovery)
446{
447 int best_phase = -1;
448 int best_acceptance_rank = std::numeric_limits<int>::max();
449 int best_certificate_rank = std::numeric_limits<int>::max();
450 double best_energy = std::numeric_limits<double>::infinity();
451 double best_force = std::numeric_limits<double>::infinity();
452 double best_curvature = std::numeric_limits<double>::infinity();
453 for (const MmfRecoveryCandidate& candidate: candidates) {
454 if (!std::isfinite(candidate.curvature) ||
455 !(candidate.curvature < 0.0)) {
456 continue;
457 }
458 const MmfRecoveryAcceptanceDecision decision = classifyMmfRecovery(
459 pre_force, candidate.recovery_force, candidate.displacement,
460 max_displacement, acceptance_force_threshold,
461 keep_force_improving_burst, reference_saddle_energy,
462 candidate.saddle_energy, reactant_energy, product_energy,
463 candidate.saddle_certified, candidate.path_mode_certified,
464 candidate.measured_descent_certified);
465 if (stats) {
466 ++stats->negative_curvature_candidates;
467 if (!decision.finite_input) {
468 ++stats->invalid_candidates;
469 }
470 if (decision.force_improves) {
471 ++stats->force_improving_candidates;
472 }
473 if (isLowerValidSaddleEnergy(reference_saddle_energy,
474 candidate.saddle_energy,
475 reactant_energy, product_energy)) {
476 if (candidate.saddle_certified) {
477 ++stats->certified_lower_energy_candidates;
478 } else {
479 ++stats->uncertified_lower_energy_candidates;
480 }
481 }
482 if (decision.uncertified_energy_descent) {
483 ++stats->uncertified_energy_descent_candidates;
484 }
485 if (decision.has_displacement_trust &&
486 !decision.within_displacement_trust) {
487 ++stats->out_of_trust_candidates;
488 }
489 }
490 const bool directional_out_of_trust =
491 allow_directional_out_of_trust_recovery && !decision.accepted &&
492 decision.force_improves && !decision.uncertified_energy_descent &&
493 decision.has_displacement_trust &&
494 !decision.within_displacement_trust;
495 if (stats && directional_out_of_trust) {
496 ++stats->directional_out_of_trust_candidates;
497 }
498 const int acceptance_rank =
499 decision.accepted ? 0 : (directional_out_of_trust ? 1 : -1);
500 if (stats) {
501 if (decision.force_improves && !decision.accepted) {
502 if (decision.has_displacement_trust &&
503 decision.within_displacement_trust &&
504 decision.threshold_limited && !decision.threshold_passed) {
505 ++stats->threshold_rejected_candidates;
506 } else if (!decision.has_displacement_trust) {
507 ++stats->no_trust_threshold_rejected_candidates;
508 }
509 }
510 }
511 if (acceptance_rank < 0) {
512 continue;
513 }
514 if (stats) ++stats->accepted_candidates;
515 const int certificate_rank = candidate.saddle_certified ? 0 : 1;
516 const bool candidate_has_energy =
517 std::isfinite(candidate.saddle_energy);
518 const bool best_has_energy = std::isfinite(best_energy);
519 bool prefer_candidate = false;
520 if (acceptance_rank != best_acceptance_rank) {
521 prefer_candidate = acceptance_rank < best_acceptance_rank;
522 } else if (certificate_rank != best_certificate_rank) {
523 prefer_candidate = certificate_rank < best_certificate_rank;
524 } else if (candidate.saddle_certified) {
525 if (candidate_has_energy != best_has_energy) {
526 prefer_candidate = candidate_has_energy;
527 } else if (candidate_has_energy &&
528 candidate.saddle_energy != best_energy) {
529 prefer_candidate = candidate.saddle_energy < best_energy;
530 } else if (candidate.recovery_force != best_force) {
531 prefer_candidate = candidate.recovery_force < best_force;
532 } else {
533 prefer_candidate = candidate.curvature < best_curvature;
534 }
535 } else if (candidate.recovery_force != best_force) {
536 prefer_candidate = candidate.recovery_force < best_force;
537 } else if (candidate_has_energy != best_has_energy) {
538 prefer_candidate = candidate_has_energy;
539 } else if (candidate_has_energy &&
540 candidate.saddle_energy != best_energy) {
541 prefer_candidate = candidate.saddle_energy < best_energy;
542 } else {
543 prefer_candidate = candidate.curvature < best_curvature;
544 }
545 // Trust gates decide whether a phase is usable. Within one trust tier,
546 // a certified saddle outranks an uncertified shoulder. Certified
547 // saddles retain the lower-energy branch; trajectory shoulders rank by
548 // true residual because their energies are not saddle energies.
549 if (prefer_candidate) {
550 best_acceptance_rank = acceptance_rank;
551 best_certificate_rank = certificate_rank;
552 best_phase = candidate.phase;
553 best_energy = candidate.saddle_energy;
554 best_force = candidate.recovery_force;
555 best_curvature = candidate.curvature;
556 }
557 }
558 return best_phase;
559}
560
561double successThresholdAfterMmf(double handoff_force, double mmf_force,
562 double baseline_threshold)
563{
564 if (!std::isfinite(handoff_force) || handoff_force <= 0.0)
565 return baseline_threshold;
566 if (!std::isfinite(mmf_force) || mmf_force <= 0.0 ||
567 mmf_force >= handoff_force)
568 return baseline_threshold;
569
570 double threshold = handoff_force;
571 if (std::isfinite(baseline_threshold) && baseline_threshold > 0.0)
572 threshold = std::min(threshold, baseline_threshold);
573 return threshold;
574}
575
576double rejectedMmfBackoffThreshold(double current_force, double force_tolerance,
577 double baseline_threshold)
578{
579 if (!std::isfinite(current_force) || current_force <= 0.0)
580 return baseline_threshold;
581 if (!std::isfinite(force_tolerance) || force_tolerance <= 0.0 ||
582 current_force <= force_tolerance)
583 return baseline_threshold;
584
585 // After reject, require a substantial residual drop before re-lease.
586 // Use half the failed force, floored at the geometric mean, so eOn-style
587 // progress is still required.
588 const double geo = std::sqrt(current_force * force_tolerance);
589 double threshold = std::max(geo, 0.5 * current_force);
590 if (std::isfinite(baseline_threshold) && baseline_threshold > 0.0)
591 threshold = std::min(threshold, baseline_threshold);
592 return threshold;
593}
594
595MmfInformationGate advanceMmfInformationGateOnSurrogateChange(
596 MmfInformationGate gate, const MmfSurrogateFingerprint& surrogate_now,
597 const MmfSurrogateFingerprint& surrogate_at_last_reject,
598 bool* refresh_snapshot)
599{
600 if (refresh_snapshot) *refresh_snapshot = false;
601 if (gate == MmfInformationGate::Open) return gate;
602 if (gate == MmfInformationGate::AwaitingActionChange) return gate;
603 if (!mmfSurrogateChanged(surrogate_now, surrogate_at_last_reject)) {
604 return gate;
605 }
606 // One subsequent surrogate change reopens the lease.
607 if (gate == MmfInformationGate::AwaitingFirstTrainingGrowth) {
608 return MmfInformationGate::Open;
609 }
610 return gate;
611}
612
613bool mmfSurrogateChanged(
614 const MmfSurrogateFingerprint& surrogate_now,
615 const MmfSurrogateFingerprint& surrogate_at_last_reject)
616{
617 return surrogate_now != surrogate_at_last_reject;
618}
619
620bool mmfPosteriorActionChanged(
621 const MmfPosteriorActionFingerprint& action_now,
622 const MmfPosteriorActionFingerprint& action_at_last_reject)
623{
624 if (action_now.surrogate.owner != action_at_last_reject.surrogate.owner) {
625 return true;
626 }
627 const auto& current = action_now.action;
628 const auto& rejected = action_at_last_reject.action;
629 if (!current.valid || !rejected.valid) return false;
630 const auto valid_geometry = [](const gpr::Coord& positions) {
631 return positions.rows() == 1 && positions.cols() > 0 &&
632 positions.allFinite();
633 };
634 if ((current.trial_positions.size() > 0 &&
635 !valid_geometry(current.trial_positions)) ||
636 (rejected.trial_positions.size() > 0 &&
637 !valid_geometry(rejected.trial_positions)))
638 return false;
639 // Releasing a rejected action requires new geometry at the observation
640 // admission scale. Inner dimer stagnation uses floating-point resolution.
641 if (valid_geometry(current.trial_positions) &&
642 valid_geometry(rejected.trial_positions) &&
643 !positionsCoincide(current.trial_positions.row(0).transpose(),
644 rejected.trial_positions.row(0).transpose()))
645 return true;
646
647 if (current.termination != rejected.termination ||
648 current.proposal_action != rejected.proposal_action ||
649 current.residual_action != rejected.residual_action ||
650 current.force_norm != rejected.force_norm) {
651 return true;
652 }
653
654 if (std::isfinite(current.curvature) && std::isfinite(rejected.curvature) &&
655 std::signbit(current.curvature) != std::signbit(rejected.curvature)) {
656 return true;
657 }
658 if (current.termination ==
660 return false;
661 }
662
663 if (current.mode.size() == 0 ||
664 current.mode.size() != rejected.mode.size() ||
665 !current.mode.allFinite() || !rejected.mode.allFinite()) {
666 return false;
667 }
668 const double current_norm = current.mode.norm();
669 const double rejected_norm = rejected.mode.norm();
670 if (!(std::isfinite(current_norm) && current_norm > 0.0 &&
671 std::isfinite(rejected_norm) && rejected_norm > 0.0 &&
672 std::isfinite(current.rotation_tolerance) &&
673 current.rotation_tolerance > 0.0 &&
674 std::isfinite(rejected.rotation_tolerance) &&
675 rejected.rotation_tolerance > 0.0)) {
676 return false;
677 }
678 const double alignment =
679 std::clamp(std::abs(gpr::field::flatDot(current.mode, rejected.mode) /
680 (current_norm * rejected_norm)),
681 0.0, 1.0);
682 const double angle = std::acos(alignment);
683 const double rotation_tolerance =
684 std::min(current.rotation_tolerance, rejected.rotation_tolerance);
685 return angle > rotation_tolerance;
686}
687
688bool shouldSuppressMmfUntilTrainingGrows(MmfInformationGate gate)
689{
690 return gate != MmfInformationGate::Open;
691}
692
693double mmfThresholdForce(double neb_force, double raw_force)
694{
695 if (std::isfinite(neb_force) && neb_force > 0.0) return neb_force;
696 if (std::isfinite(raw_force) && raw_force > 0.0) return raw_force;
697 return neb_force;
698}
699
700bool ciPosteriorConfident(const NEBPath& path, int ci_idx, double kappa)
701{
702 (void)kappa;
703 // Pairwise Bayes risk for "image i is not the band maximum":
704 // risk(i)=sum_j P(E_j >= E_i), using the Gaussian marginal difference
705 // E_i - E_j ~ N(mu_i - mu_j, var_i + var_j). The union bound makes
706 // risk(i) an upper bound on the posterior probability that any challenger
707 // beats image i, so risk(i) < 1/2 is a posterior-majority handover
708 // certificate. The decision is invariant to energy zero shifts and
709 // positive energy-unit rescaling.
710 if (ci_idx <= 0 || ci_idx >= path.numImages() - 1) return false;
711 const auto posterior_risk = [&](int idx) -> double {
712 if (idx <= 0 || idx >= path.numImages() - 1) {
713 return std::numeric_limits<double>::infinity();
714 }
715 const auto& image_i = path.image(idx);
716 const double e_i = image_i.energy;
717 const double v_i = image_i.posterior_variance;
718 if (!std::isfinite(e_i) || !std::isfinite(v_i) || v_i < 0.0) {
719 return std::numeric_limits<double>::infinity();
720 }
721 double risk = 0.0;
722 for (int j = 1; j < path.numImages() - 1; ++j) {
723 if (j == idx) continue;
724 const auto& image_j = path.image(j);
725 const double p = oie::gaussianExceedanceProbability(
726 e_i, v_i, image_j.energy, image_j.posterior_variance);
727 if (!std::isfinite(p)) return p;
728 risk += p;
729 }
730 return risk;
731 };
732 const double ci_risk = posterior_risk(ci_idx);
733 if (!std::isfinite(ci_risk)) return false;
734 constexpr double binary_bayes_decision_boundary = 0.5;
735 if (!(ci_risk < binary_bayes_decision_boundary)) return false;
736 double best_risk = ci_risk;
737 for (int i = 1; i < path.numImages() - 1; ++i) {
738 if (i == ci_idx) continue;
739 best_risk = std::min(best_risk, posterior_risk(i));
740 }
741 return ci_risk <=
742 std::nextafter(best_risk, std::numeric_limits<double>::infinity());
743}
744
745bool isPrematureForceOnlyHelped(bool is_helped_status, bool force_certified,
746 bool helped_angle_certified,
747 int ci_stable_outer_count,
748 bool helped_negative_curvature)
749{
750 if (!is_helped_status || !force_certified) return false;
751 if (helped_angle_certified) return false;
752 // Non-saddle force convergence (non-negative final curvature) locks Baker
753 // 12 on a false high critical point (~4.58 eV vs 3.17). Require a
754 // negative-curvature min-mode even when omega is not fully certified.
755 if (!helped_negative_curvature) return true;
756 // Same-outer CI activation (count==0): restoring blocks early false lock
757 // while allowing force-only Helped once CI was already active at outer
758 // start (passJ greens 05/06/11).
759 return ci_stable_outer_count < 1;
760}
761
762bool forceOnlyHelpedPathCertified(bool helped_angle_certified, double alignment,
763 double alignment_cos_tol)
764{
765 if (helped_angle_certified) return true;
766 if (!std::isfinite(alignment) || !std::isfinite(alignment_cos_tol)) {
767 return false;
768 }
769 const double a = std::abs(alignment);
770 if (a > 1.0 || alignment_cos_tol < 0.0 || alignment_cos_tol > 1.0) {
771 return false;
772 }
773 // Cosine gate: |v_min · tau| >= cos_tol (paper 0.85-0.9; surrogate 0.3).
774 // Squared power would require |a| >= sqrt(0.3)≈0.55 at cos_tol=0.3 and
775 // rejected force-only Helped with |a|~0.40 that still tracks the band
776 // (Baker 02 path-cert thrash on a wrong high barrier).
777 return a >= alignment_cos_tol;
778}
779
780bool shouldSearchMmfRecoveryPortfolio(bool dimer_converged,
781 bool helped_ran_away,
782 bool helped_path_certified,
783 bool found_saddle_mode)
784{
785 if (!found_saddle_mode) return false;
786 if (!dimer_converged) return true;
787 return !helped_ran_away && !helped_path_certified;
788}
789
790bool mmfForceCertifiedForConvergence(double dimer_force, double band_force,
791 double force_tolerance)
792{
793 if (!std::isfinite(force_tolerance) || force_tolerance <= 0.0) {
794 return false;
795 }
796 const double achieved_force =
797 (std::isfinite(dimer_force) && dimer_force > 0.0) ? dimer_force
798 : band_force;
799 return std::isfinite(achieved_force) && achieved_force < force_tolerance;
800}
801
802bool mmfBurstConvergedAfterAcceptance(MMFStatus status, bool force_certified,
803 bool helped_angle_certified,
804 double final_mode_curvature,
805 bool helped_path_certified)
806{
807 // Angle-certified Helped is a saddle certificate.
808 if (helped_angle_certified) return true;
809 // Force-only Helped can update the chain geometry, but terminal
810 // convergence requires a path certificate. Recovery handbacks use force
811 // certification plus strictly negative min-mode curvature.
812 if (status == MMFStatus::Helped && !helped_path_certified) return false;
813 const bool negative_mode_curvature =
814 std::isfinite(final_mode_curvature) && final_mode_curvature < 0.0;
815 return force_certified && negative_mode_curvature;
816}
817
818bool applyDimerSaddleSummary(GPNEBResult& result, int dimer_saddle_image_idx)
819{
820 if (!result.path) return false;
821 if (dimer_saddle_image_idx <= 0 ||
822 dimer_saddle_image_idx >= result.path->numImages() - 1) {
823 return false;
824 }
825 const auto& saddle = result.path->image(dimer_saddle_image_idx);
826 const auto& reactant = result.path->image(0);
827 const auto& product = result.path->image(result.path->numImages() - 1);
828 if (!saddle.evaluated || !std::isfinite(saddle.energy) ||
829 !std::isfinite(reactant.energy) || !std::isfinite(product.energy)) {
830 return false;
831 }
832 // Keep the band's own pair before the refined saddle replaces it, so
833 // both stages can be reported. First refinement wins: later ones
834 // would record an already-refined saddle as the band's.
835 if (!std::isfinite(result.ci_barrier_energy)) {
836 result.ci_barrier_energy = result.barrier_energy;
837 result.ci_reverse_barrier_energy = result.reverse_barrier_energy;
838 }
839 result.max_energy_image = dimer_saddle_image_idx;
840 result.barrier_energy = saddle.energy - reactant.energy;
841 result.reverse_barrier_energy = saddle.energy - product.energy;
842 return true;
843}
844
845bool shouldPureLockAfterMmfReject(MMFStatus status, bool force_improved,
846 bool adaptive_threshold_seeded,
847 MMFRejectKind reject_kind)
848{
849 return shouldPureLockAfterMmfReject(status, force_improved,
850 /*trusted_recovery_advanced=*/false,
851 adaptive_threshold_seeded, reject_kind);
852}
853
854bool shouldPureLockAfterMmfReject(MMFStatus status, bool force_improved,
855 bool trusted_recovery_advanced,
856 bool adaptive_threshold_seeded,
857 MMFRejectKind reject_kind)
858{
859 if (!adaptive_threshold_seeded) return false;
860 if (status == MMFStatus::Helped) return false;
861 if (trusted_recovery_advanced) return false;
862 if (reject_kind == MMFRejectKind::ForceOnlyBelowEndpoint) return false;
863 // Path-certificate rejects restore the band CI without changing residual.
864 // Pure-locking them freezes MMF after a single orthogonal min-mode (Baker
865 // 02: alignment~0 under thr, then pure_lock+rejected_seed for 100 outers).
866 // Keep the rejected-seed geometry guard; do not hard-lock the lease.
867 if (reject_kind == MMFRejectKind::UncertifiedPath) return false;
868 // Recovery portfolio exhausted after true-PES scoring: soft-block + seed
869 // geometry + exhausted_recovery gate; pure-lock freezes re-lease above thr
870 // (Baker 05: 4 uncertified phases → pure_lock forever).
871 if (reject_kind == MMFRejectKind::RecoveryPortfolioExhausted) return false;
872 // Pure restore-reject cycles without force progress enter the hard lock.
873 return !force_improved;
874}
875
876bool isRecoveryPortfolioExhaustedReject(bool recovery_selection_exhausted,
877 int accepted_candidates)
878{
879 return recovery_selection_exhausted && accepted_candidates == 0;
880}
881
882bool isMmfRecoveryPortfolioExhausted(bool found_saddle_mode, int selected_phase,
883 int accepted_candidates)
884{
885 return !found_saddle_mode ||
886 (selected_phase < 0 && accepted_candidates == 0);
887}
888
889bool shouldAcquireMmfMinModeProbe(bool found_saddle_mode, int selected_phase,
890 int accepted_candidates,
891 int negative_curvature_candidates,
892 int force_improving_candidates,
893 int out_of_trust_candidates)
894{
895 if (out_of_trust_candidates > 0 && force_improving_candidates == 0) {
896 return false;
897 }
898 return found_saddle_mode && selected_phase < 0 &&
899 accepted_candidates == 0 && negative_curvature_candidates > 0 &&
900 force_improving_candidates == 0;
901}
902
903bool shouldHoldMmfForExpectedImprovement(bool wait_for_true_sample,
904 Eigen::Index ntrain,
905 Eigen::Index ntrain_at_hold)
906{
907 return wait_for_true_sample && ntrain <= ntrain_at_hold;
908}
909
910double mmfMinModeProbeStep(double recovery_disp_cap, double seed_kick,
911 double max_burst_displacement)
912{
913 double step = std::numeric_limits<double>::quiet_NaN();
914 if (std::isfinite(recovery_disp_cap) && recovery_disp_cap > 0.0) {
915 step = 0.5 * recovery_disp_cap;
916 }
917 if (std::isfinite(seed_kick) && seed_kick > 0.0) {
918 const double floor = 2.0 * seed_kick;
919 step = std::isfinite(step) ? std::max(step, floor) : floor;
920 }
921 if (std::isfinite(max_burst_displacement) && max_burst_displacement > 0.0) {
922 step = std::isfinite(step) ? std::min(step, max_burst_displacement)
923 : max_burst_displacement;
924 }
925 return (std::isfinite(step) && step > 0.0) ? step : 0.1;
926}
927
928Eigen::VectorXd minModeProbePosition(const Eigen::VectorXd& seed,
929 const Eigen::VectorXd& mode, double step)
930{
931 if (seed.size() == 0 || mode.size() != seed.size() || !seed.allFinite() ||
932 !mode.allFinite() || !std::isfinite(step) || !(step > 0.0)) {
933 return {};
934 }
935 const double norm = mode.norm();
936 if (!(norm > 0.0) || !std::isfinite(norm)) {
937 return {};
938 }
939 return seed + (step / norm) * mode;
940}
941
942bool isTruePesRecoverySaddleEnergyCertified(double true_energy,
943 double reactant_energy,
944 double product_energy)
945{
946 return isTruePesSaddleEnergyCandidate(true_energy, reactant_energy,
947 product_energy);
948}
949
950bool isTruePesRecoverySaddleCertified(double true_energy, double recovery_force,
951 double force_tolerance,
952 double reactant_energy,
953 double product_energy)
954{
955 return std::isfinite(recovery_force) && recovery_force >= 0.0 &&
956 std::isfinite(force_tolerance) && force_tolerance > 0.0 &&
957 recovery_force < force_tolerance &&
958 isTruePesRecoverySaddleEnergyCertified(true_energy, reactant_energy,
959 product_energy);
960}
961
962bool isMmfAdaptiveThresholdSeeded(double current_threshold)
963{
964 return std::isfinite(current_threshold) && current_threshold > 0.0;
965}
966
967bool shouldLeaseAfterPureRejectProgress(bool pure_reject_lock,
968 bool improved_under_backoff,
969 bool improved_since_pure_reject)
970{
971 // Pure-lock re-entry is global: reopen under the adaptive threshold or
972 // when the residual drops below the pure-reject force recorded for the
973 // handoff. Climbing-image hops must not re-arm restore/reject cycles at
974 // wall-scale residuals.
975 return pure_reject_lock &&
976 (improved_under_backoff || improved_since_pure_reject);
977}
978
979bool shouldLeaseAfterExhaustedQuietStall(
980 bool pure_reject_lock, bool exhausted_recovery_reject_applies,
981 bool oie_quiet_handoff_stalled, bool oie_acquisition_quiet,
982 bool current_chain_certificate, bool current_saddle_stencil_certificate,
983 bool ci_posterior_confident, bool ci_is_energy_maximum)
984{
985 // Exhausted recovery hard-blocks ordinary certified handoff so a failed
986 // recovery portfolio does not immediately re-fire. Quiet-stall after that
987 // block is a different certificate: OIE has already spent a quiet budget
988 // without residual progress, so MMF is the only remaining action.
989 // pure_reject_lock is optional: RecoveryPortfolioExhausted deliberately
990 // skips pure-lock, and quiet-stall must still re-open the lease.
991 (void)pure_reject_lock;
992 return exhausted_recovery_reject_applies && oie_quiet_handoff_stalled &&
993 oie_acquisition_quiet && current_chain_certificate &&
994 current_saddle_stencil_certificate && ci_posterior_confident &&
995 ci_is_energy_maximum;
996}
997
998bool shouldBlockRejectedSeedReplay(bool rejected_seed_replay,
999 bool trap_detected,
1000 bool improved_since_pure_reject,
1001 bool exhausted_quiet_stall_lease)
1002{
1003 return rejected_seed_replay && !trap_detected &&
1004 !improved_since_pure_reject && !exhausted_quiet_stall_lease;
1005}
1006
1007bool shouldSkipMmfAfterSpentMinModeProbe(bool min_mode_probe_spent,
1008 bool rejected_seed_replay,
1009 bool rejected_seed_position_matches)
1010{
1011 return min_mode_probe_spent &&
1012 (rejected_seed_replay || rejected_seed_position_matches);
1013}
1014
1015PureLockHopState pureLockStateAfterCiHop(PureLockHopState state)
1016{
1017 if (!state.force_improving_recovery_active) {
1018 // Pure restore-reject pure-lock remains global across CI hops.
1019 return state;
1020 }
1021 // FI post residual is image-local: drop pure-lock and thr-void stall on
1022 // hop.
1023 state.pure_reject_lock = false;
1024 state.pure_reject_force = std::numeric_limits<double>::quiet_NaN();
1025 state.force_improving_recovery_active = false;
1026 return state;
1027}
1028
1029double resolveMmfSeedDisplacement(double configured_displacement,
1030 bool force_improving_recovery_active,
1031 bool trusted_recovery_active)
1032{
1033 if (!std::isfinite(configured_displacement) ||
1034 force_improving_recovery_active || trusted_recovery_active) {
1035 return 0.0;
1036 }
1037 return configured_displacement;
1038}
1039
1040bool shouldImmediateRereleaseAfterFi(bool force_improving_recovery_active,
1041 double post_force,
1042 double current_threshold,
1043 double force_tolerance)
1044{
1045 if (!force_improving_recovery_active) return false;
1046 if (!isMmfAdaptiveThresholdSeeded(current_threshold)) return false;
1047 if (!std::isfinite(post_force) || !(post_force > 0.0)) return false;
1048 if (!std::isfinite(force_tolerance) || !(force_tolerance > 0.0)) {
1049 return false;
1050 }
1051 // Still above NEB convergence, but inside the adaptive near-saddle bar.
1052 return post_force > force_tolerance && post_force <= current_threshold;
1053}
1054
1055bool shouldImmediateRereleaseAfterOciRecovery(
1056 bool force_improving_recovery_active, bool trusted_recovery_active,
1057 double post_force, double current_threshold, double force_tolerance,
1058 bool current_saddle_stencil_certificate)
1059{
1060 // A true-PES saddle certificate renews an existing recovery lease by
1061 // measured residual descent. The adaptive threshold admits new leases; it
1062 // does not revoke a certified local recovery while that recovery is making
1063 // progress above the convergence tolerance.
1064 if (force_improving_recovery_active && trusted_recovery_active &&
1065 current_saddle_stencil_certificate && std::isfinite(post_force) &&
1066 std::isfinite(force_tolerance) && force_tolerance > 0.0) {
1067 return post_force > force_tolerance;
1068 }
1069 if (!shouldImmediateRereleaseAfterFi(force_improving_recovery_active,
1070 post_force, current_threshold,
1071 force_tolerance)) {
1072 return false;
1073 }
1074 if (!trusted_recovery_active) return true;
1075 return current_saddle_stencil_certificate ||
1076 isConvergenceScaleForce(post_force, force_tolerance);
1077}
1078
1079bool shouldImmediateRereleaseAfterOciRecovery(
1080 const MMFRunResult& burst, double current_threshold, double force_tolerance,
1081 bool current_saddle_stencil_certificate)
1082{
1083 if (burst.requires_outer_path_refresh) return false;
1084 // A lower-energy saddle remains an accepted outer-loop observation, but
1085 // only measured force progress supports another local MMF step without a
1086 // GP refit.
1087 return shouldImmediateRereleaseAfterOciRecovery(
1088 burst.force_improving_recovery_advanced,
1089 burst.trusted_recovery_advanced, burst.newForce, current_threshold,
1090 force_tolerance,
1091 current_saddle_stencil_certificate || burst.recovery_saddle_certified);
1092}
1093
1094bool mmfAttemptConsumedAfterRecovery(bool mmf_attempted,
1095 bool trusted_recovery_advanced,
1096 bool requires_outer_path_refresh)
1097{
1098 return mmf_attempted &&
1099 !(trusted_recovery_advanced && requires_outer_path_refresh);
1100}
1101
1102bool shouldPreserveFiRecoveryGateAfterRetry(
1103 bool force_improving_recovery_active, double pre_force,
1104 double current_threshold, double force_tolerance,
1105 bool recovery_selection_exhausted)
1106{
1107 if (!force_improving_recovery_active) return false;
1108 // An exhausted scored portfolio needs new OIE information before another
1109 // local recovery lease can evaluate a different proposal.
1110 if (recovery_selection_exhausted) return false;
1111 if (!isMmfAdaptiveThresholdSeeded(current_threshold)) return false;
1112 if (!std::isfinite(pre_force) || !(pre_force > 0.0)) return false;
1113 if (!std::isfinite(force_tolerance) || !(force_tolerance > 0.0)) {
1114 return false;
1115 }
1116 return pre_force > force_tolerance && pre_force <= current_threshold;
1117}
1118
1119bool shouldPreserveTrustedRecoveryGateAfterRetry(
1120 bool trusted_recovery_active, MMFStatus status, bool force_improved,
1121 bool trusted_recovery_advanced, bool rejected_helped_handback,
1122 MMFRejectKind reject_kind, bool recovery_selection_exhausted)
1123{
1124 if (!trusted_recovery_active) return false;
1125 if (status == MMFStatus::Helped) return false;
1126 if (recovery_selection_exhausted) return false;
1127 if (rejected_helped_handback &&
1129 return false;
1130 }
1131 if (force_improved || trusted_recovery_advanced) return false;
1132 return true;
1133}
1134
1135bool shouldRecordRejectedSeedForRecoveryGate(
1136 bool preserve_fi_recovery_gate, bool preserve_trusted_recovery_gate)
1137{
1138 return preserve_trusted_recovery_gate && !preserve_fi_recovery_gate;
1139}
1140
1141double trustedRetryRejectForceAfterRetry(
1142 bool preserve_trusted_recovery_gate,
1143 double existing_trusted_retry_reject_force, double retry_reject_force)
1144{
1145 if (!preserve_trusted_recovery_gate) {
1146 return std::numeric_limits<double>::quiet_NaN();
1147 }
1148 if (std::isfinite(existing_trusted_retry_reject_force) &&
1149 existing_trusted_retry_reject_force > 0.0) {
1150 return existing_trusted_retry_reject_force;
1151 }
1152 return retry_reject_force;
1153}
1154
1155bool shouldHarvestAcceptedRecoveryObservation(bool trusted_recovery_advanced)
1156{
1157 return trusted_recovery_advanced;
1158}
1159
1160bool shouldKeepTrustedRecoveryGateAfterAdvance(bool trusted_recovery_advanced,
1161 bool force_improved)
1162{
1163 return trusted_recovery_advanced && force_improved;
1164}
1165
1166bool shouldPromoteCurrentCiHandoffMismatchToTrap(int handoff_outer_iter,
1167 int hook_outer_iter,
1168 double gp_force,
1169 double oracle_force,
1170 double handoff_threshold)
1171{
1172 if (handoff_outer_iter < 0 || hook_outer_iter < 0) return false;
1173 if (!(handoff_outer_iter < hook_outer_iter)) return false;
1174 return shouldFlagMmfHandoffTrap(gp_force, oracle_force, handoff_threshold);
1175}
1176
1177bool shouldRefreshCurrentCiHandoffPrediction(bool pending_request,
1178 int pending_ci,
1179 bool current_request,
1180 int current_ci) noexcept
1181{
1182 return !current_request || !pending_request || pending_ci != current_ci;
1183}
1184
1185bool isBandInformationExhaustedForMmf(double max_chain_energy_variance,
1186 double likelihood_noise_variance,
1187 double posterior_variance_threshold,
1188 double inner_unc_relative)
1189{
1190 (void)posterior_variance_threshold;
1191 (void)inner_unc_relative;
1192 if (!std::isfinite(max_chain_energy_variance) ||
1193 max_chain_energy_variance < 0.0) {
1194 return false;
1195 }
1196 // The likelihood floor is the no-information certificate for MMF handoff.
1197 return std::isfinite(likelihood_noise_variance) &&
1198 likelihood_noise_variance > 0.0 &&
1199 max_chain_energy_variance <= likelihood_noise_variance;
1200}
1201
1202bool isOieAcquisitionQuietForMmf(double max_chain_energy_variance,
1203 double posterior_variance_threshold)
1204{
1205 if (!std::isfinite(max_chain_energy_variance) ||
1206 max_chain_energy_variance < 0.0) {
1207 return false;
1208 }
1209 return std::isfinite(posterior_variance_threshold) &&
1210 posterior_variance_threshold > 0.0 &&
1211 max_chain_energy_variance <= posterior_variance_threshold;
1212}
1213
1214bool hasCurrentOciSaddleStencilCertificate(const ActiveLearningSession& session,
1215 const NEBPath& path, int ci_idx)
1216{
1217 return ci_idx > 0 && ci_idx < path.numImages() - 1 &&
1218 selectOciHandoffCertificateOracleTargets(ci_idx, path, session)
1219 .empty();
1220}
1221
1222bool isOracleTransitionFocalHandoff(int configured_focal_image,
1223 int ci_image_idx,
1224 bool current_chain_certificate,
1225 bool current_saddle_stencil_certificate)
1226{
1227 return configured_focal_image > 0 &&
1228 configured_focal_image == ci_image_idx &&
1229 current_chain_certificate && current_saddle_stencil_certificate;
1230}
1231
1232bool isOciMmfHandoffDataReady(bool band_acquisition_quiet,
1233 bool current_saddle_stencil_certificate,
1234 bool ci_posterior_confident,
1235 bool ci_is_energy_maximum)
1236{
1237 // A quiet band certifies the handoff through its measured local
1238 // stencil. A posterior-confident energy maximum fires WITHOUT the
1239 // stencil pre-condition: a band that keeps taking drift-bounded
1240 // steps re-stales the stencil every outer, so demanding it starves
1241 // the finisher exactly when the CI grinds just above tolerance; the
1242 // burst measures its own seed first thing and the accept path
1243 // carries the saddle certificates.
1244 return (band_acquisition_quiet && current_saddle_stencil_certificate) ||
1245 (ci_posterior_confident && ci_is_energy_maximum);
1246}
1247
1248bool isForceImprovingRecoveryStalledHandoff(
1249 bool force_improving_recovery_active, bool ci_posterior_confident,
1250 bool current_chain_certificate, bool oie_acquisition_quiet,
1251 bool oie_quiet_handoff_stalled)
1252{
1253 (void)ci_posterior_confident;
1254 return force_improving_recovery_active && current_chain_certificate &&
1255 oie_acquisition_quiet && oie_quiet_handoff_stalled;
1256}
1257
1258bool isTrustedRecoveryStalledHandoff(bool trusted_recovery_active,
1259 bool ci_posterior_confident,
1260 bool current_chain_certificate,
1261 bool ci_is_energy_maximum,
1262 bool oie_acquisition_quiet,
1263 bool oie_quiet_handoff_stalled)
1264{
1265 (void)ci_posterior_confident;
1266 return trusted_recovery_active && current_chain_certificate &&
1267 ci_is_energy_maximum && oie_acquisition_quiet &&
1268 oie_quiet_handoff_stalled;
1269}
1270
1271bool shouldUseTrustedRecoveryStalledHandoff(
1272 bool trusted_retry_progress_pending, bool trusted_recovery_stalled_handoff)
1273{
1274 (void)trusted_retry_progress_pending;
1275 return trusted_recovery_stalled_handoff;
1276}
1277
1278bool isTrustedRecoveryProgressHandoff(
1279 bool trusted_recovery_active, double trusted_retry_reject_force,
1280 double conv_force, double current_threshold, bool ci_posterior_confident,
1281 bool ci_is_energy_maximum, bool rejected_seed_replay,
1282 bool current_chain_certificate, bool oie_quiet_handoff_stalled,
1283 bool oie_acquisition_quiet)
1284{
1285 (void)current_threshold;
1286 (void)ci_posterior_confident;
1287 (void)oie_quiet_handoff_stalled;
1288 return trusted_recovery_active && ci_is_energy_maximum &&
1289 !rejected_seed_replay && current_chain_certificate &&
1290 oie_acquisition_quiet && std::isfinite(trusted_retry_reject_force) &&
1291 trusted_retry_reject_force > 0.0 && std::isfinite(conv_force) &&
1292 conv_force > 0.0 && conv_force < trusted_retry_reject_force;
1293}
1294
1295bool isCurrentChainCertifiedHandoff(bool trusted_retry_progress_pending,
1296 bool current_chain_certificate,
1297 bool rejected_seed_replay,
1298 bool ci_posterior_confident,
1299 bool ci_is_energy_maximum,
1300 bool oie_acquisition_quiet,
1301 bool exhausted_recovery_reject_active)
1302{
1303 if (exhausted_recovery_reject_active) return false;
1304 return !trusted_retry_progress_pending && current_chain_certificate &&
1305 !rejected_seed_replay && ci_posterior_confident &&
1306 ci_is_energy_maximum && oie_acquisition_quiet;
1307}
1308
1309bool exhaustedRecoveryRejectAppliesToCi(bool exhausted_recovery_reject_active,
1310 long reject_climbing_image,
1311 long climbing_image)
1312{
1313 if (!exhausted_recovery_reject_active) return false;
1314 return reject_climbing_image < 0 || climbing_image < 0 ||
1315 reject_climbing_image == climbing_image;
1316}
1317
1318bool shouldRequestCurrentCiOracleForExhaustedRecovery(
1319 bool exhausted_recovery_reject_active, long reject_climbing_image,
1320 long climbing_image)
1321{
1322 return exhaustedRecoveryRejectAppliesToCi(exhausted_recovery_reject_active,
1323 reject_climbing_image,
1324 climbing_image);
1325}
1326
1327bool isRefreshedExhaustedRecoveryHandoff(
1328 bool exhausted_recovery_reject_applies, bool current_chain_certificate,
1329 bool current_saddle_stencil_certificate, bool rejected_seed_replay,
1330 bool rejected_seed_position_matches, bool ci_posterior_confident,
1331 bool ci_is_energy_maximum)
1332{
1333 return exhausted_recovery_reject_applies && current_chain_certificate &&
1334 current_saddle_stencil_certificate && !rejected_seed_replay &&
1335 !rejected_seed_position_matches && ci_posterior_confident &&
1336 ci_is_energy_maximum;
1337}
1338
1339bool activeMmfRecoveryOwnsClimbingImage(bool force_improving_recovery_active,
1340 bool trusted_recovery_active)
1341{
1342 return force_improving_recovery_active || trusted_recovery_active;
1343}
1344
1345int activeOieRecoveryOwnerImage(int recorded_owner_image, int current_ci_image,
1346 bool force_improving_recovery_active,
1347 bool trusted_recovery_active)
1348{
1349 if (!activeMmfRecoveryOwnsClimbingImage(force_improving_recovery_active,
1350 trusted_recovery_active)) {
1351 return -1;
1352 }
1353 if (recorded_owner_image > 0) return recorded_owner_image;
1354 return current_ci_image > 0 ? current_ci_image : -1;
1355}
1356
1357bool shouldHoldOieFixedImage(bool force_improving_recovery_active,
1358 bool trusted_recovery_active)
1359{
1360 return shouldHoldOieFixedImage(force_improving_recovery_active,
1361 trusted_recovery_active,
1362 /*rejected_recovery_seed=*/false);
1363}
1364
1365bool shouldHoldOieFixedImage(bool force_improving_recovery_active,
1366 bool trusted_recovery_active,
1367 bool rejected_recovery_seed)
1368{
1369 return force_improving_recovery_active ||
1370 (trusted_recovery_active && !rejected_recovery_seed);
1371}
1372
1373bool shouldRequestOieRecoveryModelGrowth(bool force_improving_recovery_active,
1374 bool trusted_recovery_active,
1375 bool rejected_recovery_seed,
1376 MmfInformationGate info_gate)
1377{
1378 const bool action_uncertifiable =
1379 info_gate == MmfInformationGate::AwaitingFirstTrainingGrowth;
1380 return shouldHoldOieFixedImage(force_improving_recovery_active,
1381 trusted_recovery_active,
1382 rejected_recovery_seed) &&
1383 action_uncertifiable;
1384}
1385
1386bool shouldSuppressMmfRecoveryRetry(bool force_improving_recovery_active,
1387 bool trusted_recovery_active,
1388 MmfInformationGate info_gate)
1389{
1390 return activeMmfRecoveryOwnsClimbingImage(force_improving_recovery_active,
1391 trusted_recovery_active) &&
1392 shouldSuppressMmfUntilTrainingGrows(info_gate);
1393}
1394
1395bool shouldReleaseOieRecoveryForCertifiedHandover(
1396 bool active_recovery, int recovery_owner_image, int candidate_image,
1397 bool candidate_posterior_confident, bool candidate_chain_certificate,
1398 bool candidate_saddle_stencil_certificate)
1399{
1400 return active_recovery && recovery_owner_image > 0 && candidate_image > 0 &&
1401 candidate_image != recovery_owner_image &&
1402 candidate_posterior_confident && candidate_chain_certificate &&
1403 candidate_saddle_stencil_certificate;
1404}
1405
1406bool shouldReleaseOieExhaustedRecoveryForCertifiedHandover(
1407 bool exhausted_recovery_reject_active, int rejected_image,
1408 int candidate_image, bool candidate_posterior_confident,
1409 bool candidate_chain_certificate, bool candidate_saddle_stencil_certificate)
1410{
1411 return exhausted_recovery_reject_active && rejected_image > 0 &&
1412 candidate_image > 0 && candidate_image != rejected_image &&
1413 candidate_posterior_confident && candidate_chain_certificate &&
1414 candidate_saddle_stencil_certificate;
1415}
1416
1417bool shouldReleaseOieRecoveryForInvalidatedOwner(
1418 bool active_recovery, int recovery_owner_image, int retry_image,
1419 bool recovery_model_growth_ready, bool band_force_converged,
1420 bool owner_chain_certificate, bool owner_saddle_stencil_certificate,
1421 bool owner_posterior_confident, bool owner_is_energy_maximum)
1422{
1423 const bool owner_identity_matches =
1424 recovery_owner_image > 0 && recovery_owner_image == retry_image;
1425 const bool owner_certificate =
1426 owner_chain_certificate && owner_saddle_stencil_certificate &&
1427 owner_posterior_confident && owner_is_energy_maximum;
1428 return active_recovery && owner_identity_matches &&
1429 recovery_model_growth_ready && band_force_converged &&
1430 !owner_certificate;
1431}
1432
1433bool shouldAdvanceOieRecoveryInformationGate(bool active_recovery,
1434 int recovery_owner_image,
1435 int retry_image)
1436{
1437 return !active_recovery ||
1438 (recovery_owner_image > 0 && recovery_owner_image == retry_image);
1439}
1440
1441OieFixedImageLease makeOieRecoveryFixedImageLease(
1442 int ci_image_idx, bool force_improving_recovery_active,
1443 bool trusted_recovery_active, bool rejected_recovery_seed,
1444 MmfInformationGate info_gate, bool recovery_retry_blocked)
1445{
1446 if (ci_image_idx <= 0 ||
1447 !shouldHoldOieFixedImage(force_improving_recovery_active,
1448 trusted_recovery_active,
1449 rejected_recovery_seed)) {
1450 return {};
1451 }
1452 const bool model_growth_required = shouldRequestOieRecoveryModelGrowth(
1453 force_improving_recovery_active, trusted_recovery_active,
1454 rejected_recovery_seed, info_gate);
1455 const bool allow_replaceable_acquisition =
1456 !model_growth_required &&
1457 (info_gate == MmfInformationGate::AwaitingActionChange ||
1458 recovery_retry_blocked);
1459 return {ci_image_idx, model_growth_required, model_growth_required,
1460 allow_replaceable_acquisition};
1461}
1462
1463OieFixedImageLease makeOieExhaustedRecoveryFixedImageLease(
1464 int ci_image_idx, bool exhausted_recovery_reject_active,
1465 long reject_climbing_image)
1466{
1467 if (ci_image_idx <= 0 || !exhaustedRecoveryRejectAppliesToCi(
1468 exhausted_recovery_reject_active,
1469 reject_climbing_image, ci_image_idx)) {
1470 return {};
1471 }
1472 return {ci_image_idx,
1473 /*retain_climbing_marker=*/true,
1474 /*model_growth_required=*/false,
1475 /*allow_replaceable_acquisition=*/true};
1476}
1477
1478OieFixedImageLease makeOieExhaustedRecoveryEvidenceLease(
1479 int ci_image_idx, bool exhausted_recovery_reject_active,
1480 long reject_climbing_image, int candidate_image)
1481{
1482 OieFixedImageLease lease = makeOieExhaustedRecoveryFixedImageLease(
1483 ci_image_idx, exhausted_recovery_reject_active, reject_climbing_image);
1484 if (lease.image_index > 0 && candidate_image == lease.image_index) {
1485 lease.model_growth_required = true;
1486 lease.allow_replaceable_acquisition = false;
1487 }
1488 return lease;
1489}
1490
1491bool isOieRecoveryOwnerModelGrowthReady(
1492 bool model_growth_requested, const MmfSurrogateFingerprint& surrogate_now,
1493 const MmfSurrogateFingerprint& surrogate_at_request)
1494{
1495 return model_growth_requested &&
1496 mmfSurrogateChanged(surrogate_now, surrogate_at_request);
1497}
1498
1499bool isOieRecoveryModelGrowthCertified(int recovery_owner_image,
1500 int retry_image,
1501 bool recovery_model_growth_ready,
1502 bool current_chain_certificate,
1503 bool current_saddle_stencil_certificate,
1504 bool recovery_owner_is_energy_maximum)
1505{
1506 return recovery_owner_image > 0 && recovery_owner_image == retry_image &&
1507 recovery_model_growth_ready && current_chain_certificate &&
1508 current_saddle_stencil_certificate &&
1509 recovery_owner_is_energy_maximum;
1510}
1511
1512bool isOieExhaustedRecoveryModelGrowthCertified(
1513 int recovery_owner_image, int retry_image, bool recovery_model_growth_ready,
1514 bool current_chain_certificate, bool current_saddle_stencil_certificate,
1515 bool recovery_owner_is_energy_maximum, bool rejected_seed_replay)
1516{
1517 return !rejected_seed_replay &&
1518 isOieRecoveryModelGrowthCertified(
1519 recovery_owner_image, retry_image, recovery_model_growth_ready,
1520 current_chain_certificate, current_saddle_stencil_certificate,
1521 recovery_owner_is_energy_maximum);
1522}
1523
1524bool shouldUseSurfaceUpdatedTrapRetryForCurrentCiOracle(
1525 bool trap_surface_updated, bool trusted_recovery_active,
1526 double trusted_retry_reject_force, double conv_force,
1527 double current_threshold)
1528{
1529 if (!trap_surface_updated) return false;
1530 if (!trusted_recovery_active) return true;
1531 const bool trusted_retry_progress_pending =
1532 std::isfinite(trusted_retry_reject_force) &&
1533 trusted_retry_reject_force > 0.0;
1534 if (!trusted_retry_progress_pending) return false;
1535 return std::isfinite(conv_force) && conv_force > 0.0 &&
1536 std::isfinite(current_threshold) && current_threshold > 0.0 &&
1537 conv_force <= current_threshold;
1538}
1539
1540bool shouldRetireTrustedRetryAfterProgress(bool trusted_recovery_active,
1541 double trusted_retry_reject_force,
1542 double conv_force,
1543 double current_threshold)
1544{
1545 return trusted_recovery_active &&
1546 std::isfinite(trusted_retry_reject_force) &&
1547 trusted_retry_reject_force > 0.0 && std::isfinite(conv_force) &&
1548 conv_force > 0.0 && conv_force < trusted_retry_reject_force &&
1549 std::isfinite(current_threshold) && current_threshold > 0.0 &&
1550 conv_force <= current_threshold;
1551}
1552
1553bool shouldTriggerMmf(const OCINEBConfig& cfg, double convForce, bool ci_active,
1554 long climbingImage, long numImages,
1555 bool ci_posterior_confident, double current_threshold,
1556 bool trap_detected, bool trap_backoff_active,
1557 bool trap_surface_updated, MmfInformationGate info_gate,
1558 bool ci_is_energy_maximum,
1559 bool band_information_exhausted,
1560 bool oie_acquisition_quiet, bool oie_acquisition_stalled,
1561 bool certified_recovery_stalled_handoff,
1562 bool certified_handoff)
1563{
1564 if (!cfg.use_mmf || !ci_active) return false;
1565 if (climbingImage <= 0 || climbingImage > numImages) return false;
1566 if (!std::isfinite(convForce)) return false;
1567 // Lease floor is the NEB force criterion only. Model-noise-raised
1568 // resolveOciForceTolerance governs dimer acceptance / outer NEB
1569 // convergence, not whether MMF may still refine a CI whose residual
1570 // sits in (conv_tol, noise_rms]. Raising the lease floor with oracle
1571 // force/energy noise freezes MMF while the band stays hot (Baker 02:
1572 // F_CI~0.135 under thr with handoff_ready, 100+ gate-skips, bar~2.25).
1573 const double force_tolerance = mmfLeaseForceTolerance(cfg);
1574 if (!(std::isfinite(force_tolerance) && force_tolerance > 0.0 &&
1575 convForce > force_tolerance)) {
1576 return false;
1577 }
1578 // Trap: GP fixed point vs true force — lease when surface was updated,
1579 // else first trap attempt. No residual-scale magic; thr/lease policy
1580 // lives in the adaptive bar and recovery acceptance, not here.
1581 if (trap_detected && (!trap_backoff_active || trap_surface_updated)) {
1582 return true;
1583 }
1584 // A certified handoff, including a granted fixed-point lease, is
1585 // decided before the information gate. The gate waits for training
1586 // growth after a restore/reject and must not drop that grant.
1587 if (certified_handoff) return true;
1588 // After restore/reject: wait until OIE grows training past pre-burst
1589 // snapshot (force-accuracy TPE informs the posterior).
1590 if (shouldSuppressMmfUntilTrainingGrows(info_gate)) {
1591 return false;
1592 }
1593 // Exhaustion and recovery-stall void the adaptive bar once the
1594 // information gate is open.
1595 if (band_information_exhausted) return true;
1596 if (certified_recovery_stalled_handoff) return true;
1597 // Confidence lease requires a seeded near-saddle threshold, so
1598 // wall-scale residuals cannot enter MMF only by posterior confidence.
1599 if (!(std::isfinite(current_threshold) && current_threshold > 0.0)) {
1600 return false;
1601 }
1602 if (convForce > current_threshold) {
1603 return false;
1604 }
1605 // Posterior handover certificate: CI minimizes Bayes risk for "band
1606 // maximum" (pairwise Gaussian energy differences, risk < 1/2 and best).
1607 if (ci_posterior_confident) return true;
1608 // Soft OIE-quiet alone does not lease. It still participates in session
1609 // handoff bookkeeping for force records and stall flags.
1610 (void)ci_is_energy_maximum;
1611 (void)trap_backoff_active;
1612 (void)oie_acquisition_quiet;
1613 (void)oie_acquisition_stalled;
1614 return false;
1615}
1616
1617double resolveDimerVarianceTauRelative(const GPNEBConfig& neb_config,
1618 const OCINEBConfig& oci_config)
1619{
1620 (void)neb_config;
1621 if (std::isfinite(oci_config.dimer_variance_tau_rel)) {
1622 return std::max(0.0, oci_config.dimer_variance_tau_rel);
1623 }
1624 return 0.0;
1625}
1626
1627bool shouldInstallOciMmfHook(const GPNEBConfig& neb_config,
1628 const OCINEBConfig& oci_config)
1629{
1630 (void)neb_config;
1631 // MMF (the minimum-mode-following dimer that makes this OCI-NEB rather
1632 // than plain CI-NEB) must run whether or not a GP surrogate is present.
1633 // The no-GP path (Standard/AIE) runs a standalone AtomicDimer on the
1634 // true potential; eOn's reference OCINEB has no GP at all. Gating this on
1635 // gp_setup left the no-GP path as plain CI-NEB (dimer never fired), which
1636 // climbs to a higher saddle than the eOn reference.
1637 if (!oci_config.use_mmf) return false;
1638 return true;
1639}
1640
1641MmfHandoffPolicy resolveMmfHandoffPolicy(MmfHandoffPolicy configured,
1642 NEBMode mode)
1643{
1644 if (configured != MmfHandoffPolicy::Auto) return configured;
1645 if (mode == NEBMode::GP_OIE || mode == NEBMode::GP_AIE) {
1647 }
1649}
1650
1651bool shouldUseHssvdAnalyticDimerCurvature(const GPNEBConfig& neb_config)
1652{
1653 return shouldUseHssvdAnalyticDimerCurvature(neb_config, true);
1654}
1655
1656bool shouldUseHssvdAnalyticDimerCurvature(const GPNEBConfig& neb_config,
1657 bool has_spectral_posterior)
1658{
1659 return neb_config.dimer_analytic_curvature.value_or(
1660 has_spectral_posterior && (neb_config.use_hssvd_solver ||
1661 neb_config.hyperparameter_objective ==
1663}
1664
1665double resolveOciForceTolerance(const OCINEBConfig& oci_config)
1666{
1667 const bool has_base = std::isfinite(oci_config.force_tolerance) &&
1668 oci_config.force_tolerance > 0.0;
1669 double tol = oci_config.force_tolerance;
1670 if (oci_config.effective_force_tolerance) {
1671 const double live_tol = oci_config.effective_force_tolerance();
1672 if (std::isfinite(live_tol) && live_tol > 0.0 &&
1673 (!has_base || live_tol > tol)) {
1674 tol = live_tol;
1675 }
1676 }
1677 return tol;
1678}
1679
1680double mmfLeaseForceTolerance(const OCINEBConfig& oci_config)
1681{
1682 // Base NEB / OCI force criterion only. Does not follow the live
1683 // model-noise provider used by resolveOciForceTolerance.
1684 if (std::isfinite(oci_config.force_tolerance) &&
1685 oci_config.force_tolerance > 0.0) {
1686 return oci_config.force_tolerance;
1687 }
1688 return resolveOciForceTolerance(oci_config);
1689}
1690
1691class ScopedImageState {
1692public:
1693 ScopedImageState(NEBPath& path, int image_idx)
1694 : path_(path),
1695 image_idx_(image_idx),
1696 positions_(path.image(image_idx).positions),
1697 energy_(path.image(image_idx).energy),
1698 gradient_(path.image(image_idx).gradient),
1699 evaluated_(path.image(image_idx).evaluated)
1700 {
1701 }
1702
1703 ScopedImageState(const ScopedImageState&) = delete;
1704 ScopedImageState& operator=(const ScopedImageState&) = delete;
1705 ScopedImageState(ScopedImageState&&) = delete;
1706 ScopedImageState& operator=(ScopedImageState&&) = delete;
1707
1708 ~ScopedImageState()
1709 {
1710 path_.image(image_idx_).positions = positions_;
1711 path_.image(image_idx_).energy = energy_;
1712 path_.image(image_idx_).gradient = gradient_;
1713 path_.image(image_idx_).evaluated = evaluated_;
1714 path_.computeNEBForces();
1715 }
1716
1717private:
1718 NEBPath& path_;
1719 int image_idx_;
1720 Eigen::VectorXd positions_;
1721 double energy_;
1722 Eigen::VectorXd gradient_;
1723 bool evaluated_;
1724};
1725
1726} // namespace detail
1727
1728namespace {
1729
1731gpr::Coord flatToCoord1xD(const Eigen::VectorXd& v)
1732{
1733 gpr::Coord c(1, v.size());
1734 for (Eigen::Index j = 0; j < v.size(); ++j)
1735 c(0, j) = v(j);
1736 return c;
1737}
1738
1739Eigen::VectorXd coordToFlat(const gpr::Coord& c)
1740{
1741 Eigen::VectorXd v(c.cols());
1742 for (Eigen::Index j = 0; j < c.cols(); ++j)
1743 v(j) = c(0, j);
1744 return v;
1745}
1746
1747struct OciMmfHandoffTrapState {
1748 int outer_iter = -1;
1749 int ci_image_idx = -1;
1750 double gp_force = std::numeric_limits<double>::infinity();
1751 double threshold = std::numeric_limits<double>::quiet_NaN();
1752 bool requested_current_ci = false;
1753};
1754
1759double emdDistance(const Eigen::VectorXd& a, const Eigen::VectorXd& b,
1760 const gpr::AtomsConfiguration& atoms_config)
1761{
1762 if (a.size() != b.size() || a.size() == 0) {
1763 return std::numeric_limits<double>::infinity();
1764 }
1765 gpr::Coord ca = flatToCoord1xD(a);
1766 gpr::Coord cb = flatToCoord1xD(b);
1767 gpr::FieldMatrixd dist;
1768 aux::Distance distance;
1769 distance.dist_emd(ca, cb, atoms_config, dist);
1770 if (dist.size() == 0) return std::numeric_limits<double>::infinity();
1771 return dist(0, 0);
1772}
1773
1774} // namespace
1775
1776namespace detail {
1777
1781gpr::InputParameters buildDimerParameters(const GPNEBConfig& neb_config,
1782 const OCINEBConfig& oci_config,
1783 gpr::AtomsConfiguration& tmp,
1784 bool use_analytic_hssvd)
1785{
1786 gpr::InputParameters parameters;
1787 if (neb_config.gp_setup) {
1788 neb_config.gp_setup(parameters, tmp);
1789 } else {
1790 // No-GP (Standard/AIE) validation path: gp_setup is unset, so apply
1791 // the canonical AtomicDimer defaults directly (the same bounded-nugget
1792 // GP/dimer parameters gprd uses). The dimer still builds its own
1793 // surrogate; running it against the true potential here "eats" the GP
1794 // speedup, so this is a parity-validation path only -- the production
1795 // GP-OIE path inherits the local image NEB GP via attachExternalGP.
1796 gpr::CanonicalDimerDefaultOptions dd;
1798 parameters.gp_sigma2.value = 1e-5;
1799 parameters.jitter_sigma2.value = 1e-4;
1800 parameters.sigma2.value = 1e-7;
1801 parameters.magnSigma2.value = 0.0;
1802 parameters.constSigma2.value = 0.0;
1803 parameters.prior_mu.value = 0;
1804 parameters.prior_nu.value = 20;
1805 parameters.prior_s2.value = 1;
1806 parameters.optimization_alg.value = "SCG_opt";
1807 parameters.max_iter.value = 400;
1808 parameters.tolerance_func.value = 1e-3;
1809 parameters.tolerance_sol.value = 1e-3;
1810 parameters.lambda_limit.value = 1e16;
1811 parameters.lambda.value = 100.0;
1812 parameters.check_derivative.value = "false";
1813 }
1814
1815 // A GP setup that only configures the kernel leaves the dimer's own
1816 // parameters at their zero defaults; a zero translation step makes
1817 // every relaxation phase a period-one cycle at the seed. Fill what the
1818 // setup did not set from the canonical gprd defaults.
1819 {
1820 gpr::InputParameters canonical;
1821 gpr::CanonicalDimerDefaultOptions dd;
1823 if (!(parameters.dimer_sep.value > 0.0))
1824 parameters.dimer_sep.value = canonical.dimer_sep.value;
1825 if (!(parameters.param_trans.value[0] > 0.0))
1826 parameters.param_trans.value[0] = canonical.param_trans.value[0];
1827 if (!(parameters.param_trans.value[1] > 0.0))
1828 parameters.param_trans.value[1] = canonical.param_trans.value[1];
1829 if (parameters.method_rot.value.empty() ||
1830 parameters.method_rot.value == "none")
1831 parameters.method_rot.value = canonical.method_rot.value;
1832 if (parameters.method_trans.value.empty() ||
1833 parameters.method_trans.value == "none")
1834 parameters.method_trans.value = canonical.method_trans.value;
1835 if (parameters.rot_opt.value.empty() ||
1836 parameters.rot_opt.value == "none")
1837 parameters.rot_opt.value = canonical.rot_opt.value;
1838 if (!(parameters.T_anglerot_init.value > 0.0))
1839 parameters.T_anglerot_init.value = canonical.T_anglerot_init.value;
1840 if (!(parameters.T_anglerot_gp.value > 0.0))
1841 parameters.T_anglerot_gp.value = canonical.T_anglerot_gp.value;
1842 if (!(parameters.divisor_T_dimer_gp.value > 0.0))
1843 parameters.divisor_T_dimer_gp.value =
1844 canonical.divisor_T_dimer_gp.value;
1845 if (!(parameters.disp_max.value > 0.0))
1846 parameters.disp_max.value = canonical.disp_max.value;
1847 if (!(parameters.ratio_at_limit.value > 0.0))
1848 parameters.ratio_at_limit.value = canonical.ratio_at_limit.value;
1849 if (parameters.num_iter_initrot.value <= 0)
1850 parameters.num_iter_initrot.value =
1851 canonical.num_iter_initrot.value;
1852 if (!(parameters.dist_sp.value[0] > 0.0))
1853 parameters.dist_sp.value[0] = canonical.dist_sp.value[0];
1854 }
1855 parameters.T_dimer.value = resolveOciForceTolerance(oci_config);
1856 if (neb_config.n_atoms > 0) {
1857 parameters.convergence_force_norm.value =
1859 }
1860 parameters.num_iter_rot_gp.value = oci_config.dimer_max_rot_iter;
1861 parameters.num_bigiter.value = oci_config.dimer_max_phases;
1862 parameters.num_iter.value = oci_config.dimer_max_inner_iter;
1863 parameters.eval_image1.value = oci_config.dimer_eval_image1 ? 1 : 0;
1864 if (use_analytic_hssvd) {
1865 // Analytic HS-SVD curvature replaces the GP rotation phases, but
1866 // the burst keeps its accurate-evaluation initial rotations: the
1867 // attached band GP's analytic min-mode at the burst seed can point
1868 // off the true saddle mode, and a first translation along a wrong
1869 // mode lands at high force and hands back every burst identically.
1870 // The rotation phase corrects the mode against accurate
1871 // evaluations before the first translation commits.
1872 parameters.num_iter_rot_gp.value = 0;
1873 }
1874 return parameters;
1875}
1876
1877gpr::InputParameters buildDimerParameters(const GPNEBConfig& neb_config,
1878 const OCINEBConfig& oci_config,
1879 gpr::AtomsConfiguration& tmp)
1880{
1881 return buildDimerParameters(
1882 neb_config, oci_config, tmp,
1883 shouldUseHssvdAnalyticDimerCurvature(neb_config));
1884}
1885
1886MmfPosteriorActionFingerprint probeMmfPosteriorAction(
1887 ActiveLearningSession& session, int image_idx, bool dimer_use_global_gp,
1888 const Eigen::VectorXd& seed, const Eigen::VectorXd& seed_gradient,
1889 const Eigen::VectorXd& initial_mode, const GPNEBConfig& neb_config,
1890 const OCINEBConfig& oci_config)
1891{
1892 MmfPosteriorActionFingerprint result;
1893 const int owner = session.mmfModelOwner(image_idx, dimer_use_global_gp);
1894 result.surrogate = session.surrogateFingerprint(owner);
1895 if (seed.size() == 0 || seed.size() != seed_gradient.size() ||
1896 seed.size() != initial_mode.size() || !seed.allFinite() ||
1897 !seed_gradient.allFinite() || !initial_mode.allFinite() ||
1898 !(initial_mode.norm() > 0.0)) {
1899 return result;
1900 }
1901
1902 ActiveLearningSession::ModelLease model =
1903 owner >= 0 ? session.acquireImageModel(owner)
1904 : session.acquireGlobalModel();
1905 gpr::Observation middle_point;
1906 middle_point.R = flatToCoord1xD(seed);
1907 middle_point.G = flatToCoord1xD(seed_gradient);
1908 gpr::Coord orientation = flatToCoord1xD(initial_mode.normalized());
1909
1910 gpr::AtomsConfiguration parameter_atoms;
1911 const bool use_analytic_hssvd = shouldUseHssvdAnalyticDimerCurvature(
1912 neb_config, model.gp().hasReusableHssvdPosterior());
1913 gpr::InputParameters parameters = buildDimerParameters(
1914 neb_config, oci_config, parameter_atoms, use_analytic_hssvd);
1915 atmd::AtomicDimer dimer;
1916 if (neb_config.training_policy != nullptr)
1917 dimer.setTrainingPolicy(neb_config.training_policy);
1919 // The band index certificate decides the saddle claim.
1920 dimer.setForceStopCertificateStep(0.0);
1921 dimer.attachExternalGP(&model.gp());
1922 dimer.initialize(parameters, model.observations(), middle_point,
1923 orientation, session.atoms_config);
1924 dimer.setWallClockLimit(neb_config.wall_clock_limit);
1925 dimer.setKappaDimer(oci_config.dimer_kappa_beta);
1926 dimer.setUseHssvdAnalyticCurvature(use_analytic_hssvd);
1929 dimer.setAlignmentAbortTol(oci_config.alignment_cos_tol);
1931 atmd::AtomicDimer::VarianceGateConfig variance_gate =
1932 dimer.getVarianceGateConfig();
1933 variance_gate.accept_tau = oci_config.dimer_variance_tau_abs;
1934 variance_gate.accept_tau_relative =
1935 resolveDimerVarianceTauRelative(neb_config, oci_config);
1936 variance_gate.imspe_soft_threshold = oci_config.dimer_imspe_soft_threshold;
1937 variance_gate.imspe_history_size =
1938 std::max(1, oci_config.dimer_imspe_history_size);
1939 dimer.setVarianceGateConfig(variance_gate);
1940
1941 result.action =
1942 dimer.previewFirstSurrogateAction(middle_point, orientation);
1943 result.surrogate = session.surrogateFingerprint(owner);
1944 return result;
1945}
1946
1947} // namespace detail
1948
1949namespace {
1950
1951bool isRank0()
1952{
1953#ifdef GPR_HAVE_MPI
1954 int mpi_up = 0;
1955 MPI_Initialized(&mpi_up);
1956 if (mpi_up) {
1957 int rank = 0;
1958 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
1959 return rank == 0;
1960 }
1961#endif
1962 return true;
1963}
1964
1965const char* mmfInformationGateName(detail::MmfInformationGate gate)
1966{
1967 switch (gate) {
1968 case detail::MmfInformationGate::Open:
1969 return "open";
1970 case detail::MmfInformationGate::AwaitingFirstTrainingGrowth:
1971 return "awaiting_first_growth";
1972 case detail::MmfInformationGate::AwaitingActionChange:
1973 return "awaiting_action_change";
1974 }
1975 return "unknown";
1976}
1977
1978const char* mmfSurrogateOwnerName(
1979 const detail::MmfSurrogateFingerprint& surrogate)
1980{
1981 return surrogate.owner >= 0 ? "image" : "global";
1982}
1983
1984} // namespace
1985
1986namespace detail {
1987
1988bool shouldRetainMmfObservation(const Eigen::VectorXd& positions,
1989 const Eigen::VectorXd& anchor,
1990 const gpr::AtomsConfiguration& atoms_config,
1991 double max_displacement)
1992{
1993 if (positions.size() != anchor.size() || positions.size() == 0) {
1994 return false;
1995 }
1996 if (!(max_displacement > 0.0)) return true;
1997 const double displacement = emdDistance(positions, anchor, atoms_config);
1998 return std::isfinite(displacement) && displacement <= max_displacement;
1999}
2000
2001bool shouldCommitMmfObservation(const Eigen::VectorXd& positions,
2002 const Eigen::VectorXd& anchor,
2003 const gpr::AtomsConfiguration& atoms_config,
2004 double max_displacement)
2005{
2006 return shouldRetainMmfObservation(positions, anchor, atoms_config,
2007 max_displacement);
2008}
2009
2010bool shouldHarvestRejectedMmfObservation(
2011 bool helped, bool trusted_recovery_advanced,
2012 const Eigen::VectorXd& positions, const Eigen::VectorXd& anchor,
2013 const gpr::AtomsConfiguration& atoms_config, double max_displacement)
2014{
2015 return !helped && !trusted_recovery_advanced &&
2016 shouldCommitMmfObservation(positions, anchor, atoms_config,
2017 max_displacement);
2018}
2019
2020} // namespace detail
2021
2023
2024double OCINEBController::forceTolerance() const
2025{
2026 return detail::resolveOciForceTolerance(cfg_);
2027}
2028
2029std::optional<Eigen::VectorXd> OCINEBController::initialModeForPath(
2030 const NEBPath& path, int ci_image_idx) const
2031{
2032 if (ci_image_idx <= 0 || ci_image_idx >= path.numImages() - 1) {
2033 return std::nullopt;
2034 }
2035 Eigen::VectorXd mode;
2036 if (cfg_.initial_orient.size() > 0) {
2037 mode = cfg_.initial_orient;
2038 } else if (has_cached_mode_ && cached_mode_.size() > 0) {
2039 mode = cached_mode_;
2040 } else {
2041 mode = path.tangentAt(ci_image_idx);
2042 }
2043 const double norm = mode.norm();
2044 if (mode.size() != path.image(ci_image_idx).positions.size() ||
2045 !mode.allFinite() || !(std::isfinite(norm) && norm >= 1e-8)) {
2046 return std::nullopt;
2047 }
2048 mode /= norm;
2049 return mode;
2050}
2051
2053 const Eigen::VectorXd& ci_position,
2054 const gpr::AtomsConfiguration* atoms_config, long climbingImage) const
2055{
2056 if (mmf_reject_ci_position_.size() == 0 ||
2057 mmf_reject_ci_position_.size() != ci_position.size()) {
2058 return false;
2059 }
2060 if ((mmf_reject_ci_position_.array() == ci_position.array()).all()) {
2061 return true;
2062 }
2063 const bool same_reject_marker = climbingImage < 0 ||
2064 mmf_reject_climbing_image_ < 0 ||
2065 climbingImage == mmf_reject_climbing_image_;
2066 if (!same_reject_marker) {
2067 return false;
2068 }
2069 if (atoms_config == nullptr || !(cfg_.max_burst_displacement > 0.0)) {
2070 return false;
2071 }
2072 // Still inside the burst trust ball of the same rejected seed marker:
2073 // EMD metric, same scale as observation commit / recovery trust.
2074 return detail::shouldRetainMmfObservation(
2075 ci_position, mmf_reject_ci_position_, *atoms_config,
2076 cfg_.max_burst_displacement);
2077}
2078
2080 const Eigen::VectorXd& ci_position,
2081 detail::MmfSurrogateFingerprint surrogate, long climbingImage,
2082 const gpr::AtomsConfiguration* atoms_config) const
2083{
2084 if (!rejectedMmfSeedPositionMatches(ci_position, atoms_config,
2085 climbingImage)) {
2086 return false;
2087 }
2088 return !detail::mmfSurrogateChanged(surrogate,
2089 mmf_surrogate_at_last_reject_);
2090}
2091
2093 const Eigen::VectorXd& ci_position,
2094 const detail::MmfPosteriorActionFingerprint& action, long climbingImage,
2095 const gpr::AtomsConfiguration* atoms_config) const
2096{
2097 if (!rejectedMmfSeedPositionMatches(ci_position, atoms_config,
2098 climbingImage)) {
2099 return false;
2100 }
2101 return !detail::mmfPosteriorActionChanged(action,
2102 mmf_action_at_last_reject_);
2103}
2104
2105void OCINEBController::saveAdaptiveState(long climbingImage)
2106{
2107 if (climbingImage < 0) return;
2108 CiAdaptiveState& state = ci_adaptive_state_[climbingImage];
2109 state.current_threshold = current_threshold_;
2110 state.baseline_force = baseline_force_;
2111 state.trap_backoff_active = trap_backoff_active_;
2112 state.trap_surface_updated = trap_surface_updated_;
2113 state.has_cached_mode = has_cached_mode_;
2114 state.mmf_attempted = mmf_attempted_;
2115 state.soft_quiet_blocked_after_reject = soft_quiet_blocked_after_reject_;
2116 state.uncertified_hook_reject_active = uncertified_hook_reject_active_;
2117 state.oie_quiet_handoff_stalled = oie_quiet_handoff_stalled_;
2118 state.exhausted_recovery_reject_active = exhausted_recovery_reject_active_;
2119 state.best_oie_quiet_handoff_force = best_oie_quiet_handoff_force_;
2120 state.trusted_retry_reject_force = trusted_retry_reject_force_;
2121 state.cached_mode = cached_mode_;
2122}
2123
2124void OCINEBController::loadAdaptiveState(long climbingImage)
2125{
2126 const auto it = ci_adaptive_state_.find(climbingImage);
2127 if (it == ci_adaptive_state_.end()) {
2128 current_threshold_ = -1.0;
2129 baseline_force_ = -1.0;
2130 trap_backoff_active_ = false;
2131 trap_surface_updated_ = false;
2132 soft_quiet_blocked_after_reject_ = false;
2133 uncertified_hook_reject_active_ = false;
2134 oie_quiet_handoff_stalled_ = false;
2135 exhausted_recovery_reject_active_ = false;
2136 best_oie_quiet_handoff_force_ =
2137 std::numeric_limits<double>::quiet_NaN();
2138 trusted_retry_reject_force_ = std::numeric_limits<double>::quiet_NaN();
2139 has_cached_mode_ = false;
2140 mmf_attempted_ = false;
2141 cached_mode_.resize(0);
2142 return;
2143 }
2144 current_threshold_ = it->second.current_threshold;
2145 baseline_force_ = it->second.baseline_force;
2146 trap_backoff_active_ = it->second.trap_backoff_active;
2147 trap_surface_updated_ = it->second.trap_surface_updated;
2148 soft_quiet_blocked_after_reject_ =
2149 it->second.soft_quiet_blocked_after_reject;
2150 uncertified_hook_reject_active_ = it->second.uncertified_hook_reject_active;
2151 oie_quiet_handoff_stalled_ = it->second.oie_quiet_handoff_stalled;
2152 exhausted_recovery_reject_active_ =
2153 it->second.exhausted_recovery_reject_active;
2154 best_oie_quiet_handoff_force_ = it->second.best_oie_quiet_handoff_force;
2155 trusted_retry_reject_force_ = it->second.trusted_retry_reject_force;
2156 has_cached_mode_ = it->second.has_cached_mode;
2157 mmf_attempted_ = it->second.mmf_attempted;
2158 cached_mode_ = it->second.cached_mode;
2159}
2160
2161void OCINEBController::initBaseline(double baseline_force)
2162{
2163 baseline_force_ = baseline_force;
2164 // Adaptive seed only: trigger_factor * baseline. No tol-multiple cap.
2165 current_threshold_ = baseline_force_ * cfg_.trigger_factor;
2166}
2167
2169 bool handoff_data_ready)
2170{
2171 if (!std::isfinite(handoff_force) || handoff_force <= 0.0) {
2172 oie_quiet_handoff_stalled_ = false;
2173 return;
2174 }
2175 if (handoff_data_ready) {
2176 oie_quiet_handoff_stalled_ =
2177 std::isfinite(best_oie_quiet_handoff_force_) &&
2178 handoff_force >= best_oie_quiet_handoff_force_;
2179 if (!std::isfinite(best_oie_quiet_handoff_force_) ||
2180 handoff_force < best_oie_quiet_handoff_force_) {
2181 best_oie_quiet_handoff_force_ = handoff_force;
2182 }
2183 } else {
2184 oie_quiet_handoff_stalled_ = false;
2185 best_oie_quiet_handoff_force_ =
2186 std::numeric_limits<double>::quiet_NaN();
2187 }
2188 retireTrustedRetryIfProgressed(handoff_force);
2189 if (baselineSet()) {
2190 // eOn adaptive: baseline is fixed at first seed until a burst updates
2191 // the threshold via success/backoff. Do not chase every lower residual.
2192 return;
2193 }
2194 // Seed only from a handoff-ready geometry: either the whole band is quiet
2195 // or the current saddle stencil is exactly measured. The adaptive force
2196 // bar still governs the MMF lease.
2197 if (!handoff_data_ready) {
2198 return;
2199 }
2200 // Seed only when the resulting adaptive threshold remains above the
2201 // convergence force. A smaller bar cannot lease MMF before NEB convergence.
2202 if (!std::isfinite(cfg_.trigger_factor) || cfg_.trigger_factor <= 0.0) {
2203 return;
2204 }
2205 const double force_tolerance = forceTolerance();
2206 if (std::isfinite(force_tolerance) && force_tolerance > 0.0) {
2207 const double minimum_seed_force = force_tolerance / cfg_.trigger_factor;
2208 if (handoff_force <= minimum_seed_force) {
2209 return;
2210 }
2211 }
2212 initBaseline(handoff_force);
2213}
2214
2215void OCINEBController::retireTrustedRetryIfProgressed(double handoff_force)
2216{
2217 if (!detail::shouldRetireTrustedRetryAfterProgress(
2218 trusted_recovery_active_, trusted_retry_reject_force_,
2219 handoff_force, current_threshold_)) {
2220 return;
2221 }
2222 trusted_retry_reject_force_ = std::numeric_limits<double>::quiet_NaN();
2223 trap_surface_updated_ = false;
2224}
2225
2227 bool trap_detected, bool band_information_exhausted,
2228 bool current_chain_certificate) const
2229{
2230 const bool trap_retry_ready =
2231 trap_detected && (!trap_backoff_active_ || trap_surface_updated_);
2232 const bool certified_band_information_exhausted =
2233 band_information_exhausted && current_chain_certificate;
2234 return cfg_.handoff_policy != MmfHandoffPolicy::GpBandFallback ||
2235 mmf_attempted_ || trap_retry_ready ||
2236 certified_band_information_exhausted;
2237}
2238
2240 double convForce, bool ci_active, long climbingImage, long numImages,
2241 bool ci_posterior_confident, bool trap_detected, std::size_t ntrain_now,
2242 bool ci_is_energy_maximum, bool band_information_exhausted,
2243 bool oie_acquisition_quiet, bool rejected_seed_replay,
2244 bool current_chain_certificate, bool current_saddle_stencil_certificate,
2245 bool rejected_seed_position_matches, bool stagnation_handoff) const
2246{
2247 // The band walk has stopped. Lease the dimer when the residual is
2248 // still above the force tolerance. The adaptive bar is for a walk
2249 // that is still descending; it does not apply to this handoff.
2250 if (stagnation_handoff) {
2251 return detail::shouldTriggerMmf(
2252 cfg_, convForce, ci_active, climbingImage, numImages,
2253 /*ci_posterior_confident=*/true, /*current_threshold=*/0.0,
2254 /*trap_detected=*/false, /*trap_backoff_active=*/false,
2255 /*trap_surface_updated=*/false, mmf_info_gate_,
2256 /*ci_is_energy_maximum=*/true,
2257 /*band_information_exhausted=*/false,
2258 /*oie_acquisition_quiet=*/false, /*oie_acquisition_stalled=*/false,
2259 /*certified_recovery_stalled_handoff=*/false,
2260 /*certified_handoff=*/true);
2261 }
2262 if (detail::shouldHoldMmfForExpectedImprovement(
2263 mmf_wait_for_true_sample_, static_cast<Eigen::Index>(ntrain_now),
2264 mmf_wait_ntrain_)) {
2265 return false;
2266 }
2267 if (detail::shouldSuppressMmfRecoveryRetry(force_improving_recovery_active_,
2268 trusted_recovery_active_,
2269 mmf_info_gate_)) {
2270 return false;
2271 }
2272 const bool certified_band_information_exhausted =
2273 band_information_exhausted && current_chain_certificate;
2274 const bool reject_gate_applies_to_ci =
2275 mmf_reject_climbing_image_ < 0 ||
2276 climbingImage == mmf_reject_climbing_image_;
2277 const bool exhausted_recovery_reject_applies =
2278 detail::exhaustedRecoveryRejectAppliesToCi(
2279 exhausted_recovery_reject_active_, mmf_reject_climbing_image_,
2280 climbingImage);
2281 const bool improved_under_backoff =
2282 std::isfinite(current_threshold_) && current_threshold_ > 0.0 &&
2283 std::isfinite(convForce) && convForce <= current_threshold_;
2284 // Residual strictly below pure-reject handoff force. The tracked force
2285 // ratchets with live residuals so geometric progress can reopen the gate
2286 // without pinning re-entry to an initial handoff scale.
2287 const bool improved_since_pure_reject =
2288 pure_reject_lock_ && std::isfinite(pure_reject_force_) &&
2289 pure_reject_force_ > 0.0 && std::isfinite(convForce) &&
2290 convForce < pure_reject_force_;
2291 const bool pure_reject_residual_progress =
2292 detail::shouldLeaseAfterPureRejectProgress(pure_reject_lock_,
2293 improved_under_backoff,
2294 improved_since_pure_reject);
2295 const bool exhausted_quiet_stall_lease =
2296 detail::shouldLeaseAfterExhaustedQuietStall(
2297 pure_reject_lock_, exhausted_recovery_reject_applies,
2298 oie_quiet_handoff_stalled_, oie_acquisition_quiet,
2299 current_chain_certificate, current_saddle_stencil_certificate,
2300 ci_posterior_confident, ci_is_energy_maximum);
2301 // Rejected-seed replay blocks re-fire of the identical geometry. Under-thr
2302 // residual alone is not enough to re-lease the same seed: Baker 02 burned
2303 // ~30 Helped path-cert rejects at F_CI~0.135 on one geometry. Progress
2304 // below pure_reject_force, or a trap, is the only reopen without a move.
2305 const bool rejected_seed_geometry_replay =
2306 rejected_seed_replay || rejected_seed_position_matches;
2307 if (detail::shouldSkipMmfAfterSpentMinModeProbe(
2308 min_mode_probe_spent_, rejected_seed_replay,
2309 rejected_seed_position_matches)) {
2310 return false;
2311 }
2312 if (detail::shouldBlockRejectedSeedReplay(
2313 rejected_seed_geometry_replay, trap_detected,
2314 improved_since_pure_reject, exhausted_quiet_stall_lease)) {
2315 return false;
2316 }
2317 const bool trusted_retry_progress_pending =
2318 trusted_recovery_active_ &&
2319 std::isfinite(trusted_retry_reject_force_) &&
2320 trusted_retry_reject_force_ > 0.0;
2321 const bool force_recovery_stalled_handoff =
2322 detail::isForceImprovingRecoveryStalledHandoff(
2323 force_improving_recovery_active_, ci_posterior_confident,
2324 current_chain_certificate, oie_acquisition_quiet,
2325 oie_quiet_handoff_stalled_);
2326 const bool trusted_recovery_stalled_signal =
2327 detail::isTrustedRecoveryStalledHandoff(
2328 trusted_recovery_active_, ci_posterior_confident,
2329 current_chain_certificate, ci_is_energy_maximum,
2330 oie_acquisition_quiet, oie_quiet_handoff_stalled_);
2331 const bool trusted_recovery_stalled_handoff =
2332 detail::shouldUseTrustedRecoveryStalledHandoff(
2333 trusted_retry_progress_pending, trusted_recovery_stalled_signal);
2334 const bool recovery_stalled_handoff =
2335 force_recovery_stalled_handoff || trusted_recovery_stalled_handoff;
2336 const bool trusted_recovery_progress_handoff =
2337 detail::isTrustedRecoveryProgressHandoff(
2338 trusted_recovery_active_, trusted_retry_reject_force_, convForce,
2339 current_threshold_, ci_posterior_confident, ci_is_energy_maximum,
2340 rejected_seed_replay, current_chain_certificate,
2341 oie_quiet_handoff_stalled_, oie_acquisition_quiet);
2342 const bool refreshed_exhausted_recovery_handoff =
2343 detail::isRefreshedExhaustedRecoveryHandoff(
2344 exhausted_recovery_reject_applies, current_chain_certificate,
2345 current_saddle_stencil_certificate, rejected_seed_replay,
2346 rejected_seed_replay || rejected_seed_position_matches,
2347 ci_posterior_confident, ci_is_energy_maximum);
2348 const bool stale_rejected_seed_handoff =
2349 !exhausted_recovery_reject_applies && !trusted_retry_progress_pending &&
2350 soft_quiet_blocked_after_reject_ && !rejected_seed_replay &&
2351 current_chain_certificate && ci_posterior_confident &&
2352 ci_is_energy_maximum && oie_acquisition_quiet &&
2353 oie_quiet_handoff_stalled_;
2354 // A first exact CI row seeds the adaptive scale but does not void it.
2355 // Certificate-based bar bypass resolves a stalled or recovery handoff;
2356 // ordinary first contact continues reducing the force residual.
2357 const bool certificate_bar_bypass_state =
2358 oie_quiet_handoff_stalled_ || pure_reject_lock_ ||
2359 soft_quiet_blocked_after_reject_ || force_improving_recovery_active_ ||
2360 trusted_recovery_active_;
2361 const bool current_chain_certified_handoff =
2362 certificate_bar_bypass_state &&
2363 detail::isCurrentChainCertifiedHandoff(
2364 trusted_retry_progress_pending, current_chain_certificate,
2365 rejected_seed_replay, ci_posterior_confident, ci_is_energy_maximum,
2366 oie_acquisition_quiet, exhausted_recovery_reject_applies);
2367 const bool current_chain_under_threshold_handoff =
2368 !trusted_retry_progress_pending && current_chain_certificate &&
2369 !rejected_seed_replay && oie_acquisition_quiet &&
2370 std::isfinite(convForce) && convForce > 0.0 &&
2371 std::isfinite(current_threshold_) && current_threshold_ > 0.0 &&
2372 convForce <= current_threshold_;
2373 // An unattempted exact true-PES saddle stencil gives MMF every local row
2374 // it consumes. Bayes confidence and the energy-maximum certificate bind
2375 // that stencil to the active saddle, so the band-scale force bar does not
2376 // withhold the local second-order refinement.
2377 const bool exact_saddle_stencil_handoff =
2378 !mmf_attempted_ && current_saddle_stencil_certificate &&
2379 current_chain_certificate && !rejected_seed_replay &&
2380 ci_posterior_confident && ci_is_energy_maximum;
2381 const bool certified_handoff =
2382 stale_rejected_seed_handoff || current_chain_certified_handoff ||
2383 current_chain_under_threshold_handoff || exact_saddle_stencil_handoff ||
2384 refreshed_exhausted_recovery_handoff || recovery_stalled_handoff ||
2385 trusted_recovery_progress_handoff;
2386 bool soft_quiet = oie_acquisition_quiet;
2387 if (soft_quiet && soft_quiet_blocked_after_reject_ &&
2388 reject_gate_applies_to_ci) {
2389 soft_quiet = improved_under_backoff || recovery_stalled_handoff ||
2390 certified_handoff;
2391 }
2392 const bool soft_quiet_stalled = soft_quiet && oie_quiet_handoff_stalled_;
2393 const bool trap_retry_ready =
2394 trap_detected && (!trap_backoff_active_ || trap_surface_updated_);
2395 // An exact local stencil proves that MMF has current data, but it does not
2396 // prove that the GP band has settled onto the connecting path. GP-assisted
2397 // modes retain the first lease while TPE can still improve the band. A
2398 // measured trap or likelihood-floor exhaustion transfers ownership
2399 // without a system-specific force threshold. Repeated stored CI forces do
2400 // not certify a fixed band while TPE can still move other images.
2401 if (!shouldPrepareMmfHandoff(trap_detected, band_information_exhausted,
2402 current_chain_certificate)) {
2403 return false;
2404 }
2405 // Pure restore-reject lock is global until residual progress,
2406 // recovery-stall handoff, quiet-stall after exhausted recovery, or
2407 // certified noise-floor exhaustion. Soft-quiet and rejected-seed state
2408 // remain CI-scoped below.
2409 // Recovery-stall still leases: force-improving recovery locks at the post
2410 // force, so quiet-stall is the intended re-entry when OIE stops dropping.
2411 if (pure_reject_lock_ && !pure_reject_residual_progress &&
2412 !certified_band_information_exhausted && !recovery_stalled_handoff &&
2413 !certified_handoff && !exhausted_quiet_stall_lease &&
2414 !trap_retry_ready) {
2415 return false;
2416 }
2417 // After a non-Helped burst, soft quiet and confidence reopen under the
2418 // adaptive threshold, after pure-reject residual progress, or via a
2419 // certified/exhausted handoff.
2420 if (soft_quiet_blocked_after_reject_ && reject_gate_applies_to_ci &&
2421 !improved_under_backoff && !trap_detected &&
2422 !certified_band_information_exhausted && !recovery_stalled_handoff &&
2423 !certified_handoff && !exhausted_quiet_stall_lease &&
2424 !pure_reject_residual_progress) {
2425 return false;
2426 }
2427 // Pure-lock residual progress voids the adaptive thr when the CI is also
2428 // the Bayes peak (confidence required). thr often ratchets below the live
2429 // CI residual after recovery backoff (Baker 05: F~1.17, thr~0.77 after
2430 // pure-lock at 1.55). Exhausted quiet-stall is a certified handoff: voids
2431 // the bar so MMF can fire while residual sits above thr (Baker 03).
2432 const double trigger_threshold =
2433 (!baselineSet() && ci_posterior_confident) ? 0.0 : current_threshold_;
2434 const bool pure_reject_residual_handoff =
2435 pure_reject_residual_progress && ci_posterior_confident;
2436 // Stall leases and pure-reject progress still wait out a closed
2437 // information gate. Certified handoff does not: it is the argument
2438 // shouldTriggerMmf decides before that gate.
2439 const bool lease_after_information_gate =
2440 recovery_stalled_handoff || exhausted_quiet_stall_lease ||
2441 pure_reject_residual_handoff || pending_min_mode_probe_lease_;
2442 const bool certified_handoff_beats_gate =
2443 stale_rejected_seed_handoff || current_chain_certified_handoff ||
2444 current_chain_under_threshold_handoff || exact_saddle_stencil_handoff ||
2445 refreshed_exhausted_recovery_handoff ||
2446 trusted_recovery_progress_handoff;
2447 return detail::shouldTriggerMmf(
2448 cfg_, convForce, ci_active, climbingImage, numImages,
2449 ci_posterior_confident, trigger_threshold, trap_detected,
2450 trap_backoff_active_, trap_surface_updated_, mmf_info_gate_,
2451 ci_is_energy_maximum, certified_band_information_exhausted, soft_quiet,
2452 soft_quiet_stalled, lease_after_information_gate,
2453 certified_handoff_beats_gate);
2454}
2455
2457{
2458 trap_surface_updated_ = true;
2459}
2460
2462 detail::MmfSurrogateFingerprint surrogate)
2463{
2464 detail::MmfPosteriorActionFingerprint action;
2465 action.surrogate = surrogate;
2466 noteMmfRejectActionSnapshot(std::move(action));
2467}
2468
2470 detail::MmfPosteriorActionFingerprint action)
2471{
2472 using Gate = detail::MmfInformationGate;
2473 mmf_info_gate_ = action.action.valid ? Gate::AwaitingActionChange
2474 : Gate::AwaitingFirstTrainingGrowth;
2475 mmf_surrogate_at_last_reject_ = action.surrogate;
2476 mmf_action_at_last_reject_ = std::move(action);
2477}
2478
2480 detail::MmfSurrogateFingerprint surrogate)
2481{
2482 const bool changed_since_reject =
2483 detail::mmfSurrogateChanged(surrogate, mmf_surrogate_at_last_reject_);
2484 const bool was_waiting = mmf_info_gate_ != detail::MmfInformationGate::Open;
2485 if (was_waiting && changed_since_reject) {
2486 mmf_info_gate_ = detail::MmfInformationGate::Open;
2487 uncertified_hook_reject_active_ = false;
2488 trap_surface_updated_ = true;
2489 for (auto& [_, state]: ci_adaptive_state_) {
2490 if (state.trap_backoff_active) {
2491 state.trap_surface_updated = true;
2492 }
2493 }
2494 }
2495}
2496
2498 detail::MmfPosteriorActionFingerprint action)
2499{
2500 const bool changed_since_reject =
2501 detail::mmfPosteriorActionChanged(action, mmf_action_at_last_reject_);
2502 if (changed_since_reject) {
2503 min_mode_probe_spent_ = false;
2504 }
2505 const bool was_waiting = mmf_info_gate_ != detail::MmfInformationGate::Open;
2506 if (was_waiting && changed_since_reject) {
2507 mmf_info_gate_ = detail::MmfInformationGate::Open;
2508 }
2509 if (mmf_info_gate_ == detail::MmfInformationGate::Open) {
2510 uncertified_hook_reject_active_ = false;
2511 }
2512 if (was_waiting && changed_since_reject &&
2513 mmf_info_gate_ == detail::MmfInformationGate::Open) {
2514 trap_surface_updated_ = true;
2515 for (auto& [_, state]: ci_adaptive_state_) {
2516 if (state.trap_backoff_active) {
2517 state.trap_surface_updated = true;
2518 }
2519 }
2520 }
2521}
2522
2523detail::MmfPosteriorActionFingerprint OCINEBController::previewMmfAction(
2524 ActiveLearningSession& session, const NEBPath& path, int ci_image_idx,
2525 const GPNEBConfig& neb_config) const
2526{
2527 detail::MmfPosteriorActionFingerprint result;
2528 const int owner =
2529 session.mmfModelOwner(ci_image_idx, neb_config.dimer_use_global_gp);
2530 result.surrogate = session.surrogateFingerprint(owner);
2531 if (!neb_config.gp_setup) return result;
2532
2533 const std::optional<Eigen::VectorXd> initial_mode =
2534 initialModeForPath(path, ci_image_idx);
2535 if (!initial_mode) return result;
2536 Eigen::VectorXd seed = path.image(ci_image_idx).positions;
2537 const double seed_displacement = detail::resolveMmfSeedDisplacement(
2538 cfg_.perturb_along_tangent, force_improving_recovery_active_,
2539 trusted_recovery_active_);
2540 if (seed_displacement != 0.0) {
2541 seed += seed_displacement * *initial_mode;
2542 }
2543
2544 Eigen::VectorXd seed_gradient;
2545 const int observation_index =
2546 detail::findPositionIndex(session.training_obs, seed);
2547 if (observation_index >= 0 &&
2548 observation_index < session.training_obs.G.rows() &&
2549 session.training_obs.G.cols() == seed.size() &&
2550 session.training_obs.G.row(observation_index).allFinite()) {
2551 seed_gradient =
2552 session.training_obs.G.row(observation_index).transpose();
2553 } else if (detail::positionsCoincide(seed,
2554 path.image(ci_image_idx).positions) &&
2555 path.image(ci_image_idx).gradient.size() == seed.size() &&
2556 path.image(ci_image_idx).gradient.allFinite()) {
2557 seed_gradient = path.image(ci_image_idx).gradient;
2558 } else {
2560 owner >= 0 ? session.acquireImageModel(owner)
2561 : session.acquireGlobalModel();
2562 gpr::Observation predicted;
2563 predicted.R = flatToCoord1xD(seed);
2564 model.gp().calculatePotentialDispatched(predicted);
2565 if (predicted.G.rows() != 1 || predicted.G.cols() != seed.size() ||
2566 !predicted.G.allFinite()) {
2567 result.surrogate = session.surrogateFingerprint(owner);
2568 return result;
2569 }
2570 seed_gradient = predicted.G.row(0).transpose();
2571 }
2572
2573 return detail::probeMmfPosteriorAction(
2574 session, ci_image_idx, neb_config.dimer_use_global_gp, seed,
2575 seed_gradient, *initial_mode, neb_config, cfg_);
2576}
2577
2579 const Eigen::VectorXd& owner_position, long owner_image)
2580{
2581 if (!detail::activeMmfRecoveryOwnsClimbingImage(
2582 force_improving_recovery_active_, trusted_recovery_active_)) {
2583 return;
2584 }
2585 if (force_improving_recovery_active_) {
2586 pure_reject_lock_ = false;
2587 pure_reject_force_ = std::numeric_limits<double>::quiet_NaN();
2588 }
2589 force_improving_recovery_active_ = false;
2590 trusted_recovery_active_ = false;
2591 recovery_owner_image_ = -1;
2592 trusted_retry_reject_force_ = std::numeric_limits<double>::quiet_NaN();
2593 trap_surface_updated_ = false;
2594 mmf_info_gate_ = detail::MmfInformationGate::Open;
2595 mmf_surrogate_at_last_reject_ = {};
2596 mmf_action_at_last_reject_ = {};
2597 exhausted_recovery_reject_active_ = true;
2598 noteMmfRejectCiPosition(owner_position, owner_image);
2599}
2600
2602{
2603 if (!exhausted_recovery_reject_active_) return;
2604 exhausted_recovery_reject_active_ = false;
2605 soft_quiet_blocked_after_reject_ = false;
2606 pure_reject_lock_ = false;
2607 pure_reject_force_ = std::numeric_limits<double>::quiet_NaN();
2608 trap_backoff_active_ = false;
2609 trap_surface_updated_ = false;
2610 uncertified_hook_reject_active_ = false;
2611 oie_quiet_handoff_stalled_ = false;
2612 best_oie_quiet_handoff_force_ = std::numeric_limits<double>::quiet_NaN();
2613 mmf_info_gate_ = detail::MmfInformationGate::Open;
2614 mmf_surrogate_at_last_reject_ = {};
2615 mmf_action_at_last_reject_ = {};
2616 mmf_reject_ci_position_.resize(0);
2617 mmf_reject_climbing_image_ = -1;
2618}
2619
2621 double convForce, const Eigen::VectorXd& ci_position,
2622 detail::MmfSurrogateFingerprint surrogate, long climbingImage)
2623{
2624 detail::MmfPosteriorActionFingerprint action;
2625 action.surrogate = surrogate;
2626 recordUncertifiedMmfHookReject(convForce, ci_position, std::move(action),
2627 climbingImage);
2628}
2629
2631 double convForce, const Eigen::VectorXd& ci_position,
2632 detail::MmfPosteriorActionFingerprint action, long climbingImage)
2633{
2634 if (baselineSet()) {
2635 updateThresholdBackoff(convForce);
2636 } else {
2637 trap_backoff_active_ = true;
2638 trap_surface_updated_ = false;
2639 soft_quiet_blocked_after_reject_ = true;
2640 }
2641 force_improving_recovery_active_ = false;
2642 trusted_recovery_active_ = false;
2643 recovery_owner_image_ = -1;
2644 noteMmfRejectActionSnapshot(std::move(action));
2645 noteMmfRejectCiPosition(ci_position, climbingImage);
2646 uncertified_hook_reject_active_ = true;
2647 // Hook-rejected Helped restores the CI (side saddle / below-endpoint): a
2648 // pure restore. Without pure-lock Baker 08 re-fired the same Helped→hook
2649 // reject loop.
2650 if (detail::isMmfAdaptiveThresholdSeeded(current_threshold_) &&
2651 std::isfinite(convForce) && convForce > 0.0) {
2652 pure_reject_lock_ = true;
2653 pure_reject_force_ = convForce;
2654 }
2655}
2656
2658 double convForce, bool ci_active, long climbingImage, long numImages,
2659 int outerIter, bool ci_posterior_confident, bool trap_detected,
2660 std::size_t ntrain_now, bool ci_is_energy_maximum)
2661{
2662 if (!cfg_.use_mmf || !ci_active) return false;
2663 updateStabilityForOuter(climbingImage, outerIter);
2664 const bool valid_climbing_image =
2665 climbingImage > 0 && climbingImage <= numImages;
2666 const bool active_recovery_needs_oracle =
2667 detail::activeMmfRecoveryOwnsClimbingImage(
2668 force_improving_recovery_active_, trusted_recovery_active_);
2669 const bool exhausted_recovery_needs_oracle =
2670 detail::shouldRequestCurrentCiOracleForExhaustedRecovery(
2671 exhausted_recovery_reject_active_, mmf_reject_climbing_image_,
2672 climbingImage);
2673 if (valid_climbing_image &&
2674 (active_recovery_needs_oracle || exhausted_recovery_needs_oracle)) {
2675 return true;
2676 }
2677 const bool trap_retry_needs_oracle =
2678 detail::shouldUseSurfaceUpdatedTrapRetryForCurrentCiOracle(
2679 trap_surface_updated_, trusted_recovery_active_,
2680 trusted_retry_reject_force_, convForce, current_threshold_);
2681 const bool effective_trap = trap_detected || trap_retry_needs_oracle;
2682 if (!shouldPrepareMmfHandoff(effective_trap)) return false;
2683 // An unseeded confident saddle requests the exact local data needed to
2684 // decide whether the dimer can consume this geometry. The request builds
2685 // a certificate; it does not itself lease an MMF burst.
2686 if (!baselineSet()) {
2687 const double force_tolerance = forceTolerance();
2688 return climbingImage > 0 && climbingImage <= numImages &&
2689 ci_posterior_confident && ci_is_energy_maximum &&
2690 std::isfinite(convForce) && std::isfinite(force_tolerance) &&
2691 force_tolerance > 0.0 && convForce > force_tolerance;
2692 }
2693 return shouldTrigger(convForce, ci_active, climbingImage, numImages,
2694 ci_posterior_confident, effective_trap, ntrain_now,
2695 ci_is_energy_maximum);
2696}
2697
2699{
2700 if (climbingImage == previousClimbingImage_) return;
2701 if (previousClimbingImage_ < 0) {
2702 previousClimbingImage_ = climbingImage;
2703 saveAdaptiveState(climbingImage);
2704 return;
2705 }
2706 // The climbing image moved: persist the outgoing image's adaptive
2707 // trigger state and restore the incoming one.
2708 saveAdaptiveState(previousClimbingImage_);
2709 previousClimbingImage_ = climbingImage;
2710 loadAdaptiveState(climbingImage);
2711 // FI pure-lock post residual is image-local; pure-restore stays global.
2712 const detail::PureLockHopState hop = detail::pureLockStateAfterCiHop(
2713 {pure_reject_lock_, pure_reject_force_,
2714 force_improving_recovery_active_, trusted_recovery_active_});
2715 pure_reject_lock_ = hop.pure_reject_lock;
2716 pure_reject_force_ = hop.pure_reject_force;
2717 force_improving_recovery_active_ = hop.force_improving_recovery_active;
2718 trusted_recovery_active_ = hop.trusted_recovery_active;
2719 if (!detail::activeMmfRecoveryOwnsClimbingImage(
2720 force_improving_recovery_active_, trusted_recovery_active_)) {
2721 recovery_owner_image_ = -1;
2722 }
2723}
2724
2726 int outerIter)
2727{
2728 if (outerIter == lastStabilityOuter_ &&
2729 climbingImage == lastStabilityClimbingImage_) {
2730 return;
2731 }
2732 updateStability(climbingImage);
2733 lastStabilityOuter_ = outerIter;
2734 lastStabilityClimbingImage_ = climbingImage;
2735}
2736
2737void OCINEBController::updateThresholdSuccess(double convForce, double newForce)
2738{
2739 const double max_threshold = baseline_force_ * cfg_.trigger_factor;
2740 current_threshold_ =
2741 detail::successThresholdAfterMmf(convForce, newForce, max_threshold);
2742 trap_backoff_active_ = false;
2743 trap_surface_updated_ = false;
2744 uncertified_hook_reject_active_ = false;
2745 soft_quiet_blocked_after_reject_ = false;
2746 pure_reject_lock_ = false;
2747 force_improving_recovery_active_ = false;
2748 trusted_recovery_active_ = false;
2749 recovery_owner_image_ = -1;
2750 exhausted_recovery_reject_active_ = false;
2751 oie_quiet_handoff_stalled_ = false;
2752 best_oie_quiet_handoff_force_ = std::numeric_limits<double>::quiet_NaN();
2753 mmf_info_gate_ = detail::MmfInformationGate::Open;
2754 mmf_surrogate_at_last_reject_ = {};
2755 mmf_action_at_last_reject_ = {};
2756}
2757
2758void OCINEBController::updateThresholdBackoff(double convForce)
2759{
2760 const double max_threshold = baseline_force_ * cfg_.trigger_factor;
2761 // Geometric-mean bar for recovery phase selection only (eOn adaptive).
2762 current_threshold_ = detail::rejectedMmfBackoffThreshold(
2763 convForce, forceTolerance(), max_threshold);
2764 trap_backoff_active_ = true;
2765 trap_surface_updated_ = false;
2766 uncertified_hook_reject_active_ = false;
2767 soft_quiet_blocked_after_reject_ = true;
2768 force_improving_recovery_active_ = false;
2769 recovery_owner_image_ = -1;
2770 exhausted_recovery_reject_active_ = false;
2771 oie_quiet_handoff_stalled_ = false;
2772 best_oie_quiet_handoff_force_ = std::numeric_limits<double>::quiet_NaN();
2773 // The surrogate snapshot is set by the caller; gate transitions compare
2774 // the exact model lease MMF would consume.
2775}
2776
2777void detail::configureBurstDimerSecant(atmd::AtomicDimer& dimer,
2778 const optim::SecantHessianConfig& band)
2779{
2780 auto dimer_secant = band;
2781 dimer_secant.quadratic_prior_mean = false;
2782 dimer.setSecantHessianConfig(dimer_secant);
2783 dimer.setSecantOrientationSeed(false);
2784}
2785
2786std::vector<StagedDimerObservation> detail::stageDimerObservationUpdates(
2787 const gpr::Observation& initial, const gpr::Coord& positions,
2788 const gpr::FieldMatrixd& energies, const gpr::Coord& gradients,
2789 double energy_origin)
2790{
2791 std::vector<StagedDimerObservation> staged;
2792 for (Eigen::Index row = 0; row < positions.rows(); ++row) {
2793 // Coalescing a measured neighbour replaces a retained row in place.
2794 // Compare in the dimer's energy coordinates to avoid introducing a
2795 // round trip through the absolute energy origin for unchanged rows.
2796 const bool unchanged =
2797 row < initial.R.rows() &&
2798 (initial.R.row(row).array() == positions.row(row).array()).all() &&
2799 initial.E(row, 0) - energy_origin == energies(row, 0) &&
2800 (initial.G.row(row).array() == gradients.row(row).array()).all();
2801 if (unchanged) continue;
2802 staged.push_back({positions.row(row).transpose(),
2803 energies(row, 0) + energy_origin,
2804 gradients.row(row).transpose()});
2805 }
2806 return staged;
2807}
2808
2809void OCINEBController::runBurstUnderSessionModelLease(
2810 int ci_image_idx, NEBOracle& oracle, const GPNEBConfig& neb_config,
2811 ActiveLearningSession& session, const Eigen::VectorXd& initialMode,
2812 const gpr::Observation& middle_point, atmd::AtomicDimer& dimer,
2813 bool per_image_ready, MMFRunResult& result,
2814 std::vector<StagedDimerObservation>& staged_dimer_observations)
2815{
2816 ActiveLearningSession::ModelLease model = [&]() {
2817 if (per_image_ready) {
2818 return session.acquireImageModel(ci_image_idx);
2819 }
2820 return session.acquireGlobalModel();
2821 }();
2822 auto restore_model = model.scopedParameterRestore();
2823
2824 gpr::Observation init_observations = model.observations();
2825 gpr::Coord init_orient_coord = flatToCoord1xD(initialMode);
2826
2827 gpr::AtomsConfiguration tmp;
2828 const bool use_analytic_hssvd =
2829 detail::shouldUseHssvdAnalyticDimerCurvature(
2830 neb_config, model.gp().hasReusableHssvdPosterior());
2831 gpr::InputParameters parameters =
2832 detail::buildDimerParameters(neb_config, cfg_, tmp, use_analytic_hssvd);
2833
2834 // The lease owns the attached GP handle for the full dimer
2835 // execution. AtomicDimer may refit theta against its burst
2836 // observations; the scoped restorer reinstalls the entry theta
2837 // and refactorizes over the harvested training rows.
2838 dimer.attachExternalGP(&model.gp());
2839 dimer.initialize(parameters, init_observations, middle_point,
2840 init_orient_coord, session.atoms_config);
2841 dimer.setKappaDimer(cfg_.dimer_kappa_beta);
2842 dimer.setUseHssvdAnalyticCurvature(use_analytic_hssvd);
2845 ++mmf_bursts_fired_;
2846 mmf_attempted_ = true;
2847 // OCI-NEB uses certificate-governed termination. The dimer axis stays
2848 // aligned with the tangent that seeds the burst; a positive explicit
2849 // phase budget remains an operator override.
2850 dimer.setAlignmentAbortTol(cfg_.alignment_cos_tol);
2852 // Posterior-variance acceptance gate + IMSPE soft-skip. The
2853 // variance gate is the primary control on dimer oracle traffic:
2854 // a dimer outer phase only queries the true potential where the
2855 // GP posterior variance exceeds dimer_variance_tau_rel *
2856 // magnSigma2 (or the absolute cap dimer_variance_tau_abs).
2857 // Without it every dimer outer phase fires an oracle call up to
2858 // the phase budget. The IMSPE soft-skip is an optional second
2859 // filter: candidates that pass the variance gate are scored over
2860 // the dimer's EMD-filtered recent-query ring buffer and low
2861 // scores suppress the call. EMD dedup remains the safety net for
2862 // genuinely redundant samples.
2863 {
2864 atmd::AtomicDimer::VarianceGateConfig vg =
2865 dimer.getVarianceGateConfig();
2866 vg.accept_tau = cfg_.dimer_variance_tau_abs;
2868 detail::resolveDimerVarianceTauRelative(neb_config, cfg_);
2869 vg.imspe_soft_threshold = cfg_.dimer_imspe_soft_threshold;
2870 vg.imspe_history_size = std::max(1, cfg_.dimer_imspe_history_size);
2871 dimer.setVarianceGateConfig(vg);
2872 }
2873#ifdef USE_READCON_DB
2874 dimer.setObservationArchive(session.observationArchive());
2875#endif
2876 pot::PotentialWrapper potential = makePotentialWrapperFromOracle(oracle);
2877 detail::configureBurstDimerSecant(dimer, neb_config.secant_hessian);
2878 const gpr::optim::SecantCurvatureCounts replayed_secants =
2879 dimer.secantLedger();
2880 dimer.execute(potential);
2881 gpr::optim::SecantCurvatureCounts fresh_secants = dimer.secantLedger();
2882 fresh_secants.pairs_accepted -= replayed_secants.pairs_accepted;
2883 fresh_secants.pairs_rejected -= replayed_secants.pairs_rejected;
2884 fresh_secants.hvp_calls -= replayed_secants.hvp_calls;
2885 fresh_secants.consistency_rejections -=
2886 replayed_secants.consistency_rejections;
2887 session.addSecantCounts(fresh_secants);
2888
2889 result.oracle_calls += static_cast<int>(dimer.getTotalForceCalls());
2890 mmf_iterations_used_ += static_cast<long>(dimer.getIterations());
2891
2892 // Stage appended measurements and replacements of retained rows.
2893 // The controller's acceptance and locality rules select which rows
2894 // condition the band; the observation archive retains every acquisition.
2895 // Restoring the energy origin preserves absolute oracle energies.
2896 {
2897 gpr::Coord& dimer_R =
2899 gpr::FieldMatrixd& dimer_E =
2902 const gpr::FieldMatrixd e_zero = dimer.getEnergyZeroLevel();
2903 const double e0 = (e_zero.size() > 0) ? e_zero(0, 0) : 0.0;
2904 staged_dimer_observations = detail::stageDimerObservationUpdates(
2905 init_observations, dimer_R, dimer_E, dimer_G, e0);
2906 }
2907
2908 restore_model.restore();
2909}
2910
2911void OCINEBController::runBurstOnTruePotential(
2912 NEBOracle& oracle, const GPNEBConfig& neb_config,
2913 ActiveLearningSession& session, bool trap_detected,
2914 const Eigen::VectorXd& initialMode, const gpr::Observation& middle_point,
2915 atmd::AtomicDimer& dimer, double pre_neb_force, bool has_gp,
2916 MMFRunResult& result,
2917 std::vector<StagedDimerObservation>& staged_dimer_observations)
2918{
2919 // No GP surrogate (Standard / AIE): run a standalone dimer directly
2920 // on the true potential, as gprd does -- no session model lease, no
2921 // external GP attach, no observation staging. AtomicDimer builds its
2922 // own internal surrogate from the oracle evaluations it makes around
2923 // the climbing image, and the result handling below reads the dimer
2924 // trajectory exactly as in the GP path.
2925 gpr::Observation empty_obs;
2926 gpr::Coord init_orient_coord = flatToCoord1xD(initialMode);
2927 gpr::AtomsConfiguration tmp;
2928 gpr::InputParameters parameters =
2929 detail::buildDimerParameters(neb_config, cfg_, tmp);
2930 // The fresh dimer's own likelihood must carry the same model-noise
2931 // floor the session GP uses: its rows come from the same oracle,
2932 // whose reported energy uncertainty (running median) IS the data
2933 // noise. A default 1e-5 likelihood against near-duplicate dimer
2934 // steps makes the local fit near-singular and its min-mode
2935 // curvature garbage (observed -253 to -1.2e11 on the rejected
2936 // bursts of 01/03/25), so every recovery phase rejects.
2937 const double* energy_noise_rms =
2938 detail::oracleEnergyNoiseRmsPtr(neb_config);
2939 if (energy_noise_rms != nullptr) {
2940 const double rms = *energy_noise_rms;
2941 if (std::isfinite(rms) && rms > 0.0) {
2942 parameters.gp_sigma2.value =
2943 std::max(parameters.gp_sigma2.value, rms * rms);
2944 }
2945 }
2946 dimer.setKappaDimer(cfg_.dimer_kappa_beta);
2947 dimer.setSelfOwnedModelProfile(neb_config.model_profile);
2948 dimer.setSelfOwnedUseZblPriorMean(neb_config.use_zbl_prior_mean);
2949 dimer.setSelfOwnedUseFfPriorMean(neb_config.use_ff_prior_mean);
2950 dimer.initialize(parameters, empty_obs, middle_point, init_orient_coord,
2951 session.atoms_config);
2952 if (energy_noise_rms != nullptr) {
2953 const double rms = *energy_noise_rms;
2954 if (std::isfinite(rms) && rms > 0.0) {
2955 dimer.setLikelihoodNoiseFloorSigma2(rms * rms);
2956 }
2957 }
2959 detail::shouldUseHssvdAnalyticDimerCurvature(neb_config));
2962 ++mmf_bursts_fired_;
2963 mmf_attempted_ = true;
2964 dimer.setAlignmentAbortTol(cfg_.alignment_cos_tol);
2966 // Relax the band-tangent leash near the saddle ONLY where the chain
2967 // tangent is an unreliable saddle-mode seed: the GP is over-confident-
2968 // but-inaccurate at the CI (trap_detected), or the CI has reached the
2969 // adaptive acceptance threshold. Far from the saddle, or on a confident
2970 // band, the leash stays in force so the burst cannot wander onto a
2971 // wrong saddle (the failure mode if the leash is relaxed
2972 // unconditionally).
2973 const bool near_threshold =
2974 std::isfinite(current_threshold_) && current_threshold_ > 0.0 &&
2975 pre_neb_force > 0.0 && pre_neb_force <= current_threshold_;
2976 dimer.setLeashRelaxWhenClose(trap_detected || near_threshold);
2977 {
2978 atmd::AtomicDimer::VarianceGateConfig vg =
2979 dimer.getVarianceGateConfig();
2980 vg.accept_tau = cfg_.dimer_variance_tau_abs;
2982 detail::resolveDimerVarianceTauRelative(neb_config, cfg_);
2983 vg.imspe_soft_threshold = cfg_.dimer_imspe_soft_threshold;
2984 vg.imspe_history_size = std::max(1, cfg_.dimer_imspe_history_size);
2985 dimer.setVarianceGateConfig(vg);
2986 }
2987#ifdef USE_READCON_DB
2988 dimer.setObservationArchive(session.observationArchive());
2989#endif
2990 pot::PotentialWrapper potential = makePotentialWrapperFromOracle(oracle);
2991 detail::configureBurstDimerSecant(dimer, neb_config.secant_hessian);
2992 dimer.execute(potential);
2993 session.addSecantCounts(dimer.secantCounts());
2994 result.oracle_calls += static_cast<int>(dimer.getTotalForceCalls());
2995 mmf_iterations_used_ += static_cast<long>(dimer.getIterations());
2996
2997 // When a session GP exists (the trapped-CI route), stage EVERY fresh
2998 // dimer row (the burst started from empty_obs, so all rows are new
2999 // oracle evaluations) back into the active set so the global band GP
3000 // sharpens around the saddle the fresh local fit just located. In the
3001 // genuine no-GP modes (Standard/AIE) has_gp is false, nothing is staged
3002 // and the commit loop below is a no-op.
3003 if (has_gp) {
3004 gpr::Coord& dimer_R =
3006 gpr::FieldMatrixd& dimer_E =
3009 const gpr::FieldMatrixd e_zero = dimer.getEnergyZeroLevel();
3010 const double e0 = (e_zero.size() > 0) ? e_zero(0, 0) : 0.0;
3011 staged_dimer_observations = detail::stageDimerObservationUpdates(
3012 empty_obs, dimer_R, dimer_E, dimer_G, e0);
3013 }
3014}
3015
3016void OCINEBController::recordBurstOutcome(
3017 NEBPath& path, int ci_image_idx, const GPNEBConfig& neb_config,
3018 ActiveLearningSession& session, const Eigen::VectorXd& savedPositions,
3019 bool adaptive_threshold_seeded, bool force_improved,
3020 double threshold_pre_force, double threshold_post_force,
3021 MMFRunResult& result)
3022{
3023 if (result.status == MMFStatus::Helped) {
3024 updateThresholdSuccess(threshold_pre_force, threshold_post_force);
3025 pure_reject_force_ = std::numeric_limits<double>::quiet_NaN();
3026 trusted_retry_reject_force_ = std::numeric_limits<double>::quiet_NaN();
3027 } else if (force_improved || result.trusted_recovery_advanced) {
3028 // Accepted recovery without Helped advances the chain but does not
3029 // certify the saddle. Keep the adaptive bar fixed and avoid recording
3030 // the saved CI as a restore-reject seed.
3031 result.force_improving_recovery_advanced = force_improved;
3032 mmf_reject_ci_position_.resize(0);
3033 mmf_reject_climbing_image_ = -1;
3034 exhausted_recovery_reject_active_ = false;
3035 trusted_retry_reject_force_ = std::numeric_limits<double>::quiet_NaN();
3036 const double problem_force_tol = forceTolerance();
3037 const bool residual_at_problem_tol =
3038 std::isfinite(threshold_post_force) && threshold_post_force > 0.0 &&
3039 std::isfinite(problem_force_tol) && problem_force_tol > 0.0 &&
3040 threshold_post_force <= problem_force_tol;
3041 // When residual is still above problem force criterion, do not arm
3042 // pure_lock / force_improving suppress / soft_quiet. Baker 02 stopped
3043 // at non-descent handback F=0.056 (above force_pass 0.05) then froze
3044 // MMF on pure_lock+awaiting_action_change with no recovery growth.
3045 // Leave the gate open so a Helped completion can finish under tol.
3046 if (residual_at_problem_tol) {
3047 soft_quiet_blocked_after_reject_ = true;
3048 force_improving_recovery_active_ = force_improved;
3049 trusted_recovery_active_ =
3050 detail::shouldKeepTrustedRecoveryGateAfterAdvance(
3051 result.trusted_recovery_advanced, force_improved);
3052 recovery_owner_image_ =
3053 detail::activeMmfRecoveryOwnsClimbingImage(
3054 force_improving_recovery_active_, trusted_recovery_active_)
3055 ? ci_image_idx
3056 : -1;
3057 if (force_improved && adaptive_threshold_seeded) {
3058 pure_reject_lock_ = true;
3059 pure_reject_force_ = threshold_post_force;
3060 } else {
3061 pure_reject_lock_ = false;
3062 pure_reject_force_ = std::numeric_limits<double>::quiet_NaN();
3063 }
3064 } else {
3065 soft_quiet_blocked_after_reject_ = false;
3066 force_improving_recovery_active_ = false;
3067 trusted_recovery_active_ = false;
3068 recovery_owner_image_ = -1;
3069 pure_reject_lock_ = false;
3070 pure_reject_force_ = std::numeric_limits<double>::quiet_NaN();
3071 mmf_info_gate_ = detail::MmfInformationGate::Open;
3072 }
3074 previewMmfAction(session, path, ci_image_idx, neb_config));
3075 } else {
3076 const bool preserve_fi_recovery_gate =
3077 detail::shouldPreserveFiRecoveryGateAfterRetry(
3078 force_improving_recovery_active_, threshold_pre_force,
3079 current_threshold_, forceTolerance(),
3080 result.recovery_selection_exhausted);
3081 const bool preserve_trusted_recovery_gate =
3082 detail::shouldPreserveTrustedRecoveryGateAfterRetry(
3083 trusted_recovery_active_, result.status, force_improved,
3084 result.trusted_recovery_advanced,
3085 result.rejected_helped_handback, result.reject_kind,
3086 result.recovery_selection_exhausted);
3087 if (!preserve_fi_recovery_gate && !preserve_trusted_recovery_gate) {
3088 updateThresholdBackoff(threshold_pre_force);
3089 exhausted_recovery_reject_active_ =
3090 result.recovery_selection_exhausted;
3091 }
3092 if (preserve_fi_recovery_gate || preserve_trusted_recovery_gate) {
3093 if (detail::shouldRecordRejectedSeedForRecoveryGate(
3094 preserve_fi_recovery_gate,
3095 preserve_trusted_recovery_gate)) {
3096 noteMmfRejectCiPosition(savedPositions, ci_image_idx);
3097 } else {
3098 mmf_reject_ci_position_.resize(0);
3099 mmf_reject_climbing_image_ = -1;
3100 }
3101 soft_quiet_blocked_after_reject_ = true;
3102 force_improving_recovery_active_ = preserve_fi_recovery_gate;
3103 trusted_recovery_active_ = preserve_trusted_recovery_gate;
3104 if (recovery_owner_image_ < 1) {
3105 recovery_owner_image_ = ci_image_idx;
3106 }
3107 exhausted_recovery_reject_active_ = false;
3108 pure_reject_lock_ = preserve_fi_recovery_gate;
3109 trusted_retry_reject_force_ =
3110 detail::trustedRetryRejectForceAfterRetry(
3111 preserve_trusted_recovery_gate, trusted_retry_reject_force_,
3112 threshold_pre_force);
3113 } else {
3114 noteMmfRejectCiPosition(savedPositions, ci_image_idx);
3115 trusted_recovery_active_ = false;
3116 recovery_owner_image_ = -1;
3117 exhausted_recovery_reject_active_ =
3118 result.recovery_selection_exhausted;
3119 trusted_retry_reject_force_ =
3120 std::numeric_limits<double>::quiet_NaN();
3121 pure_reject_lock_ = detail::shouldPureLockAfterMmfReject(
3122 result.status, force_improved, result.trusted_recovery_advanced,
3123 adaptive_threshold_seeded, result.reject_kind);
3124 }
3125 if (pure_reject_lock_) {
3126 // Pure-lock reopen needs residual strictly below the handoff
3127 // force. Never raise pure_reject_force_ with the live residual:
3128 // ratcheting it to the current force makes
3129 // convForce < pure_reject_force_ impossible and freezes MMF
3130 // forever on period-2 residual thrash (Baker 03 pure_lock).
3131 if (std::isfinite(threshold_pre_force) &&
3132 threshold_pre_force > 0.0 &&
3133 (!std::isfinite(pure_reject_force_) ||
3134 threshold_pre_force < pure_reject_force_)) {
3135 pure_reject_force_ = threshold_pre_force;
3136 }
3137 } else {
3138 pure_reject_force_ = std::numeric_limits<double>::quiet_NaN();
3139 }
3140 // The retry baseline includes every retained row from this burst.
3141 // Only a changed first dimer action reopens the information gate.
3143 previewMmfAction(session, path, ci_image_idx, neb_config));
3144 if (result.mode_probe_acquired) {
3145 // A consumed probe blocks repeated action at the rejected seed.
3146 // A different seed or posterior action retires this evidence.
3148 }
3149 }
3150}
3151
3153 NEBOracle& oracle,
3154 const GPNEBConfig& neb_config,
3155 ActiveLearningSession& session,
3156 bool trap_detected)
3157{
3158 MMFRunResult result;
3159 pending_min_mode_probe_lease_ = false;
3160 const Eigen::Index ntrain_now = session.training_obs.R.rows();
3161 if (mmf_wait_for_true_sample_ && ntrain_now > mmf_wait_ntrain_) {
3162 mmf_wait_for_true_sample_ = false;
3163 }
3164 if (!rejectedMmfSeedPositionMatches(path.image(ci_image_idx).positions,
3165 &session.atoms_config,
3166 static_cast<long>(ci_image_idx))) {
3167 min_mode_probe_spent_ = false;
3168 }
3169 trap_surface_updated_ = false;
3170 std::vector<StagedDimerObservation> staged_dimer_observations;
3171
3172 // Save pre-MMF position so PositiveCurvature can restore it.
3173 Eigen::VectorXd savedPositions = path.image(ci_image_idx).positions;
3174 // Seed CI energy (absolute PES). The band placed the climbing image near
3175 // the true saddle, which sits strictly above both endpoints. A burst that
3176 // force-converges along a poorly-aligned min-mode can translate the CI down
3177 // a negative-curvature SHOULDER whose energy dips below this seed (and
3178 // below a band endpoint), which the GPNEB true-PES saddle-energy
3179 // certificate then correctly rejects -- the run grinds to the iteration
3180 // cap. Used below to refuse committing such a downhill, un-angle-certified
3181 // Helped geometry.
3182 const bool savedCiEnergyValid =
3183 path.image(ci_image_idx).evaluated &&
3184 std::isfinite(path.image(ci_image_idx).energy);
3185 const double savedCiEnergy = path.image(ci_image_idx).energy;
3186
3187 // Optional operator-specified burst-displacement guard. The default is
3188 // certificate-driven: saddle energy, force, curvature, and adjacent-path
3189 // checks decide whether a Helped handback is admissible. Recovery phases
3190 // derive their trust ball from adjacent path spacing when no operator cap
3191 // is configured.
3192 const double burst_disp_cap = cfg_.max_burst_displacement;
3193
3194 const auto local_spacing_to = [&](int image_idx) -> double {
3195 if (image_idx < 0 || image_idx >= path.numImages()) {
3196 return std::numeric_limits<double>::infinity();
3197 }
3198 const Eigen::VectorXd& neighbor_positions =
3199 path.image(image_idx).positions;
3200 if (neighbor_positions.size() != savedPositions.size() ||
3201 neighbor_positions.size() == 0) {
3202 return std::numeric_limits<double>::infinity();
3203 }
3204 return emdDistance(savedPositions, neighbor_positions,
3205 session.atoms_config);
3206 };
3207 const double recovery_disp_cap =
3208 detail::effectiveMmfRecoveryDisplacementCap(
3209 burst_disp_cap, local_spacing_to(ci_image_idx - 1),
3210 local_spacing_to(ci_image_idx + 1));
3211
3212 path.computeNEBForces();
3213 const double pre_neb_force = path.nebForce(ci_image_idx).norm();
3214 const double pre_force = path.saddleForce(ci_image_idx);
3215 result.previousForce = pre_force;
3216
3217 // ---- Build initial mode (configured -> cached -> path tangent) ----
3218 const std::optional<Eigen::VectorXd> initial_mode =
3219 initialModeForPath(path, ci_image_idx);
3220 if (!initial_mode) {
3221 result.status = MMFStatus::Skipped;
3222 result.newForce = pre_force;
3223 result.alignment = 0.0;
3224 return result;
3225 }
3226 const Eigen::VectorXd initialMode = *initial_mode;
3227
3228 if (!neb_config.rgsaddle_library.empty())
3230 if (cfg_.rg_minmode_dimer) {
3231 RgsaddleClient dest;
3232 if (dest.load()) {
3233 const Eigen::Index dof = savedPositions.size();
3234 const int64_t n_atoms = dof / 3;
3235 RgMinMode minmode;
3236 if (n_atoms >= 1 && dof == 3 * n_atoms &&
3237 minmode.bind(dest, n_atoms, savedPositions.data(),
3238 initialMode.data(), cfg_.force_tolerance,
3240 std::max(1, cfg_.dimer_max_rot_iter), 1e-3)) {
3241 GprRgsaddleUser surface_user;
3242 surface_user.gp = &session.gp;
3243 gpr_rgsaddle_report_t rg_report{};
3244 const long rg_cap = cfg_.max_steps > 0 ? cfg_.max_steps : 16;
3245 bool rg_ok = false;
3246 for (long s = 0; s < rg_cap; ++s) {
3247 if (!minmode.step(&gprRgsaddleSurface, &surface_user,
3248 rg_report)) {
3249 break;
3250 }
3251 rg_ok = true;
3252 if (rg_report.max_force <= cfg_.force_tolerance) {
3253 break;
3254 }
3255 }
3256 Eigen::VectorXd rg_pos(dof);
3257 if (rg_ok && minmode.position(rg_pos.data()) &&
3258 rg_pos.allFinite() && rg_report.curvature < 0.0) {
3259 path.image(ci_image_idx).positions = rg_pos;
3260 result.status = MMFStatus::Helped;
3261 result.newForce = rg_report.max_force;
3262 result.final_mode_curvature = rg_report.curvature;
3263 result.alignment = std::abs(initialMode.dot(
3264 path.tangentAt(ci_image_idx).normalized()));
3265 result.oracle_calls = static_cast<int>(rg_report.rotations);
3266 result.shouldResetOptimizer = true;
3267 return result;
3268 }
3269 }
3270 }
3271 }
3272
3273 // ---- Kick CI position along the mode ----
3274 Eigen::VectorXd ci_pos = savedPositions;
3275 const double seed_displacement = detail::resolveMmfSeedDisplacement(
3276 cfg_.perturb_along_tangent, force_improving_recovery_active_,
3277 trusted_recovery_active_);
3278 if (seed_displacement != 0.0) {
3279 ci_pos += seed_displacement * initialMode;
3280 }
3281
3282 // ---- Construct dimer ----
3283 //
3284 // We pass ~middle_point~ with R only (no E/G). The dimer's
3285 // ~evaluateAccurateEnergyAndForceAtMidPoint~ then takes the
3286 // ~middle_point_init.E.size() == 0~ branch, which (i) calls the
3287 // oracle once at this position, (ii) sets ~E_zero_level~ to that
3288 // energy, (iii) cuts off ~all_obs.E~ relative to ~E_zero_level~
3289 // *without* clobbering ~all_obs~, and (iv) appends the kicked
3290 // middle point as a fresh row. The alternative (pre-seed E here
3291 // and let the dimer take the else-branch) blows away
3292 // ~init_observations~ in the dimer's first step, which would
3293 // erase every NEB training point from the shared GP's view.
3294 gpr::Observation middle_point;
3295 middle_point.R = flatToCoord1xD(ci_pos);
3296
3297 // Pick the GP the dimer will run against. Prefer the CI image's
3298 // *per-image* GP -- the dimer's burst lives entirely in the CI
3299 // image's neighbourhood, so its trajectory + harvested rows are
3300 // legitimate data for image ~ci_image_idx~'s local surrogate but
3301 // would re-anchor a global theta to the clustered burst region.
3302 // The MMF gate in gpNEB ensures the CI image has enough direct
3303 // active-learning samples before this hook fires, so the
3304 // per-image attach is the common path. Fall back to the global GP
3305 // only if the per-image surrogate is missing.
3306 // The global band GP inherits the full distributed dataset and runs on the
3307 // distributed (ScaLAPACK) backend; the per-image GP is ~5x slower
3308 // (per-image Eigen-Cholesky maintenance + unstable theta on the clustered
3309 // burst rows). The burst's scopedParameterRestore reinstalls the entry
3310 // theta afterward, so the only stated reason for the per-image route
3311 // (re-anchoring the global theta on burst rows) is already protected. Route
3312 // to the global GP by default; per-image stays an explicit opt-in.
3313 const int dimer_model_owner =
3314 session.mmfModelOwner(ci_image_idx, neb_config.dimer_use_global_gp);
3315 const bool per_image_ready = dimer_model_owner >= 0;
3316
3318 if (neb_config.training_policy != nullptr)
3319 dimer.setTrainingPolicy(neb_config.training_policy);
3320 dimer.setWallClockLimit(neb_config.wall_clock_limit);
3321 dimer.setProjectRigidModesForConvergence(true);
3322 // The band index certificate decides the saddle claim.
3323 dimer.setForceStopCertificateStep(0.0);
3324 const bool has_gp = static_cast<bool>(neb_config.gp_setup);
3325 // The burst leases the SESSION GP by default: it is warm on the band's
3326 // accumulated rows around the CI, so the dimer runs on the surrogate and
3327 // pays the oracle only for validation. Bootstrapping a fresh local
3328 // surrogate re-learns the neighbourhood from new oracle rows on EVERY
3329 // burst (~28 calls each; Baker 01 spent 449 of its 642 calls inside 16
3330 // bursts, 70 percent of the budget, versus the ~35-call budget of a
3331 // whole standalone GP-dimer search). Escalate to the fresh fit on
3332 // EVIDENCE, not prediction: (a) trap_detected marks the session GP as
3333 // over-confident-but-inaccurate at the CI, and (b) a rejected burst with
3334 // the same seed and unchanged surrogate information means the leased
3335 // curvature already sent the dimer down a wrong or unproductive mode --
3336 // that retry pays the fresh bootstrap. Boards with lease-always
3337 // lost the systems whose rescue WAS the sharp from-scratch curvature
3338 // (eboard3: 23/25 flipped to failure) while fresh-always burned 70
3339 // percent of the call budget; the failure-triggered escalation takes
3340 // each regime where the evidence points.
3341 detail::MmfPosteriorActionFingerprint dimer_action;
3342 dimer_action.surrogate = session.surrogateFingerprint(dimer_model_owner);
3343 if (rejectedMmfSeedPositionMatches(savedPositions, &session.atoms_config,
3344 static_cast<long>(ci_image_idx))) {
3345 dimer_action =
3346 previewMmfAction(session, path, ci_image_idx, neb_config);
3347 }
3348 const bool reject_latched_here = rejectedMmfSeedReplay(
3349 savedPositions, dimer_action, static_cast<long>(ci_image_idx),
3350 &session.atoms_config);
3351 const bool lease_session_gp =
3352 has_gp && !trap_detected && !reject_latched_here;
3353 Eigen::VectorXd curvature_seed = initialMode;
3354 // A dimer whose oracle failed past its consecutive-failure bound (or at
3355 // its start) ends the climbing-image refinement, not the band: the
3356 // burst is reported failed, the climbing image keeps its measured
3357 // state, and convergence rests on the band's own certificates.
3358 try {
3359 if (neb_config.secant_hessian.seed_curvature) {
3360 const auto* secant = session.imageSecantHessian(ci_image_idx);
3361 const optim::SecantSeed seed =
3362 secant != nullptr
3363 ? optim::secantSeedDirection(*secant, initialMode)
3366 curvature_seed = seed.direction;
3367 else
3368 std::cout << "[secant-seed] climbing-image burst keeps its "
3369 "mode: "
3370 << optim::secantSeedStatusName(seed.status) << "\n";
3371 }
3372 if (lease_session_gp) {
3373 runBurstUnderSessionModelLease(ci_image_idx, oracle, neb_config,
3374 session, curvature_seed,
3375 middle_point, dimer, per_image_ready,
3376 result, staged_dimer_observations);
3377 } else {
3378 runBurstOnTruePotential(oracle, neb_config, session, trap_detected,
3379 curvature_seed, middle_point, dimer,
3380 pre_neb_force, has_gp, result,
3381 staged_dimer_observations);
3382 }
3383 } catch (const OracleSessionRestartRequested&) {
3384 throw;
3385 } catch (const std::runtime_error& error) {
3386 std::cout << "[ocineb] climbing-image dimer stopped by oracle "
3387 "failures: "
3388 << error.what() << "; refinement failed, band kept"
3389 << std::endl;
3390 result.oracle_calls += static_cast<int>(dimer.getTotalForceCalls());
3391 result.status = MMFStatus::Skipped;
3392 result.convergedAfterMMF = false;
3393 result.refinement_failed = true;
3394 path.image(ci_image_idx).positions = savedPositions;
3395 path.computeNEBForces();
3396 return result;
3397 }
3398
3399 // ---- Recovery configuration from the dimer trajectory history --
3400 // OCI-NEB (Goswami et al.): a burst that converged to the saddle
3401 // writes that converged configuration back and caches its mode.
3402 // A burst that did NOT converge -- the alignment criterion aborted
3403 // it, or it exhausted the N_mmf step budget -- advances the
3404 // climbing image to the configuration with the most negative
3405 // curvature found anywhere along the dimer trajectory, recovered
3406 // from the per-phase history. A trajectory that never found a
3407 // negative-curvature mode never approached a saddle: restore.
3408 Eigen::VectorXd dimer_final_pos = dimer.getFinalCoordOfMidPoint();
3409 gpr::Coord final_orient_coord = dimer.getFinalOrientation();
3410 const Eigen::VectorXd finalMode =
3411 final_orient_coord.cols() > 0
3412 ? coordToFlat(final_orient_coord).normalized()
3413 : Eigen::VectorXd();
3414 Eigen::VectorXd currentTangent = path.tangentAt(ci_image_idx).normalized();
3415 result.alignment =
3416 (finalMode.size() == currentTangent.size() && finalMode.size() > 0)
3417 ? std::abs(finalMode.dot(currentTangent))
3418 : 0.0;
3419
3420 const gpr::FieldMatrixd e_zero = dimer.getEnergyZeroLevel();
3421 const double e0 = (e_zero.size() > 0) ? e_zero(0, 0) : 0.0;
3422
3423 // Scan the dimer trajectory for the most-negative-curvature phase.
3424 const std::vector<atmd::AtomicDimer::DimerPhaseRecord>& history =
3425 dimer.getPhaseHistory();
3426 int best_phase = -1;
3427 double best_curv = std::numeric_limits<double>::infinity();
3428 for (int h = 0; h < static_cast<int>(history.size()); ++h) {
3429 if (std::isfinite(history[h].curvature) &&
3430 history[h].curvature < best_curv) {
3431 best_curv = history[h].curvature;
3432 best_phase = h;
3433 }
3434 }
3435 const bool found_saddle_mode = (best_phase >= 0 && best_curv < 0.0);
3436 const bool hit_step_budget =
3437 cfg_.max_steps > 0 &&
3438 dimer.getIterations() >= static_cast<gpr::Index_t>(cfg_.max_steps);
3439
3440 const double helped_emd_disp =
3441 (dimer.getConverged() &&
3442 dimer_final_pos.size() == savedPositions.size())
3443 ? emdDistance(dimer_final_pos, savedPositions, session.atoms_config)
3444 : std::numeric_limits<double>::infinity();
3445 const bool dimerAngleCertified =
3446 found_saddle_mode && dimer.isMinModeAngleCertified();
3447 const bool helpedPathCertified = detail::forceOnlyHelpedPathCertified(
3448 dimerAngleCertified, result.alignment, cfg_.alignment_cos_tol);
3449 // The EMD displacement cap is an anti-run-away heuristic for modes that
3450 // drag the CI off the path. Angle-certified saddles may exceed the local
3451 // displacement guard; force-only Helped remains localized.
3452 const bool helped_ran_away =
3453 detail::shouldRejectUncertifiedHelpedDisplacement(
3454 dimer.getConverged(), dimerAngleCertified, helped_emd_disp,
3455 burst_disp_cap);
3456
3457 const double dimerFinalEnergy = dimer.getFinalEnergy() + e0;
3458 result.final_rotation_omega = dimer.getFinalRotationAngle();
3459 // NEB force at the dimer endpoint (chain objective), same metric as
3460 // force-improving recovery. Used to override the energy-basin guard.
3461 const double helped_neb_force = [&]() -> double {
3462 if (!(dimer.getConverged() &&
3463 dimer_final_pos.size() == savedPositions.size() &&
3464 dimer_final_pos.size() > 0)) {
3465 return std::numeric_limits<double>::infinity();
3466 }
3467 const Eigen::VectorXd g_final = dimer.getFinalGradientAtMidPoint();
3468 detail::ScopedImageState restore(path, ci_image_idx);
3469 path.image(ci_image_idx).positions = dimer_final_pos;
3470 path.image(ci_image_idx).energy = dimerFinalEnergy;
3471 path.image(ci_image_idx).gradient = g_final;
3472 path.image(ci_image_idx).evaluated = true;
3473 path.computeNEBForces();
3474 return path.nebForce(ci_image_idx).norm();
3475 }();
3476 const bool helped_force_improves = std::isfinite(helped_neb_force) &&
3477 std::isfinite(pre_neb_force) &&
3478 helped_neb_force < pre_neb_force;
3479 // Basin guard. The dimer force-converged but lacks a path-local saddle
3480 // certificate, or it translated the climbing image to a geometry whose
3481 // absolute energy fell below the seed CI energy without force progress.
3482 // Both are wrong-direction descents off poorly-aligned modes onto
3483 // negative-curvature shoulders. Restore the band-placed CI so the burst
3484 // can re-trigger with a fresh mode. Strict energy inequality (no
3485 // tolerance) keeps a flat saddle that converges at the seed energy
3486 // acceptable.
3487 //
3488 // Endpoint floor for force-only Helped: even force-improving handbacks are
3489 // refused when the dimer energy sits below either path endpoint.
3490 // Seed-relative descent may still force-improve on ridges above both
3491 // endpoints.
3492 const bool helped_descended_below_seed = savedCiEnergyValid &&
3493 std::isfinite(dimerFinalEnergy) &&
3494 dimerFinalEnergy < savedCiEnergy;
3495 const bool helped_below_endpoints =
3496 detail::shouldRejectForceOnlyHelpedBelowEndpoints(
3497 dimer.getConverged(), dimerAngleCertified, dimerFinalEnergy,
3498 path.image(0).energy, path.image(path.numImages() - 1).energy);
3499 // Apply the caller's optional energy limit with the same oracle-noise
3500 // allowance as the main search.
3501 const double ceiling_slack =
3502 (neb_config.oracle_energy_noise_rms &&
3503 std::isfinite(*neb_config.oracle_energy_noise_rms) &&
3504 *neb_config.oracle_energy_noise_rms > 0.0)
3505 ? *neb_config.oracle_energy_noise_rms
3506 : 0.0;
3507 const bool helped_above_ceiling =
3508 std::isfinite(session.path_energy_ceiling) &&
3509 std::isfinite(dimerFinalEnergy) &&
3510 dimerFinalEnergy > session.path_energy_ceiling + ceiling_slack;
3511 const bool helped_wrong_mode =
3512 !helpedPathCertified || helped_above_ceiling ||
3513 (!dimerAngleCertified &&
3514 (helped_below_endpoints ||
3515 (helped_descended_below_seed && !helped_force_improves)));
3516 const bool search_recovery_portfolio =
3517 detail::shouldSearchMmfRecoveryPortfolio(
3518 dimer.getConverged(), helped_ran_away, helpedPathCertified,
3519 found_saddle_mode);
3520 // The recovery portfolio retains measured evidence from uncertified path
3521 // modes; the basin and displacement guards reject invalid handbacks.
3522
3523 // A true midpoint force under the final tolerance is the result, the
3524 // way Sella returns the geometry of the evaluation that crossed fmax.
3525 // Path-angle evidence is not another force call. A runaway or a point
3526 // above the energy ceiling is not that candidate.
3527 const double dimer_true_force = dimer.getFinalForceNormForConvergence();
3528 const bool dimer_force_under_tolerance =
3529 dimer.getConverged() && std::isfinite(dimer_true_force) &&
3530 dimer_true_force < forceTolerance();
3531 if (dimer.getConverged() && !helped_ran_away && !helped_above_ceiling &&
3532 (dimer_force_under_tolerance || !helped_wrong_mode)) {
3533 // Helped: the dimer reached the saddle-force criterion and certified
3534 // the saddle on its min-mode angle or path-local mode power. Write the
3535 // converged configuration back and cache the mode.
3536 cached_mode_ = finalMode;
3537 has_cached_mode_ = true;
3538 const Eigen::VectorXd g_final = dimer.getFinalGradientAtMidPoint();
3539 path.image(ci_image_idx).positions = dimer_final_pos;
3540 path.image(ci_image_idx).energy = dimerFinalEnergy;
3541 path.image(ci_image_idx).gradient = g_final;
3542 path.image(ci_image_idx).evaluated = true;
3543 result.newForce = saddleForceMagnitude(g_final);
3544 result.status = MMFStatus::Helped;
3545 // Angle/curvature saddle certificate. The dimer converged to a
3546 // negative-curvature mode whose axis is rotation-aligned with the true
3547 // lowest-curvature eigenvector (omega within the dimer's own rotation
3548 // tolerance). found_saddle_mode is the burst-history negative-curvature
3549 // check; isMinModeAngleCertified() couples it with the converged
3550 // omega + curvature. This lets a flat / late saddle whose force lingers
3551 // in (conv_tol, 2 conv_tol) be accepted on the geometry of the saddle,
3552 // not on a force gate the band recompute never clears.
3553 result.min_mode_angle_certified = dimerAngleCertified;
3554 result.final_mode_curvature = dimer.getLatestModeCurvature();
3555 helpedModeCurvatureSlot() = result.final_mode_curvature;
3556 if (isRank0()) {
3557 std::cout << "[ocineb] burst @ outer hook: Helped, dimer "
3558 << "converged to saddle (force " << pre_force << " -> "
3559 << result.newForce
3560 << ", omega=" << result.final_rotation_omega
3561 << ", curv=" << result.final_mode_curvature
3562 << ", angle_certified="
3563 << (result.min_mode_angle_certified ? 1 : 0) << ")"
3564 << std::endl;
3565 }
3566 } else if (dimer.getConverged() && !helped_ran_away && helped_wrong_mode &&
3567 !search_recovery_portfolio) {
3568 // Force-converged on a poorly-aligned min-mode: side saddle below an
3569 // endpoint, or seed-relative descent without force progress. Reject
3570 // and restore the band-placed CI; do not certify convergence or
3571 // collapse thr via Helped success.
3572 path.image(ci_image_idx).positions = savedPositions;
3573 path.image(ci_image_idx).evaluated = true;
3574 has_cached_mode_ = false;
3575 result.status = MMFStatus::Skipped;
3576 result.newForce = pre_force;
3577 result.min_mode_angle_certified = false;
3578 result.rejected_helped_handback = true;
3579 if (!helpedPathCertified) {
3581 } else if (helped_below_endpoints) {
3583 } else {
3585 }
3586 if (isRank0()) {
3587 if (!helpedPathCertified) {
3588 std::cout << "[ocineb] burst @ outer hook: Helped rejected "
3589 << "(force-only lacks path certificate: alignment="
3590 << result.alignment
3591 << ", tol=" << cfg_.alignment_cos_tol
3592 << ", omega=" << result.final_rotation_omega
3593 << "), restored CI position" << std::endl;
3594 } else if (helped_below_endpoints) {
3595 std::cout << "[ocineb] burst @ outer hook: Helped rejected "
3596 << "("
3597 << detail::forceOnlyHelpedBelowEndpointDiagnostic(
3598 dimerFinalEnergy, path.image(0).energy,
3599 path.image(path.numImages() - 1).energy)
3600 << ", omega=" << result.final_rotation_omega
3601 << "), restored CI position" << std::endl;
3602 } else {
3603 std::cout
3604 << "[ocineb] burst @ outer hook: Helped rejected "
3605 << "(unaligned min-mode descended below seed CI energy: "
3606 << dimerFinalEnergy << " < " << savedCiEnergy
3607 << ", omega=" << result.final_rotation_omega
3608 << "), restored CI position" << std::endl;
3609 }
3610 }
3611 } else if (dimer.getConverged() && helped_ran_away) {
3612 // The dimer reported convergence but translated the CI past the
3613 // EMD displacement bound: it followed a spurious downhill mode
3614 // of the per-image GP off the reaction path. A run-away climbs
3615 // along the NEB tangent, so the alignment check stays satisfied
3616 // -- only the EMD bound catches it. Reject and restore.
3617 path.image(ci_image_idx).positions = savedPositions;
3618 path.image(ci_image_idx).evaluated = true;
3619 has_cached_mode_ = false;
3620 result.status = MMFStatus::Skipped;
3621 result.newForce = pre_force;
3622 result.rejected_helped_handback = true;
3624 if (isRank0()) {
3625 std::cout << "[ocineb] burst @ outer hook: Helped rejected "
3626 << "(EMD displacement " << helped_emd_disp << " > cap "
3627 << burst_disp_cap
3628 << ", angle_certified=" << (dimerAngleCertified ? 1 : 0)
3629 << ", omega=" << result.final_rotation_omega
3630 << "), restored CI position" << std::endl;
3631 }
3632 } else if (!found_saddle_mode) {
3633 // PositiveCurvature: no negative-curvature mode anywhere along
3634 // the trajectory -- the CI never approached a saddle. The scan has
3635 // no phase that can support another local recovery retry.
3636 path.image(ci_image_idx).positions = savedPositions;
3637 path.image(ci_image_idx).evaluated = true;
3638 has_cached_mode_ = false;
3640 result.newForce = pre_force;
3642 detail::isMmfRecoveryPortfolioExhausted(
3643 /*found_saddle_mode=*/false, /*selected_phase=*/-1,
3644 /*accepted_candidates=*/0);
3646 if (isRank0()) {
3647 std::cout << "[ocineb] burst @ outer hook: PositiveCurvature "
3648 << "(no negative mode along trajectory, min curv = "
3649 << best_curv << "), restored CI position" << std::endl;
3650 }
3651 } else {
3652 // Alignment failure, path-uncertified force convergence, or
3653 // step-budget exhaustion recovers through the negative-curvature
3654 // phase with the strongest accepted true-PES evidence. A recovery
3655 // handback advances the chain without declaring terminal convergence.
3656 std::vector<detail::MmfRecoveryCandidate> recovery_candidates;
3657 recovery_candidates.reserve(history.size());
3658 // Cache true-oracle (E, G) per accepted phase for handback commit.
3659 std::vector<Eigen::VectorXd> true_phase_grad(history.size());
3660 std::vector<double> true_phase_energy(
3661 static_cast<std::size_t>(history.size()),
3662 std::numeric_limits<double>::quiet_NaN());
3663 int reused_oracle_phases = 0;
3664 int oracle_phase_queries = 0;
3665 const double reactant_E = path.image(0).energy;
3666 const double product_E = path.image(path.numImages() - 1).energy;
3667 for (int h = 0; h < static_cast<int>(history.size()); ++h) {
3668 const auto& phase = history[h];
3669 if (!std::isfinite(phase.curvature) || !(phase.curvature < 0.0)) {
3670 continue;
3671 }
3672 const Eigen::VectorXd phase_pos = coordToFlat(phase.position);
3673 if (phase_pos.size() != savedPositions.size() ||
3674 phase_pos.size() == 0) {
3675 continue;
3676 }
3677 const double phase_disp =
3678 emdDistance(phase_pos, savedPositions, session.atoms_config);
3679 // True-PES evaluation: proposal from dimer trajectory, certificate
3680 // from the oracle. Replaces dimer-internal phase energy/gradient
3681 // for recovery scoring and optional handback.
3682 const detail::MmfRecoveryPhaseEvidence recorded_evidence =
3683 detail::recordedMmfRecoveryPhaseEvidence(phase, e0,
3684 phase_pos.size());
3685 double true_E = recorded_evidence.energy;
3686 Eigen::VectorXd true_G = recorded_evidence.gradient;
3687 bool true_pes_evidence_certified =
3688 recorded_evidence.oracle_certified;
3689 if (recorded_evidence.oracle_certified) {
3690 ++reused_oracle_phases;
3691 } else {
3692 try {
3693 const auto true_eval =
3694 detail::evaluateOieOraclePosition(phase_pos, oracle);
3695 true_E = true_eval.first;
3696 true_G = true_eval.second;
3697 true_pes_evidence_certified = true;
3698 ++result.oracle_calls;
3699 ++oracle_phase_queries;
3700 } catch (const OracleSessionRestartRequested&) {
3701 throw;
3702 } catch (...) {
3703 // Preserve the phase as an uncertified fallback when the
3704 // recovery oracle cannot provide its true-PES evidence.
3705 true_E = phase.energy + e0;
3706 true_G = coordToFlat(phase.gradient);
3707 }
3708 }
3709 if (!std::isfinite(true_E) || true_G.size() != phase_pos.size()) {
3710 true_E = phase.energy + e0;
3711 true_G = coordToFlat(phase.gradient);
3712 true_pes_evidence_certified = false;
3713 }
3714 true_phase_energy[static_cast<std::size_t>(h)] = true_E;
3715 true_phase_grad[static_cast<std::size_t>(h)] = true_G;
3716 const double phase_neb_force = [&]() {
3717 detail::ScopedImageState restore(path, ci_image_idx);
3718 path.image(ci_image_idx).positions = phase_pos;
3719 path.image(ci_image_idx).energy = true_E;
3720 path.image(ci_image_idx).gradient = true_G;
3721 path.image(ci_image_idx).evaluated = true;
3722 path.computeNEBForces();
3723 return path.nebForce(ci_image_idx).norm();
3724 }();
3725 const double phase_raw_force =
3726 true_G.size() > 0 ? saddleForceMagnitude(true_G)
3727 : std::numeric_limits<double>::infinity();
3728 // Best residual at the phase (min of NEB and raw). Baseline is
3729 // max(pre_neb, pre_raw); a phase that improves either metric can
3730 // beat that bar. NEB-only scoring rejected Baker 05 recoveries
3731 // when raw improved but NEB did not (or the reverse).
3732 double phase_recovery_force =
3733 std::numeric_limits<double>::infinity();
3734 if (std::isfinite(phase_neb_force) && phase_neb_force > 0.0) {
3735 phase_recovery_force = phase_neb_force;
3736 }
3737 if (std::isfinite(phase_raw_force) && phase_raw_force > 0.0) {
3738 phase_recovery_force =
3739 std::isfinite(phase_recovery_force)
3740 ? std::min(phase_recovery_force, phase_raw_force)
3741 : phase_raw_force;
3742 }
3743 const bool phase_saddle_certified =
3744 true_pes_evidence_certified &&
3745 detail::isTruePesRecoverySaddleCertified(
3746 true_E, phase_raw_force, forceTolerance(), reactant_E,
3747 product_E);
3748 const bool phase_path_mode_certified =
3749 detail::forceOnlyHelpedPathCertified(
3750 /*helped_angle_certified=*/false, phase.reference_alignment,
3751 cfg_.alignment_cos_tol);
3752 recovery_candidates.push_back(
3753 {/*phase=*/h,
3754 /*curvature=*/phase.curvature,
3755 /*recovery_force=*/phase_recovery_force,
3756 /*displacement=*/phase_disp,
3757 /*saddle_energy=*/true_E,
3758 /*saddle_certified=*/phase_saddle_certified,
3759 /*path_mode_certified=*/phase_path_mode_certified,
3760 /*measured_descent_certified=*/
3762 }
3763 const double recovery_baseline =
3764 detail::mmfRecoveryForceBaseline(pre_neb_force, pre_force);
3765 const double recovery_reference_energy =
3766 savedCiEnergyValid ? savedCiEnergy
3767 : std::numeric_limits<double>::quiet_NaN();
3768 detail::MmfRecoverySelectionStats recovery_selection_stats;
3769 int recovery_phase = detail::chooseMmfRecoveryPhase(
3770 recovery_candidates, recovery_baseline, recovery_disp_cap,
3771 current_threshold_, cfg_.keep_force_improving_burst,
3772 recovery_reference_energy, reactant_E, product_E,
3773 &recovery_selection_stats,
3774 /*allow_directional_out_of_trust_recovery=*/true);
3775 if (detail::shouldAcquireMmfMinModeProbe(
3776 /*found_saddle_mode=*/true, recovery_phase,
3777 recovery_selection_stats.accepted_candidates,
3778 recovery_selection_stats.negative_curvature_candidates,
3779 recovery_selection_stats.force_improving_candidates,
3780 recovery_selection_stats.out_of_trust_candidates)) {
3781 const Eigen::VectorXd& probe_mode =
3782 (finalMode.size() == savedPositions.size() &&
3783 finalMode.allFinite())
3784 ? finalMode
3785 : initialMode;
3786 const double probe_step = detail::mmfMinModeProbeStep(
3787 recovery_disp_cap, seed_displacement,
3788 cfg_.max_burst_displacement);
3789 const Eigen::VectorXd probe_pos = detail::minModeProbePosition(
3790 savedPositions, probe_mode, probe_step);
3791 if (probe_pos.size() == savedPositions.size() &&
3792 !detail::hasPosition(session.training_obs, probe_pos)) {
3793 try {
3794 const auto true_eval =
3795 detail::evaluateOieOraclePosition(probe_pos, oracle);
3796 const double probe_E = true_eval.first;
3797 const Eigen::VectorXd& probe_G = true_eval.second;
3798 ++result.oracle_calls;
3799 if (std::isfinite(probe_E) &&
3800 probe_G.size() == probe_pos.size() &&
3801 probe_G.allFinite()) {
3803 ci_image_idx, probe_pos, probe_E, probe_G);
3804 result.mode_probe_acquired = true;
3805 const double probe_disp = emdDistance(
3806 probe_pos, savedPositions, session.atoms_config);
3807 const double probe_neb_force = [&]() {
3808 detail::ScopedImageState restore(path,
3809 ci_image_idx);
3810 path.image(ci_image_idx).positions = probe_pos;
3811 path.image(ci_image_idx).energy = probe_E;
3812 path.image(ci_image_idx).gradient = probe_G;
3813 path.image(ci_image_idx).evaluated = true;
3814 path.computeNEBForces();
3815 return path.nebForce(ci_image_idx).norm();
3816 }();
3817 const double probe_raw =
3818 probe_G.size() > 0
3819 ? saddleForceMagnitude(probe_G)
3820 : std::numeric_limits<double>::infinity();
3821 double probe_recovery_force =
3822 std::numeric_limits<double>::infinity();
3823 if (std::isfinite(probe_neb_force) &&
3824 probe_neb_force > 0.0) {
3825 probe_recovery_force = probe_neb_force;
3826 }
3827 if (std::isfinite(probe_raw) && probe_raw > 0.0) {
3828 probe_recovery_force =
3829 std::isfinite(probe_recovery_force)
3830 ? std::min(probe_recovery_force, probe_raw)
3831 : probe_raw;
3832 }
3833 const bool probe_saddle_certified =
3834 detail::isTruePesRecoverySaddleCertified(
3835 probe_E, probe_raw, forceTolerance(),
3836 reactant_E, product_E);
3837 const bool accept_probe =
3838 detail::shouldAcceptMmfRecovery(
3839 recovery_baseline, probe_recovery_force,
3840 probe_disp, recovery_disp_cap,
3841 current_threshold_,
3842 cfg_.keep_force_improving_burst,
3843 recovery_reference_energy, probe_E, reactant_E,
3844 product_E, probe_saddle_certified,
3845 /*candidate_path_mode_certified=*/false,
3846 /*candidate_measured_descent_certified=*/
3847 true);
3848 if (isRank0()) {
3849 std::cout << "[ocineb] burst @ outer hook: "
3850 "min-mode true-PES probe "
3851 << "step=" << probe_step
3852 << " disp=" << probe_disp
3853 << " force=" << probe_recovery_force
3854 << " accepted=" << (accept_probe ? 1 : 0)
3855 << std::endl;
3856 }
3857 if (accept_probe) {
3858 path.image(ci_image_idx).positions = probe_pos;
3859 path.image(ci_image_idx).energy = probe_E;
3860 path.image(ci_image_idx).gradient = probe_G;
3861 path.image(ci_image_idx).evaluated = true;
3862 path.computeNEBForces();
3863 result.newForce = probe_raw;
3864 result.trusted_recovery_advanced = true;
3866 probe_recovery_force < recovery_baseline;
3868 probe_saddle_certified;
3869 result.requires_outer_path_refresh = true;
3870 result.recovery_selection_exhausted = false;
3872 }
3873 }
3874 } catch (const OracleSessionRestartRequested&) {
3875 throw;
3876 } catch (...) {
3877 }
3878 }
3879 }
3880 has_cached_mode_ = false;
3881 result.status =
3882 hit_step_budget ? MMFStatus::MaxIterations : MMFStatus::Skipped;
3883 if (recovery_phase < 0 && result.trusted_recovery_advanced &&
3884 result.mode_probe_acquired) {
3885 if (isRank0()) {
3886 std::cout << "[ocineb] burst @ outer hook: min-mode probe "
3887 "advanced CI (force "
3888 << pre_force << " -> " << result.newForce << ")\n";
3889 }
3890 } else if (recovery_phase < 0) {
3891 if (recovery_selection_stats.out_of_trust_candidates > 0 &&
3892 recovery_selection_stats.accepted_candidates == 0) {
3893 // Mode walk left the trust ball. Hold MMF until EI (or
3894 // another true oracle) adds a row. A GP recovery trial
3895 // that only moves the climbing image does not count.
3896 mmf_wait_for_true_sample_ = true;
3897 mmf_wait_ntrain_ = session.training_obs.R.rows();
3898 }
3900 detail::isMmfRecoveryPortfolioExhausted(
3901 /*found_saddle_mode=*/true, recovery_phase,
3902 recovery_selection_stats.accepted_candidates);
3903 if (result.recovery_selection_exhausted) {
3905 }
3906 path.image(ci_image_idx).positions = savedPositions;
3907 path.image(ci_image_idx).evaluated = true;
3908 result.newForce = pre_force;
3909 if (isRank0()) {
3910 std::cout
3911 << "[ocineb] burst @ outer hook: recovery rejected "
3912 << "(min curv = " << best_curv << ", candidates="
3913 << recovery_selection_stats.negative_curvature_candidates
3914 << ", invalid="
3915 << recovery_selection_stats.invalid_candidates
3916 << ", force_improving="
3917 << recovery_selection_stats.force_improving_candidates
3918 << ", out_of_trust="
3919 << recovery_selection_stats.out_of_trust_candidates
3920 << ", directional_out_of_trust="
3921 << recovery_selection_stats
3922 .directional_out_of_trust_candidates
3923 << ", threshold_rejected="
3924 << recovery_selection_stats.threshold_rejected_candidates
3925 << ", no_trust_threshold="
3926 << recovery_selection_stats
3927 .no_trust_threshold_rejected_candidates
3928 << ", certified_lower_energy="
3929 << recovery_selection_stats
3930 .certified_lower_energy_candidates
3931 << ", uncertified_lower_energy="
3932 << recovery_selection_stats
3933 .uncertified_lower_energy_candidates
3934 << ", uncertified_energy_descent="
3935 << recovery_selection_stats
3936 .uncertified_energy_descent_candidates
3937 << ", accepted="
3938 << recovery_selection_stats.accepted_candidates
3939 << ", oracle_phase_queries=" << oracle_phase_queries
3940 << ", reused_oracle_phases=" << reused_oracle_phases
3941 << "), restored "
3942 << "CI position" << std::endl;
3943 }
3944 } else {
3946 history[recovery_phase];
3947 const Eigen::VectorXd best_pos = coordToFlat(best.position);
3948 // Prefer true-oracle gradient when available for the selected
3949 // phase.
3950 Eigen::VectorXd best_grad =
3951 (recovery_phase >= 0 &&
3952 recovery_phase < static_cast<int>(true_phase_grad.size()) &&
3953 true_phase_grad[static_cast<std::size_t>(recovery_phase)]
3954 .size() == best_pos.size())
3955 ? true_phase_grad[static_cast<std::size_t>(recovery_phase)]
3956 : coordToFlat(best.gradient);
3957 const double best_true_E =
3958 (recovery_phase >= 0 &&
3959 recovery_phase < static_cast<int>(true_phase_energy.size()) &&
3960 std::isfinite(true_phase_energy[static_cast<std::size_t>(
3961 recovery_phase)]))
3962 ? true_phase_energy[static_cast<std::size_t>(
3963 recovery_phase)]
3964 : best.energy + e0;
3965 const auto selected_candidate = std::find_if(
3966 recovery_candidates.begin(), recovery_candidates.end(),
3967 [recovery_phase](const detail::MmfRecoveryCandidate& c) {
3968 return c.phase == recovery_phase;
3969 });
3970 const double recovery_neb_force =
3971 selected_candidate != recovery_candidates.end()
3972 ? selected_candidate->recovery_force
3973 : std::numeric_limits<double>::infinity();
3974 const double recovery_saddle_energy =
3975 selected_candidate != recovery_candidates.end()
3976 ? selected_candidate->saddle_energy
3977 : std::numeric_limits<double>::infinity();
3978 const double recovery_displacement =
3979 selected_candidate != recovery_candidates.end()
3980 ? selected_candidate->displacement
3981 : std::numeric_limits<double>::infinity();
3982 const double best_force =
3983 (best_grad.size() > 0)
3984 ? saddleForceMagnitude(best_grad)
3985 : std::numeric_limits<double>::infinity();
3986 const bool reject_uncertified_handback =
3987 !(selected_candidate != recovery_candidates.end() &&
3988 selected_candidate->path_mode_certified &&
3989 selected_candidate->measured_descent_certified) &&
3990 detail::shouldRejectUncertifiedMmfRecoveryHandback(
3991 best_force, recovery_displacement, recovery_disp_cap,
3992 forceTolerance());
3993 if (reject_uncertified_handback) {
3994 path.image(ci_image_idx).positions = savedPositions;
3995 path.image(ci_image_idx).evaluated = true;
3996 result.newForce = pre_force;
3997 if (isRank0()) {
3998 std::cout << "[ocineb] burst @ outer hook: recovery "
3999 << "rejected (EMD displacement "
4000 << recovery_displacement << " > cap "
4001 << recovery_disp_cap << ", raw force "
4002 << best_force << " within convergence band), "
4003 << "restored CI position" << std::endl;
4004 }
4005 } else {
4006 path.image(ci_image_idx).positions = best_pos;
4007 path.image(ci_image_idx).energy = best_true_E;
4008 path.image(ci_image_idx).gradient = best_grad;
4009 path.image(ci_image_idx).evaluated = true;
4010 result.newForce = best_force;
4011 result.trusted_recovery_advanced = true;
4012 // Curvature + force saddle certificate for a burst that
4013 // exhausted its phase/step budget without the dimer declaring
4014 // full convergence (the common 08/20 path: the dimer finds a
4015 // clear negative-curvature mode and drives the chain NEB force
4016 // down, but a flat / late saddle keeps the raw force in the
4017 // (conv_tol, 2 conv_tol) band so getConverged() never fires).
4018 // Recovery must not set min_mode_angle_certified from
4019 // curvature + force alone (no rotation omega): that
4020 // pseudo-angle let Baker 17 accept a high false ridge while
4021 // Helped angle-primary exit fired. Force + negative curvature
4022 // (final_mode_curvature) is the recovery acceptance path;
4023 // true omega cert remains Helped-only
4024 // (isMinModeAngleCertified).
4025 result.min_mode_angle_certified = false;
4026 result.final_mode_curvature = best.curvature;
4027 const bool recovery_saddle_certified =
4028 selected_candidate != recovery_candidates.end() &&
4029 selected_candidate->saddle_certified;
4030 result.recovery_saddle_certified = recovery_saddle_certified;
4031 result.requires_outer_path_refresh = !recovery_saddle_certified;
4033 recovery_saddle_certified &&
4034 detail::isLowerValidSaddleEnergy(recovery_reference_energy,
4035 recovery_saddle_energy,
4036 reactant_E, product_E);
4037 if (isRank0()) {
4038 std::cout
4039 << "[ocineb] burst @ outer hook: "
4040 << detail::trustedRecoveryAdvanceDiagnostic(
4041 dimer.getRelaxationTerminationReason(),
4042 recovery_phase, history.size(), best.curvature,
4043 recovery_baseline, recovery_neb_force, pre_force,
4044 best_force, recovery_reference_energy,
4045 recovery_saddle_energy, reactant_E, product_E,
4046 recovery_saddle_certified)
4047 << std::endl;
4048 }
4049 }
4050 }
4051 }
4052
4053 const auto training_revision_before = session.trainingRevision();
4054 // Accurate dimer rows remain useful even when their geometry is rejected.
4055 // Helped commits its trajectory, trusted recovery certifies the accepted
4056 // chain row, and restore-reject commits only rows inside the local-spacing
4057 // trust ball.
4058 const bool harvest_helped_trajectory = result.status == MMFStatus::Helped;
4059 if (harvest_helped_trajectory) {
4060 for (std::size_t si = 0; si < staged_dimer_observations.size(); ++si) {
4061 const StagedDimerObservation& staged =
4062 staged_dimer_observations[si];
4063 const bool is_final =
4064 staged.positions.size() == dimer_final_pos.size() &&
4065 (staged.positions.array() == dimer_final_pos.array()).all();
4066 if (!is_final && !detail::shouldCommitMmfObservation(
4067 staged.positions, savedPositions,
4068 session.atoms_config, burst_disp_cap)) {
4069 continue;
4070 }
4071 session.appendObservation(ci_image_idx, staged.positions,
4072 staged.energy, staged.gradient,
4075 }
4076 } else if (detail::shouldHarvestAcceptedRecoveryObservation(
4077 result.trusted_recovery_advanced)) {
4078 const auto& accepted = path.image(ci_image_idx);
4079 detail::appendAcceptedMmfRecoveryObservation(session, ci_image_idx,
4080 accepted);
4081 } else {
4082 for (const StagedDimerObservation& staged: staged_dimer_observations) {
4083 if (!detail::shouldHarvestRejectedMmfObservation(
4084 harvest_helped_trajectory, result.trusted_recovery_advanced,
4085 staged.positions, savedPositions, session.atoms_config,
4086 recovery_disp_cap)) {
4087 continue;
4088 }
4089 session.appendObservation(ci_image_idx, staged.positions,
4090 staged.energy, staged.gradient,
4093 }
4094 }
4095 if (session.trainingRevision() != training_revision_before) {
4096 (void)session.refitGPIfTrainingChanged(/*reinit_seeds=*/false);
4098 }
4099
4100 if (isRank0()) {
4101 std::cout << "[ocineb] burst: status="
4102 << static_cast<int>(result.status) << " force " << pre_force
4103 << " -> " << result.newForce
4104 << " alignment=" << result.alignment
4105 << " threshold=" << current_threshold_
4106 << " oracle+=" << result.oracle_calls << std::endl;
4107 }
4108
4109 // ---- Adaptive threshold update ----
4110 path.computeNEBForces();
4111 const double post_neb_force = path.nebForce(ci_image_idx).norm();
4112 const double threshold_pre_force =
4113 detail::mmfThresholdForce(pre_neb_force, pre_force);
4114 const double threshold_post_force =
4115 detail::mmfThresholdForce(post_neb_force, result.newForce);
4116 // Only a true Helped (dimer force-converged and accepted) clears the
4117 // soft-quiet reject block. Partial force progress tightens the adaptive
4118 // bar while keeping the rejected-position and training-growth guards.
4119 const bool force_improved = std::isfinite(threshold_post_force) &&
4120 std::isfinite(threshold_pre_force) &&
4121 threshold_post_force < threshold_pre_force &&
4123 const bool adaptive_threshold_seeded =
4124 detail::isMmfAdaptiveThresholdSeeded(current_threshold_);
4125 recordBurstOutcome(path, ci_image_idx, neb_config, session, savedPositions,
4126 adaptive_threshold_seeded, force_improved,
4127 threshold_pre_force, threshold_post_force, result);
4128
4129 mmf_attempted_ = detail::mmfAttemptConsumedAfterRecovery(
4130 mmf_attempted_, result.trusted_recovery_advanced,
4132
4133 // ---- Final convergence + reset-optimizer decision ----
4134 // Second-order evidence is required: a low force holds at ANY stationary
4135 // point (shoulders, minima), so force alone must not accept the burst.
4136 // Angle-certified or path-certified Helped is a saddle. Recovery uses
4137 // force certification plus negative curvature; unpath-certified Helped is
4138 // restored before it can terminate.
4139 const bool force_certified = detail::mmfForceCertifiedForConvergence(
4140 result.newForce, threshold_post_force, forceTolerance());
4141 const bool helped_angle_certified =
4143 const bool helped_path_certified =
4144 result.status == MMFStatus::Helped &&
4145 detail::forceOnlyHelpedPathCertified(
4146 helped_angle_certified, result.alignment, cfg_.alignment_cos_tol);
4147 // Classical no-GP OCINEB measurements on this exact oracle refute
4148 // the earlier locality gate here: the far-walked certified saddles
4149 // it blocked (Baker 19 at 0.456 vs classical 0.4506, Baker 16 at
4150 // 0.281 vs classical 0.280, Baker 17 at 1.3025 vs classical 1.3026)
4151 // were the CLASSICAL answers; the band's own hump was the artifact.
4152 // A certified true-force saddle above both endpoints terminates
4153 // (the pass-candidate check in the hook guards the one genuine
4154 // failure ever observed, a below-endpoint side saddle on 08).
4155 result.convergedAfterMMF =
4156 (dimer_force_under_tolerance && result.status == MMFStatus::Helped) ||
4157 detail::mmfBurstConvergedAfterAcceptance(
4158 result.status, force_certified, helped_angle_certified,
4159 result.final_mode_curvature, helped_path_certified);
4160 result.shouldResetOptimizer =
4161 !path.image(ci_image_idx).positions.isApprox(savedPositions);
4162
4163 // The dimer model lease restores the entry theta and refactorizes
4164 // the attached global or per-image model over the harvested rows.
4165 // The session's active-owner marker matches the singleton factor
4166 // consumed by prediction dispatch.
4167
4168 return result;
4169}
4170
4171// One OCI-NEB outer iteration: the body of the outer_iter_hook installed
4172// below. It is a free function rather than 570 lines of lambda because its
4173// captures are its parameters -- the hook captures explicitly, so the
4174// interface is exactly this list.
4176 const std::shared_ptr<OCINEBController>& controller, NEBOracle& oracle,
4177 const GPNEBConfig& neb_config, int& total_oracle_calls, int& bursts_fired,
4178 int& dimer_saddle_image_idx,
4179 const std::shared_ptr<OciMmfHandoffTrapState>& handoff_trap_state,
4180 const GPNEBConfig::OuterIterHook& caller_hook, NEBPath& path,
4181 int ci_image_idx, int outer_iter, ActiveLearningSession& sess,
4182 bool& converged, bool trap_detected)
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;
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="
4653 << " lower_saddle_progress="
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}
4672
4673OCINEBResult runOCINEB(NEBOracle oracle, const Eigen::VectorXd& initial,
4674 const Eigen::VectorXd& final_state, int n_images,
4675 const GPNEBConfig& neb_config,
4676 const OCINEBConfig& oci_config_in,
4677 ActiveLearningSession& session)
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}
4946
4948 const OCINEBConfig& oci_config, const GPNEBConfig& neb_config,
4949 ActiveLearningSession& session, NEBOracle& oracle,
4950 const Eigen::VectorXd& x_seed, double e_seed, const Eigen::VectorXd& g_seed,
4951 const Eigen::VectorXd& mode_seed, double energy_ceiling)
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
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;
5036 parameters.num_bigiter.value = canonical.num_bigiter.value;
5037 }
5038
5040 if (neb_config.training_policy != nullptr)
5041 dimer.setTrainingPolicy(neb_config.training_policy);
5042 dimer.setProjectRigidModesForConvergence(true);
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);
5053 dimer.setHssvdModeSelectionPolicy(
5055 dimer.setPreserveInitialAlignmentReference(false);
5056 dimer.setAlignmentAbortTol(0.0);
5057 dimer.setAbortOnDegenerateProbes(true);
5058 dimer.setMeasuredEnergyCeiling(energy_ceiling);
5059 dimer.setAbortOnInteratomicCollapse(true);
5060 dimer.setRejectHigherIndexSurrogateConvergence(true);
5061 {
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
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 =
5094 dimer.getMidPointCoordForAllObservationPointsRef();
5095 gpr::FieldMatrixd& dimer_E =
5096 dimer.getEnergyForAllObservationPointsRef();
5097 gpr::Coord& dimer_G = dimer.getGradientForAllObservationPointsRef();
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 =
5108 dimer.getRelaxationTerminationReason() ==
5110 out.force = dimer.getFinalForceNormForConvergence();
5111 out.curvature = dimer.getFinalCurvature();
5112 out.positions = dimer.getFinalCoordOfMidPoint();
5113 out.gradient = dimer.getFinalGradientAtMidPoint();
5114 out.energy = dimer.getFinalEnergy() + e0;
5115 restore_model.restore();
5116 return out;
5117}
5118
5119OCINEBResult runOCINEBRefined(NEBOracle oracle, const Eigen::VectorXd& initial,
5120 const Eigen::VectorXd& final_state, int n_images,
5121 GPNEBConfig neb_config,
5122 const OCINEBConfig& oci_config,
5123 ActiveLearningSession& session)
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) {
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,
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
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 &&
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 +=
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}
5394
5396 const Eigen::VectorXd& initial,
5397 const Eigen::VectorXd& final_state,
5398 int active_n_images, const GPNEBConfig& neb_config,
5399 const OCINEBConfig& oci_config,
5400 ActiveLearningSession& session)
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;
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;
5457 result.band_midpoint_holds = mid.holds;
5458 result.band_midpoint_excess = mid.excess;
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;
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.
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;
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}
5753
5754int reduceOracleProviderCalls(int local_calls)
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}
5772
5773} // namespace neb
5774} // namespace gpr
TPE-style OIE acquisition over the discrete interior-image axis.
Adapter: ~NEBOracle~ lambda -> ~potPotentialWrapper~.
GP-OCINEB controller – faithful port of the eOn ~NEBOcinebController~ pattern (eOn/client/ NEBOcinebC...
Atomic dimer.
void initialize(const gpr::InputParameters &parameters, const gpr::Observation &initial_data, const gpr::Observation &middle_point, const gpr::Coord &initial_orientation, const gpr::AtomsConfiguration &init_atom_config)
Initilalize with initial data.
void setVarianceGateConfig(const VarianceGateConfig &cfg) noexcept
gpr::optim::SecantCurvatureCounts secantCounts() const
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
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
void setSecantOrientationSeed(bool enabled) noexcept
void setSelfOwnedUseFfPriorMean(bool use) noexcept
void setLikelihoodNoiseFloorSigma2(double floor_sigma2) noexcept
gpr::FieldMatrixd & getEnergyForAllObservationPointsRef()
Return energies for all observed points.
void setUseHssvdAnalyticCurvature(bool enabled) noexcept
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...
DimerSurrogateActionCertificate previewFirstSurrogateAction(const gpr::Observation &oracle_middle_point, const gpr::Coord &initial_orientation)
gpr::Index_t getTotalForceCalls() const
Return the total number of force calls.
void setSelfOwnedUseZblPriorMean(bool use) noexcept
void attachExternalGP(gpr::GaussianProcessRegression *external_gp) noexcept
Attach an externally-owned GPR model. Must be called BEFORE ~initialize~. The dimer will use this GP ...
void setSecantHessianConfig(const gpr::optim::SecantHessianConfig &config)
Replace the true-force secant and drop its history.
void setProjectRigidModesForConvergence(bool enabled) noexcept
void setSelfOwnedModelProfile(gpr::GPModelProfile profile) noexcept
gpr::Coord & getMidPointCoordForAllObservationPointsRef()
Return gpr::Coordinates of all observed points.
void execute(pot::PotentialWrapper &general_potential)
This function uses the atomic GP-dimer method to converge to a saddle point, starting from somewhere ...
gpr::Index_t getIterations() const
Return the total number of cycles.
void setLeashRelaxWhenClose(bool enabled) noexcept
void dist_emd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the Earth Mover's Distance between sets of configurations.
void calculateVarianceDispatched(Observation &image1)
void calculatePotentialDispatched(Observation &image1)
Definition Predict.cpp:982
double getMagnSigma2()
Definition SexpatCF.inl:53
ScopedParameterRestore scopedParameterRestore() &
Definition Session.h:2775
gpr::GaussianProcessRegression & gp() const
Definition Session.h:2642
const gpr::Observation & observations() const
Definition Session.h:2647
NEB path: chain of images between two endpoints.
Definition NEBPath.h:57
int highestEnergyImageIndex() const
Highest finite interior energy, or -1 when none exists.
Definition NEBPath.cpp:1132
int numImages() const
Definition NEBPath.h:338
Eigen::VectorXd tangentAt(int i) const
Improved (energy-weighted) tangent at image i, normalised. Used by the OCINEB controller to seed the ...
Definition NEBPath.h:321
const Eigen::VectorXd & nebForce(int i) const
Get the NEB force for image i.
Definition NEBPath.h:257
int highestEnergyImageIndexPreferring(int preferred) const
Definition NEBPath.cpp:1165
void computeNEBForces()
Compute NEB forces for all intermediate images.
Definition NEBPath.cpp:880
Image & image(int i)
Access image i.
Definition NEBPath.h:329
double saddleForce(int i) const
Definition NEBPath.h:263
void noteMmfRejectActionSnapshot(detail::MmfPosteriorActionFingerprint action)
Enter the information wait with the posterior action MMF would consume.
void recordUncertifiedMmfHookReject(double convForce, const Eigen::VectorXd &ci_position, detail::MmfSurrogateFingerprint surrogate, long climbingImage=-1)
MMFRunResult run(NEBPath &path, int ci_image_idx, NEBOracle &oracle, const GPNEBConfig &neb_config, ActiveLearningSession &session, bool trap_detected=false)
bool wantsCurrentCiOracle(double convForce, bool ci_active, long climbingImage, long numImages, int outerIter, bool ci_posterior_confident, bool trap_detected=false, std::size_t ntrain_now=0, bool ci_is_energy_maximum=false)
void updateStabilityForOuter(long climbingImage, int outerIter)
Idempotent stability update keyed by GP-NEB outer iteration.
void noteMmfRejectSurrogateSnapshot(detail::MmfSurrogateFingerprint surrogate)
Enter AwaitingFirstTrainingGrowth with the model lease MMF consumed.
bool shouldTrigger(double convForce, bool ci_active, long climbingImage, long numImages, bool ci_posterior_confident, bool trap_detected=false, std::size_t ntrain_now=0, bool ci_is_energy_maximum=false, bool band_information_exhausted=false, bool oie_acquisition_quiet=false, bool rejected_seed_replay=false, bool current_chain_certificate=false, bool current_saddle_stencil_certificate=false, bool rejected_seed_position_matches=false, bool stagnation_handoff=false) const
void releaseRecoveryOwnerForCertifiedHandover(const Eigen::VectorXd &owner_position, long owner_image)
bool rejectedMmfSeedReplay(const Eigen::VectorXd &ci_position, detail::MmfSurrogateFingerprint surrogate, long climbingImage=-1, const gpr::AtomsConfiguration *atoms_config=nullptr) const
void noteMmfActionChange(detail::MmfPosteriorActionFingerprint action)
void noteMmfSurrogateChange(detail::MmfSurrogateFingerprint surrogate)
void initBaseline(double baseline_force)
bool rejectedMmfSeedPositionMatches(const Eigen::VectorXd &ci_position, const gpr::AtomsConfiguration *atoms_config=nullptr, long climbingImage=-1) const
bool shouldPrepareMmfHandoff(bool trap_detected=false, bool band_information_exhausted=false, bool current_chain_certificate=false) const
void noteMmfMinModeProbeConsumed()
Record that the rejected action consumed a true-potential mode probe.
detail::MmfPosteriorActionFingerprint previewMmfAction(ActiveLearningSession &session, const NEBPath &path, int ci_image_idx, const GPNEBConfig &neb_config) const
void noteMmfRejectCiPosition(const Eigen::VectorXd &ci_position, long climbingImage=-1)
void updateStability(long climbingImage)
void recordMmfHandoffForce(double handoff_force, bool handoff_data_ready=false)
bool step(rgsaddle_surface_fn surface, void *user, rgsaddle_report_t &report)
Definition RgMinMode.h:83
bool bind(RgsaddleClient &client, int64_t n_atoms, const double *position, const double *mode, double force_tol, Kind kind=Kind::Dimer, int32_t force_gate=2, int32_t max_rotations=16, double rotation_tol=1e-3)
Definition RgMinMode.h:44
static constexpr Kind kOciBurstKind
Definition RgMinMode.h:23
bool position(double *out)
Definition RgMinMode.h:91
bool load(const std::string &path={})
A JSON object assembled field by field; one line of a record stream.
JsonRecord & add(std::string_view key, double value)
Type-erased wrapper around any potential that provides a force() interface.
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
eon_relax_band_t * band
DimerRelaxationTerminationReason
@ InvalidParameters
The search parameters cannot define a dimer (non-positive separation).
@ WallClockLimit
The shared monotonic wall-clock deadline was reached.
@ InvalidAtomsConfiguration
execute() rejected the atom configuration before any search step.
@ OracleBudget
The caller's oracle-call budget was spent.
double flatDot(const Eigen::MatrixBase< DerivedA > &a, const Eigen::MatrixBase< DerivedB > &b)
Half surrogate(GaussianProcessRegression &gp, const Eigen::VectorXd &x, Kind kind, const Options &options)
double gaussianExceedanceProbability(double reference_mean, double reference_variance, double challenger_mean, double challenger_variance)
Probability that a Gaussian challenger equals or exceeds a Gaussian reference under the independent-m...
The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition,...
int reduceOracleProviderCalls(int local_calls)
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)
double testingHelpedModeCurvature()
int vibrationalIndexOuterBudget(const GPNEBConfig &config, int n_images)
Outer-iteration cap, including the per-image reading.
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)
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)
std::function< std::pair< double, Eigen::VectorXd >( const Eigen::VectorXd &positions)> NEBOracle
Oracle function: positions -> (energy, gradient).
Definition GPNEB.h:82
@ 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)
rgsaddle_status_t gprRgsaddleSurface(void *user, rgsaddle_surface_request_t *req)
pot::PotentialWrapper makePotentialWrapperFromOracle(NEBOracle oracle)
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
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)
double indexGateVarianceThreshold(double noise_variance) noexcept
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)
void applyVibrationalIndexDecision(GPNEBResult &result, const VibrationalIndexDecision &decision, int outer_budget)
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 runOCINEBRefined(NEBOracle oracle, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int n_images, GPNEBConfig neb_config, const OCINEBConfig &oci_config, ActiveLearningSession &session)
MMFStatus
Outcome of one MMF burst, mirroring eOn's enum class.
@ 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.
double saddleForceMagnitude(const Eigen::VectorXd &gradient)
Definition NEBPath.cpp:25
NEBMode
NEB evaluation mode.
Definition GPNEB.h:68
constexpr double stencilStepOrDefault(double requested) noexcept
The requested stencil step, or the default when none was requested.
SecantSeed secantSeedDirection(const SecantHessian &secant, const Eigen::VectorXd &current_direction)
const char * secantSeedStatusName(SecantSeedStatus status) noexcept
void setBofillRgsaddleLibrary(const char *path)
MlflowRun * activeRun() noexcept
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
bool collectiveWallClockLimitReached(const std::shared_ptr< const WallClockLimit > &limit, const linalg::MpiContext &context)
Definition PhaseTimers.h:81
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
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.
STL namespace.
rgsaddle_report_t gpr_rgsaddle_report_t
One entry of the dimer trajectory history – the midpoint configuration and dimer curvature estimate a...
double energy
energy relative to E_zero_level
double curvature
dimer curvature estimate this phase
gpr::Coord position
midpoint coordinates (1 x D)
gpr::Coord gradient
midpoint gradient (1 x D)
bool measured_descent_certified
The true-PES force strictly improves the preceding accepted center.
Stores configurations of all atoms in the system.
Definition Structures.h:832
Structure of the input parameters. All input parameters are pairs of string names and values.
Definition Structures.h:370
KeyValuePair< double[2]> param_trans
Definition Structures.h:440
KeyValuePair< double > T_anglerot_gp
Definition Structures.h:484
KeyValuePair< double > prior_s2
Definition Structures.h:650
KeyValuePair< int > max_iter
Definition Structures.h:674
KeyValuePair< std::string > optimization_alg
Definition Structures.h:614
KeyValuePair< double > dimer_sep
Definition Structures.h:425
KeyValuePair< double > lambda
Definition Structures.h:678
KeyValuePair< double > prior_nu
Definition Structures.h:649
KeyValuePair< double > T_anglerot_init
Definition Structures.h:474
KeyValuePair< double > jitter_sigma2
Definition Structures.h:613
KeyValuePair< double > ratio_at_limit
Definition Structures.h:512
KeyValuePair< std::string > method_trans
Definition Structures.h:435
KeyValuePair< std::string > rot_opt
Definition Structures.h:670
KeyValuePair< int > convergence_force_norm
Definition Structures.h:461
KeyValuePair< std::string > method_rot
Definition Structures.h:430
KeyValuePair< double > constSigma2
Definition Structures.h:618
KeyValuePair< int > divisor_T_dimer_gp
Definition Structures.h:498
KeyValuePair< int > num_iter
Definition Structures.h:537
KeyValuePair< int > num_iter_initrot
Definition Structures.h:479
KeyValuePair< int > eval_image1
Definition Structures.h:446
KeyValuePair< double > lambda_limit
Definition Structures.h:677
KeyValuePair< double > disp_max
Definition Structures.h:505
KeyValuePair< double > tolerance_func
Definition Structures.h:675
KeyValuePair< std::string > check_derivative
Definition Structures.h:672
KeyValuePair< double[4]> dist_sp
Definition Structures.h:374
KeyValuePair< double > tolerance_sol
Definition Structures.h:676
KeyValuePair< double > prior_mu
Definition Structures.h:648
KeyValuePair< int > num_bigiter
Definition Structures.h:532
KeyValuePair< double > sigma2
Definition Structures.h:616
KeyValuePair< double > magnSigma2
Definition Structures.h:617
KeyValuePair< double > gp_sigma2
Definition Structures.h:612
KeyValuePair< double > T_dimer
Definition Structures.h:453
KeyValuePair< int > num_iter_rot_gp
Definition Structures.h:490
Observation data: energy, gradient and positions.
FieldMatrixd E
static void notePeak(const char *phase) noexcept
static SurrogateFingerprint global(std::uint64_t revision)
Definition Session.h:211
int mmfModelOwner(int image_idx, bool dimer_use_global_gp) const
Definition Session.h:1080
SurrogateFingerprint surrogateFingerprint(int owner) const
Definition Session.h:1070
bool hasCurrentChainCertificate(int image_idx, const Eigen::VectorXd &positions) const
Definition Session.h:2081
ModelLease acquireImageModel(int i)
Definition Session.h:2792
void appendCurrentChainObservation(int image_idx, const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient, ObservationRetention retention=ObservationRetention::RecordAcquisition, optim::SecantAccounting secant_accounting=optim::SecantAccounting::Count)
Definition Session.h:1994
gpr::Observation training_obs
Definition Session.h:246
std::uint64_t trainingRevision() const noexcept
Definition Session.h:1043
void addSecantCounts(const optim::SecantCurvatureCounts &extra)
Definition Session.h:406
bool refitGPIfTrainingChanged(bool reinit_seeds)
Definition Session.h:3301
SurrogateFingerprint mmfSurrogateFingerprint(int image_idx, bool dimer_use_global_gp) const
Definition Session.h:1093
gpr::GaussianProcessRegression gp
Definition Session.h:471
gpr::AtomsConfiguration atoms_config
Definition Session.h:1129
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
const optim::SecantHessian * imageSecantHessian(int image_idx) const noexcept
Definition Session.h:351
int worst_segment
segment with the highest energy upper bound
double excess
mean E_mid - E_ci for that segment (eV)
double escapeEnergyCeiling(double refused_energy) const noexcept
bool certified
both required curvature signs are resolved
bool evaluated
the surrogate Hessian was available
bool verified
the complete non-rigid subspace was evaluated
int rounds
Hessian-vector products taken.
std::string reason
why evaluation or sign resolution failed
Configuration for GP-NEB.
Definition GPNEB.h:246
gpr::optim::SecantHessianConfig secant_hessian
Definition GPNEB.h:536
double lbfgs_max_move
Definition GPNEB.h:960
OuterIterHook outer_iter_hook
Definition GPNEB.h:1225
Eigen::Index oracle_batch_chunk
Definition GPNEB.h:259
bool outer_budget_per_image
Definition GPNEB.h:300
const policy::TrainingPolicy * training_policy
Definition GPNEB.h:1269
bool band_midpoint_certificate
Definition GPNEB.h:866
OieFixedImageLeaseProvider oie_fixed_image_lease
Definition GPNEB.h:1265
const double * oracle_energy_noise_rms
Definition GPNEB.h:268
std::vector< double > initial_rest_lengths
Definition GPNEB.h:542
OuterIterHookReject outer_iter_hook_reject
Definition GPNEB.h:1233
double inner_unc_relative
Definition GPNEB.h:1140
OieInnerHandoffPriority oie_inner_handoff_priority
Definition GPNEB.h:1252
NEBBatchOracle batch_oracle
Definition GPNEB.h:253
bool force_stop_certificate
Definition GPNEB.h:847
std::function< void(const NEBOracleOptimizationOutcome &)> oracle_optimization_outcome
Definition GPNEB.h:275
gpr::optim::VibrationalStencil vibrational_stencil
Definition GPNEB.h:852
policy::SearchKind training_search_kind
Label published to the policy. runOCINEB sets OciNeb.
Definition GPNEB.h:1271
CurrentCiOraclePriority current_ci_oracle_priority
Definition GPNEB.h:1242
std::string rgsaddle_library
Definition GPNEB.h:711
double first_attempt_wall_seconds
Definition GPNEB.h:502
bool * oracle_noise_updates_enabled
Definition GPNEB.h:271
OieFixedImage oie_fixed_image
Definition GPNEB.h:1259
bool hold_refined_spacing
Definition GPNEB.h:873
std::shared_ptr< const gpr::WallClockLimit > wall_clock_limit
Definition GPNEB.h:485
std::function< void(gpr::InputParameters &, gpr::AtomsConfiguration &)> gp_setup
Definition GPNEB.h:1204
double band_certificate_force_scale
Definition GPNEB.h:494
std::function< void( NEBPath &path, int ci_image_idx, int outer_iter, ActiveLearningSession &session, bool &converged, bool trap_detected)> OuterIterHook
Definition GPNEB.h:1222
bool ci_index_certificate
Definition GPNEB.h:839
double ci_stencil_step
Definition GPNEB.h:856
int oracle_transition_focal_image
Definition GPNEB.h:546
EigenMatrix initial_path
Definition GPNEB.h:538
double attempt_wall_seconds
Definition GPNEB.h:482
std::function< bool()> oracle_session_restart_requested
Definition GPNEB.h:279
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
GPNEBStopReason stop_reason
Definition GPNEB.h:3684
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
std::unique_ptr< NEBPath > path
Definition GPNEB.h:3682
GP-NEB GaussianProcessRegression as dest PointSurface.
gpr::GaussianProcessRegression * gp
Eigen::VectorXd gradient
Definition NEBPath.h:42
double posterior_variance
Definition NEBPath.h:51
double energy
Definition NEBPath.h:41
Eigen::VectorXd positions
Definition NEBPath.h:40
Eigen::VectorXd positions
final midpoint
int oracle_calls
oracle rows the search paid
bool converged
true-force convergence at the midpoint
int phases
measured dimer phases
Eigen::VectorXd gradient
true gradient at the final midpoint
bool wall_clock_limit
shared search deadline expired
Result of one ~OCINEBControllerrun~ invocation.
MMFRejectKind reject_kind
Reason for rejected_helped_handback, used by recovery-gate policy.
bool shouldResetOptimizer
Whether the caller should reset its outer optimiser state.
double alignment
Alignment of final mode to current path tangent.
bool convergedAfterMMF
True iff newForce < force_tolerance.
bool trusted_recovery_advanced
A non-Helped recovery phase was accepted and written to the chain.
MMFStatus status
Final dimer-status for reporting / accounting.
double previousForce
Oracle force at CI image before this MMF burst.
bool recovery_selection_exhausted
The recovery selector found no acceptable phase to hand back.
MmfHandoffPolicy handoff_policy
int dimer_imspe_history_size
EMD-filtered ring-buffer size for the dimer IMSPE soft-skip.
std::function< double()> effective_force_tolerance
Eigen::VectorXd initial_orient
double dimer_kappa_beta
Xiao contour curvature restraint; zero disables, paper uses 5 Angstrom.
int refinements
Number of band refinements (image doublings) folded into this result.
bool ci_index_evaluated
Climbing-image index certificate (see certifyClimbingImageIndex).
bool band_midpoint_evaluated
Surrogate midpoint check of the returned band (certifyBandMidpoints).
Eigen::VectorXd ci_final_position
Outcome of a saddle polish (see polishSaddleOnSurrogate).
Eigen::VectorXd gradient
true gradient at positions
double energy
true energy at positions
int oracle_calls
true-PES evaluations spent
int steps
accepted Newton steps
Eigen::VectorXd direction
SecantSeedStatus status