Loading...
Searching...
No Matches
GPNEB.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 "GPNEB.h"
6
9#include "../ml/PhaseTimers.h"
11#include "BandStall.h"
12#include "OCINEBController.h"
13#include "OieOracleConsensus.h"
14#include "RgFireEngine.h"
15#include "RgLbfgsEngine.h"
16#include "RgsaddleBandEngine.h"
17#include "RgsaddleClient.h"
18#include "SubstrateFactor.h"
23
24#ifdef GPR_HAVE_MPI
25#include <mpi.h>
26#endif
27
28#include <unistd.h>
29
30#include <algorithm>
31#include <chrono>
32#include <deque>
33#include <memory>
34#include <type_traits>
35#if defined(__GLIBC__)
36#include <malloc.h>
37#endif
38#include <cmath>
39#include <cstdint>
40#include <cstdlib>
41#include <cstring>
42#include <fstream>
43#include <iostream>
44#include <limits>
45#include <map>
46#include <numeric>
47#include <optional>
48#include <random>
49#include <sstream>
50#include <stdexcept>
51#include <streambuf>
52#include <tuple>
53#include <utility>
54#include <vector>
55
60#include "../dimer/Dimer.h"
62#include "LocalGP.h"
63#include "PairSplineModel.h"
68#include "gpr/ml/TrustRadius.h"
72
73namespace gpr {
74namespace neb {
75
76namespace {
77
78// Optional quiet path for batch farms: when GPNEBConfig::verbose is false,
79// diagnostic streams discard bytes without changing control flow.
80class NebNullBuf final : public std::streambuf {
81protected:
82 int overflow(int ch) override
83 {
84 return traits_type::not_eof(ch);
85 }
86};
87
88thread_local bool g_neb_log_verbose = true;
89
90struct NebVerboseGuard {
91 bool previous;
92 explicit NebVerboseGuard(bool verbose) : previous(g_neb_log_verbose)
93 {
94 g_neb_log_verbose = verbose;
95 }
96 ~NebVerboseGuard()
97 {
98 g_neb_log_verbose = previous;
99 }
100};
101
102std::ostream& neb_log()
103{
104 static NebNullBuf null_buf;
105 static std::ostream null_stream(&null_buf);
106 return g_neb_log_verbose ? std::cout : null_stream;
107}
108
109} // namespace
110
111#include "GPNEBAdaptiveSo3.inc"
112
113namespace detail {
114
115std::ostream& bandLog()
116{
117 return neb_log();
118}
119
120std::vector<Eigen::Index> selectLocalPolishDofs(
121 const Eigen::VectorXd& initial, const Eigen::VectorXd& final_state,
122 double fraction, double radius)
123{
124 std::vector<Eigen::Index> dofs;
125 if (initial.size() != final_state.size() || initial.size() == 0)
126 return dofs;
127 const Eigen::Index per = (initial.size() % 3 == 0) ? 3 : 1;
128 const Eigen::Index groups = initial.size() / per;
129 const Eigen::VectorXd delta = final_state - initial;
130 std::vector<double> motion(static_cast<std::size_t>(groups), 0.0);
131 double largest = 0.0;
132 for (Eigen::Index g = 0; g < groups; ++g) {
133 motion[static_cast<std::size_t>(g)] =
134 delta.segment(g * per, per).norm();
135 largest = std::max(largest, motion[static_cast<std::size_t>(g)]);
137 std::vector<char> picked(static_cast<std::size_t>(groups), 0);
138 if (largest > 0.0 && std::isfinite(largest)) {
139 const double floor = std::clamp(fraction, 0.0, 1.0) * largest;
140 for (Eigen::Index g = 0; g < groups; ++g)
141 picked[static_cast<std::size_t>(g)] =
142 motion[static_cast<std::size_t>(g)] >= floor &&
143 motion[static_cast<std::size_t>(g)] > 0.0;
144 } else {
145 // A band without endpoint motion polishes every coordinate.
146 std::fill(picked.begin(), picked.end(), 1);
148 if (radius > 0.0 && per == 3) {
149 std::vector<char> grown = picked;
150 for (Eigen::Index g = 0; g < groups; ++g) {
151 if (!picked[static_cast<std::size_t>(g)]) continue;
152 for (Eigen::Index h = 0; h < groups; ++h) {
153 if (grown[static_cast<std::size_t>(h)]) continue;
154 const double distance =
155 (initial.segment(g * 3, 3) - initial.segment(h * 3, 3))
156 .norm();
157 if (distance <= radius) grown[static_cast<std::size_t>(h)] = 1;
158 }
159 }
160 picked.swap(grown);
161 }
162 for (Eigen::Index g = 0; g < groups; ++g) {
163 if (!picked[static_cast<std::size_t>(g)]) continue;
164 for (Eigen::Index k = 0; k < per; ++k)
165 dofs.push_back(g * per + k);
166 }
167 return dofs;
168}
172inline double residentSetMegabytes()
173{
174 std::ifstream statm("/proc/self/statm");
175 long pages = 0, resident = 0;
176 if (!(statm >> pages >> resident)) return 0.0;
177 const long page = sysconf(_SC_PAGESIZE);
178 return static_cast<double>(resident) * static_cast<double>(page) /
179 (1024.0 * 1024.0);
180}
181
182OieFixedImageLease resolveOieFixedImageLease(const GPNEBConfig& config,
183 const NEBPath& path,
184 int ci_image_idx, int outer_iter)
185{
186 OieFixedImageLease lease;
187 if (config.oie_fixed_image_lease) {
188 lease = config.oie_fixed_image_lease(path, ci_image_idx, outer_iter);
189 } else if (config.oie_fixed_image) {
190 lease.image_index =
191 config.oie_fixed_image(path, ci_image_idx, outer_iter);
192 }
193 if (lease.image_index <= 0 || lease.image_index >= path.numImages() - 1) {
194 return {};
195 }
196 return lease;
197}
199OieFixedImageLease arbitrateOieRecoveryBandOwnership(
200 OieFixedImageLease local_recovery_lease, int ci_idx,
201 int adjacent_recovery_ci_idx, int adjacent_recovery_target_idx)
202{
203 const bool adjacent_recovery_owns_band =
204 ci_idx > 0 && adjacent_recovery_ci_idx == ci_idx &&
205 (adjacent_recovery_target_idx == ci_idx - 1 ||
206 adjacent_recovery_target_idx == ci_idx + 1);
207 return adjacent_recovery_owns_band ? OieFixedImageLease{}
208 : local_recovery_lease;
209}
210
211void OieRecoveryStencilAnchor::clear()
212{
213 owner_image_ = -1;
214 positions_.clear();
215 committed_handoff_pending_ = false;
216 release_after_restore_ = false;
217}
218
219bool OieRecoveryStencilAnchor::update(const NEBPath& path,
220 const OieFixedImageLease& lease)
221{
222 const bool valid_lease = lease.model_growth_required &&
223 lease.image_index > 0 &&
224 lease.image_index < path.numImages() - 1;
225 if (!valid_lease) {
226 if (active() &&
227 (committed_handoff_pending_ || release_after_restore_)) {
228 const bool changed = !release_after_restore_;
229 committed_handoff_pending_ = false;
230 release_after_restore_ = true;
231 return changed;
232 }
233 const bool changed = active();
234 clear();
235 return changed;
237 if (owner_image_ == lease.image_index && positions_.size() == 3) {
238 return false;
239 }
240
241 std::vector<Eigen::VectorXd> positions;
242 positions.reserve(3);
243 for (int image = lease.image_index - 1; image <= lease.image_index + 1;
244 ++image) {
245 const Eigen::VectorXd& image_positions = path.image(image).positions;
246 if (image_positions.size() == 0 || !image_positions.allFinite()) {
247 const bool changed = active();
248 clear();
249 return changed;
250 }
251 positions.push_back(image_positions);
252 }
253 owner_image_ = lease.image_index;
254 positions_ = std::move(positions);
255 committed_handoff_pending_ = false;
256 release_after_restore_ = false;
257 return true;
258}
259
260bool OieRecoveryStencilAnchor::reanchor(const NEBPath& path,
261 const OieFixedImageLease& lease)
262{
263 clear();
264 const bool changed = update(path, lease);
265 committed_handoff_pending_ = active();
266 return changed;
267}
268
269bool OieRecoveryStencilAnchor::restore(NEBPath& path)
270{
271 if (!active() || positions_.size() != 3 || owner_image_ <= 0 ||
272 owner_image_ >= path.numImages() - 1) {
273 if (release_after_restore_) clear();
274 return false;
275 }
276 for (int image = owner_image_ - 1; image <= owner_image_ + 1; ++image) {
277 const Eigen::VectorXd& anchored =
278 positions_[static_cast<std::size_t>(image - owner_image_ + 1)];
279 if (anchored.size() != path.image(image).positions.size()) {
280 if (release_after_restore_) clear();
281 return false;
282 }
283 }
284 for (int image = owner_image_ - 1; image <= owner_image_ + 1; ++image) {
285 path.image(image).positions =
286 positions_[static_cast<std::size_t>(image - owner_image_ + 1)];
287 if (image > 0 && image < path.numImages() - 1) {
288 path.image(image).evaluated = false;
289 }
290 }
291 if (release_after_restore_) clear();
292 return true;
293}
294
295void OieRecoveryStencilAnchor::applyActiveImageMask(
296 std::vector<char>& active_images, int n_images) const
297{
298 if (!active() || n_images <= 2 || owner_image_ >= n_images - 1) return;
299 if (active_images.empty()) {
300 active_images.assign(static_cast<std::size_t>(n_images), 1);
301 }
302 if (active_images.size() != static_cast<std::size_t>(n_images)) return;
303 for (int image = owner_image_ - 1; image <= owner_image_ + 1; ++image) {
304 if (image > 0 && image < n_images - 1) {
305 active_images[static_cast<std::size_t>(image)] = 0;
306 }
308}
309
310bool OieRecoveryGrowthTrial::improvesForce() const noexcept
311{
312 return std::isfinite(source_force) && std::isfinite(trial_force) &&
313 trial_force < source_force;
314}
315
316std::optional<OieRecoveryGrowthTrial> makeOieRecoveryGrowthTrial(
317 const NEBPath& path, int image_index, const Eigen::VectorXd& positions,
318 double energy, const Eigen::VectorXd& gradient)
319{
320 if (image_index <= 0 || image_index >= path.numImages() - 1 ||
321 positions.size() != path.image(image_index).positions.size() ||
322 gradient.size() != positions.size() || !positions.allFinite() ||
323 !gradient.allFinite() || !std::isfinite(energy) ||
324 positionsCoincide(positions, path.image(image_index).positions)) {
325 return std::nullopt;
326 }
327
328 NEBPath source = path;
329 source.computeNEBForces();
330 NEBPath candidate = path;
331 candidate.image(image_index).positions = positions;
332 candidate.image(image_index).energy = energy;
333 candidate.image(image_index).gradient = gradient;
334 candidate.image(image_index).evaluated = true;
335 candidate.computeNEBForces();
336
337 const double source_force = source.nebForceMagnitude(image_index);
338 const double trial_force = candidate.nebForceMagnitude(image_index);
339 if (!std::isfinite(source_force) || !std::isfinite(trial_force)) {
340 return std::nullopt;
341 }
342
343 OieRecoveryGrowthTrial trial;
344 trial.image_index = image_index;
345 trial.source_stencil_positions.reserve(3);
346 for (int image = image_index - 1; image <= image_index + 1; ++image) {
347 trial.source_stencil_positions.push_back(path.image(image).positions);
348 }
349 trial.positions = positions;
350 trial.energy = energy;
351 trial.gradient = gradient;
352 trial.source_force_vector = source.nebForce(image_index);
353 trial.trial_force_vector = candidate.nebForce(image_index);
354 trial.source_force = source_force;
355 trial.trial_force = trial_force;
356 return trial;
357}
358
359bool commitOieRecoveryGrowthTrial(NEBPath& path,
360 const OieRecoveryGrowthTrial& trial)
361{
362 if (!trial.improvesForce() || trial.image_index <= 0 ||
363 trial.image_index >= path.numImages() - 1 ||
364 trial.source_stencil_positions.size() != 3 ||
365 trial.positions.size() !=
366 path.image(trial.image_index).positions.size() ||
367 trial.gradient.size() != trial.positions.size()) {
368 return false;
369 }
370 for (int image = trial.image_index - 1; image <= trial.image_index + 1;
371 ++image) {
372 if (!positionsCoincide(
373 path.image(image).positions,
374 trial.source_stencil_positions[static_cast<std::size_t>(
375 image - trial.image_index + 1)])) {
376 return false;
377 }
378 }
379
380 NEBPath source = path;
381 source.computeNEBForces();
382 NEBPath candidate = path;
383 candidate.image(trial.image_index).positions = trial.positions;
384 candidate.image(trial.image_index).energy = trial.energy;
385 candidate.image(trial.image_index).gradient = trial.gradient;
386 candidate.image(trial.image_index).evaluated = true;
387 candidate.computeNEBForces();
388 if (!(candidate.nebForceMagnitude(trial.image_index) <
389 source.nebForceMagnitude(trial.image_index))) {
390 return false;
391 }
392
393 path.image(trial.image_index).positions = trial.positions;
394 path.image(trial.image_index).energy = trial.energy;
395 path.image(trial.image_index).gradient = trial.gradient;
396 path.image(trial.image_index).evaluated = true;
397 path.computeNEBForces();
398 return true;
399}
400
401int resolveOieFixedImage(const GPNEBConfig& config, const NEBPath& path,
402 int ci_image_idx, int outer_iter)
403{
404 return resolveOieFixedImageLease(config, path, ci_image_idx, outer_iter)
405 .image_index;
406}
407
408int resolveOieLocalRecoveryImage(int fixed_image, int ci_candidate_idx,
409 bool ci_candidate_posterior_confident)
410{
411 return fixed_image > 0 && fixed_image == ci_candidate_idx &&
412 ci_candidate_posterior_confident
413 ? fixed_image
414 : -1;
415}
416
417bool oieLocalRecoveryOwnsReplaceableWork(
418 int n_images, int local_recovery_image,
419 const std::vector<char>& image_evaluated,
420 const std::vector<char>& image_observed_current)
421{
422 if (local_recovery_image <= 0 || local_recovery_image >= n_images - 1) {
423 return false;
424 }
425 const auto has_current_data =
426 [local_recovery_image](const std::vector<char>& mask) {
427 return local_recovery_image < static_cast<int>(mask.size()) &&
428 mask[static_cast<std::size_t>(local_recovery_image)] != 0;
429 };
430 return has_current_data(image_evaluated) ||
431 has_current_data(image_observed_current);
432}
433
434bool oieLocalRecoverySuppressesReplaceableWork(
435 bool local_recovery_owns_replaceable_work,
436 bool allow_replaceable_acquisition)
437{
438 return local_recovery_owns_replaceable_work &&
439 !allow_replaceable_acquisition;
440}
441
442bool shouldAcquireOieOwnerModelGrowth(bool model_growth_required)
443{
444 return model_growth_required;
445}
446
447int selectOieRecoveryCandidateCertificateImage(
448 int n_images, int recovery_owner, bool model_growth_required,
449 int candidate_image, bool candidate_handover_certified)
450{
451 const auto interior = [n_images](int image) {
452 return image > 0 && image < n_images - 1;
453 };
454 return model_growth_required && interior(recovery_owner) &&
455 interior(candidate_image) &&
456 candidate_image != recovery_owner &&
457 !candidate_handover_certified
458 ? candidate_image
459 : -1;
460}
461
462bool shouldDeferOieFixedPointRecovery(bool local_recovery_owns_replaceable_work,
463 bool oracle_target_selected)
464{
465 return local_recovery_owns_replaceable_work && !oracle_target_selected;
466}
467
468void OieFixedPointHistory::observeTraining(Eigen::Index row_count,
469 std::uint64_t revision)
470{
471 if (row_count != row_count_ || revision != revision_) {
472 resolutions.clear();
473 mmf_grants.clear();
474 }
475 row_count_ = row_count;
476 revision_ = revision;
477}
478
479bool posteriorVarianceExceedsTolerance(double max_variance, double threshold)
480{
481 return threshold > 0.0 && std::isfinite(threshold) && max_variance > 0.0 &&
482 std::isfinite(max_variance) && max_variance > threshold;
483}
484
485bool posteriorVarianceConverged(double max_variance, double threshold)
486{
487 if (!(threshold > 0.0) || !std::isfinite(threshold)) return true;
488 return max_variance >= 0.0 && std::isfinite(max_variance) &&
489 max_variance <= threshold;
490}
491
514bool posteriorVarianceResolvedAcrossBand(double max_variance,
515 double median_variance,
516 double threshold, double spread_factor)
517{
518 if (!posteriorVarianceConverged(max_variance, threshold)) return false;
519 if (!(spread_factor > 0.0) || !std::isfinite(spread_factor)) return true;
520 if (!(median_variance > 0.0) || !std::isfinite(median_variance)) {
521 // No usable typical value: the absolute test is all there is.
522 return true;
523 }
524 return max_variance <= spread_factor * median_variance;
525}
526
531double medianPositive(std::vector<double> values)
532{
533 values.erase(std::remove_if(
534 values.begin(), values.end(),
535 [](double v) { return !(v > 0.0) || !std::isfinite(v); }),
536 values.end());
537 if (values.empty()) return -1.0;
538 const std::size_t mid = values.size() / 2;
539 std::nth_element(values.begin(), values.begin() + mid, values.end());
540 return values[mid];
541}
542
543OieBandPosteriorReadiness assessOieBandPosteriorReadiness(
544 const std::vector<ObservationVariance>& per_image_variance,
545 double energy_variance_threshold, double force_tolerance,
546 double likelihood_noise_variance,
547 const std::vector<char>& image_observed_current)
548{
549 OieBandPosteriorReadiness readiness;
550 readiness.per_image_deficit.assign(per_image_variance.size(), 0.0);
551 if (per_image_variance.size() <= 2) return readiness;
552
553 const bool assess_energy = energy_variance_threshold > 0.0 &&
554 std::isfinite(energy_variance_threshold);
555 const double force_tolerance_variance =
556 force_tolerance > 0.0 && std::isfinite(force_tolerance)
557 ? force_tolerance * force_tolerance
558 : 0.0;
559 const double noise_variance =
560 likelihood_noise_variance > 0.0 &&
561 std::isfinite(likelihood_noise_variance)
562 ? likelihood_noise_variance
563 : 0.0;
564
565 double best_unobserved_deficit = 1.0;
566 for (std::size_t i = 1; i + 1 < per_image_variance.size(); ++i) {
567 const ObservationVariance& variance = per_image_variance[i];
568 const bool observed =
569 i < image_observed_current.size() && image_observed_current[i] != 0;
570 const double energy_variance =
571 sanitizePosteriorVariance(variance.energy);
572 const double energy_ratio =
573 assess_energy ? energy_variance / energy_variance_threshold : 0.0;
574 readiness.max_energy_ratio =
575 std::max(readiness.max_energy_ratio, energy_ratio);
576
577 // The trace sums the posterior force variance over every
578 // coordinate of the image, so its ceiling is the per-coordinate
579 // bound times the coordinate count: the force is resolved when
580 // its posterior standard deviation per coordinate sits under the
581 // convergence force (or the oracle noise, whichever is larger).
582 // A ceiling of tol^2 alone against the trace is a factor of the
583 // coordinate count too strict, and with a fixed nugget the band
584 // measured one image per outer until every image was known to a
585 // fraction of the tolerance (irc 25_hcnh2: 401 calls, CI at 0.02).
586 const double force_variance =
587 observationGradientVarianceTrace(variance);
588 const double force_variance_ceiling =
589 static_cast<double>(variance.gradient.size()) *
590 std::max(force_tolerance_variance, noise_variance);
591 const double force_ratio = force_variance_ceiling > 0.0
592 ? force_variance / force_variance_ceiling
593 : 0.0;
594 readiness.max_force_ratio =
595 std::max(readiness.max_force_ratio, force_ratio);
596
597 const double deficit = std::max(energy_ratio, force_ratio);
598 readiness.per_image_deficit[i] = deficit;
599 // Joint training rows exhaust local information. Residual variance on
600 // those rows (LOO calibration, dual prior remainder) is diagnostic
601 // only: it must not block readiness or re-select the same geometry.
602 if (observed) continue;
603
604 readiness.energy_resolved =
605 readiness.energy_resolved && energy_ratio <= 1.0;
606 readiness.force_resolved =
607 readiness.force_resolved && force_ratio <= 1.0;
608 if (deficit > best_unobserved_deficit) {
609 best_unobserved_deficit = deficit;
610 readiness.acquisition_image = static_cast<int>(i);
611 }
612 }
613 return readiness;
614}
615
616int selectOieInnerProposalAcquisitionImage(
617 const OieBandPosteriorReadiness& readiness) noexcept
618{
619 return !readiness.resolved() && readiness.acquisition_image > 0
620 ? readiness.acquisition_image
621 : -1;
622}
623
624double effectivePosteriorVarianceThreshold(
625 const GPNEBConfig& config, std::optional<double> signal_variance)
626{
627 const double base = config.unc_convergence;
628 if (!(base > 0.0) || !std::isfinite(base)) return base;
629 if (!signal_variance.has_value()) return base;
630 const double signal = *signal_variance;
631 if (!(signal > 0.0) || !std::isfinite(signal)) return base;
632 return base * signal;
633}
634
635double effectiveModelNoiseTolerance(const GPNEBConfig& config)
636{
637 const double requested_tol = config.conv_tol;
638 if (!(std::isfinite(requested_tol) && requested_tol >= 0.0)) {
639 return requested_tol;
640 }
641 double noise_floor = 0.0;
642 if (config.oracle_force_noise_rms &&
643 std::isfinite(*config.oracle_force_noise_rms) &&
644 *config.oracle_force_noise_rms > 0.0) {
645 noise_floor = *config.oracle_force_noise_rms;
646 }
647 // The requested force criterion and force RMS are independent resolution
648 // scales, so their Gaussian convolution is a quadrature smear. Energy RMS
649 // remains in the likelihood covariance and is not converted with a
650 // numerical optimizer displacement.
651 return noise_floor > 0.0 ? std::hypot(requested_tol, noise_floor)
652 : requested_tol;
653}
654
655double forwardBarrierEnergy(const NEBPath& path, int saddle_image)
656{
657 // highestEnergyImageIndex is -1 when the band has no finite interior
658 // energy. Indexing that image is out of range; the barrier is unknown.
659 if (path.numImages() < 1 || saddle_image < 0 ||
660 saddle_image >= path.numImages()) {
661 return std::numeric_limits<double>::quiet_NaN();
662 }
663 return path.image(saddle_image).energy - path.image(0).energy;
664}
665
666static double reverseBarrierEnergy(const NEBPath& path, int saddle_image)
667{
668 if (path.numImages() < 2 || saddle_image < 0 ||
669 saddle_image >= path.numImages()) {
670 return std::numeric_limits<double>::quiet_NaN();
671 }
672 return path.image(saddle_image).energy -
673 path.image(path.numImages() - 1).energy;
674}
675
676void throwIfOracleSessionRestartRequested(
677 const std::function<bool()>& restart_requested)
678{
679 bool requested = restart_requested && restart_requested();
680#ifdef GPR_HAVE_MPI
681 int mpi_up = 0;
682 MPI_Initialized(&mpi_up);
683 if (mpi_up) {
684 const int local = requested ? 1 : 0;
685 int global = 0;
686 MPI_Allreduce(&local, &global, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
687 requested = global != 0;
688 }
689#endif
690 if (requested) throw OracleSessionRestartRequested{};
691}
692
693bool publishOracleSessionPathCheckpoint(const GPNEBConfig& config,
694 const NEBPath& path,
695 int focal_image_index)
696{
697 if (!config.oracle_session_path_checkpoint || path.numImages() < 2) {
698 return false;
699 }
700 const Eigen::Index coordinates = path.image(0).positions.size();
701 if (coordinates <= 0) return false;
702 NEBOracleSessionCheckpoint checkpoint;
703 checkpoint.positions.resize(path.numImages(), coordinates);
704 for (int i = 0; i < path.numImages(); ++i) {
705 if (path.image(i).positions.size() != coordinates ||
706 !path.image(i).positions.allFinite()) {
707 return false;
708 }
709 checkpoint.positions.row(i) = path.image(i).positions.transpose();
710 }
711 if (focal_image_index <= 0 || focal_image_index >= path.numImages() - 1) {
712 focal_image_index = climbingStopImage(path);
713 }
714 checkpoint.focal_image_index = focal_image_index;
715 config.oracle_session_path_checkpoint(checkpoint);
716 return true;
717}
718
719bool modelNoiseRaisesConvergenceTolerance(const GPNEBConfig& config)
720{
721 const double tol = effectiveModelNoiseTolerance(config);
722 return std::isfinite(config.conv_tol) && std::isfinite(tol) &&
723 tol > config.conv_tol;
724}
725
726const double* oracleEnergyNoiseRmsPtr(const GPNEBConfig& config) noexcept
727{
728 return config.oracle_energy_noise_rms != nullptr
729 ? config.oracle_energy_noise_rms
730 : config.oracle_noise_rms;
731}
732
733GPNEBConvergenceStatus convergenceStatusForCurrentTolerance(
734 const GPNEBConfig& config)
735{
736 return modelNoiseRaisesConvergenceTolerance(config)
739}
740
741// Median EMD pairwise distance over the training set, the anchor for the
742// scale-free trust radius. dist_emd builds the full n x n EMD matrix between
743// the training rows and themselves; the strict-upper-triangle median is the
744// system-size-adaptive spread the radius scales with. EMD is positively
745// homogeneous of degree 1 in the coordinate differences, so the median EMD
746// scales linearly with the system, mirroring the Euclidean property the
747// ScaleFreeTrustRegion derivation relies on. Returns 0 when fewer than two
748// rows or the backend yields no usable pairwise entry.
749double emdMedianPairwiseDistance(const gpr::Coord& R_train,
750 const gpr::AtomsConfiguration& atoms_config)
751{
752 const Eigen::Index n = R_train.rows();
753 if (n < 2) return 0.0;
755 aux::Distance distance;
756 distance.dist_emd(R_train, R_train, atoms_config, pair);
757 if (pair.rows() != n || pair.cols() != n) return 0.0;
758 std::vector<double> vals;
759 vals.reserve(static_cast<std::size_t>(n) * (n - 1) / 2);
760 for (Eigen::Index i = 0; i < n; ++i) {
761 for (Eigen::Index j = i + 1; j < n; ++j) {
762 const double d = pair(i, j);
763 if (std::isfinite(d) && d > 0.0) vals.push_back(d);
764 }
765 }
766 if (vals.empty()) return 0.0;
767 const std::size_t mid = vals.size() / 2;
768 std::nth_element(vals.begin(), vals.begin() + mid, vals.end());
769 double median = vals[mid];
770 if (vals.size() % 2 == 0) {
771 const double lo = *std::max_element(vals.begin(), vals.begin() + mid);
772 median = 0.5 * (lo + median);
773 }
774 return median;
775}
776
777double sanitizePosteriorVariance(double variance)
778{
779 // Preserve +Inf as maximally uncertain. A raw NaN stays NaN so
780 // posteriorVarianceConverged rejects it. Negative finite artifacts
781 // and -Inf clamp to 0.
782 if (std::isnan(variance)) return variance;
783 if (std::isinf(variance) && variance > 0.0) return variance;
784 return variance > 0.0 ? variance : 0.0;
785}
786
787bool posteriorVarianceWithinNoiseFloor(double variance, double noise_variance)
788{
789 if (!(noise_variance > 0.0) || !std::isfinite(noise_variance)) {
790 return true;
791 }
792 if (variance < 0.0 && std::isfinite(variance)) {
793 variance = 0.0;
794 }
795 // A variance one last bit above the likelihood floor is still the
796 // floor. Acquiring it does not change a certificate.
797 return variance >= 0.0 && std::isfinite(variance) &&
798 gpr::numerics::withinThreshold(variance, noise_variance);
799}
800
801bool chainPosteriorVarianceWithinNoiseFloor(
802 const std::vector<double>& posterior_energy_variance, int n_images,
803 double noise_variance)
804{
805 if (!(noise_variance > 0.0) || !std::isfinite(noise_variance)) {
806 return true;
807 }
808 if (n_images <= 2) return true;
809 if (static_cast<int>(posterior_energy_variance.size()) < n_images) {
810 return false;
811 }
812 for (int i = 1; i < n_images - 1; ++i) {
813 if (!posteriorVarianceWithinNoiseFloor(posterior_energy_variance[i],
814 noise_variance)) {
815 return false;
816 }
817 }
818 return true;
819}
820
821double oieTerminalSweepReferenceForce(double pre_oracle_relaxed_force,
822 double post_oracle_force,
823 bool has_true_force_eval)
824{
825 return has_true_force_eval && std::isfinite(post_oracle_force)
826 ? post_oracle_force
827 : pre_oracle_relaxed_force;
828}
829
830bool oieCiPosteriorForceCertificate(bool ci_active, double current_ci_force,
831 double ci_variance, double conv_tol,
832 double variance_threshold)
833{
834 return ci_active && std::isfinite(conv_tol) && conv_tol >= 0.0 &&
835 std::isfinite(current_ci_force) && current_ci_force < conv_tol &&
836 posteriorVarianceConverged(ci_variance, variance_threshold);
837}
838
839double imspeRelativeGain(double selected_score, double chain_trace)
840{
841 if (!(selected_score >= 0.0) || !std::isfinite(selected_score)) {
842 return std::numeric_limits<double>::infinity();
843 }
844 if (!(chain_trace > 0.0) || !std::isfinite(chain_trace)) {
845 return std::numeric_limits<double>::infinity();
846 }
847 return selected_score / chain_trace;
848}
849
850double oracleBatchForceResolution(const gpr::Observation& acquired,
851 ConvergenceNormType force_norm,
852 double force_tolerance)
853{
854 if (acquired.R.rows() == 0 || acquired.G.rows() != acquired.R.rows() ||
855 acquired.G.cols() != acquired.R.cols() ||
856 !(std::isfinite(force_tolerance) && force_tolerance > 0.0))
857 return std::numeric_limits<double>::quiet_NaN();
858 double resolution = std::numeric_limits<double>::infinity();
859 for (Eigen::Index row = 0; row < acquired.G.rows(); ++row) {
860 const double force = gpr::forceNorm(acquired.G.row(row), force_norm);
861 if (!std::isfinite(force))
862 return std::numeric_limits<double>::quiet_NaN();
863 // The smallest row budget prevents one large force from masking
864 // an unresolved force on another configuration in the batch.
865 resolution = std::min(resolution, std::max(force, force_tolerance));
866 }
867 return resolution;
868}
869
870bool shouldUseFixedThetaRefreshFromImspe(
871 const GPNEBConfig& config, AcquisitionType acquisition,
872 double selected_score, double chain_trace, bool reinit_hyperparams,
873 bool frozen_sweep, bool rejected_proposal, bool oracle_updates_current_path)
874{
875 if (!(config.imspe_refit_skip_relative_tol > 0.0) ||
876 !std::isfinite(config.imspe_refit_skip_relative_tol)) {
877 return false;
878 }
879 if (acquisition != AcquisitionType::IMSPE) return false;
880 if (reinit_hyperparams || frozen_sweep || rejected_proposal) return false;
881 if (!oracle_updates_current_path) return false;
882 const double relative_gain = imspeRelativeGain(selected_score, chain_trace);
883 return std::isfinite(relative_gain) &&
884 relative_gain < config.imspe_refit_skip_relative_tol;
885}
886
887bool shouldUseFixedThetaRefreshAfterAcquisition(
888 const GPNEBConfig& config, AcquisitionType acquisition,
889 double selected_imspe_score, double imspe_chain_trace,
890 bool reinit_hyperparams, bool frozen_sweep, bool rejected_proposal,
891 bool oracle_updates_current_path)
892{
893 if (reinit_hyperparams || frozen_sweep || rejected_proposal ||
894 !oracle_updates_current_path) {
895 return false;
896 }
897 if (acquisition == AcquisitionType::TPE) return true;
898 return shouldUseFixedThetaRefreshFromImspe(
899 config, acquisition, selected_imspe_score, imspe_chain_trace,
900 reinit_hyperparams, frozen_sweep, rejected_proposal,
901 oracle_updates_current_path);
902}
903
904bool shouldUseFixedThetaRefreshForOracleBatch(
905 const GPNEBConfig& config, AcquisitionType acquisition,
906 std::size_t oracle_batch_size, double selected_imspe_score,
907 double imspe_chain_trace, bool reinit_hyperparams, bool frozen_sweep,
908 bool rejected_proposal, bool oracle_updates_current_path,
909 bool model_boundary_evidence, bool recovery_model_growth)
910{
911 if (oracle_batch_size == 0) return false;
912 if (model_boundary_evidence) return false;
913 if (recovery_model_growth) {
914 return oracle_batch_size == 1 && !frozen_sweep;
915 }
916 if (oracle_batch_size > 1 && acquisition != AcquisitionType::TPE) {
917 return false;
918 }
919 return shouldUseFixedThetaRefreshAfterAcquisition(
920 config, acquisition, selected_imspe_score, imspe_chain_trace,
921 reinit_hyperparams, frozen_sweep, rejected_proposal,
922 oracle_updates_current_path);
923}
924
925bool shouldRunOciMmfHookOnCurrentTrueCi(
926 bool ci_active, int hook_ci_idx, int oracle_idx,
927 bool oracle_updates_current_path, int n_images, bool hook_ci_evaluated,
928 int max_force_idx, double ci_force, double max_band_force, double conv_tol,
929 double max_chain_energy_variance, double posterior_variance_threshold,
930 double inner_unc_relative, bool controller_requests_handoff,
931 bool adjacent_mep_certificate_failed)
932{
933 if (!ci_active) return false;
934 if (hook_ci_idx <= 0 || hook_ci_idx >= n_images - 1) return false;
935 if (adjacent_mep_certificate_failed) return false;
936 // The climbing image's true force is already the final tolerance. The
937 // band returns that geometry; another dimer burst would buy forces the
938 // search has finished with.
939 if (std::isfinite(ci_force) && std::isfinite(conv_tol) && conv_tol > 0.0 &&
940 ci_force < conv_tol)
941 return false;
942 if (controller_requests_handoff) return true;
943 const bool oracle_in_ci_stencil =
944 oracle_idx >= hook_ci_idx - 1 && oracle_idx <= hook_ci_idx + 1;
945 const bool current_true_ci_stencil =
946 oracle_updates_current_path && oracle_in_ci_stencil;
947 // Acquisition-idle freeze: the picker returned no target while true force
948 // remains above problem tolerance. Check this before the evaluated-flag
949 // gate because freeze loops can clear image.evaluated while still carrying
950 // a residual force; the dimer re-oracles the CI geometry. Do not fire
951 // while acquisition is still active.
952 const bool acquisition_idle = (oracle_idx < 0);
953 if (acquisition_idle && std::isfinite(max_band_force) &&
954 std::isfinite(conv_tol) && conv_tol > 0.0 &&
955 max_band_force > conv_tol) {
956 return true;
957 }
958 const bool acquisition_exhausted = detail::isBandInformationExhaustedForMmf(
959 max_chain_energy_variance, /*likelihood_noise_variance=*/0.0,
960 posterior_variance_threshold, inner_unc_relative);
961 if (acquisition_exhausted && std::isfinite(max_band_force) &&
962 std::isfinite(conv_tol) && conv_tol > 0.0 &&
963 max_band_force > conv_tol) {
964 return true;
965 }
966 // Classical OCI: burst when the force residual lives on the CI stencil.
967 const bool max_force_in_ci_stencil =
968 max_force_idx >= hook_ci_idx - 1 && max_force_idx <= hook_ci_idx + 1;
969 if (max_force_in_ci_stencil &&
970 (hook_ci_evaluated || current_true_ci_stencil)) {
971 return true;
972 }
973 if (!hook_ci_evaluated) return false;
974 // CI-quiet / band-loud (Henkelman CI-NEB + eOn OCINEB): a true saddle has
975 // vanishing projected force on the climbing image; residual force on other
976 // images is a spring/band defect. Refining the CI with the dimer targets
977 // the geometrically relevant image instead of a spring-dominated neighbor.
978 if (std::isfinite(ci_force) && std::isfinite(max_band_force) &&
979 std::isfinite(conv_tol) && conv_tol > 0.0 && ci_force < conv_tol &&
980 max_band_force > conv_tol) {
981 return true;
982 }
983 const bool relative_ci_residual =
984 std::isfinite(ci_force) && std::isfinite(max_band_force) &&
985 std::isfinite(conv_tol) && conv_tol > 0.0 &&
986 std::isfinite(inner_unc_relative) && inner_unc_relative > 0.0 &&
987 ci_force > conv_tol && max_band_force > conv_tol &&
988 ci_force <= inner_unc_relative * max_band_force;
989 if (relative_ci_residual) {
990 return true;
991 }
992 // OIE-quiet CI residual while whole-band max force is off-CI: open the
993 // controller so its adaptive threshold, quiet-stall state, and reject
994 // backoff can arbitrate MMF handoff.
995 if (std::isfinite(ci_force) && std::isfinite(conv_tol) && conv_tol > 0.0 &&
996 ci_force > conv_tol &&
997 isOieAcquisitionQuietForMmf(max_chain_energy_variance,
998 posterior_variance_threshold)) {
999 return true;
1000 }
1001 return false;
1002}
1003
1004bool shouldPrioritizeCurrentCiOracleForOciMmfHandoff(
1005 bool controller_requests_handoff, bool ci_active, int ci_idx, int n_images,
1006 double ci_force, double conv_tol, double max_chain_energy_variance,
1007 double posterior_variance_threshold)
1008{
1009 if (!controller_requests_handoff) return false;
1010 if (!ci_active) return false;
1011 if (ci_idx <= 0 || ci_idx >= n_images - 1) return false;
1012 if (!(std::isfinite(conv_tol) && conv_tol > 0.0 &&
1013 std::isfinite(ci_force) && ci_force > conv_tol)) {
1014 return false;
1015 }
1016 (void)max_chain_energy_variance;
1017 (void)posterior_variance_threshold;
1018 return true;
1019}
1020
1021ObservationVariance jointObservationVariance(const gpr::Observation& variance,
1022 Eigen::Index row)
1023{
1024 ObservationVariance result;
1025 if (row < 0) return result;
1026 // E is one row of per-image energies; G is one row per image.
1027 if (variance.E.rows() > 0 && row < variance.E.cols()) {
1028 result.energy = sanitizePosteriorVariance(variance.E(0, row));
1029 if (std::isnan(result.energy)) result.energy = 0.0;
1030 }
1031 if (row < variance.G.rows() && variance.G.cols() > 0) {
1032 result.gradient.resize(variance.G.cols());
1033 for (Eigen::Index j = 0; j < variance.G.cols(); ++j) {
1034 result.gradient(j) = sanitizePosteriorVariance(variance.G(row, j));
1035 if (std::isnan(result.gradient(j))) result.gradient(j) = 0.0;
1036 }
1037 }
1038 return result;
1039}
1040
1041std::vector<ObservationVariance> evaluateOieGlobalVariances(
1042 const std::vector<char>& prediction_required,
1043 const std::vector<char>& force_certification_required,
1044 const std::function<void(const std::vector<char>&,
1045 std::vector<ObservationVariance>&)>& evaluate)
1046{
1047 if (prediction_required.size() != force_certification_required.size())
1048 throw std::invalid_argument(
1049 "global variance query masks differ in size");
1050 std::vector<char> required = prediction_required;
1051 for (std::size_t i = 0; i < required.size(); ++i)
1052 required[i] = required[i] || force_certification_required[i];
1053 std::vector<ObservationVariance> result;
1054 evaluate(required, result);
1055 return result;
1056}
1057
1058ObservationVariance jointForceCertificationVariance(
1059 const ObservationVariance& reported_variance,
1060 double reported_variance_calibration)
1061{
1062 ObservationVariance result = reported_variance;
1063 if (reported_variance_calibration > 1.0 &&
1064 std::isfinite(reported_variance_calibration)) {
1065 result.gradient /= reported_variance_calibration;
1066 }
1067 return result;
1068}
1069
1070double observationGradientVarianceTrace(const ObservationVariance& variance)
1071{
1072 const double trace = variance.gradient.sum();
1073 return sanitizePosteriorVariance(trace);
1074}
1075
1076double measuredVarianceCalibration(double force_error,
1077 double reported_force_variance,
1078 Eigen::Index dof, double noise_variance)
1079{
1080 // The maximum-likelihood scale of a Gaussian whose one observed
1081 // standardized residual is z: z^2, so the reported variance times the
1082 // factor reproduces the measured squared error. The likelihood noise
1083 // enters the reported variance once per coordinate because the
1084 // measurement carries it too. Floored at one: an error inside the
1085 // reported spread leaves the surrogate's own variance in force.
1086 if (!std::isfinite(force_error) || !std::isfinite(reported_force_variance))
1087 return 1.0;
1088 const double noise = std::isfinite(noise_variance) && noise_variance > 0.0
1089 ? noise_variance
1090 : 0.0;
1091 const double reported =
1092 reported_force_variance +
1093 static_cast<double>(std::max<Eigen::Index>(dof, 0)) * noise;
1094 if (!(reported > 0.0)) return 1.0;
1095 return std::max(1.0, force_error * force_error / reported);
1096}
1097
1098double posteriorSquaredErrorBound(Eigen::Index dof)
1099{
1100 // Upper 95% point of a chi-square variable over its degrees of freedom,
1101 // by the Wilson-Hilferty cube: with a calibrated posterior the squared
1102 // error over the variance trace has mean one and a spread of
1103 // sqrt(2 / dof), so the bound falls toward one as the molecule grows.
1104 constexpr double kNormalUpper95 = 1.6448536269514722;
1105 const double nu = static_cast<double>(std::max<Eigen::Index>(dof, 1));
1106 const double spread = 2.0 / (9.0 * nu);
1107 const double root = 1.0 - spread + kNormalUpper95 * std::sqrt(spread);
1108 return root * root * root;
1109}
1110
1111bool driftAdvanceOutsidePosterior(double force_error,
1112 double reported_force_variance,
1113 Eigen::Index dof, double noise_variance)
1114{
1115 if (!std::isfinite(force_error) || !(force_error > 0.0)) return false;
1116 if (measuredVarianceCalibration(force_error, reported_force_variance, dof,
1117 noise_variance) >
1118 posteriorSquaredErrorBound(dof)) {
1119 return true;
1120 }
1121 if (!std::isfinite(reported_force_variance)) return false;
1122 const double noise = std::isfinite(noise_variance) && noise_variance > 0.0
1123 ? noise_variance
1124 : 0.0;
1125 const double reported =
1126 reported_force_variance +
1127 static_cast<double>(std::max<Eigen::Index>(dof, 0)) * noise;
1128 return !(reported > 0.0);
1129}
1130
1131bool keptDriftOutsidePosterior(bool kept_advance, bool measured_on_band,
1132 double force_error,
1133 double reported_force_variance, Eigen::Index dof,
1134 double noise_variance)
1135{
1136 return kept_advance && measured_on_band &&
1137 driftAdvanceOutsidePosterior(force_error, reported_force_variance,
1138 dof, noise_variance);
1139}
1140
1141double gradientFidelityTrustRadius(const GPNEBConfig& config, double radius,
1142 double fidelity)
1143{
1144 if (!std::isfinite(fidelity)) return radius;
1145 const double cap = std::max(
1146 config.trust_adaptive_floor,
1147 config.trust_adaptive_A /
1148 std::sqrt(std::max(1.0, static_cast<double>(config.n_atoms))));
1149 ScaleFreeTrustConfig measured;
1150 measured.tau = 1.0;
1151 measured.shrink_factor = 0.25;
1152 measured.radius_ceiling = cap;
1153 ScaleFreeTrustRegion trust(measured);
1154 trust.initFromTrainingSpread(radius);
1155 return trust.updateRadiusFromRhoValue(1.0 - fidelity);
1156}
1157
1158bool allInteriorImagesObserved(const NEBPath& path, const gpr::Observation& obs,
1159 int climbing_image)
1160{
1161 if (path.numImages() <= 2 || climbing_image == 0 ||
1162 climbing_image >= path.numImages() - 1) {
1163 return false;
1164 }
1165 const int begin = climbing_image > 0 ? std::max(1, climbing_image - 1) : 1;
1166 const int end = climbing_image > 0
1167 ? std::min(path.numImages() - 1, climbing_image + 2)
1168 : path.numImages() - 1;
1169 for (int i = begin; i < end; ++i) {
1170 if (!hasPosition(obs, path.image(i).positions)) return false;
1171 }
1172 return true;
1173}
1174
1175bool ciActivationForceGateReady(const GPNEBConfig& config, bool ci_active,
1176 int outer, double band_force, double f0);
1177
1178bool shouldActivateClimbingImage(const GPNEBConfig& config, bool ci_active,
1179 int outer, double band_force, double f0,
1180 double ci_candidate_variance)
1181{
1182 // Adaptive activation uses the current mixed exact/GP whole-band force.
1183 // The threshold is the eOn-style maximum of the absolute and relative
1184 // gates. Candidate variance can request an oracle through
1185 // shouldEvaluateClimbingImageCandidate; it does not block a
1186 // force-certified activation.
1187 (void)ci_candidate_variance;
1188 return ciActivationForceGateReady(config, ci_active, outer, band_force, f0);
1189}
1190
1191bool ciActivationForceGateReady(const GPNEBConfig& config, bool ci_active,
1192 int outer, double band_force, double f0)
1193{
1194 (void)outer;
1195 if (!config.climbing_image || ci_active || band_force <= 0.0 ||
1196 !std::isfinite(band_force)) {
1197 return false;
1198 }
1199 // eOn gate: max of the absolute tolerance and the relative fraction of
1200 // the initial force baseline. The absolute arm stands alone so an
1201 // unset baseline (no oracle rows yet, or a baseline refresh race)
1202 // cannot indefinitely refuse activation of a relaxed band.
1203 double threshold = 0.0;
1204 if (config.ci_activation_tol > 0.0 &&
1205 std::isfinite(config.ci_activation_tol)) {
1206 threshold = std::max(threshold, config.ci_activation_tol);
1207 }
1208 if (config.ci_activation_factor > 0.0 &&
1209 std::isfinite(config.ci_activation_factor) && f0 > 0.0 &&
1210 std::isfinite(f0)) {
1211 threshold = std::max(threshold, config.ci_activation_factor * f0);
1212 }
1213 return threshold > 0.0 && band_force < threshold;
1214}
1215
1216bool shouldEvaluateClimbingImageCandidate(const GPNEBConfig& config,
1217 bool ci_active, int outer,
1218 double band_force, double f0,
1219 double ci_candidate_variance,
1220 std::optional<double> signal_variance)
1221{
1222 const double threshold =
1223 effectivePosteriorVarianceThreshold(config, signal_variance);
1224 return ciActivationForceGateReady(config, ci_active, outer, band_force,
1225 f0) &&
1226 posteriorVarianceExceedsTolerance(ci_candidate_variance, threshold);
1227}
1228
1229bool shouldSampleCurrentChainForCiActivation(const GPNEBConfig& config,
1230 bool ci_active, int outer,
1231 double band_force, double f0)
1232{
1233 (void)outer;
1234 if (!config.climbing_image || ci_active) {
1235 return false;
1236 }
1237 if (f0 <= 0.0 || !std::isfinite(f0)) return true;
1238 if (band_force <= 0.0 || !std::isfinite(band_force)) return true;
1239 return false;
1240}
1241
1242int selectCurrentChainPriorityForOieOracle(
1243 bool ci_active, int ci_idx, bool ci_activation_needs_oracle,
1244 int ci_candidate_idx, double ci_certificate_deficit,
1245 double chain_certificate_deficit, bool saddle_handoff_needs_ci_oracle,
1246 bool ci_candidate_handover_needs_oracle, bool ci_convergence_needs_oracle,
1247 int chain_certificate_idx, bool accepted_drift_pending)
1248{
1249 if (ci_activation_needs_oracle) return ci_candidate_idx;
1250 // Serve the binding oracle certificate. Ordinary OIE progress uses the
1251 // predicted saddle's uncertainty deficit; saddle handoff uses the local
1252 // CI-neighborhood certificate because the dimer consumes the local true
1253 // force stencil.
1254 if (!ci_active) return -1;
1255 // A posterior-confident peak at another image invalidates forces computed
1256 // with the installed climbing marker. Confirm that peak on the true PES
1257 // before ranking force or uncertainty deficits on the current topology.
1258 if (ci_candidate_handover_needs_oracle) return ci_candidate_idx;
1259 // A posterior-confident CI inside the live convergence tolerance needs an
1260 // exact force certificate before replaceable acquisition can continue.
1261 if (ci_convergence_needs_oracle) return ci_idx;
1262 const bool ci_unmet =
1263 std::isfinite(ci_certificate_deficit) && ci_certificate_deficit > 1.0;
1264 if (!std::isfinite(chain_certificate_deficit)) {
1265 chain_certificate_deficit = 0.0;
1266 }
1267 const bool chain_unmet = chain_certificate_deficit > 1.0;
1268 // The saddle handoff feeds the climbing image itself (the marker) to the
1269 // dimer, so it oracles the marker only when the local saddle certificate
1270 // is at least as binding as the chain certificate.
1271 if (saddle_handoff_needs_ci_oracle) {
1272 if (!chain_unmet ||
1273 (std::isfinite(ci_certificate_deficit) &&
1274 ci_certificate_deficit >= chain_certificate_deficit)) {
1275 return ci_idx;
1276 }
1277 return chain_certificate_idx;
1278 }
1279 // Other CI-progress branches oracle the GP-predicted saddle image because
1280 // confirming that prediction on the true PES advances the climbing image
1281 // toward the saddle.
1282 if (ci_unmet &&
1283 (!chain_unmet || ci_certificate_deficit >= chain_certificate_deficit)) {
1284 return ci_candidate_idx;
1285 }
1286 if (chain_unmet) return chain_certificate_idx;
1287 // Accepted path motion carries current-geometry evidence. Once both
1288 // uncertainty certificates are met, measure that frontier before replaying
1289 // the already-certified saddle candidate.
1290 if (accepted_drift_pending) return -1;
1291 // Confirmation: when both uncertainty certificates are met, still oracle
1292 // the climbing-image candidate so the true-PES saddle is bound before
1293 // posterior exploration may move the acquisition elsewhere.
1294 if (!ci_unmet && !chain_unmet) return ci_candidate_idx;
1295 return -1;
1296}
1297
1298double oieSaddleCertificateDeficit(
1299 int saddle_candidate_idx, const NEBPath& path,
1300 const std::vector<double>& posterior_energy_variance, double conv_tol,
1301 double variance_threshold)
1302{
1303 (void)conv_tol;
1304 if (saddle_candidate_idx <= 0 ||
1305 saddle_candidate_idx >= path.numImages() - 1) {
1306 return 0.0;
1307 }
1308
1309 double deficit = 0.0;
1310 if (variance_threshold > 0.0 && std::isfinite(variance_threshold) &&
1311 saddle_candidate_idx <
1312 static_cast<int>(posterior_energy_variance.size())) {
1313 const double variance = posterior_energy_variance[saddle_candidate_idx];
1314 if (variance >= 0.0 && std::isfinite(variance)) {
1315 deficit = std::max(deficit, variance / variance_threshold);
1316 }
1317 }
1318 return deficit;
1319}
1320
1321double oieSaddleForceConfirmationDeficit(int saddle_candidate_idx,
1322 const NEBPath& path, double conv_tol)
1323{
1324 if (saddle_candidate_idx <= 0 ||
1325 saddle_candidate_idx >= path.numImages() - 1 || !(conv_tol > 0.0) ||
1326 !std::isfinite(conv_tol)) {
1327 return 0.0;
1328 }
1329 const double force = path.nebForceMagnitude(saddle_candidate_idx);
1330 if (!(force >= 0.0) || !std::isfinite(force)) return 0.0;
1331 return force / conv_tol;
1332}
1333
1334bool shouldRequestOieSaddleForceConfirmation(
1335 const double predicted_force, const double convergence_force_tolerance)
1336{
1337 return predicted_force >= 0.0 && std::isfinite(predicted_force) &&
1338 convergence_force_tolerance > 0.0 &&
1339 std::isfinite(convergence_force_tolerance) &&
1340 predicted_force <= convergence_force_tolerance;
1341}
1342
1359double oieSaddleForceLowerConfidenceBound(double predicted_force,
1360 double gradient_variance_trace,
1361 double kappa)
1362{
1363 if (!std::isfinite(predicted_force) || predicted_force < 0.0) {
1364 return predicted_force;
1365 }
1366 if (!(kappa > 0.0) || !std::isfinite(kappa) ||
1367 !(gradient_variance_trace > 0.0) ||
1368 !std::isfinite(gradient_variance_trace)) {
1369 return predicted_force;
1370 }
1371 // The trace sums the per-degree-of-freedom gradient variances, so
1372 // its square root is the scale of the force uncertainty vector and
1373 // is commensurable with a force norm.
1374 return std::max(
1375 0.0, predicted_force - kappa * std::sqrt(gradient_variance_trace));
1376}
1377
1378double oieSaddleNeighborhoodCertificateDeficit(
1379 int saddle_center_idx, const NEBPath& path,
1380 const std::vector<double>& posterior_energy_variance, double conv_tol,
1381 double variance_threshold)
1382{
1383 return selectCurrentOieChainCertificateTarget(
1384 /*saddle_handoff_needs_ci_oracle=*/true, saddle_center_idx,
1385 /*climbing_image_converged_only=*/true, path,
1386 posterior_energy_variance, conv_tol, variance_threshold)
1387 .deficit;
1388}
1389
1390OieChainCertificateTarget selectCurrentOieChainCertificateTarget(
1391 bool saddle_handoff_needs_ci_oracle, int ci_idx,
1392 bool climbing_image_converged_only, const NEBPath& path,
1393 const std::vector<double>& posterior_energy_variance,
1394 double force_tolerance, double variance_threshold,
1395 int adjacent_recovery_target_idx, double adjacent_recovery_deficit)
1396{
1397 OieChainCertificateTarget target;
1398 auto consider = [&](double deficit, int image_index) {
1399 if (image_index <= 0 || image_index >= path.numImages() - 1 ||
1400 !(deficit >= 0.0) || !std::isfinite(deficit)) {
1401 return;
1402 }
1403 if (deficit > target.deficit) {
1404 target.deficit = deficit;
1405 target.image_index = image_index;
1406 }
1407 };
1408 auto considerForceResidual = [&](double force, int image_index) {
1409 if (!(force_tolerance > 0.0) || !std::isfinite(force_tolerance)) {
1410 return;
1411 }
1412 if (force >= 0.0 && std::isfinite(force)) {
1413 consider(force / force_tolerance, image_index);
1414 }
1415 };
1416 auto considerForce = [&](int image_index) {
1417 considerForceResidual(path.nebForceMagnitude(image_index), image_index);
1418 };
1419 auto considerCiOnlyForce = [&](int image_index) {
1420 double force = std::numeric_limits<double>::quiet_NaN();
1421 if (image_index == ci_idx) {
1422 const Eigen::VectorXd& ci_force = path.nebForce(image_index);
1423 if (ci_force.size() > 0) {
1424 force = path.saddleForce(image_index);
1425 }
1426 } else {
1427 force = ciPerpendicularForceResidual(path, image_index);
1428 }
1429 considerForceResidual(force, image_index);
1430 };
1431 auto considerVariance = [&](int image_index) {
1432 if (!(variance_threshold > 0.0) || !std::isfinite(variance_threshold) ||
1433 image_index < 0 ||
1434 image_index >= static_cast<int>(posterior_energy_variance.size())) {
1435 return;
1436 }
1437 const double variance = posterior_energy_variance[image_index];
1438 if (variance >= 0.0 && std::isfinite(variance)) {
1439 consider(variance / variance_threshold, image_index);
1440 }
1441 };
1442
1443 if (saddle_handoff_needs_ci_oracle) {
1444 if (ci_idx <= 0 || ci_idx >= path.numImages() - 1) return target;
1445 const int lo = std::max(1, ci_idx - 1);
1446 const int hi = std::min(path.numImages() - 2, ci_idx + 1);
1447 for (int i = lo; i <= hi; ++i) {
1448 if (climbing_image_converged_only) {
1449 considerCiOnlyForce(i);
1450 } else {
1451 considerForce(i);
1452 }
1453 considerVariance(i);
1454 }
1455 if (climbing_image_converged_only) return target;
1456 }
1457
1458 for (int i = 1; i < path.numImages() - 1; ++i) {
1459 if (!climbing_image_converged_only && i != ci_idx) {
1460 considerForce(i);
1461 }
1462 considerVariance(i);
1463 }
1464 consider(adjacent_recovery_deficit, adjacent_recovery_target_idx);
1465 return target;
1466}
1467
1468bool shouldExpandOciHandoffStencil(bool ci_active,
1469 bool saddle_handoff_needs_ci_oracle,
1470 double local_certificate_deficit)
1471{
1472 return ci_active && saddle_handoff_needs_ci_oracle &&
1473 std::isfinite(local_certificate_deficit) &&
1474 local_certificate_deficit > 1.0;
1475}
1476
1477namespace {
1478
1479template <typename HasCurrentData>
1480std::vector<int> selectOciHandoffStencilTargets(
1481 int ci_idx, int n_images, HasCurrentData&& has_current_data)
1482{
1483 std::vector<int> targets;
1484 if (ci_idx <= 0 || ci_idx >= n_images - 1) return targets;
1485 auto add_if_missing = [&](int idx) {
1486 if (idx <= 0 || idx >= n_images - 1) return;
1487 if (has_current_data(idx)) return;
1488 targets.push_back(idx);
1489 };
1490 add_if_missing(ci_idx);
1491 add_if_missing(ci_idx - 1);
1492 add_if_missing(ci_idx + 1);
1493 return targets;
1494}
1495
1496} // namespace
1497
1498std::vector<int> selectOciHandoffStencilOracleTargets(
1499 int ci_idx, int n_images, const std::vector<char>& image_evaluated,
1500 const std::vector<char>& image_observed_current)
1501{
1502 auto has_true_current_data = [&](int idx) {
1503 const bool evaluated = idx >= 0 &&
1504 idx < static_cast<int>(image_evaluated.size()) &&
1505 image_evaluated[idx] != 0;
1506 const bool observed =
1507 idx >= 0 && idx < static_cast<int>(image_observed_current.size()) &&
1508 image_observed_current[idx] != 0;
1509 return evaluated || observed;
1510 };
1511 return selectOciHandoffStencilTargets(ci_idx, n_images,
1512 has_true_current_data);
1513}
1514
1515std::vector<int> selectOciHandoffCertificateOracleTargets(
1516 int ci_idx, const NEBPath& path, const ActiveLearningSession& session)
1517{
1518 return selectOciHandoffStencilTargets(
1519 ci_idx, path.numImages(), [&](int image_idx) {
1520 return session.hasCurrentChainCertificate(
1521 image_idx, path.image(image_idx).positions);
1522 });
1523}
1524
1525std::vector<int> selectOieActivationTripletOracleTargets(
1526 int ci_candidate_idx, int n_images,
1527 const std::vector<char>& image_evaluated,
1528 const std::vector<char>& image_observed_current,
1529 const std::vector<double>& posterior_energy_variance)
1530{
1531 std::vector<int> targets;
1532 const int triplet_center_idx = ci_candidate_idx;
1533 if (triplet_center_idx <= 1 || triplet_center_idx >= n_images - 2) {
1534 return targets;
1535 }
1536 auto has_true_current_data = [&](int idx) {
1537 const bool evaluated = idx >= 0 &&
1538 idx < static_cast<int>(image_evaluated.size()) &&
1539 image_evaluated[idx] != 0;
1540 const bool observed =
1541 idx >= 0 && idx < static_cast<int>(image_observed_current.size()) &&
1542 image_observed_current[idx] != 0;
1543 return evaluated || observed;
1544 };
1545 if (!has_true_current_data(triplet_center_idx)) {
1546 targets.push_back(triplet_center_idx);
1547 return targets;
1548 }
1549
1550 const int neighbor_indices[2] = {triplet_center_idx - 1,
1551 triplet_center_idx + 1};
1552 std::vector<std::pair<int, double>> missing_neighbors;
1553 for (const int idx: neighbor_indices) {
1554 if (idx <= 0 || idx >= n_images - 1) continue;
1555 if (has_true_current_data(idx)) continue;
1556 const double variance =
1557 idx < static_cast<int>(posterior_energy_variance.size())
1558 ? posterior_energy_variance[idx]
1559 : -std::numeric_limits<double>::infinity();
1560 missing_neighbors.push_back({idx, variance});
1561 }
1562 std::sort(missing_neighbors.begin(), missing_neighbors.end(),
1563 [](const auto& lhs, const auto& rhs) {
1564 const bool lhs_finite = std::isfinite(lhs.second);
1565 const bool rhs_finite = std::isfinite(rhs.second);
1566 if (lhs_finite != rhs_finite) return lhs_finite;
1567 if (lhs.second != rhs.second) return lhs.second > rhs.second;
1568 return lhs.first < rhs.first;
1569 });
1570 if (!missing_neighbors.empty()) {
1571 targets.push_back(missing_neighbors.front().first);
1572 }
1573 return targets;
1574}
1575
1576bool shouldRetainOieRestartSnapshot(bool ci_active, const char* inner_exit,
1577 int accepted_inner_steps,
1578 double relaxed_gp_force,
1579 bool measured_reparam_restart_protected)
1580{
1581 if (measured_reparam_restart_protected) return false;
1582 if (inner_exit == nullptr) return false;
1583 if (std::strcmp(inner_exit, "converged") == 0) return true;
1584 if (!ci_active) return false;
1585 if (accepted_inner_steps <= 0) return false;
1586 if (!std::isfinite(relaxed_gp_force)) return false;
1587 return std::strcmp(inner_exit, "trust_cert") == 0 ||
1588 std::strcmp(inner_exit, "drift") == 0 ||
1589 std::strcmp(inner_exit, "itercap") == 0 ||
1590 std::strcmp(inner_exit, "cycle") == 0 ||
1591 std::strcmp(inner_exit, "ei") == 0;
1592}
1593
1594bool shouldProtectMeasuredProposalRestart(bool candidate_applied,
1595 bool improved_before_refit,
1596 bool improved_after_refit) noexcept
1597{
1598 return candidate_applied && (improved_before_refit || improved_after_refit);
1599}
1600
1601bool shouldScheduleOiePathMotionReparam(const GPNEBConfig& config,
1602 bool path_moved)
1603{
1604 return config.oie_hook_reparam && path_moved;
1605}
1606
1607bool shouldScheduleOieHookReparam(const GPNEBConfig& config,
1608 bool hook_moved_chain)
1609{
1610 return shouldScheduleOiePathMotionReparam(config, hook_moved_chain);
1611}
1612
1613bool shouldQueueOieHookReparamCandidate(
1614 bool proposal_moves_band, bool all_candidate_images_observed) noexcept
1615{
1616 return proposal_moves_band && all_candidate_images_observed;
1617}
1618
1619bool gpInnerIterationAllowed(int inner_iteration, int configured_limit)
1620{
1621 return gpr::iterationAllowedByLimit(inner_iteration, configured_limit);
1622}
1623
1624bool oieAttemptWallBudgetExhausted(double elapsed_seconds,
1625 double longest_outer_seconds,
1626 double budget_seconds) noexcept
1627{
1628 if (!(budget_seconds > 0.0) || !std::isfinite(budget_seconds)) return false;
1629 if (!std::isfinite(elapsed_seconds)) return true;
1630 if (!std::isfinite(longest_outer_seconds)) return true;
1631 return std::max(0.0, elapsed_seconds) +
1632 std::max(0.0, longest_outer_seconds) >=
1633 budget_seconds;
1634}
1635
1636bool shouldStopOieInnerAtCoordinateResolution(
1637 const Eigen::VectorXd& accepted_positions,
1638 const Eigen::VectorXd& proposed_positions) noexcept
1639{
1640 return positionsCoincide(accepted_positions, proposed_positions);
1641}
1642
1643bool shouldBypassOieInnerForHandoff(const OieInnerHandoffPrecheck& state,
1644 int accepted_inner_steps)
1645{
1646 if (accepted_inner_steps != 0) return false;
1647 if (!state.handoff_data_ready) return false;
1648 if (!state.current_chain_certificate) return false;
1649 if (state.rejected_seed_replay) return false;
1650 if (!state.planned_current_chain_or_ci) return false;
1651 if (std::isfinite(state.ci_force) &&
1652 std::isfinite(state.handoff_force_threshold) &&
1653 state.handoff_force_threshold > 0.0 &&
1654 state.ci_force > state.handoff_force_threshold) {
1655 return false;
1656 }
1657 if (state.current_saddle_stencil_certificate) return true;
1658 return state.soft_quiet_blocked_after_reject ||
1659 state.trusted_recovery_active ||
1660 state.trusted_retry_progress_pending ||
1661 state.oie_quiet_handoff_stalled;
1662}
1663
1664OieLowerBarrierAction selectOieLowerBarrierAction(
1665 bool have_best_climb_positions, int best_climb_ci_idx,
1666 double best_climb_barrier, double best_climb_force, double current_barrier,
1667 const OieLowerBarrierEvidence& current_evidence, double posterior_spread)
1668{
1669 const auto keep_current = OieLowerBarrierAction::KeepCurrent;
1670 if (!have_best_climb_positions || best_climb_ci_idx <= 0) {
1671 return keep_current;
1672 }
1673 if (!std::isfinite(best_climb_barrier) || !std::isfinite(current_barrier)) {
1674 return keep_current;
1675 }
1676 if (std::isfinite(posterior_spread) && posterior_spread >= 0.0 &&
1677 current_barrier - best_climb_barrier >
1678 std::sqrt(2.0) * posterior_spread) {
1679 return OieLowerBarrierAction::RestoreCertifiedBest;
1680 }
1681 if (!(best_climb_barrier > current_barrier)) {
1682 return keep_current;
1683 }
1684 if (!(std::isfinite(best_climb_force) && best_climb_force > 0.0)) {
1685 return keep_current;
1686 }
1687 if (current_evidence.independentlyCertified()) return keep_current;
1688 if (current_evidence.true_pes_local_max &&
1689 !current_evidence.adjacent_mep_checked) {
1690 return OieLowerBarrierAction::CompleteCurrentCertificate;
1691 }
1692 return OieLowerBarrierAction::RestoreCertifiedBest;
1693}
1694
1695bool shouldAcceptOieCiOnlyConvergence(bool pending_band_action_active,
1696 bool ci_active,
1697 bool climbing_image_converged_only,
1698 bool ci_force_is_measured,
1699 bool saddle_energy_ok,
1700 bool below_path_ceiling, double ci_force,
1701 double model_noise_tol)
1702{
1703 if (pending_band_action_active) return false;
1704 if (!ci_active || !climbing_image_converged_only) return false;
1705 if (!ci_force_is_measured) return false;
1706 if (!saddle_energy_ok || !below_path_ceiling) return false;
1707 if (!std::isfinite(ci_force) || !std::isfinite(model_noise_tol) ||
1708 !(model_noise_tol > 0.0) || !(ci_force < model_noise_tol)) {
1709 return false;
1710 }
1711 return true;
1712}
1713
1714double oieContinuationMerit(bool ci_active, bool climbing_image_converged_only,
1715 const NEBPath& path)
1716{
1717 const double missing = std::numeric_limits<double>::quiet_NaN();
1718 if (!ci_active || !climbing_image_converged_only) return missing;
1719 const int index = selectOieClimbingImageIndex(ci_active, path);
1720 if (index <= 0 || index >= path.numImages() - 1) return missing;
1721 const auto& image = path.image(index);
1722 if (!image.evaluated || image.gradient.size() == 0 ||
1723 image.gradient.size() != image.positions.size() ||
1724 !image.gradient.allFinite())
1725 return missing;
1726 return path.saddleForce(index);
1727}
1728
1729double oieContinuationReward(double best_merit_at_pull,
1730 double merit_now) noexcept
1731{
1732 if (!(std::isfinite(best_merit_at_pull) && best_merit_at_pull > 0.0) ||
1733 !(std::isfinite(merit_now) && merit_now >= 0.0))
1734 return std::numeric_limits<double>::quiet_NaN();
1735 return std::max(best_merit_at_pull - merit_now, 0.0) / best_merit_at_pull;
1736}
1737
1738double sampleOieContinuationReward(const OieContinuationArm& arm,
1739 std::mt19937_64& rng)
1740{
1741 // Fractional evidence for a bounded reward, with a uniform Beta prior.
1742 // Every finite history retains positive density throughout (0, 1).
1743 std::gamma_distribution<double> success(1.0 + arm.reward_sum, 1.0);
1744 std::gamma_distribution<double> failure(
1745 1.0 + static_cast<double>(arm.pulls) - arm.reward_sum, 1.0);
1746 const double x = success(rng);
1747 const double y = failure(rng);
1748 return x / (x + y);
1749}
1750
1751bool OieContinuationRewards::begin(bool restore, double measured_merit) noexcept
1752{
1753 if (pending()) return false;
1754 selected_ = restore ? 1 : 0;
1755 reference_ = std::isfinite(best_) ? best_ : measured_merit;
1756 return true;
1757}
1758
1759void OieContinuationRewards::observe(double measured_merit) noexcept
1760{
1761 if (!(std::isfinite(measured_merit) && measured_merit >= 0.0)) return;
1762 if (measured_merit > 0.0) best_ = std::min(best_, measured_merit);
1763 if (!pending()) return;
1764 const double reward = oieContinuationReward(reference_, measured_merit);
1765 if (std::isfinite(reward)) {
1766 auto& selected = selected_ == 1 ? restore_ : continue_;
1767 ++selected.pulls;
1768 selected.reward_sum += reward;
1769 selected.reward_sum_sq += reward * reward;
1770 }
1771 selected_ = -1;
1772 reference_ = std::numeric_limits<double>::quiet_NaN();
1773}
1774
1775const char* oieLowerBarrierActionName(OieLowerBarrierAction action) noexcept
1776{
1777 switch (action) {
1778 case OieLowerBarrierAction::KeepCurrent:
1779 return "keep_current";
1780 case OieLowerBarrierAction::CompleteCurrentCertificate:
1781 return "complete_certificate";
1782 case OieLowerBarrierAction::RestoreCertifiedBest:
1783 return "restore_best";
1784 }
1785 return "unknown";
1786}
1787
1788bool shouldUseOieBestClimbRestart(
1789 bool ci_active, bool have_best_climb_positions, double best_climb_force,
1790 double latest_restart_force, int best_climb_ci_idx,
1791 double best_climb_barrier, int latest_climb_ci_idx,
1792 double latest_climb_barrier)
1793{
1794 if (!(ci_active && have_best_climb_positions &&
1795 std::isfinite(best_climb_force) && best_climb_force > 0.0)) {
1796 return false;
1797 }
1798 // Energy-certified indices (ci_idx > 0) come from
1799 // hasTruePesSaddleEnergyCertificate at snapshot time. An uncertified
1800 // latest path must not displace a certified best climb: Baker 01 lost a
1801 // ~2.17 eV certified pass to a lower-force uncertified shoulder that
1802 // later force-quieted at 0.53 eV.
1803 const bool best_certified = best_climb_ci_idx > 0;
1804 const bool latest_certified = latest_climb_ci_idx > 0;
1805 if (best_certified && !latest_certified) {
1806 return true;
1807 }
1808 if (std::isfinite(latest_restart_force) && latest_restart_force > 0.0 &&
1809 latest_restart_force < best_climb_force) {
1810 return false;
1811 }
1812 const bool latest_is_lower_barrier_branch =
1813 latest_certified && best_certified &&
1814 latest_climb_ci_idx != best_climb_ci_idx &&
1815 std::isfinite(latest_climb_barrier) &&
1816 std::isfinite(best_climb_barrier) &&
1817 latest_climb_barrier < best_climb_barrier;
1818 if (latest_is_lower_barrier_branch) {
1819 return false;
1820 }
1821 return true;
1822}
1823
1824bool shouldPreferLatestOieClimbRestart(bool ci_active,
1825 bool have_latest_climb_positions,
1826 bool latest_climb_from_drift)
1827{
1828 return ci_active && have_latest_climb_positions && latest_climb_from_drift;
1829}
1830
1831OieRelaxationRestartSource selectOieRelaxationRestartSource(
1832 bool frozen_sweep, bool use_best_climb, bool use_best_path,
1833 bool use_latest_climb, bool use_latest_equal)
1834{
1835 if (frozen_sweep) return OieRelaxationRestartSource::CurrentPath;
1836 if (use_best_climb) return OieRelaxationRestartSource::BestClimb;
1837 if (use_best_path) return OieRelaxationRestartSource::BestPath;
1838 if (use_latest_climb) return OieRelaxationRestartSource::LatestClimb;
1839 if (use_latest_equal) return OieRelaxationRestartSource::LatestEqual;
1840 return OieRelaxationRestartSource::CurrentPath;
1841}
1842
1843double oieRestartReferenceForce(bool ci_active, bool have_best_climb_positions,
1844 double best_path_force, double best_climb_force)
1845{
1846 if (ci_active && have_best_climb_positions && best_climb_force > 0.0 &&
1847 std::isfinite(best_climb_force)) {
1848 return best_climb_force;
1849 }
1850 return best_path_force;
1851}
1852
1853bool shouldRetainOieHookRestartSnapshot(bool ci_active, bool hook_ran,
1854 bool hook_converged)
1855{
1856 return ci_active && hook_ran && !hook_converged;
1857}
1858
1859bool shouldPromoteOieHookRestartSnapshot(bool hook_ran, bool hook_converged,
1860 bool hook_left_chain_moved)
1861{
1862 return hook_ran && !hook_converged && hook_left_chain_moved;
1863}
1864
1865bool shouldRestoreRejectedOieHookConvergence(bool hook_converged,
1866 bool hook_certified)
1867{
1868 return hook_converged && !hook_certified;
1869}
1870
1871bool shouldRetainRejectedOieHookSaddleForRethread(bool hook_converged,
1872 bool hook_certified,
1873 bool saddle_energy_ok,
1874 bool adjacent_mep_ok)
1875{
1876 return hook_converged && !hook_certified && saddle_energy_ok &&
1877 !adjacent_mep_ok;
1878}
1879
1880bool shouldSkipOieInnerAfterRejectedHookConvergence(bool hook_converged,
1881 bool hook_certified)
1882{
1883 return hook_converged && !hook_certified;
1884}
1885
1886bool shouldSkipOieInnerAfterRejectedHookAttempt(bool hook_ran,
1887 bool hook_added_training,
1888 bool hook_converged,
1889 bool hook_certified,
1890 bool hook_moved_chain)
1891{
1892 if (!hook_ran || !hook_added_training) return false;
1893 if (hook_certified || hook_moved_chain) return false;
1894 return hook_converged ? !hook_certified : true;
1895}
1896
1897bool shouldRetainOieBestClimbSnapshot(bool ci_active, double candidate_force,
1898 double best_climb_force,
1899 bool true_saddle_energy_certificate,
1900 double /*candidate_barrier*/,
1901 double /*best_climb_barrier*/)
1902{
1903 return ci_active && true_saddle_energy_certificate &&
1904 std::isfinite(candidate_force) && candidate_force > 0.0 &&
1905 candidate_force < best_climb_force;
1906}
1907
1908bool isOieCurrentCiForceAnchor(bool ci_active, bool oracle_updates_current_path,
1909 int oracle_idx, int ci_idx, int max_force_idx)
1910{
1911 return ci_active && oracle_updates_current_path && oracle_idx == ci_idx &&
1912 max_force_idx == ci_idx;
1913}
1914
1915double oieClimbMeritForce(bool ci_active, bool oracle_updates_current_path,
1916 int oracle_idx, int ci_idx, double ci_force,
1917 double whole_band_force, int whole_band_force_idx,
1918 bool convergence_uses_ci_only)
1919{
1920 if (!(ci_active && oracle_updates_current_path && oracle_idx == ci_idx)) {
1921 return std::numeric_limits<double>::infinity();
1922 }
1923 if (convergence_uses_ci_only) {
1924 return (std::isfinite(ci_force) && ci_force > 0.0)
1925 ? ci_force
1926 : std::numeric_limits<double>::infinity();
1927 }
1928 if (whole_band_force_idx != ci_idx) {
1929 return std::numeric_limits<double>::infinity();
1930 }
1931 return (std::isfinite(whole_band_force) && whole_band_force > 0.0)
1932 ? whole_band_force
1933 : std::numeric_limits<double>::infinity();
1934}
1935
1936bool shouldUseCiOnlyClimbMerit(bool /*mmf_handoff_snapshot*/,
1937 bool convergence_uses_ci_only)
1938{
1939 return convergence_uses_ci_only;
1940}
1941
1942bool isTruePesSaddleEnergyCandidate(double saddle_energy,
1943 double reactant_energy,
1944 double product_energy)
1945{
1946 if (!std::isfinite(saddle_energy) || !std::isfinite(reactant_energy) ||
1947 !std::isfinite(product_energy)) {
1948 return false;
1949 }
1950 const double saddle_ulp_above =
1951 std::nextafter(saddle_energy, std::numeric_limits<double>::infinity());
1952 return saddle_ulp_above >= reactant_energy &&
1953 saddle_ulp_above >= product_energy;
1954}
1955
1956bool hasTruePesSaddleEnergyCertificate(const NEBPath& path, int saddle_index,
1957 double force_quiet_tol,
1958 bool force_quiet_adjacent)
1959{
1960 if (saddle_index <= 0 || saddle_index >= path.numImages() - 1) {
1961 return false;
1962 }
1963 const auto& saddle = path.image(saddle_index);
1964 if (!saddle.evaluated) return false;
1965 if (!isTruePesSaddleEnergyCandidate(
1966 saddle.energy, path.image(0).energy,
1967 path.image(path.numImages() - 1).energy)) {
1968 return false;
1969 }
1970 (void)force_quiet_adjacent;
1971 // Strict local maximum on the band: both adjacent images, when they
1972 // carry true energies, must sit strictly below the candidate. A flat
1973 // product-adjacent basin (Baker 03 H2CO dual-channel bar~0.02 with
1974 // model-noise floor accept; Baker 19 similar) otherwise certifies a
1975 // near-endpoint plateau as a "saddle" because ULP-above-endpoints is
1976 // nearly vacuous there.
1977 //
1978 // High-force neighbors still refute with energy: skipping them allowed
1979 // Baker 01 to drop from a ~2.17 eV pass to a force-quiet 0.53 eV
1980 // shoulder while the ridge neighbors remained high-energy / high-force
1981 // and were ignored. After an MMF move that lowers only the CI, the band
1982 // must re-relax (or reparam) until neighbors sit below the refined
1983 // saddle; that is the correct NEB ordering, not a certificate hole.
1984 // A dimer/MMF hook carries a second-order saddle certificate and can use
1985 // force-quiet adjacent refutations here; the separate adjacent
1986 // perpendicular-force certificate checks that the path runs through it.
1987 for (const int adj: {saddle_index - 1, saddle_index + 1}) {
1988 if (adj <= 0 || adj >= path.numImages() - 1) continue;
1989 const auto& neigh = path.image(adj);
1990 if (!neigh.evaluated || !std::isfinite(neigh.energy)) continue;
1991 if (!(neigh.energy < saddle.energy)) return false;
1992 }
1993 // A higher evaluated image refutes the candidate only while its true
1994 // force is at or below force_quiet_tol. Above that tolerance the
1995 // energy is an upper bound on the MEP nearby. The tolerance is
1996 // eV/Angstrom, compared with the maximum atomic force.
1997 for (int i = 1; i < path.numImages() - 1; ++i) {
1998 if (i == saddle_index) continue;
1999 const auto& image = path.image(i);
2000 if (!image.evaluated || !std::isfinite(image.energy)) continue;
2001 if (!(image.energy > saddle.energy)) continue;
2002 const double atomic_force = path.forceMagnitude(image.gradient);
2003 if (std::isfinite(force_quiet_tol) && force_quiet_tol >= 0.0 &&
2004 std::isfinite(atomic_force) && atomic_force <= force_quiet_tol) {
2005 return false;
2006 }
2007 }
2008 return true;
2009}
2010
2031double g_ci_reassign_confidence = 0.0;
2032double g_ci_energy_noise_variance = 0.0;
2033
2034void setClimbingImageReassignConfidence(double confidence,
2035 double energy_noise_sigma) noexcept
2036{
2037 g_ci_reassign_confidence = confidence > 0.0 ? confidence : 0.0;
2038 const double s = energy_noise_sigma > 0.0 ? energy_noise_sigma : 0.0;
2039 g_ci_energy_noise_variance = s * s;
2040}
2041
2051double climbingEnergyVariance(const Image& image) noexcept
2052{
2053 if (image.evaluated) return g_ci_energy_noise_variance;
2054 if (std::isfinite(image.posterior_variance) &&
2055 image.posterior_variance > 0.0) {
2056 return image.posterior_variance;
2057 }
2058 return 0.0;
2059}
2060
2061int activeClimbingMarkerIndex(const NEBPath& path)
2062{
2063 for (int i = 1; i < path.numImages() - 1; ++i) {
2064 if (path.image(i).is_climbing) return i;
2065 }
2066 return -1;
2067}
2068
2069int highestEvaluatedInteriorImageIndex(const NEBPath& path)
2070{
2071 int best = -1;
2072 double best_e = -std::numeric_limits<double>::infinity();
2073 for (int i = 1; i < path.numImages() - 1; ++i) {
2074 const auto& image = path.image(i);
2075 if (!image.evaluated || !std::isfinite(image.energy)) continue;
2076 if (best < 0 || image.energy > best_e) {
2077 best = i;
2078 best_e = image.energy;
2079 }
2080 }
2081 return best;
2082}
2083
2084bool anyEvaluatedInterior(const NEBPath& path)
2085{
2086 for (int i = 1; i < path.numImages() - 1; ++i) {
2087 if (path.image(i).evaluated) return true;
2088 }
2089 return false;
2090}
2091
2092bool hasUnevaluatedInterior(const NEBPath& path)
2093{
2094 for (int i = 1; i < path.numImages() - 1; ++i) {
2095 if (!path.image(i).evaluated) return true;
2096 }
2097 return false;
2098}
2099
2100void assignClimbingImageFromEvaluatedEnergies(NEBPath& path)
2101{
2102 for (int i = 0; i < path.numImages(); ++i) {
2103 path.image(i).is_climbing = false;
2104 }
2105 const int climb = highestEvaluatedInteriorImageIndex(path);
2106 if (climb > 0 && climb < path.numImages() - 1) {
2107 path.image(climb).is_climbing = true;
2108 }
2109}
2110
2111bool oieActivationCandidateTripletEvaluated(const NEBPath& path, int candidate)
2112{
2113 if (candidate <= 1 || candidate >= path.numImages() - 2) return false;
2114 return path.image(candidate - 1).evaluated &&
2115 path.image(candidate).evaluated &&
2116 path.image(candidate + 1).evaluated;
2117}
2118
2119struct OieClimbingArmEvidence {
2120 int index = -1;
2121 bool current_exact = false;
2122 double mean = std::numeric_limits<double>::quiet_NaN();
2123 double variance = std::numeric_limits<double>::infinity();
2124 double lower = -std::numeric_limits<double>::infinity();
2125 double upper = std::numeric_limits<double>::infinity();
2126
2127 [[nodiscard]] bool valid() const
2128 {
2129 return index > 0 && std::isfinite(mean);
2130 }
2131};
2132
2133double oieSelectorVariance(const Image& image,
2134 const std::vector<double>& posterior_variance,
2135 int index)
2136{
2137 if (image.evaluated) return 0.0;
2138 if (index >= 0 && index < static_cast<int>(posterior_variance.size())) {
2139 const double variance = posterior_variance[index];
2140 if (variance >= 0.0 && std::isfinite(variance)) return variance;
2141 }
2142 return std::numeric_limits<double>::infinity();
2143}
2144
2145OieClimbingArmEvidence oieClimbingArmEvidence(
2146 const NEBPath& path, const std::vector<double>& posterior_energy_variance,
2147 int index, double confidence_width)
2148{
2149 OieClimbingArmEvidence evidence;
2150 if (index <= 0 || index >= path.numImages() - 1) return evidence;
2151 const auto& image = path.image(index);
2152 if (!std::isfinite(image.energy)) return evidence;
2153
2154 evidence.index = index;
2155 evidence.current_exact = image.evaluated;
2156 evidence.mean = image.energy;
2157 const double variance =
2158 oieSelectorVariance(image, posterior_energy_variance, index);
2159 evidence.variance = variance;
2160 const double width =
2161 (confidence_width > 0.0 && std::isfinite(confidence_width))
2162 ? confidence_width
2163 : 0.0;
2164 if (!std::isfinite(variance)) {
2165 evidence.lower = -std::numeric_limits<double>::infinity();
2166 evidence.upper = std::numeric_limits<double>::infinity();
2167 return evidence;
2168 }
2169 const double sigma = std::sqrt(std::max(0.0, variance));
2170 evidence.lower = evidence.mean - width * sigma;
2171 evidence.upper = evidence.mean + width * sigma;
2172 return evidence;
2173}
2174
2175double oieSelectorSwitchTolerance(double lhs, double rhs)
2176{
2177 if (!std::isfinite(lhs) || !std::isfinite(rhs))
2178 return std::numeric_limits<double>::infinity();
2179 const double scale = std::max({1.0, std::abs(lhs), std::abs(rhs)});
2180 return std::numeric_limits<double>::epsilon() * scale;
2181}
2182
2183bool oieCandidateVarianceCertified(const OieClimbingArmEvidence& evidence,
2184 double variance_ceiling)
2185{
2186 if (!(variance_ceiling > 0.0) || !std::isfinite(variance_ceiling)) {
2187 return true;
2188 }
2189 if (!evidence.current_exact) return false;
2190 return evidence.variance >= 0.0 && std::isfinite(evidence.variance) &&
2191 evidence.variance <= variance_ceiling;
2192}
2193
2194Eigen::VectorXd ciPerpendicularForceVector(const NEBPath& path, int image_idx)
2195{
2196 if (image_idx <= 0 || image_idx >= path.numImages() - 1) {
2197 return {};
2198 }
2199 const auto& image = path.image(image_idx);
2200 if (!image.evaluated || image.gradient.size() == 0) {
2201 return {};
2202 }
2203 Eigen::VectorXd tangent = path.tangentAt(image_idx);
2204 const double tangent_norm = tangent.norm();
2205 Eigen::VectorXd perpendicular_force = -image.gradient;
2206 if (tangent_norm > 0.0) {
2207 tangent /= tangent_norm;
2208 perpendicular_force -= perpendicular_force.dot(tangent) * tangent;
2209 }
2210 return perpendicular_force;
2211}
2212
2213double ciPerpendicularForceResidual(const NEBPath& path, int image_idx)
2214{
2215 const Eigen::VectorXd perpendicular_force =
2216 ciPerpendicularForceVector(path, image_idx);
2217 if (perpendicular_force.size() == 0 || !perpendicular_force.allFinite()) {
2218 return std::numeric_limits<double>::quiet_NaN();
2219 }
2220 return perpendicular_force.lpNorm<Eigen::Infinity>();
2221}
2222
2223bool bandPathCertificateHolds(const NEBPath& path, double band_force_scale)
2224{
2225 if (!(std::isfinite(band_force_scale) && band_force_scale > 0.0)) {
2226 return true;
2227 }
2228 const int ci = climbingStopImage(path);
2229 if (ci <= 0 || ci >= path.numImages() - 1) return true;
2230 double worst = 0.0;
2231 for (const int j: {ci - 1, ci + 1}) {
2232 if (j <= 0 || j >= path.numImages() - 1) continue;
2233 // Read the residual off the stored gradient rather than through
2234 // ciPerpendicularForceResidual: that helper gates on Image::evaluated,
2235 // which the inner relaxation clears, so a returned band reports NaN and
2236 // the certificate would pass vacuously on exactly the bands it exists
2237 // to refuse.
2238 const auto& image = path.image(j);
2239 if (image.gradient.size() == 0 || !image.gradient.allFinite()) continue;
2240 Eigen::VectorXd tangent = path.tangentAt(j);
2241 Eigen::VectorXd force = -image.gradient;
2242 const double tangent_norm = tangent.norm();
2243 if (tangent_norm > 0.0 && tangent.size() == force.size()) {
2244 tangent /= tangent_norm;
2245 force -= force.dot(tangent) * tangent;
2246 }
2247 const double residual = force.lpNorm<Eigen::Infinity>();
2248 if (std::isfinite(residual)) worst = std::max(worst, residual);
2249 }
2250 return worst <= band_force_scale;
2251}
2252
2253double chordTangentPerpendicularLeak(const NEBPath& path, int image_idx,
2254 double tangential_force)
2255{
2256 if (image_idx <= 0 || image_idx >= path.numImages() - 1 ||
2257 !std::isfinite(tangential_force)) {
2258 return 0.0;
2259 }
2260 const Eigen::VectorXd forward =
2261 path.image(image_idx + 1).positions - path.image(image_idx).positions;
2262 const Eigen::VectorXd backward =
2263 path.image(image_idx).positions - path.image(image_idx - 1).positions;
2264 const double nf = forward.norm();
2265 const double nb = backward.norm();
2266 if (!(nf > 0.0) || !(nb > 0.0) || forward.size() != backward.size()) {
2267 return 0.0;
2268 }
2269 // Turning angle phi between consecutive chords. For a C^3 curve with arc
2270 // spacing h, phi = kappa*h + O(h^3) and the angle between the chord and
2271 // the true tangent at the image is kappa*h/2 + O(h^2)
2272 // (scripts/derive_chord_tangent_bound.py); the identity is exact on a
2273 // circular arc. A force parallel to the true tangent projects onto the
2274 // chord as |F| cos(phi/2) along and |F| sin(phi/2) across, so the across
2275 // component equals the MEASURED along-chord component times tan(phi/2).
2276 // Using the along-chord component (not |F|) keeps an off-path image from
2277 // inflating its own allowance: its extra perpendicular force does not
2278 // enter the tangential projection.
2279 const double cos_phi =
2280 std::clamp(forward.dot(backward) / (nf * nb), -1.0, 1.0);
2281 const double phi = std::acos(cos_phi);
2282 return std::abs(tangential_force) * std::tan(0.5 * phi);
2283}
2284
2285BandDiscretizationCertificate bandDiscretizationCertificateReport(
2286 const NEBPath& path, double force_tol, bool bound_leak)
2287{
2288 BandDiscretizationCertificate out;
2289 if (!(std::isfinite(force_tol) && force_tol > 0.0)) {
2290 out.holds = true;
2291 return out;
2292 }
2293 const int ci = climbingStopImage(path);
2294 if (ci <= 0 || ci >= path.numImages() - 1) {
2295 out.holds = true;
2296 return out;
2297 }
2298 out.holds = true;
2299 for (const int j: {ci - 1, ci + 1}) {
2300 if (j <= 0 || j >= path.numImages() - 1) continue;
2301 const auto& image = path.image(j);
2302 if (image.gradient.size() == 0 || !image.gradient.allFinite()) continue;
2303 Eigen::VectorXd tangent = path.tangentAt(j);
2304 Eigen::VectorXd force = -image.gradient;
2305 const double tangent_norm = tangent.norm();
2306 double tangential_force = 0.0;
2307 if (tangent_norm > 0.0 && tangent.size() == force.size()) {
2308 tangent /= tangent_norm;
2309 tangential_force = force.dot(tangent);
2310 force -= tangential_force * tangent;
2311 }
2312 // The search stops on path.forceMagnitude (max per-atom force when
2313 // the coordinates are atomic). The residual and the leak have to
2314 // be that same norm: |F·tau| is the full-vector projection, and on
2315 // a many-atom band it is several times the per-atom force, so a
2316 // leak built from it hides a neighbour whose own perpendicular
2317 // force is above the tolerance the climbing image just met.
2318 // The leak itself is |F_along| tan(phi/2), so it moves with the
2319 // slope left at the neighbour when the climb stops. A tighter
2320 // stopping force can raise it. The decision is this neighbour's
2321 // residual minus its own leak, not the larger leak on one
2322 // neighbour against the larger residual on the other, and not
2323 // the leak against the tolerance.
2324 const auto norm = path.convergenceForceNorm(force.size());
2325 const double residual = gpr::forceNorm(force, norm);
2326 const double along = gpr::forceNorm(tangential_force * tangent, norm);
2327 if (!std::isfinite(residual) || !std::isfinite(along)) continue;
2328 out.evaluated = true;
2329 // An image on the MEP carries a true force parallel to the true
2330 // tangent. Seen through the chord tangent that force leaks
2331 // tan(phi/2) of its along-chord part into the perpendicular
2332 // residual, in whatever norm measured both. Anything above the
2333 // leak plus the convergence tolerance is a perpendicular force
2334 // the discretization cannot explain. The leak itself is O(h) in
2335 // the image spacing. Bounding the leak by the tolerance is
2336 // optional: a neighbour 2 eV below its climbing image carries a
2337 // large along-chord force and a turning angle near pi/2, and
2338 // leak + tol would then admit any perpendicular force.
2339 const double leak = chordTangentPerpendicularLeak(path, j, along);
2340 // The residual must be explained by the band's own geometry. The
2341 // leak itself is bounded only on request: the reference CI-NEB is an
2342 // eight-image band with the same leak at its climbing-image
2343 // neighbours, and a certificate stricter than the reference bought
2344 // refinements on every sharp ridge (01_hcn: leak 0.15 at 0.07 A
2345 // spacing after four of them) without changing the barrier.
2346 const bool image_ok =
2347 residual <= leak + force_tol && (!bound_leak || leak <= force_tol);
2348 const double unexplained = residual - leak;
2349 if (out.worst_image < 0 ||
2350 unexplained > out.residual_max - out.leak_max) {
2351 out.worst_image = j;
2352 out.leak_max = leak;
2353 out.residual_max = residual;
2354 }
2355 if (!image_ok) out.holds = false;
2356 }
2357 return out;
2358}
2359
2360bool bandDiscretizationCertificateHolds(const NEBPath& path, double force_tol,
2361 bool bound_leak)
2362{
2363 return bandDiscretizationCertificateReport(path, force_tol, bound_leak)
2364 .holds;
2365}
2366
2367std::vector<double> chordLeakSpringRestLengths(const NEBPath& path,
2368 double force_tol)
2369{
2370 std::vector<double> rest;
2371 const int n = path.numImages();
2372 if (n < 3 || !(force_tol > 0.0) || !std::isfinite(force_tol)) return rest;
2373 std::vector<double> d(static_cast<std::size_t>(n - 1), 0.0);
2374 double total_length = 0.0;
2375 for (int i = 0; i + 1 < n; ++i) {
2376 d[static_cast<std::size_t>(i)] =
2377 (path.image(i + 1).positions - path.image(i).positions).norm();
2378 if (!(d[static_cast<std::size_t>(i)] > 0.0)) return rest;
2379 total_length += d[static_cast<std::size_t>(i)];
2380 }
2381 if (!(total_length > 0.0)) return rest;
2382 // Image monitor m_j = 2 leak_j / h_j with h_j the mean adjacent
2383 // spacing: the leak per unit spacing, |F_along| times the path
2384 // curvature to leading order.
2385 std::vector<double> m(static_cast<std::size_t>(n), 0.0);
2386 bool any = false;
2387 for (int j = 1; j + 1 < n; ++j) {
2388 const auto& image = path.image(j);
2389 if (image.gradient.size() != image.positions.size() ||
2390 !image.gradient.allFinite())
2391 continue;
2392 Eigen::VectorXd tangent = path.tangentAt(j);
2393 const double tangent_norm = tangent.norm();
2394 if (!(tangent_norm > 0.0)) continue;
2395 const double tangential_force =
2396 -image.gradient.dot(tangent) / tangent_norm;
2397 const double leak =
2398 chordTangentPerpendicularLeak(path, j, tangential_force);
2399 const double h = 0.5 * (d[static_cast<std::size_t>(j - 1)] +
2400 d[static_cast<std::size_t>(j)]);
2401 if (!std::isfinite(leak) || !(h > 0.0)) continue;
2402 m[static_cast<std::size_t>(j)] = 2.0 * leak / h;
2403 any = true;
2404 }
2405 if (!any) return rest;
2406 m[0] = m[1];
2407 m[static_cast<std::size_t>(n - 1)] = m[static_cast<std::size_t>(n - 2)];
2408 const double monitor_floor = 2.0 * force_tol / total_length;
2409 std::vector<double> weight(static_cast<std::size_t>(n - 1), 0.0);
2410 double weight_sum = 0.0;
2411 for (int i = 0; i + 1 < n; ++i) {
2412 const double monitor =
2413 std::max({m[static_cast<std::size_t>(i)],
2414 m[static_cast<std::size_t>(i + 1)], monitor_floor});
2415 weight[static_cast<std::size_t>(i)] = 1.0 / monitor;
2416 weight_sum += weight[static_cast<std::size_t>(i)];
2417 }
2418 if (!(weight_sum > 0.0) || !std::isfinite(weight_sum)) return rest;
2419 rest.resize(static_cast<std::size_t>(n - 1));
2420 for (int i = 0; i + 1 < n; ++i) {
2421 rest[static_cast<std::size_t>(i)] =
2422 total_length * weight[static_cast<std::size_t>(i)] / weight_sum;
2423 }
2424 return rest;
2425}
2426
2427EigenMatrix resamplePathByRestLengths(const NEBPath& path, int n_images_total,
2428 const std::vector<double>& rest_lengths)
2429{
2430 const int n = path.numImages();
2431 const Eigen::Index dof = n > 0 ? path.image(0).positions.size() : 0;
2432 EigenMatrix out(std::max(n_images_total, 0), dof);
2433 if (n < 2 || n_images_total < 2 || dof == 0) return out;
2434 // Cumulative arc length of the polyline and cumulative rest fractions.
2435 std::vector<double> s(static_cast<std::size_t>(n), 0.0);
2436 for (int i = 1; i < n; ++i)
2437 s[static_cast<std::size_t>(i)] =
2438 s[static_cast<std::size_t>(i - 1)] +
2439 (path.image(i).positions - path.image(i - 1).positions).norm();
2440 std::vector<double> c(static_cast<std::size_t>(n), 0.0);
2441 const bool use_rest =
2442 static_cast<int>(rest_lengths.size()) == n - 1 &&
2443 std::all_of(rest_lengths.begin(), rest_lengths.end(),
2444 [](double r) { return std::isfinite(r) && r > 0.0; });
2445 if (use_rest) {
2446 double total = 0.0;
2447 for (double r: rest_lengths)
2448 total += r;
2449 for (int i = 1; i < n; ++i)
2450 c[static_cast<std::size_t>(i)] =
2451 c[static_cast<std::size_t>(i - 1)] +
2452 rest_lengths[static_cast<std::size_t>(i - 1)] / total;
2453 } else {
2454 for (int i = 0; i < n; ++i)
2455 c[static_cast<std::size_t>(i)] =
2456 static_cast<double>(i) / static_cast<double>(n - 1);
2457 }
2458 c[static_cast<std::size_t>(n - 1)] = 1.0;
2459 const double L = s[static_cast<std::size_t>(n - 1)];
2460 for (int k = 0; k < n_images_total; ++k) {
2461 // Fraction of the new image: the cumulative rest fraction
2462 // interpolated linearly in the coarse image index.
2463 const double u = static_cast<double>(k) /
2464 static_cast<double>(n_images_total - 1) *
2465 static_cast<double>(n - 1);
2466 const int j = std::min(static_cast<int>(std::floor(u)), n - 2);
2467 const double t = u - static_cast<double>(j);
2468 const double frac = c[static_cast<std::size_t>(j)] +
2469 t * (c[static_cast<std::size_t>(j + 1)] -
2470 c[static_cast<std::size_t>(j)]);
2471 const double target = frac * L;
2472 int m = 0;
2473 while (m < n - 2 && s[static_cast<std::size_t>(m + 1)] < target)
2474 ++m;
2475 const double denom =
2476 s[static_cast<std::size_t>(m + 1)] - s[static_cast<std::size_t>(m)];
2477 const double alpha =
2478 denom > std::numeric_limits<double>::min()
2479 ? (target - s[static_cast<std::size_t>(m)]) / denom
2480 : 0.0;
2481 out.row(k) =
2482 (path.image(m).positions +
2483 alpha * (path.image(m + 1).positions - path.image(m).positions))
2484 .transpose();
2485 }
2486 out.row(0) = path.image(0).positions.transpose();
2487 out.row(n_images_total - 1) = path.image(n - 1).positions.transpose();
2488 return out;
2489}
2490
2491int ridgeSubdivisionsForLeak(double leak, double force_tol)
2492{
2493 if (!(force_tol > 0.0) || !std::isfinite(leak) || !(leak > force_tol))
2494 return 1;
2495 const double pieces = std::ceil(std::sqrt(leak / force_tol));
2496 return static_cast<int>(std::clamp(pieces, 1.0, 8.0));
2497}
2498
2499EigenMatrix insertMidpointsAroundClimbingImage(
2500 const NEBPath& path, std::vector<double>* rest_lengths, int subdivisions)
2501{
2502 const int n = path.numImages();
2503 const int ci = climbingStopImage(path);
2504 const int m = std::max(1, subdivisions);
2505 if (n < 3 || ci <= 0 || ci >= n - 1) return EigenMatrix();
2506 const Eigen::Index dof = path.image(0).positions.size();
2507 const int added = 2 * (m - 1) + 2;
2508 EigenMatrix out(n + added, dof);
2509 int row = 0;
2510 for (int i = 0; i < n; ++i) {
2511 out.row(row++) = path.image(i).positions.transpose();
2512 if (i == ci - 1 || i == ci) {
2513 // `m` points at the fractions k/(m+1) cut the segment into
2514 // m + 1 pieces; m = 1 is the midpoint.
2515 for (int k = 1; k <= m; ++k) {
2516 const double t = static_cast<double>(k) / (m + 1.0);
2517 out.row(row++) = ((1.0 - t) * path.image(i).positions +
2518 t * path.image(i + 1).positions)
2519 .transpose();
2520 }
2521 }
2522 }
2523 if (rest_lengths) {
2524 rest_lengths->assign(static_cast<std::size_t>(n + added - 1), 0.0);
2525 for (int i = 0; i + 1 < n + added; ++i)
2526 (*rest_lengths)[static_cast<std::size_t>(i)] =
2527 (out.row(i + 1) - out.row(i)).norm();
2528 }
2529 return out;
2530}
2531
2532int selectLargestFailingCiAdjacentPerpendicularForce(const NEBPath& path,
2533 int ci_idx,
2534 double force_tol)
2535{
2536 if (ci_idx <= 0 || ci_idx >= path.numImages() - 1 ||
2537 !(std::isfinite(force_tol) && force_tol > 0.0)) {
2538 return -1;
2539 }
2540 int selected = -1;
2541 double selected_residual = force_tol;
2542 for (int image_idx: {ci_idx - 1, ci_idx + 1}) {
2543 const double residual = ciPerpendicularForceResidual(path, image_idx);
2544 if (!std::isfinite(residual) || residual < force_tol) continue;
2545 if (selected < 0 || residual > selected_residual) {
2546 selected = image_idx;
2547 selected_residual = residual;
2548 }
2549 }
2550 return selected;
2551}
2552
2553int selectLargestFailingBandPerpendicularForce(const NEBPath& path, int ci_idx,
2554 double force_tol)
2555{
2556 // The accept certificate is band-wide (bandPerpendicularForceConverged),
2557 // so the recovery target search must cover the same set: every interior
2558 // image except the climbing image itself. A CI-adjacent-only search
2559 // leaves a non-adjacent violator unserviced and the certified accept
2560 // unreachable (02_hcch: adjacents pass after their trials commit, one
2561 // far image stays above tol, and the outer loop cycles at a fixed
2562 // point instead of converging).
2563 if (ci_idx <= 0 || ci_idx >= path.numImages() - 1 ||
2564 !(std::isfinite(force_tol) && force_tol > 0.0)) {
2565 return -1;
2566 }
2567 int selected = -1;
2568 double selected_residual = force_tol;
2569 for (int image_idx = 1; image_idx < path.numImages() - 1; ++image_idx) {
2570 if (image_idx == ci_idx) continue;
2571 const double residual = ciPerpendicularForceResidual(path, image_idx);
2572 if (!std::isfinite(residual) || residual < force_tol) continue;
2573 if (selected < 0 || residual > selected_residual) {
2574 selected = image_idx;
2575 selected_residual = residual;
2576 }
2577 }
2578 return selected;
2579}
2580
2581int selectOieAdjacentMepRecoveryTarget(bool ci_active,
2582 bool local_recovery_owner,
2583 const NEBPath& path, int ci_idx,
2584 double energy_force_tol,
2585 double mep_force_tol)
2586{
2587 if (!ci_active ||
2588 !hasTruePesSaddleEnergyCertificate(path, ci_idx, energy_force_tol)) {
2589 return -1;
2590 }
2591 const int target =
2592 selectLargestFailingBandPerpendicularForce(path, ci_idx, mep_force_tol);
2593 if (target < 0) return -1;
2594
2595 // Recovery ownership uses the saddle convergence norm. The climbing
2596 // reflection preserves L2 but can redistribute force between atoms.
2597 const double ci_residual = path.saddleForce(ci_idx);
2598 if (local_recovery_owner && ci_residual >= mep_force_tol) return -1;
2599 const double adjacent_residual = ciPerpendicularForceResidual(path, target);
2600 return std::isfinite(adjacent_residual) && adjacent_residual > ci_residual
2601 ? target
2602 : -1;
2603}
2604
2605bool ciAdjacentPerpendicularForceConverged(const NEBPath& path, int ci_idx,
2606 double conv_tol)
2607{
2608 // MEP certificate for CI-only convergence: the climbing image sitting at a
2609 // true-PES saddle is necessary but not sufficient -- the produced path must
2610 // run THROUGH that saddle. A dimer/MMF burst can drag the climbing image to
2611 // a genuine but off-path saddle (Baker 21: band at the 0.29 rotation path,
2612 // burst refines image 11 onto a 5.38 saddle, CI force < tol, band true
2613 // force 63). On the MEP the PERPENDICULAR true force vanishes at every
2614 // image; the parallel (spring-balanced) component is excluded, so this does
2615 // not re-introduce the image-count-dependent whole-band spring stranding
2616 // (01_hcn).
2617 //
2618 // Evaluated CI-adjacent images may refute the path certificate with a
2619 // large perpendicular true force. Missing adjacent true gradients carry no
2620 // refuting evidence; the saddle energy and MMF second-order certificates
2621 // carry the acceptance when the OIE stencil has not sampled the neighbors.
2622 for (int j = ci_idx - 1; j <= ci_idx + 1; j += 2) {
2623 const double residual = ciPerpendicularForceResidual(path, j);
2624 if (std::isfinite(residual) && !(residual < conv_tol)) return false;
2625 }
2626 return true;
2627}
2628
2629bool hasOieHookConvergenceCertificate(const NEBPath& path, int saddle_index,
2630 double energy_force_tol,
2631 double mep_force_tol, bool climbing_only)
2632{
2633 if (!hasTruePesSaddleEnergyCertificate(
2634 path, saddle_index, energy_force_tol,
2635 /*force_quiet_adjacent=*/!climbing_only)) {
2636 return false;
2637 }
2638 const double force_tol =
2639 (std::isfinite(mep_force_tol) && mep_force_tol > 0.0)
2640 ? mep_force_tol
2641 : energy_force_tol;
2642 if (climbing_only) {
2643 const auto& image = path.image(saddle_index);
2644 if (image.positions.size() == 0 ||
2645 image.gradient.size() != image.positions.size() ||
2646 !image.gradient.allFinite()) {
2647 return false;
2648 }
2649 const double force = path.saddleForce(saddle_index);
2650 return std::isfinite(force) && force < force_tol;
2651 }
2652 return ciAdjacentPerpendicularForceConverged(path, saddle_index, force_tol);
2653}
2654
2655std::string oieHookConvergenceRejectionDiagnostic(const NEBPath& path,
2656 int saddle_index,
2657 double energy_force_tol,
2658 double mep_force_tol,
2659 bool climbing_only)
2660{
2661 struct Residual {
2662 bool present = false;
2663 double value = std::numeric_limits<double>::quiet_NaN();
2664 };
2665
2666 const bool saddle_energy_ok = hasTruePesSaddleEnergyCertificate(
2667 path, saddle_index, energy_force_tol,
2668 /*force_quiet_adjacent=*/!climbing_only);
2669 const double force_tol =
2670 (std::isfinite(mep_force_tol) && mep_force_tol > 0.0)
2671 ? mep_force_tol
2672 : energy_force_tol;
2673 auto residual_at = [&](int image_idx) {
2674 Residual residual;
2675 residual.value = ciPerpendicularForceResidual(path, image_idx);
2676 residual.present = std::isfinite(residual.value);
2677 return residual;
2678 };
2679 const Residual left = residual_at(saddle_index - 1);
2680 const Residual right = residual_at(saddle_index + 1);
2681 bool adj_perp_ok = true;
2682 for (const Residual& residual: {left, right}) {
2683 if (residual.present && !(residual.value < force_tol)) {
2684 adj_perp_ok = false;
2685 }
2686 }
2687 std::ostringstream os;
2688 os << "saddle_index=" << saddle_index
2689 << " saddle_energy_ok=" << (saddle_energy_ok ? 1 : 0)
2690 << " adj_perp_ok=" << (adj_perp_ok ? 1 : 0)
2691 << " adj_perp_required=" << (climbing_only ? 0 : 1)
2692 << " energy_tol=" << energy_force_tol << " mep_tol=" << force_tol;
2693 auto write_residual = [&](const char* label, const Residual& residual) {
2694 os << ' ' << label << '=';
2695 if (residual.present) {
2696 os << residual.value;
2697 } else {
2698 os << "missing";
2699 }
2700 };
2701 write_residual("left_perp_linf", left);
2702 write_residual("right_perp_linf", right);
2703 // Name the band-wide blocker: the accept demands every interior image
2704 // under mep_tol, and a reject with quiet adjacents is otherwise
2705 // unreadable from this line alone.
2706 int worst_idx = -1;
2707 double worst_residual = -std::numeric_limits<double>::infinity();
2708 for (int i = 1; i < path.numImages() - 1; ++i) {
2709 if (i == saddle_index) continue;
2710 const double residual = ciPerpendicularForceResidual(path, i);
2711 if (std::isfinite(residual) && residual > worst_residual) {
2712 worst_idx = i;
2713 worst_residual = residual;
2714 }
2715 }
2716 os << " band_worst_idx=" << worst_idx << " band_worst_perp_linf=";
2717 if (worst_idx >= 0) {
2718 os << worst_residual;
2719 } else {
2720 os << "missing";
2721 }
2722 return os.str();
2723}
2724
2725bool shouldAcceptOieHookConvergence(bool hook_converged, const NEBPath& path,
2726 int saddle_index, double energy_force_tol,
2727 double mep_force_tol, bool climbing_only)
2728{
2729 return hook_converged && hasOieHookConvergenceCertificate(
2730 path, saddle_index, energy_force_tol,
2731 mep_force_tol, climbing_only);
2732}
2733
2734bool bandPerpendicularForceConverged(const NEBPath& path, double force_tol)
2735{
2736 // Whole-band MEP certificate: every interior image must sit under
2737 // force_tol, not only the climbing-image stencil. A CI-local
2738 // stencil can pass on a flat ridge while a neighbor bead remains
2739 // above the true crossing. Every interior image must carry finite
2740 // true-PES data; the caller evaluates missing interiors first.
2741 if (!(std::isfinite(force_tol) && force_tol > 0.0)) return false;
2742 for (int i = 1; i < path.numImages() - 1; ++i) {
2743 if (!path.image(i).evaluated) return false;
2744 const double residual = ciPerpendicularForceResidual(path, i);
2745 if (!std::isfinite(residual) || residual >= force_tol) return false;
2746 }
2747 return true;
2748}
2749
2750bool oieHookChemistryQuietAtTolerance(bool hook_converged,
2751 bool saddle_energy_ok, double ci_force,
2752 double effective_force_tol)
2753{
2754 return hook_converged && saddle_energy_ok && std::isfinite(ci_force) &&
2755 std::isfinite(effective_force_tol) && effective_force_tol >= 0.0 &&
2756 ci_force < effective_force_tol;
2757}
2758
2759bool outerConvergenceCertifiedByTolerance(const GPNEBConfig& config,
2760 const NEBPath& path, bool ci_active,
2761 double convergence_force)
2762{
2763 // OIE and GP-OIE start from zero interior gradients. That placeholder
2764 // is not an oracle, so outer 0 cannot certify until an interior image
2765 // has been evaluated.
2766 if ((config.mode == NEBMode::OIE || config.mode == NEBMode::GP_OIE) &&
2767 !anyEvaluatedInterior(path)) {
2768 return false;
2769 }
2770 if (!std::isfinite(convergence_force)) return false;
2771 if (std::isfinite(config.conv_tol) && config.conv_tol >= 0.0 &&
2772 convergence_force < config.conv_tol) {
2773 return true;
2774 }
2775
2776 const double model_noise_tol = effectiveModelNoiseTolerance(config);
2777 if (!(std::isfinite(model_noise_tol) &&
2778 convergence_force < model_noise_tol)) {
2779 return false;
2780 }
2781
2782 if (config.climbing_image_converged_only && ci_active &&
2783 modelNoiseRaisesConvergenceTolerance(config)) {
2784 // A climbing marker names the bead whose force was inverted.
2785 // Without one, the certificate stays on the highest-energy image.
2786 const int ci_idx = climbingStopImage(path);
2787 if (ci_idx <= 0 || ci_idx >= path.numImages() - 1) return false;
2788 return hasTruePesSaddleEnergyCertificate(path, ci_idx, config.conv_tol);
2789 }
2790 return true;
2791}
2792
2801bool bandBracketsSaddle(const NEBPath& path)
2802{
2803 const int n = path.numImages();
2804 if (n < 3) return false;
2805 const double e0 = path.image(0).energy;
2806 const double en = path.image(n - 1).energy;
2807 if (!std::isfinite(e0) || !std::isfinite(en)) return false;
2808 double imax = -std::numeric_limits<double>::infinity();
2809 bool any_evaluated = false;
2810 for (int i = 1; i < n - 1; ++i) {
2811 const auto& img = path.image(i);
2812 if (!img.evaluated || !std::isfinite(img.energy)) continue;
2813 any_evaluated = true;
2814 imax = std::max(imax, img.energy);
2815 }
2816 return any_evaluated && imax > std::max(e0, en);
2817}
2818
2819int selectOieClimbingImageCandidateIndex(bool ci_active, const NEBPath& path,
2820 double reassign_confidence)
2821{
2822 // Activation follows the GP mean maximum. Active reassignment follows the
2823 // highest current exact energy and retains the marker when no exact
2824 // interior row exists at the current geometry.
2825 const int fallback = path.highestLocalMaximumImageIndex();
2826 if (!ci_active) return fallback;
2827 const int evaluated = highestEvaluatedInteriorImageIndex(path);
2828 const int active_marker = activeClimbingMarkerIndex(path);
2829 if (evaluated > 0) {
2830 // A band with two comparable maxima flips the marker between them
2831 // on every acquisition when the test is a strict comparison: each
2832 // new exact energy makes one side momentarily higher, the climb
2833 // restarts there, and the previous side overtakes on the next
2834 // outer. The band cannot converge because it is never climbing the
2835 // same barrier twice running.
2836 //
2837 // The incumbent is kept unless a rival beats it by more than the
2838 // margin, which is the tolerance the climb is being converged to:
2839 // below that the two are not distinguishable as the higher saddle,
2840 // and picking either one and staying is what lets the search
2841 // finish. Above it the rival is genuinely higher and takes over.
2842 if (active_marker > 0 && active_marker != evaluated &&
2843 reassign_confidence > 0.0) {
2844 const auto& incumbent = path.image(active_marker);
2845 const auto& rival = path.image(evaluated);
2846 if (incumbent.evaluated && std::isfinite(incumbent.energy) &&
2847 std::isfinite(rival.energy)) {
2848 const double mean = rival.energy - incumbent.energy;
2849 const double var = climbingEnergyVariance(incumbent) +
2850 climbingEnergyVariance(rival);
2851 // No uncertainty on either side leaves the strict
2852 // comparison, which is the right answer when the two
2853 // energies are exact and distinct.
2854 const double sigma = var > 0.0 ? std::sqrt(var) : 0.0;
2855 if (mean <= reassign_confidence * sigma) {
2856 return active_marker;
2857 }
2858 }
2859 }
2860 return evaluated;
2861 }
2862 return active_marker > 0 ? active_marker : fallback;
2863}
2864
2865int selectOieClimbingImageCandidateIndex(bool ci_active, const NEBPath& path)
2866{
2867 return selectOieClimbingImageCandidateIndex(ci_active, path,
2868 g_ci_reassign_confidence);
2869}
2870
2871int selectOieClimbingImageIndex(bool ci_active, const NEBPath& path)
2872{
2873 return selectOieClimbingImageIndex(ci_active, path, std::vector<double>{},
2874 /*confidence_width=*/0.0);
2875}
2876
2877int selectOieClimbingImageIndex(
2878 bool ci_active, const NEBPath& path,
2879 const std::vector<double>& posterior_energy_variance,
2880 double confidence_width)
2881{
2882 return selectOieClimbingImageIndex(
2883 ci_active, path, posterior_energy_variance, confidence_width,
2884 /*variance_ceiling=*/std::numeric_limits<double>::infinity());
2885}
2886
2887int selectOieClimbingImageIndex(
2888 bool ci_active, const NEBPath& path,
2889 const std::vector<double>& posterior_energy_variance,
2890 double confidence_width, double variance_ceiling)
2891{
2892 // Consumers use the installed marker as the climbing image. Explicit
2893 // refresh functions own reassignment, including posterior handover and
2894 // L-BFGS history reset, so an unrelated acquisition cannot make force,
2895 // convergence, and MMF consumers disagree about which image climbs.
2896 (void)posterior_energy_variance;
2897 (void)confidence_width;
2898 (void)variance_ceiling;
2899 const int active_marker = activeClimbingMarkerIndex(path);
2900 if (ci_active && active_marker > 0) return active_marker;
2901 return selectOieClimbingImageCandidateIndex(ci_active, path);
2902}
2903
2904void refreshOieClimbingImageMarker(bool ci_active, NEBPath& path)
2905{
2906 if (!ci_active) return;
2907 const int ci_idx = selectOieClimbingImageCandidateIndex(ci_active, path);
2908 for (int i = 0; i < path.numImages(); ++i) {
2909 path.image(i).is_climbing = false;
2910 }
2911 if (ci_idx > 0 && ci_idx < path.numImages() - 1) {
2912 path.image(ci_idx).is_climbing = true;
2913 }
2914}
2915
2916void refreshOieClimbingImageMarker(
2917 bool ci_active, NEBPath& path,
2918 const std::vector<double>& posterior_energy_variance,
2919 double confidence_width)
2920{
2921 refreshOieClimbingImageMarker(
2922 ci_active, path, posterior_energy_variance, confidence_width,
2923 /*variance_ceiling=*/std::numeric_limits<double>::infinity());
2924}
2925
2926void refreshOieClimbingImageMarker(
2927 bool ci_active, NEBPath& path,
2928 const std::vector<double>& posterior_energy_variance,
2929 double confidence_width, double variance_ceiling)
2930{
2931 if (!ci_active) return;
2932 const int previous_ci_idx = activeClimbingMarkerIndex(path);
2933 const int candidate_idx =
2934 selectOieClimbingImageCandidateIndex(ci_active, path);
2935 refreshOieClimbingImageMarkerFromPosteriorCandidate(
2936 ci_active, path, candidate_idx, posterior_energy_variance,
2937 confidence_width, variance_ceiling, previous_ci_idx);
2938}
2939
2940void refreshOieClimbingImageMarkerFromPosteriorCandidate(
2941 bool ci_active, NEBPath& path, int posterior_candidate_idx,
2942 const std::vector<double>& posterior_energy_variance,
2943 double confidence_width, double variance_ceiling, int previous_ci_idx)
2944{
2945 if (!ci_active) return;
2946
2947 for (int i = 1; i < path.numImages() - 1; ++i) {
2948 const double variance =
2949 i < static_cast<int>(posterior_energy_variance.size())
2950 ? posterior_energy_variance[static_cast<std::size_t>(i)]
2951 : std::numeric_limits<double>::infinity();
2952 path.image(i).posterior_variance =
2953 variance >= 0.0 && std::isfinite(variance)
2954 ? variance
2955 : std::numeric_limits<double>::infinity();
2956 }
2957
2958 int selected = previous_ci_idx;
2959 if (selected <= 0 || selected >= path.numImages() - 1) {
2960 selected = activeClimbingMarkerIndex(path);
2961 }
2962 if (selected <= 0 || selected >= path.numImages() - 1) {
2963 selected = selectOieClimbingImageIndex(
2964 ci_active, path, posterior_energy_variance, confidence_width,
2965 variance_ceiling);
2966 } else if (posterior_candidate_idx != selected &&
2967 posterior_candidate_idx > 0 &&
2968 posterior_candidate_idx < path.numImages() - 1) {
2969 const auto& candidate = path.image(posterior_candidate_idx);
2970 const bool within_variance_ceiling = posteriorVarianceConverged(
2971 candidate.posterior_variance, variance_ceiling);
2972 if (candidate.evaluated && within_variance_ceiling &&
2973 ciPosteriorConfident(path, posterior_candidate_idx,
2974 confidence_width)) {
2975 selected = posterior_candidate_idx;
2976 }
2977 }
2978
2979 for (int i = 0; i < path.numImages(); ++i) {
2980 path.image(i).is_climbing = false;
2981 }
2982 if (selected > 0 && selected < path.numImages() - 1) {
2983 path.image(selected).is_climbing = true;
2984 }
2985 path.computeNEBForces();
2986}
2987
2988OieClimbingImageMarkerRefreshState refreshOieClimbingImageMarkerAndResetHistory(
2989 bool ci_active, NEBPath& path, BandRelaxationEngine& optimizer)
2990{
2991 return refreshOieClimbingImageMarkerAndResetHistory(
2992 ci_active, path, optimizer, /*protected_ci_idx=*/-1);
2993}
2994
2995OieClimbingImageMarkerRefreshState refreshOieClimbingImageMarkerAndResetHistory(
2996 bool ci_active, NEBPath& path, BandRelaxationEngine& optimizer,
2997 int protected_ci_idx)
2998{
2999 OieClimbingImageMarkerRefreshState state;
3000 state.previous_ci_idx = activeClimbingMarkerIndex(path);
3001 if (ci_active && protected_ci_idx > 0 &&
3002 protected_ci_idx < path.numImages() - 1) {
3003 for (int i = 0; i < path.numImages(); ++i) {
3004 path.image(i).is_climbing = i == protected_ci_idx;
3005 }
3006 } else {
3007 refreshOieClimbingImageMarker(ci_active, path);
3008 }
3009 state.current_ci_idx = activeClimbingMarkerIndex(path);
3010 state.changed = state.previous_ci_idx != state.current_ci_idx;
3011 if (state.changed) {
3012 optimizer.reset();
3013 }
3014 return state;
3015}
3016
3017bool restoreOiePathPositions(NEBPath& path,
3018 const std::vector<Eigen::VectorXd>& positions,
3019 bool preserve_climbing_marker)
3020{
3021 if (positions.size() != static_cast<size_t>(path.numImages())) {
3022 return false;
3023 }
3024 for (int i = 0; i < path.numImages(); ++i) {
3025 if (positions[i].size() != path.image(i).positions.size()) {
3026 return false;
3027 }
3028 }
3029 for (int i = 1; i < path.numImages() - 1; ++i) {
3030 const bool keep_marker =
3031 preserve_climbing_marker && path.image(i).is_climbing;
3032 path.image(i).positions = positions[i];
3033 path.image(i).evaluated = false;
3034 path.image(i).is_climbing = keep_marker;
3035 }
3036 return true;
3037}
3038
3039bool restoreOieMeasuredClimb(NEBPath& path,
3040 const std::vector<Eigen::VectorXd>& positions,
3041 int climbing_index, double energy,
3042 const Eigen::VectorXd& gradient)
3043{
3044 if (climbing_index <= 0 || climbing_index >= path.numImages() - 1 ||
3045 !std::isfinite(energy) ||
3046 gradient.size() != path.image(climbing_index).positions.size() ||
3047 !gradient.allFinite()) {
3048 return false;
3049 }
3050 for (const auto& position: positions) {
3051 if (!position.allFinite()) return false;
3052 }
3053 if (!restoreOiePathPositions(path, positions,
3054 /*preserve_climbing_marker=*/false)) {
3055 return false;
3056 }
3057 for (int i = 0; i < path.numImages(); ++i) {
3058 path.image(i).is_climbing = i == climbing_index;
3059 }
3060 auto& climb = path.image(climbing_index);
3061 climb.energy = energy;
3062 climb.gradient = gradient;
3063 climb.evaluated = true;
3064 return true;
3065}
3066
3067double updateInitialForceBaseline(double current_baseline, double oracle_force,
3068 bool ci_active)
3069{
3070 if (ci_active) return current_baseline;
3071 if (current_baseline > 0.0 && std::isfinite(current_baseline)) {
3072 return current_baseline;
3073 }
3074 if (oracle_force > 0.0 && std::isfinite(oracle_force)) {
3075 return oracle_force;
3076 }
3077 return current_baseline;
3078}
3079
3080double oieActivationOracleForce(bool oracle_updates_current_path,
3081 double oracle_target_force,
3082 bool current_ci_oracle_updates_path,
3083 double current_ci_oracle_force)
3084{
3085 if (current_ci_oracle_updates_path && current_ci_oracle_force > 0.0 &&
3086 std::isfinite(current_ci_oracle_force)) {
3087 return current_ci_oracle_force;
3088 }
3089 if (oracle_updates_current_path && oracle_target_force > 0.0 &&
3090 std::isfinite(oracle_target_force)) {
3091 return oracle_target_force;
3092 }
3093 return std::numeric_limits<double>::infinity();
3094}
3095
3096double oieCurrentTrueForceCertificate(
3097 const NEBPath& path, const std::vector<char>& image_evaluated,
3098 const std::vector<char>& image_observed_current)
3099{
3100 double max_force = 0.0;
3101 bool has_true_current_force = false;
3102 for (int i = 1; i < path.numImages() - 1; ++i) {
3103 const bool evaluated = i < static_cast<int>(image_evaluated.size()) &&
3104 image_evaluated[i] != 0;
3105 const bool observed_current =
3106 i < static_cast<int>(image_observed_current.size()) &&
3107 image_observed_current[i] != 0;
3108 if (!evaluated && !observed_current) continue;
3109 const double force = path.nebForceMagnitude(i);
3110 if (!std::isfinite(force) || force < 0.0) continue;
3111 has_true_current_force = true;
3112 max_force = std::max(max_force, force);
3113 }
3114 return has_true_current_force ? max_force
3115 : std::numeric_limits<double>::infinity();
3116}
3117
3118OieBandForceSummary summarizeOieBandForces(const NEBPath& path)
3119{
3120 OieBandForceSummary summary;
3121 summary.interior_images = std::max(0, path.numImages() - 2);
3122 for (int i = 1; i < path.numImages() - 1; ++i) {
3123 const double norm = path.nebForceMagnitude(i);
3124 const double force = std::isfinite(norm)
3125 ? norm
3126 : std::numeric_limits<double>::infinity();
3127 summary.max_neb_force = std::max(summary.max_neb_force, force);
3128 if (!path.image(i).evaluated) continue;
3129 if (summary.measured_images++ == 0)
3130 summary.max_measured_neb_force = force;
3131 else
3132 summary.max_measured_neb_force =
3133 std::max(summary.max_measured_neb_force, force);
3134 }
3135 return summary;
3136}
3137
3138bool shouldFlagGpMinTrap(double max_gp_force, double oracle_force,
3139 double conv_tol, double inner_conv_tol,
3140 const char* inner_exit)
3141{
3142 const bool has_force_tolerance = std::isfinite(conv_tol) && conv_tol > 0.0;
3143 const bool gp_force_fixed = has_force_tolerance &&
3144 std::isfinite(max_gp_force) &&
3145 max_gp_force >= 0.0 && max_gp_force < conv_tol;
3146 const bool trust_fixed =
3147 inner_exit != nullptr && std::strcmp(inner_exit, "trust_cert") == 0;
3148 // Surrogate chaos trap (Baker 16 class): true CI force is already at
3149 // the problem tolerance (chemically “quiet”) while the GP force is
3150 // still above that same tolerance; the global GP is a bad OCI lease
3151 // (fresh local GP recovers). Both thresholds are the problem’s force
3152 // tolerance, not a free multiplicative factor.
3153 const bool surrogate_chaos =
3154 inner_exit != nullptr &&
3155 (std::strcmp(inner_exit, "drift") == 0 ||
3156 std::strcmp(inner_exit, "itercap") == 0 ||
3157 std::strcmp(inner_exit, "cycle") == 0) &&
3158 std::isfinite(max_gp_force) && std::isfinite(oracle_force) &&
3159 has_force_tolerance && oracle_force <= conv_tol &&
3160 max_gp_force > conv_tol;
3161 const bool oracle_mismatch_exceeds_inner_resolution =
3162 conv_tol >= 0.0 && inner_conv_tol > 0.0 &&
3163 std::isfinite(oracle_force) && std::isfinite(conv_tol) &&
3164 std::isfinite(inner_conv_tol) &&
3165 (oracle_force - conv_tol) > inner_conv_tol;
3166 if (surrogate_chaos) return true;
3167 return has_force_tolerance && std::isfinite(oracle_force) &&
3168 (gp_force_fixed || trust_fixed) &&
3169 oracle_mismatch_exceeds_inner_resolution;
3170}
3171
3172bool shouldFlagMmfHandoffTrap(double gp_force, double oracle_force,
3173 double handoff_threshold)
3174{
3175 return std::isfinite(gp_force) && std::isfinite(oracle_force) &&
3176 std::isfinite(handoff_threshold) && handoff_threshold > 0.0 &&
3177 gp_force <= handoff_threshold && oracle_force > handoff_threshold;
3178}
3179
3180bool shouldInvalidateOieClimbRestartSnapshot(
3181 bool ci_active, bool oracle_updates_current_path, int oracle_idx,
3182 int ci_idx, double gp_force, double oracle_force, double conv_tol,
3183 double inner_conv_tol, const char* inner_exit)
3184{
3185 return ci_active && oracle_updates_current_path && oracle_idx == ci_idx &&
3186 shouldFlagGpMinTrap(gp_force, oracle_force, conv_tol, inner_conv_tol,
3187 inner_exit);
3188}
3189
3190std::optional<double> oieBbForceStepLength(
3191 const Eigen::VectorXd& previous_position,
3192 const Eigen::VectorXd& previous_force,
3193 const Eigen::VectorXd& current_position,
3194 const Eigen::VectorXd& current_force)
3195{
3196 if (previous_position.size() == 0 ||
3197 previous_position.size() != current_position.size() ||
3198 previous_force.size() != current_force.size() ||
3199 previous_force.size() != current_position.size()) {
3200 return std::nullopt;
3201 }
3202 if (!previous_position.allFinite() || !current_position.allFinite() ||
3203 !previous_force.allFinite() || !current_force.allFinite()) {
3204 return std::nullopt;
3205 }
3206
3207 const Eigen::VectorXd s = current_position - previous_position;
3208 const Eigen::VectorXd dforce = current_force - previous_force;
3209 const double numerator = s.squaredNorm();
3210 const double denominator = -s.dot(dforce);
3211 if (!(numerator > 0.0) || !std::isfinite(numerator) ||
3212 !(denominator > 0.0) || !std::isfinite(denominator)) {
3213 return std::nullopt;
3214 }
3215
3216 const double alpha = numerator / denominator;
3217 if (!(alpha > 0.0) || !std::isfinite(alpha)) return std::nullopt;
3218 return alpha;
3219}
3220
3221MeasuredBandRecoveryState::MeasuredBandRecoveryState(int n_images)
3222 : inverse_curvature_(static_cast<std::size_t>(std::max(0, n_images)),
3223 std::numeric_limits<double>::quiet_NaN())
3224{
3225}
3226
3227bool MeasuredBandRecoveryState::observeAcceptedStep(
3228 int image_index, const Eigen::VectorXd& previous_position,
3229 const Eigen::VectorXd& previous_force,
3230 const Eigen::VectorXd& current_position,
3231 const Eigen::VectorXd& current_force)
3232{
3233 if (image_index < 0 ||
3234 image_index >= static_cast<int>(inverse_curvature_.size())) {
3235 return false;
3236 }
3237 const auto alpha = oieBbForceStepLength(previous_position, previous_force,
3238 current_position, current_force);
3239 if (!alpha) return false;
3240 inverse_curvature_[static_cast<std::size_t>(image_index)] = *alpha;
3241 return true;
3242}
3243
3244double MeasuredBandRecoveryState::inverseCurvature(
3245 int image_index, double fallback) const noexcept
3246{
3247 if (image_index < 0 ||
3248 image_index >= static_cast<int>(inverse_curvature_.size())) {
3249 return fallback;
3250 }
3251 const double learned =
3252 inverse_curvature_[static_cast<std::size_t>(image_index)];
3253 return learned > 0.0 && std::isfinite(learned) ? learned : fallback;
3254}
3255
3256void MeasuredBandRecoveryState::reset() noexcept
3257{
3258 std::fill(inverse_curvature_.begin(), inverse_curvature_.end(),
3259 std::numeric_limits<double>::quiet_NaN());
3260}
3261
3262std::optional<double> measuredSecantBacktrackFraction(
3263 const Eigen::VectorXd& source_position, const Eigen::VectorXd& source_force,
3264 const Eigen::VectorXd& trial_position, const Eigen::VectorXd& trial_force)
3265{
3266 if (source_position.size() == 0 ||
3267 source_position.size() != trial_position.size() ||
3268 source_force.size() != trial_force.size() ||
3269 source_force.size() != source_position.size()) {
3270 return std::nullopt;
3271 }
3272 if (!source_position.allFinite() || !trial_position.allFinite() ||
3273 !source_force.allFinite() || !trial_force.allFinite()) {
3274 return std::nullopt;
3275 }
3276
3277 const Eigen::VectorXd step = trial_position - source_position;
3278 const double source_directional_force = step.dot(source_force);
3279 const double directional_curvature = -step.dot(trial_force - source_force);
3280 if (!(step.squaredNorm() > 0.0) || !(source_directional_force > 0.0) ||
3281 !(directional_curvature > source_directional_force) ||
3282 !std::isfinite(source_directional_force) ||
3283 !std::isfinite(directional_curvature)) {
3284 return std::nullopt;
3285 }
3286
3287 const double fraction = source_directional_force / directional_curvature;
3288 if (!(fraction > 0.0 && fraction < 1.0) || !std::isfinite(fraction)) {
3289 return std::nullopt;
3290 }
3291 return fraction;
3292}
3293
3294MeasuredResidualStepAssessment assessMeasuredResidualStep(
3295 const Eigen::VectorXd& source_position, const Eigen::VectorXd& source_force,
3296 double source_residual, const Eigen::VectorXd& trial_position,
3297 const Eigen::VectorXd& trial_force, double trial_residual,
3298 bool trial_certificate)
3299{
3300 MeasuredResidualStepAssessment assessment;
3301 if (trial_certificate && std::isfinite(source_residual) &&
3302 std::isfinite(trial_residual) && source_residual >= 0.0 &&
3303 trial_residual < source_residual) {
3304 assessment.action = MeasuredResidualStepAction::Accept;
3305 return assessment;
3306 }
3307
3308 assessment.backtrack_fraction = measuredSecantBacktrackFraction(
3309 source_position, source_force, trial_position, trial_force);
3310 if (assessment.backtrack_fraction) {
3311 assessment.action = MeasuredResidualStepAction::Backtrack;
3312 }
3313 return assessment;
3314}
3315
3316bool AdjacentMepRecoveryState::arm(const NEBPath& path, int ci_idx,
3317 int target_idx, double force_tol)
3318{
3319 if (ci_idx <= 0 || ci_idx >= path.numImages() - 1 ||
3320 (target_idx != ci_idx - 1 && target_idx != ci_idx + 1) ||
3321 target_idx <= 0 || target_idx >= path.numImages() - 1 ||
3322 !(std::isfinite(force_tol) && force_tol > 0.0)) {
3323 clear();
3324 return false;
3325 }
3326 if (target_idx_ == target_idx && hasPendingTrial() &&
3327 activeFor(path, ci_idx)) {
3328 force_tol_ = force_tol;
3329 return true;
3330 }
3331 const bool retains_measured_curvature =
3332 ci_idx_ == ci_idx && target_idx_ == target_idx;
3333 const auto measured_inverse_curvature =
3334 retains_measured_curvature ? measured_inverse_curvature_ : std::nullopt;
3335 clear();
3336 const Image& source = path.image(target_idx);
3337 Eigen::VectorXd source_force = ciPerpendicularForceVector(path, target_idx);
3338 const double source_residual =
3339 source_force.size() > 0 && source_force.allFinite()
3340 ? source_force.lpNorm<Eigen::Infinity>()
3341 : std::numeric_limits<double>::quiet_NaN();
3342 if (!source.evaluated || source.positions.size() == 0 ||
3343 source_force.size() != source.positions.size() ||
3344 !std::isfinite(source_residual) || source_residual < force_tol) {
3345 return false;
3346 }
3347
3348 ci_idx_ = ci_idx;
3349 target_idx_ = target_idx;
3350 force_tol_ = force_tol;
3351 source_residual_ = source_residual;
3352 ci_position_ = path.image(ci_idx).positions;
3353 source_path_images_.reserve(static_cast<std::size_t>(path.numImages()));
3354 for (int i = 0; i < path.numImages(); ++i) {
3355 source_path_images_.push_back(path.image(i));
3356 }
3357 source_image_ = source;
3358 source_tangent_ = path.tangentAt(target_idx);
3359 if (source_tangent_.size() == source.positions.size() &&
3360 source_tangent_.allFinite()) {
3361 const double tangent_norm = source_tangent_.norm();
3362 if (tangent_norm > 0.0) source_tangent_ /= tangent_norm;
3363 } else {
3364 source_tangent_.resize(0);
3365 }
3366 source_perpendicular_force_ = std::move(source_force);
3367 measured_inverse_curvature_ = measured_inverse_curvature;
3368 return true;
3369}
3370
3371void AdjacentMepRecoveryState::clear() noexcept
3372{
3373 ci_idx_ = -1;
3374 target_idx_ = -1;
3375 force_tol_ = 0.0;
3376 source_residual_ = std::numeric_limits<double>::quiet_NaN();
3377 ci_position_.resize(0);
3378 source_path_images_.clear();
3379 source_image_ = Image{};
3380 source_tangent_.resize(0);
3381 source_perpendicular_force_.resize(0);
3382 pending_trial_position_.resize(0);
3383 measured_inverse_curvature_.reset();
3384}
3385
3386bool AdjacentMepRecoveryState::activeFor(const NEBPath& path, int ci_idx) const
3387{
3388 return ci_idx_ == ci_idx && ci_idx > 0 && ci_idx < path.numImages() - 1 &&
3389 target_idx_ > 0 && target_idx_ < path.numImages() - 1 &&
3390 positionsCoincide(ci_position_, path.image(ci_idx).positions) &&
3391 positionsCoincide(source_image_.positions,
3392 path.image(target_idx_).positions);
3393}
3394
3395double AdjacentMepRecoveryState::deficit() const noexcept
3396{
3397 if (!(force_tol_ > 0.0) || !std::isfinite(force_tol_) ||
3398 !std::isfinite(source_residual_)) {
3399 return 0.0;
3400 }
3401 return source_residual_ / force_tol_;
3402}
3403
3404bool AdjacentMepRecoveryState::stageTrial(const NEBPath& path)
3405{
3406 if (target_idx_ <= 0 || target_idx_ >= path.numImages() - 1) {
3407 return false;
3408 }
3409 const Eigen::VectorXd& positions = path.image(target_idx_).positions;
3410 if (positions.size() != source_image_.positions.size() ||
3411 !positions.allFinite() ||
3412 positionsCoincide(positions, source_image_.positions)) {
3413 return false;
3414 }
3415 pending_trial_position_ = positions;
3416 return true;
3417}
3418
3419bool AdjacentMepRecoveryState::setPendingTrialPosition(
3420 Eigen::VectorXd positions)
3421{
3422 if (positions.size() != source_image_.positions.size() ||
3423 !positions.allFinite() ||
3424 positionsCoincide(positions, source_image_.positions)) {
3425 return false;
3426 }
3427 pending_trial_position_ = std::move(positions);
3428 return true;
3429}
3430
3431bool AdjacentMepRecoveryState::backtrackPendingTrial(double fraction)
3432{
3433 if (!hasPendingTrial() || !(fraction > 0.0 && fraction < 1.0) ||
3434 !std::isfinite(fraction)) {
3435 return false;
3436 }
3437 return setPendingTrialPosition(
3438 source_image_.positions +
3439 fraction * (pending_trial_position_ - source_image_.positions));
3440}
3441
3442bool AdjacentMepRecoveryState::restoreTargetSource(NEBPath& path) const
3443{
3444 if (target_idx_ <= 0 || target_idx_ >= path.numImages() - 1 ||
3445 source_image_.positions.size() == 0 ||
3446 source_image_.positions.size() !=
3447 path.image(target_idx_).positions.size()) {
3448 return false;
3449 }
3450 Image& target = path.image(target_idx_);
3451 target.positions = source_image_.positions;
3452 target.energy = source_image_.energy;
3453 target.gradient = source_image_.gradient;
3454 target.evaluated = source_image_.evaluated;
3455 return true;
3456}
3457bool AdjacentMepRecoveryState::restoreSource(NEBPath& path) const
3458{
3459 if (target_idx_ <= 0 || target_idx_ >= path.numImages() - 1 ||
3460 source_image_.positions.size() == 0 ||
3461 source_path_images_.size() !=
3462 static_cast<std::size_t>(path.numImages())) {
3463 return false;
3464 }
3465 for (int i = 0; i < path.numImages(); ++i) {
3466 if (source_path_images_[static_cast<std::size_t>(i)].positions.size() !=
3467 path.image(i).positions.size()) {
3468 return false;
3469 }
3470 }
3471 for (int i = 0; i < path.numImages(); ++i) {
3472 path.image(i) = source_path_images_[static_cast<std::size_t>(i)];
3473 }
3474 Image& target = path.image(target_idx_);
3475 target.positions = source_image_.positions;
3476 target.energy = source_image_.energy;
3477 target.gradient = source_image_.gradient;
3478 target.evaluated = source_image_.evaluated;
3479 path.computeNEBForces();
3480 return true;
3481}
3482
3483AdjacentMepTrialAssessment AdjacentMepRecoveryState::assessPendingTrial(
3484 const NEBPath& source_path, double trial_energy,
3485 const Eigen::VectorXd& trial_gradient, double energy_force_tol) const
3486{
3487 AdjacentMepTrialAssessment assessment;
3488 if (!hasPendingTrial() || ci_idx_ <= 0 ||
3489 ci_idx_ >= source_path.numImages() - 1 || target_idx_ <= 0 ||
3490 target_idx_ >= source_path.numImages() - 1 ||
3491 trial_gradient.size() != pending_trial_position_.size() ||
3492 !std::isfinite(trial_energy) || !trial_gradient.allFinite()) {
3493 return assessment;
3494 }
3495
3496 NEBPath trial_path = source_path;
3497 Image& trial = trial_path.image(target_idx_);
3498 trial.positions = pending_trial_position_;
3499 trial.energy = trial_energy;
3500 trial.gradient = trial_gradient;
3501 trial.evaluated = true;
3502 assessment.perpendicular_force =
3503 ciPerpendicularForceVector(trial_path, target_idx_);
3504 if (assessment.perpendicular_force.size() > 0 &&
3505 assessment.perpendicular_force.allFinite()) {
3506 assessment.residual =
3507 assessment.perpendicular_force.lpNorm<Eigen::Infinity>();
3508 }
3509 assessment.saddle_energy_certificate = hasTruePesSaddleEnergyCertificate(
3510 trial_path, ci_idx_, energy_force_tol);
3511 assessment.step = assessMeasuredResidualStep(
3512 source_image_.positions, source_perpendicular_force_, source_residual_,
3513 pending_trial_position_, assessment.perpendicular_force,
3514 assessment.residual, assessment.saddle_energy_certificate);
3515 return assessment;
3516}
3517
3518AdjacentMepTrialAssessment AdjacentMepRecoveryState::observePendingTrial(
3519 const NEBPath& source_path, double trial_energy,
3520 const Eigen::VectorXd& trial_gradient, double energy_force_tol)
3521{
3522 AdjacentMepTrialAssessment assessment = assessPendingTrial(
3523 source_path, trial_energy, trial_gradient, energy_force_tol);
3524 retainMeasuredInverseCurvature(trial_gradient);
3525 return assessment;
3526}
3527
3528void AdjacentMepRecoveryState::retainMeasuredInverseCurvature(
3529 const Eigen::VectorXd& trial_gradient)
3530{
3531 if (source_tangent_.size() != trial_gradient.size() ||
3532 !trial_gradient.allFinite()) {
3533 return;
3534 }
3535 Eigen::VectorXd trial_perpendicular_force = -trial_gradient;
3536 trial_perpendicular_force -=
3537 trial_perpendicular_force.dot(source_tangent_) * source_tangent_;
3538 const auto measured_inverse_curvature = oieBbForceStepLength(
3539 source_image_.positions, source_perpendicular_force_,
3540 pending_trial_position_, trial_perpendicular_force);
3541 if (measured_inverse_curvature) {
3542 measured_inverse_curvature_ = measured_inverse_curvature;
3543 }
3544}
3545
3546bool AdjacentMepRecoveryState::commitPendingTrial(
3547 NEBPath& path, double trial_energy, const Eigen::VectorXd& trial_gradient)
3548{
3549 if (!hasPendingTrial() || target_idx_ <= 0 ||
3550 target_idx_ >= path.numImages() - 1 ||
3551 trial_gradient.size() != pending_trial_position_.size() ||
3552 !std::isfinite(trial_energy) || !trial_gradient.allFinite()) {
3553 return false;
3554 }
3555 Image& target = path.image(target_idx_);
3556 target.positions = pending_trial_position_;
3557 target.energy = trial_energy;
3558 target.gradient = trial_gradient;
3559 target.evaluated = true;
3560 path.computeNEBForces();
3561 retainMeasuredInverseCurvature(trial_gradient);
3562 return true;
3563}
3564
3575bool applyOieMeasuredClimbingImageStep(
3576 NEBPath& path, int image_idx, ActiveLearningSession& session,
3577 NEBOracle& oracle, int& oracle_calls, bool project_rotations,
3578 double conv_tol, double max_radius, double& radius,
3579 bool surrogate_measured_non_descent, int outer, bool verbose,
3580 const std::array<double, 9>& cell,
3581 const geometry::ElementPairContactFloor& contact_floor,
3582 bool* marginal_progress)
3583{
3584 if (marginal_progress != nullptr) *marginal_progress = false;
3585 if (image_idx <= 0 || image_idx >= path.numImages() - 1) return false;
3586 Image& image = path.image(image_idx);
3587 if (!std::isfinite(radius) || radius < 0.0) return false;
3588 const Eigen::Index dof = image.positions.size();
3589 if (!image.evaluated || image.gradient.size() != dof || dof % 3 != 0 ||
3590 !image.gradient.allFinite() || !image.positions.allFinite() ||
3591 !(std::isfinite(conv_tol) && conv_tol >= 0.0))
3592 return false;
3593 const double true_force = path.forceMagnitude(image.gradient);
3594 if (!(true_force > conv_tol)) return false;
3595 auto model = session.acquireGlobalModel();
3596 gpr::Observation probe;
3597 probe.R.resize(1, dof);
3598 probe.R.row(0) = image.positions.transpose();
3599 model.gp().calculatePotentialDispatched(probe);
3600 if (probe.G.rows() < 1 || probe.G.cols() != dof ||
3601 !probe.G.row(0).allFinite())
3602 return false;
3603 const Eigen::VectorXd model_error_vector =
3604 probe.G.row(0).transpose() - image.gradient;
3605 const double model_error = path.forceMagnitude(model_error_vector);
3606 // A step the oracle measured worse than its origin was rejected and
3607 // halved the radius (the trust-region contraction); a step measured
3608 // better, or a new best climb, restores the full radius. Below the
3609 // coordinate resolution there is no step left to take.
3610 if (!(radius > 0.0) || radius * radius <= 1.0e-12) return false;
3611 // A surrogate walk from this point that the oracle measured as
3612 // non-descent is the same evidence as a model error above the
3613 // residual: the model cannot converge the image from here on its own.
3614 if (!surrogate_measured_non_descent &&
3615 !(model_error > true_force - conv_tol))
3616 return false;
3617 // The physical subspace: the complement of the rigid motions.
3618 const Eigen::MatrixXd rigid =
3619 dimer::rigid_motion_basis(probe.R, project_rotations);
3620 Eigen::MatrixXd Q;
3621 if (rigid.cols() > 0 && rigid.cols() < dof) {
3622 Eigen::HouseholderQR<Eigen::MatrixXd> qr(rigid);
3623 const Eigen::MatrixXd full = qr.householderQ();
3624 Q = full.rightCols(dof - rigid.cols());
3625 } else if (rigid.cols() == 0) {
3626 Q = Eigen::MatrixXd::Identity(dof, dof);
3627 } else {
3628 return false;
3629 }
3630 gpr::GaussianProcessRegression::PreparedHssvdHessianVector prepared;
3631 const bool have_prepared =
3632 model.gp().prepareMeanHessianVectorHssvd(probe.R, prepared);
3633 Eigen::MatrixXd HQ;
3634 bool have_block = have_prepared &&
3635 model.gp().applyMeanHessianBlockHssvd(prepared, Q, HQ) &&
3636 HQ.rows() == dof && HQ.cols() == Q.cols() &&
3637 HQ.allFinite();
3638 if (!have_block) {
3639 HQ.resize(dof, Q.cols());
3640 for (Eigen::Index c = 0; c < Q.cols(); ++c) {
3641 Eigen::VectorXd hv;
3642 const Eigen::VectorXd q = Q.col(c);
3643 const bool ok =
3644 have_prepared
3645 ? model.gp().applyMeanHessianVectorHssvd(prepared, q, hv)
3646 : model.gp().calculateMeanHessianVectorDispatched(probe.R,
3647 q, hv);
3648 if (!ok || hv.size() != dof || !hv.allFinite()) return false;
3649 HQ.col(c) = hv;
3650 }
3651 }
3652 Eigen::MatrixXd Hsub = Q.transpose() * HQ;
3653 Hsub = (0.5 * (Hsub + Hsub.transpose())).eval();
3654 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(Hsub);
3655 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0 ||
3656 !(es.eigenvalues()(0) < 0.0))
3657 return false;
3658 const gpr::optim::SpectralTrustRegionStep solved =
3660 es.eigenvalues(), Eigen::MatrixXd(Q * es.eigenvectors()), 0,
3661 Eigen::VectorXd(-image.gradient), radius, {});
3662 if (!solved.valid) return false;
3663 // The step and its measurement are one action. A stepped image left
3664 // for the next outer's acquisition was restored to its measured
3665 // geometry by the drift bookkeeping and refused by three acquisition
3666 // gates in turn; measured here, the row enters the session and the
3667 // image carries its true force into the next convergence check.
3668 const Eigen::VectorXd stepped = contact_floor.limitStep(
3669 image.positions, Eigen::VectorXd(image.positions + solved.step), cell);
3670 const double stepped_length = (stepped - image.positions).norm();
3671 if (stepped_length * stepped_length <= 1.0e-12 ||
3672 contact_floor.violated(stepped, cell)) {
3673 radius = 0.0;
3674 return false;
3675 }
3676 double energy = std::numeric_limits<double>::quiet_NaN();
3677 Eigen::VectorXd gradient;
3678 try {
3679 std::tie(energy, gradient) = evaluateOieOraclePosition(stepped, oracle);
3680 } catch (const OracleSessionRestartRequested&) {
3681 throw;
3682 } catch (const std::exception& error) {
3683 if (verbose) {
3684 std::cout << "[oie-measured-step] outer=" << outer
3685 << " image=" << image_idx
3686 << " oracle refused the stepped geometry: "
3687 << error.what() << std::endl;
3688 }
3689 return false;
3690 }
3691 ++oracle_calls;
3692 if (!std::isfinite(energy) || gradient.size() != dof ||
3693 !gradient.allFinite())
3694 return false;
3695 const double stepped_force = path.forceMagnitude(gradient);
3696 // The row is information either way; the image moves only when the
3697 // oracle measured the step as progress.
3698 session.appendObservation(image_idx, stepped, energy, gradient);
3699 session.refreshCovarianceCache();
3700 const bool accepted = stepped_force < true_force;
3701 // The step is aimed at the zero of the force, so the model predicts the
3702 // whole residual is removed. A step that removes less than a tenth of the
3703 // force above tolerance shows the model has no predictive power at this
3704 // length: only the shrinking radius made the force fall. Restoring the
3705 // full radius then repeats the same sequence of rejected halvings from
3706 // a point that has not moved.
3707 const bool marginal = accepted && (true_force - stepped_force) <
3708 0.1 * (true_force - conv_tol);
3709 if (marginal_progress != nullptr) *marginal_progress = marginal;
3710 if (accepted) {
3711 image.positions = stepped;
3712 image.energy = energy;
3713 image.gradient = gradient;
3714 image.evaluated = true;
3715 path.computeNEBForces();
3716 radius = marginal ? 0.0 : max_radius;
3717 } else {
3718 // The trust-region contraction; the halvings end at the coordinate
3719 // resolution, and a new best climb restores the radius.
3720 radius = 0.5 * std::min(radius, stepped_length);
3721 }
3722 if (verbose) {
3723 std::cout << "[oie-measured-step] outer=" << outer
3724 << " image=" << image_idx << " true_force=" << true_force
3725 << " model_error=" << model_error << " tolerance=" << conv_tol
3726 << " length=" << stepped_length
3727 << " proposed_length=" << solved.length
3728 << " sigma=" << solved.sigma
3729 << " lowest_curvature=" << es.eigenvalues()(0)
3730 << " flat=" << solved.flat
3731 << " stepped_force=" << stepped_force
3732 << (accepted ? " accepted" : " rejected")
3733 << " next_radius=" << radius << std::endl;
3734 }
3735 return accepted;
3736}
3737
3738bool applyOieBbForceCorrection(NEBPath& path, int image_idx,
3739 const Eigen::VectorXd& previous_position,
3740 const Eigen::VectorXd& previous_force,
3741 const Eigen::VectorXd& current_force,
3742 double conv_tol, double max_step)
3743{
3744 if (image_idx <= 0 || image_idx >= path.numImages() - 1) return false;
3745 Image& image = path.image(image_idx);
3746 if (current_force.size() != image.positions.size()) return false;
3747 if (!(std::isfinite(conv_tol) && conv_tol >= 0.0)) return false;
3748 if (!(std::isfinite(max_step) && max_step > 0.0)) return false;
3749 if (!current_force.allFinite()) return false;
3750 const double force_norm = current_force.norm();
3751 if (!(std::isfinite(force_norm) && force_norm > conv_tol)) return false;
3752
3753 const auto alpha = oieBbForceStepLength(previous_position, previous_force,
3754 image.positions, current_force);
3755 if (!alpha) return false;
3756 Eigen::VectorXd step = *alpha * current_force;
3757 if (!step.allFinite()) return false;
3758 step = limitBandMotion(step, image.positions.size(), max_step);
3759 if (step.size() != image.positions.size() || step.squaredNorm() == 0.0) {
3760 return false;
3761 }
3762
3763 image.positions += step;
3764 image.evaluated = false;
3765 return true;
3766}
3767
3768bool shouldApplyOieTrueForceBbCorrection(
3769 bool ci_active, bool current_ci_oracle_updates_path, int current_ci_idx,
3770 int previous_ci_idx, double current_ci_force, double previous_ci_force,
3771 bool true_saddle_energy_certificate)
3772{
3773 if (!ci_active || !current_ci_oracle_updates_path) return false;
3774 if (!true_saddle_energy_certificate) return false;
3775 if (current_ci_idx <= 0 || previous_ci_idx <= 0 ||
3776 current_ci_idx != previous_ci_idx) {
3777 return false;
3778 }
3779 if (!(std::isfinite(current_ci_force) && current_ci_force >= 0.0 &&
3780 std::isfinite(previous_ci_force) && previous_ci_force >= 0.0)) {
3781 return false;
3782 }
3783 return current_ci_force >
3784 std::nextafter(previous_ci_force,
3785 std::numeric_limits<double>::infinity());
3786}
3787
3788double oieGpInnerTolerance(const GPNEBConfig& config,
3789 double smallest_oracle_force, bool ci_active)
3790{
3791 // The inner GP relaxation is a surrogate fixed-point solve; the outer
3792 // convergence certificate is still the true oracle force. Keep the
3793 // surrogate tolerance strictly below the oracle tolerance so a
3794 // GP-stationary climbing image must be refined before the true-force
3795 // certificate can pass. The configured divisor supplies that separation,
3796 // including the climbing-image-only branch.
3797 const double margin_divisor =
3798 (config.gp_tol_divisor > 1.0 && std::isfinite(config.gp_tol_divisor))
3799 ? config.gp_tol_divisor
3800 : 10.0;
3801 const double floor_tol =
3802 (config.conv_tol > 0.0 && std::isfinite(config.conv_tol))
3803 ? config.conv_tol / margin_divisor
3804 : ((config.inner_conv_tol > 0.0 &&
3805 std::isfinite(config.inner_conv_tol))
3806 ? config.inner_conv_tol
3807 : 0.0);
3808 // CI-only acceptance is on the true PES at conv_tol. Chase GP to the
3809 // same oracle threshold so the inner loop exits to a true-force check
3810 // rather than burning itercap when CI GP plateaus between floor_tol and
3811 // conv_tol (Baker 18: ci_gp~0.05–0.13, floor=conv/10, exit=itercap every
3812 // outer while max_gp_F stays O(1)).
3813 if (ci_active && config.climbing_image_converged_only) {
3814 return (config.conv_tol > 0.0 && std::isfinite(config.conv_tol))
3815 ? config.conv_tol
3816 : floor_tol;
3817 }
3818 if (!(config.gp_tol_divisor > 0.0) ||
3819 !std::isfinite(smallest_oracle_force) ||
3820 !(smallest_oracle_force > 0.0) || !(config.conv_tol > 0.0)) {
3821 return floor_tol;
3822 }
3823
3824 const double ratio =
3825 std::clamp(smallest_oracle_force / config.conv_tol, 1.0, 10.0);
3826 const double t = 1.0 - (ratio - 1.0) / 9.0;
3827 const double divisor = 2.0 + t * (config.gp_tol_divisor - 2.0);
3828 if (!(divisor > 0.0) || !std::isfinite(divisor)) return floor_tol;
3829 return std::max(floor_tol, smallest_oracle_force / divisor);
3830}
3831
3832double oieGpForceErrorTolerance(const GPNEBConfig& config,
3833 double inner_tolerance, double oracle_force,
3834 double predicted_force, double force_error)
3835{
3836 if (!(config.conv_tol > 0.0) || !std::isfinite(config.conv_tol) ||
3837 !std::isfinite(oracle_force) || !std::isfinite(predicted_force) ||
3838 !std::isfinite(force_error) || force_error < 0.0 ||
3839 oracle_force <= config.conv_tol ||
3840 !(predicted_force < config.conv_tol)) {
3841 return inner_tolerance;
3842 }
3843 const double divisor =
3844 config.gp_tol_divisor > 1.0 && std::isfinite(config.gp_tol_divisor)
3845 ? config.gp_tol_divisor
3846 : 10.0;
3847 // The measured residual consumes part of the true-force tolerance:
3848 // ||F_true|| <= ||F_GP|| + ||F_true - F_GP||. This local error budget
3849 // tightens a false surrogate convergence; the outer oracle still
3850 // certifies every candidate. The configured floor bounds inner work.
3851 return std::min(inner_tolerance, std::max(config.conv_tol / divisor,
3852 config.conv_tol - force_error));
3853}
3854
3855void OieMeasuredForceMargin::observe(int image_index, double oracle_force,
3856 double force_error)
3857{
3858 image_index_ = image_index;
3859 oracle_force_ = oracle_force;
3860 force_error_ = force_error;
3861}
3862
3863double OieMeasuredForceMargin::tolerance(const GPNEBConfig& config,
3864 int image_index,
3865 double inner_tolerance,
3866 double predicted_force) const
3867{
3868 if (image_index != image_index_) return inner_tolerance;
3869 // A measured force within one stopping tolerance of convergence can
3870 // cross the threshold during relaxation even when its initial GP force
3871 // is outside it. Retain its error through that crossing. Further away,
3872 // retain the residual only if its interval reaches the threshold.
3873 if (oracle_force_ - config.conv_tol > config.conv_tol &&
3874 oracle_force_ - force_error_ > config.conv_tol)
3875 return inner_tolerance;
3876 return oieGpForceErrorTolerance(config, inner_tolerance, oracle_force_,
3877 predicted_force, force_error_);
3878}
3879
3880double oieGpRelaxationForce(const GPNEBConfig& config, bool ci_active,
3881 double chain_force, double ci_force,
3882 bool ci_saddle_energy_certified)
3883{
3884 // Measured energy certificates belong to outer acceptance. Surrogate
3885 // relaxation precedes that measurement and follows the active phase.
3886 (void)ci_saddle_energy_certified;
3887 if (ci_active && config.climbing_image_converged_only) {
3888 return ci_force;
3889 }
3890 return chain_force;
3891}
3892
3893bool oieGpInnerForceConverged(bool climbing_only_phase, double relaxation_force,
3894 double chain_force, double relaxation_tolerance,
3895 double chain_tolerance)
3896{
3897 return relaxation_force < relaxation_tolerance &&
3898 (climbing_only_phase || chain_force < chain_tolerance);
3899}
3900
3901OieRelaxableForceMeasure measureOieRelaxableForces(const NEBPath& path,
3902 int ci_image_idx,
3903 int fixed_image_idx)
3904{
3905 OieRelaxableForceMeasure measure;
3906 for (int i = 1; i < path.numImages() - 1; ++i) {
3907 if (i == fixed_image_idx) continue;
3908 const double force = path.forceMagnitude(path.nebForce(i));
3909 if (!std::isfinite(force)) {
3910 measure.max_force = std::numeric_limits<double>::infinity();
3911 } else {
3912 measure.max_force = std::max(measure.max_force, force);
3913 }
3914 // The climbing reflection can redistribute forces between atoms.
3915 // Saddle stationarity uses the physical gradient in the same norm
3916 // as the true-surface convergence check.
3917 if (i == ci_image_idx) {
3918 measure.climbing_force =
3919 path.image(i).is_climbing ? path.saddleForce(i) : force;
3920 }
3921 }
3922 if (ci_image_idx == fixed_image_idx) {
3923 measure.climbing_force = measure.max_force;
3924 }
3925 return measure;
3926}
3927
3928bool isImageWithinTrainingTrust(const Eigen::VectorXd& positions,
3929 const gpr::Observation& training_obs,
3930 const gpr::TrustRadius& trust,
3931 double trust_threshold)
3932{
3933 if (!(trust_threshold >= 0.0) || training_obs.R.rows() == 0 ||
3934 training_obs.R.cols() != positions.size()) {
3935 return false;
3936 }
3937 const double distance = trust.distanceToTraining(positions);
3938 return gpr::numerics::withinThreshold(distance, trust_threshold);
3939}
3940
3941bool imageWithinSurrogateTrust(const Eigen::VectorXd& positions,
3942 const gpr::AtomsConfiguration& atoms_config,
3943 const gpr::Observation& global_observations,
3944 const gpr::SexpatCF& global_kernel,
3945 const gpr::Observation& trust_observations,
3946 const gpr::TrustRadius& trust,
3947 std::optional<double> measured_radius)
3948{
3949 if (measured_radius &&
3950 !isImageWithinTrainingTrust(positions, trust_observations, trust,
3951 *measured_radius))
3952 return false;
3953 return imageWithinPredictionKernelSupport(
3954 positions, atoms_config, global_observations, global_kernel);
3955}
3956
3957bool clipImageToOuterTrust(Eigen::VectorXd& positions,
3958 const gpr::Observation& training_obs,
3959 const gpr::TrustRadius& trust,
3960 double trust_threshold)
3961{
3962 if (!(trust_threshold > 0.0) || training_obs.R.rows() == 0 ||
3963 training_obs.R.cols() != positions.size()) {
3964 return false;
3965 }
3966 const double dist = trust.distanceToTraining(positions);
3967 if (!std::isfinite(dist) ||
3968 gpr::numerics::withinThreshold(dist, trust_threshold))
3969 return false;
3970
3971 const std::vector<int> nearest = trust.kNearestIndices(positions, 1);
3972 if (nearest.empty()) return false;
3973
3974 const Eigen::VectorXd nearest_position =
3975 training_obs.R.row(nearest.front()).transpose();
3976 Eigen::VectorXd projected;
3977 if (!trust.projectLineToTrustBoundary(nearest_position, positions,
3978 trust_threshold, projected)) {
3979 return false;
3980 }
3981 positions = projected;
3982 return true;
3983}
3984
3985ProposalAcquisitionTarget prepareOieBoundaryAcquisition(
3986 ProposalAcquisitionTarget target, const gpr::Observation& training_obs,
3987 const gpr::TrustRadius& trust, double trust_threshold)
3988{
3989 if (!target || !target.positions.allFinite()) return {};
3990 (void)clipImageToOuterTrust(target.positions, training_obs, trust,
3991 trust_threshold);
3992 if (!isImageWithinTrainingTrust(target.positions, training_obs, trust,
3993 trust_threshold) ||
3994 hasPosition(training_obs, target.positions)) {
3995 return {};
3996 }
3997 return target;
3998}
3999
4000bool imageWithinPredictionKernelSupport(
4001 const Eigen::VectorXd& positions,
4002 const gpr::AtomsConfiguration& atoms_config,
4003 const gpr::Observation& global_observations,
4004 const gpr::FieldMatrixd& global_length_scale,
4005 const gpr::Observation* local_observations,
4006 const gpr::FieldMatrixd* local_length_scale)
4007{
4008 const bool use_local = local_observations && local_length_scale;
4009 const gpr::Observation& observations =
4010 use_local ? *local_observations : global_observations;
4011 const gpr::FieldMatrixd& length_scale =
4012 use_local ? *local_length_scale : global_length_scale;
4013 if (length_scale.size() == 0) return true;
4014 if (observations.R.rows() == 0 ||
4015 observations.R.cols() != positions.size()) {
4016 return false;
4017 }
4018
4019 gpr::Coord probe_row(1, positions.size());
4020 probe_row.row(0) = positions.transpose();
4021 aux::Distance kernel_distance;
4022 gpr::FieldMatrixd kernel_distance_matrix;
4023 kernel_distance.dist_at(probe_row, observations.R, atoms_config,
4024 length_scale, kernel_distance_matrix);
4025 for (Eigen::Index c = 0; c < kernel_distance_matrix.cols(); ++c) {
4026 // Correlation distance 1 is the support boundary. A last-bit
4027 // step past it is still inside: leaving opens a kernel-drift
4028 // acquisition.
4029 if (gpr::numerics::withinThreshold(kernel_distance_matrix(0, c), 1.0)) {
4030 return true;
4031 }
4032 }
4033 return false;
4034}
4035
4036bool imageWithinPredictionKernelSupport(
4037 const Eigen::VectorXd& positions,
4038 const gpr::AtomsConfiguration& atoms_config,
4039 const gpr::Observation& global_observations,
4040 const gpr::SexpatCF& global_kernel,
4041 const gpr::Observation* local_observations,
4042 const gpr::SexpatCF* local_kernel)
4043{
4044 const bool use_local = local_observations && local_kernel;
4045 const auto& observations =
4046 use_local ? *local_observations : global_observations;
4047 const auto& kernel = use_local ? *local_kernel : global_kernel;
4048 if (kernel.getLengthScaleRef().size() == 0) return true;
4049 if (observations.R.rows() == 0 ||
4050 observations.R.cols() != positions.size()) {
4051 return false;
4052 }
4053 const gpr::Coord probe = positions.transpose();
4054 gpr::FieldMatrixd distances;
4055 kernel.correlationDistances(probe, observations.R, atoms_config, distances);
4056 for (Eigen::Index j = 0; j < distances.cols(); ++j) {
4057 if (gpr::numerics::withinThreshold(distances(0, j), 1.0)) {
4058 return true;
4059 }
4060 }
4061 return false;
4062}
4063
4064namespace {
4065
4066bool validPoolingVariance(double variance)
4067{
4068 return variance >= 0.0 && std::isfinite(variance);
4069}
4070
4071bool finiteGradient(const Eigen::VectorXd& gradient)
4072{
4073 return gradient.size() > 0 && gradient.allFinite();
4074}
4075
4076double productGaussianMean(double global_value, double global_variance,
4077 double local_value, double local_variance)
4078{
4079 if (global_variance <= local_variance) {
4080 const double ratio = global_variance / local_variance;
4081 return (global_value + local_value * ratio) / (1.0 + ratio);
4082 }
4083 const double ratio = local_variance / global_variance;
4084 return (global_value * ratio + local_value) / (1.0 + ratio);
4085}
4086
4087Eigen::VectorXd productGaussianMean(const Eigen::VectorXd& global_value,
4088 double global_variance,
4089 const Eigen::VectorXd& local_value,
4090 double local_variance)
4091{
4092 if (global_variance <= local_variance) {
4093 const double ratio = global_variance / local_variance;
4094 return (global_value + local_value * ratio) / (1.0 + ratio);
4095 }
4096 const double ratio = local_variance / global_variance;
4097 return (global_value * ratio + local_value) / (1.0 + ratio);
4098}
4099
4100double productGaussianVariance(double global_variance, double local_variance)
4101{
4102 if (global_variance <= local_variance) {
4103 return global_variance / (1.0 + global_variance / local_variance);
4104 }
4105 return local_variance / (1.0 + local_variance / global_variance);
4106}
4107
4108} // namespace
4109
4110bool precisionPoolEnergyGradient(double global_energy,
4111 const Eigen::VectorXd& global_gradient,
4112 double global_variance, double local_energy,
4113 const Eigen::VectorXd& local_gradient,
4114 double local_variance, double& pooled_energy,
4115 Eigen::VectorXd& pooled_gradient)
4116{
4117 const bool global_ok = std::isfinite(global_energy) &&
4118 finiteGradient(global_gradient) &&
4119 validPoolingVariance(global_variance);
4120 const bool local_ok = std::isfinite(local_energy) &&
4121 finiteGradient(local_gradient) &&
4122 validPoolingVariance(local_variance);
4123
4124 if (global_ok && local_ok) {
4125 if (global_variance == 0.0 && local_variance == 0.0) {
4126 if (global_energy != local_energy ||
4127 global_gradient.size() != local_gradient.size() ||
4128 !global_gradient.isApprox(local_gradient, 0.0)) {
4129 return false;
4130 }
4131 pooled_energy = global_energy;
4132 pooled_gradient = global_gradient;
4133 return true;
4134 }
4135 if (global_variance == 0.0) {
4136 pooled_energy = global_energy;
4137 pooled_gradient = global_gradient;
4138 } else if (local_variance == 0.0) {
4139 pooled_energy = local_energy;
4140 pooled_gradient = local_gradient;
4141 } else {
4142 pooled_energy = productGaussianMean(global_energy, global_variance,
4143 local_energy, local_variance);
4144 if (global_gradient.size() == local_gradient.size()) {
4145 pooled_gradient =
4146 productGaussianMean(global_gradient, global_variance,
4147 local_gradient, local_variance);
4148 } else if (global_variance <= local_variance) {
4149 pooled_gradient = global_gradient;
4150 } else {
4151 pooled_gradient = local_gradient;
4152 }
4153 }
4154 return std::isfinite(pooled_energy) && pooled_gradient.allFinite();
4155 }
4156
4157 if (global_ok) {
4158 pooled_energy = global_energy;
4159 pooled_gradient = global_gradient;
4160 return true;
4161 }
4162 if (local_ok) {
4163 pooled_energy = local_energy;
4164 pooled_gradient = local_gradient;
4165 return true;
4166 }
4167 return false;
4168}
4169
4170bool precisionPoolVariance(double global_variance, double local_variance,
4171 double& pooled_variance)
4172{
4173 const bool global_ok = validPoolingVariance(global_variance);
4174 const bool local_ok = validPoolingVariance(local_variance);
4175 if (global_ok && local_ok) {
4176 pooled_variance =
4177 (global_variance == 0.0 || local_variance == 0.0)
4178 ? 0.0
4179 : productGaussianVariance(global_variance, local_variance);
4180 return pooled_variance >= 0.0 && std::isfinite(pooled_variance);
4181 }
4182 if (global_ok) {
4183 pooled_variance = global_variance;
4184 return true;
4185 }
4186 if (local_ok) {
4187 pooled_variance = local_variance;
4188 return true;
4189 }
4190 return false;
4191}
4192
4193bool acceptTrustCertifiedProposal(
4194 GlobalLBFGSObjective& objective, const Eigen::VectorXd& accepted_positions,
4195 const std::function<bool()>& trust_at_current, int max_bisections,
4196 Eigen::VectorXd* rejected_positions,
4197 const std::function<bool(Eigen::VectorXd&)>& project_to_trust,
4198 const std::function<double()>& certified_step)
4199{
4200 if (rejected_positions) rejected_positions->resize(0);
4201 const Eigen::VectorXd proposed_positions = objective.positions();
4202 auto certified = [&]() {
4203 // Inner-loop certification guards against extrapolation by
4204 // checking that every chain image is inside the per-image GP
4205 // training envelope.
4206 return objective.stepAdmissible(accepted_positions,
4207 objective.positions()) &&
4208 (!trust_at_current || trust_at_current());
4209 };
4210 if (certified()) {
4211 if (shouldStopOieInnerAtCoordinateResolution(accepted_positions,
4212 proposed_positions)) {
4213 if (rejected_positions) *rejected_positions = proposed_positions;
4214 objective.setPositions(accepted_positions);
4215 (void)objective.refresh(false);
4216 return false;
4217 }
4218 return true;
4219 }
4220 auto recordRejectedPositions = [&](const Eigen::VectorXd& positions) {
4221 if (rejected_positions && rejected_positions->size() == 0) {
4222 *rejected_positions = positions;
4223 }
4224 };
4225 if (accepted_positions.size() != proposed_positions.size()) {
4226 recordRejectedPositions(proposed_positions);
4227 if (accepted_positions.size() == proposed_positions.size()) {
4228 objective.setPositions(accepted_positions);
4229 }
4230 (void)objective.refresh(false);
4231 return false;
4232 }
4233
4234 objective.setPositions(accepted_positions);
4235 (void)objective.refresh(false);
4236 if (!certified()) {
4237 recordRejectedPositions(accepted_positions);
4238 return false;
4239 }
4240
4241 Eigen::VectorXd best_positions = accepted_positions;
4242 bool have_certified_step = false;
4243 if (certified_step) {
4244 // Closed-form maximal certified step (TrustRadius::
4245 // certifiedLineStep, min over interior images): a single
4246 // Lipschitz-bound evaluation replaces the bisection below, at the
4247 // cost of being conservative (it may accept less than the true
4248 // trust-boundary alpha).
4249 const double alpha = std::clamp(certified_step(), 0.0, 1.0);
4250 if (alpha > 0.0) {
4251 const Eigen::VectorXd trial_positions =
4252 accepted_positions +
4253 alpha * (proposed_positions - accepted_positions);
4254 objective.setPositions(trial_positions);
4255 const bool trial_certified =
4256 objective.refresh(false) && certified();
4257 if (trial_certified && !shouldStopOieInnerAtCoordinateResolution(
4258 accepted_positions, trial_positions)) {
4259 best_positions = trial_positions;
4260 have_certified_step = true;
4261 } else if (!trial_certified) {
4262 recordRejectedPositions(trial_positions);
4263 }
4264 }
4265 } else {
4266 double lo = 0.0;
4267 double hi = 1.0;
4268 const int n_bisect = std::max(0, max_bisections);
4269 for (int iter = 0; iter < n_bisect; ++iter) {
4270 const double alpha = 0.5 * (lo + hi);
4271 const Eigen::VectorXd trial_positions =
4272 accepted_positions +
4273 alpha * (proposed_positions - accepted_positions);
4274 objective.setPositions(trial_positions);
4275 if (!objective.refresh(false)) {
4276 recordRejectedPositions(trial_positions);
4277 hi = alpha;
4278 continue;
4279 }
4280 if (!certified()) {
4281 recordRejectedPositions(trial_positions);
4282 hi = alpha;
4283 continue;
4284 }
4285 lo = alpha;
4286 best_positions = trial_positions;
4287 have_certified_step =
4288 alpha > 0.0 && !shouldStopOieInnerAtCoordinateResolution(
4289 accepted_positions, trial_positions);
4290 }
4291 }
4292 if (have_certified_step) {
4293 objective.setPositions(best_positions);
4294 (void)objective.refresh(false);
4295 return true;
4296 }
4297 if (project_to_trust) {
4298 Eigen::VectorXd projected_positions = proposed_positions;
4299 if (project_to_trust(projected_positions) &&
4300 projected_positions.size() == proposed_positions.size() &&
4301 !shouldStopOieInnerAtCoordinateResolution(accepted_positions,
4302 projected_positions)) {
4303 objective.setPositions(projected_positions);
4304 if (objective.refresh(false) && certified()) {
4305 return true;
4306 }
4307 recordRejectedPositions(projected_positions);
4308 }
4309 }
4310 recordRejectedPositions(proposed_positions);
4311 objective.setPositions(accepted_positions);
4312 (void)objective.refresh(false);
4313 return false;
4314}
4315
4316bool acceptPosteriorCertifiedProposal(
4317 GlobalLBFGSObjective& objective, const Eigen::VectorXd& accepted_positions,
4318 const std::function<bool()>& posterior_resolved_at_current,
4319 Eigen::VectorXd* rejected_positions)
4320{
4321 return acceptTrustCertifiedProposal(
4322 objective, accepted_positions, posterior_resolved_at_current,
4323 std::numeric_limits<double>::digits, rejected_positions);
4324}
4325
4326bool shouldProbeRejectedProposalVariance(bool step_certified, bool drift_break)
4327{
4328 return !step_certified && !drift_break;
4329}
4330
4331bool shouldLatchRejectedProposalAcquisition(bool step_certified, bool)
4332{
4333 return !step_certified;
4334}
4335
4336int selectAcceptedDriftCurrentChainPriority(bool step_certified,
4337 bool drift_break, int drift_image,
4338 int n_images) noexcept
4339{
4340 if (!step_certified || !drift_break) return -1;
4341 if (drift_image <= 0 || drift_image >= n_images - 1) return -1;
4342 return drift_image;
4343}
4344
4345bool isAcceptedDriftCurrentChainPriorityPending(
4346 int drift_image, int n_images, const std::vector<char>& image_evaluated,
4347 const std::vector<char>& image_observed_current) noexcept
4348{
4349 if (drift_image <= 0 || drift_image >= n_images - 1) return false;
4350 const auto contains = [drift_image](const std::vector<char>& mask) {
4351 return drift_image < static_cast<int>(mask.size()) &&
4352 mask[static_cast<std::size_t>(drift_image)] != 0;
4353 };
4354 return !contains(image_evaluated) && !contains(image_observed_current);
4355}
4356
4357bool cumulativeTrustTravelExceeded(
4358 const std::vector<double>& accumulated_travel,
4359 const std::vector<double>& proposed_step_travel, double trust_threshold)
4360{
4361 if (!(trust_threshold > 0.0) || !std::isfinite(trust_threshold))
4362 return false;
4363 const std::size_t count =
4364 std::min(accumulated_travel.size(), proposed_step_travel.size());
4365 for (std::size_t i = 0; i < count; ++i) {
4366 const double accumulated = accumulated_travel[i];
4367 const double step = proposed_step_travel[i];
4368 if (!(accumulated >= 0.0) || !std::isfinite(accumulated) ||
4369 !(step >= 0.0) || !std::isfinite(step)) {
4370 continue;
4371 }
4372 const double total = accumulated + step;
4373 if (!std::isfinite(total) ||
4374 gpr::numerics::exceedsThreshold(total, trust_threshold))
4375 return true;
4376 }
4377 return false;
4378}
4379
4380int selectUnobservedAcquisitionIndex(
4381 const std::vector<double>& scores, const std::vector<char>& eligible,
4382 const std::vector<Eigen::VectorXd>& positions,
4383 const gpr::Observation& training_obs, int current_idx)
4384{
4385 const int n = static_cast<int>(
4386 std::min({scores.size(), eligible.size(), positions.size()}));
4387 if (current_idx > 0 && current_idx < n && eligible[current_idx] &&
4388 !hasPosition(training_obs, positions[current_idx])) {
4389 return current_idx;
4390 }
4391
4392 int best_idx = -1;
4393 double best_score = -std::numeric_limits<double>::infinity();
4394 for (int i = 1; i < n; ++i) {
4395 if (!eligible[i]) continue;
4396 if (!std::isfinite(scores[i])) continue;
4397 if (positions[i].size() == 0) continue;
4398 if (hasPosition(training_obs, positions[i])) continue;
4399 if (gpr::numerics::clearlyGreater(scores[i], best_score)) {
4400 best_score = scores[i];
4401 best_idx = i;
4402 }
4403 }
4404 return best_idx > 0 ? best_idx : current_idx;
4405}
4406
4407double expectedImprovementScore(double mu, double mu_best, double sigma)
4408{
4409 return gpr::bo::expectedImprovementScore(mu, mu_best, sigma);
4410}
4411
4412int selectExpectedImprovementImage(const std::vector<double>& energies,
4413 const std::vector<double>& energy_variances,
4414 const std::vector<char>& eligible)
4415{
4416 const int n = static_cast<int>(
4417 std::min({energies.size(), energy_variances.size(), eligible.size()}));
4418 double mu_best = -std::numeric_limits<double>::infinity();
4419 for (int i = 1; i < n; ++i) {
4420 if (gpr::numerics::clearlyGreater(energies[i], mu_best)) {
4421 mu_best = energies[i];
4422 }
4423 }
4424 int best_idx = -1;
4425 double best_score = 0.0;
4426 for (int i = 1; i < n; ++i) {
4427 if (!eligible[i]) continue;
4428 const double sigma = std::sqrt(std::max(0.0, energy_variances[i]));
4429 const double score =
4430 expectedImprovementScore(energies[i], mu_best, sigma);
4431 if (gpr::numerics::clearlyGreater(score, best_score)) {
4432 best_score = score;
4433 best_idx = i;
4434 }
4435 }
4436 return best_idx;
4437}
4438
4439bool shouldStopOieInnerForExpectedImprovement(int accepted_inner_steps,
4440 int ei_image, double ei_score,
4441 double energy_variance_threshold)
4442{
4443 if (!(energy_variance_threshold >= 0.0)) return false;
4444 const double certified_ei_ceiling =
4445 std::sqrt(energy_variance_threshold / (2.0 * M_PI));
4446 return accepted_inner_steps > 0 && ei_image > 0 &&
4447 gpr::numerics::exceedsThreshold(ei_score, certified_ei_ceiling);
4448}
4449
4450ProposalAcquisitionTarget selectRejectedProposalAcquisitionTarget(
4451 const Eigen::VectorXd& proposal_positions, Eigen::Index image_dof,
4452 const std::vector<double>& scores, const std::vector<char>& eligible,
4453 const gpr::Observation& training_obs, int current_idx)
4454{
4455 ProposalAcquisitionTarget target;
4456 if (image_dof <= 0 || proposal_positions.size() == 0) return target;
4457 if (proposal_positions.size() % image_dof != 0) return target;
4458
4459 const int n_interior =
4460 static_cast<int>(proposal_positions.size() / image_dof);
4461 const int n = static_cast<int>(std::min(scores.size(), eligible.size()));
4462 auto proposalAt = [&](int image_idx) -> Eigen::VectorXd {
4463 if (image_idx <= 0 || image_idx > n_interior) {
4464 return Eigen::VectorXd();
4465 }
4466 const Eigen::Index offset =
4467 static_cast<Eigen::Index>(image_idx - 1) * image_dof;
4468 return proposal_positions.segment(offset, image_dof);
4469 };
4470 auto unobservedProposalAt = [&](int image_idx) {
4471 if (image_idx <= 0 || image_idx >= n) return Eigen::VectorXd();
4472 if (!eligible[image_idx]) return Eigen::VectorXd();
4473 Eigen::VectorXd positions = proposalAt(image_idx);
4474 if (positions.size() == 0) return Eigen::VectorXd();
4475 if (hasPosition(training_obs, positions)) return Eigen::VectorXd();
4476 return positions;
4477 };
4478
4479 Eigen::VectorXd current_positions = unobservedProposalAt(current_idx);
4480 if (current_positions.size() > 0) {
4481 target.image_index = current_idx;
4482 target.positions = std::move(current_positions);
4483 return target;
4484 }
4485
4486 double best_score = -std::numeric_limits<double>::infinity();
4487 for (int i = 1; i <= n_interior && i < n; ++i) {
4488 if (!std::isfinite(scores[i])) continue;
4489 Eigen::VectorXd positions = unobservedProposalAt(i);
4490 if (positions.size() == 0) continue;
4491 if (gpr::numerics::clearlyGreater(scores[i], best_score)) {
4492 best_score = scores[i];
4493 target.image_index = i;
4494 target.positions = std::move(positions);
4495 }
4496 }
4497 return target;
4498}
4499
4500ProposalAcquisitionTarget selectRestrictedVarianceAcquisitionTarget(
4501 const Eigen::VectorXd& proposal_positions, Eigen::Index image_dof,
4502 const std::vector<double>& posterior_energy_variance, double noise_variance,
4503 const gpr::Observation& training_obs)
4504{
4505 ProposalAcquisitionTarget target;
4506 if (image_dof <= 0 || proposal_positions.size() == 0) return target;
4507 if (proposal_positions.size() % image_dof != 0) return target;
4508
4509 const int n_interior =
4510 static_cast<int>(proposal_positions.size() / image_dof);
4511 const int n_var = static_cast<int>(posterior_energy_variance.size());
4512 double best_rank = -1.0;
4513 for (int i = 1; i <= n_interior && i < n_var; ++i) {
4514 const double variance = posterior_energy_variance[i];
4515 if (posteriorVarianceWithinNoiseFloor(variance, noise_variance)) {
4516 continue;
4517 }
4518 const Eigen::Index offset =
4519 static_cast<Eigen::Index>(i - 1) * image_dof;
4520 Eigen::VectorXd positions =
4521 proposal_positions.segment(offset, image_dof);
4522 if (positions.size() == 0 || hasPosition(training_obs, positions)) {
4523 continue;
4524 }
4525 const double rank = std::isfinite(variance)
4526 ? variance
4527 : std::numeric_limits<double>::infinity();
4528 if (gpr::numerics::clearlyGreater(rank, best_rank)) {
4529 best_rank = rank;
4530 target.image_index = i;
4531 target.positions = std::move(positions);
4532 }
4533 }
4534 return target;
4535}
4536
4537bool OiePendingBandAction::stage(const AcquisitionType acquisition,
4538 const Eigen::VectorXd& source_positions,
4539 const Eigen::VectorXd& trial_positions,
4540 const Eigen::Index image_dof)
4541{
4542 clear();
4543 if (acquisition != AcquisitionType::PSBAX || image_dof <= 0 ||
4544 source_positions.size() == 0 ||
4545 source_positions.size() != trial_positions.size() ||
4546 source_positions.size() % image_dof != 0 ||
4547 !source_positions.allFinite() || !trial_positions.allFinite() ||
4548 positionsCoincide(source_positions, trial_positions)) {
4549 return false;
4550 }
4551 source_positions_ = source_positions;
4552 trial_positions_ = trial_positions;
4553 image_dof_ = image_dof;
4554 return true;
4555}
4556
4557void OiePendingBandAction::clear()
4558{
4559 source_positions_.resize(0);
4560 trial_positions_.resize(0);
4561 image_dof_ = 0;
4562}
4563
4564bool OiePendingBandAction::active() const noexcept
4565{
4566 return image_dof_ > 0 && source_positions_.size() > 0 &&
4567 source_positions_.size() == trial_positions_.size() &&
4568 source_positions_.size() % image_dof_ == 0;
4569}
4570
4571bool OiePendingBandAction::sourceMatches(const Eigen::VectorXd& positions) const
4572{
4573 return active() && positionsCoincide(source_positions_, positions);
4574}
4575
4576const Eigen::VectorXd& OiePendingBandAction::sourcePositions() const noexcept
4577{
4578 return source_positions_;
4579}
4580
4581const Eigen::VectorXd& OiePendingBandAction::trialPositions() const noexcept
4582{
4583 return trial_positions_;
4584}
4585
4586Eigen::Index OiePendingBandAction::imageDof() const noexcept
4587{
4588 return image_dof_;
4589}
4590
4591OieBandActionAcquisition selectOieBandActionAcquisition(
4592 const Eigen::VectorXd& action_positions, const Eigen::Index image_dof,
4593 const EigenMatrix& posterior_covariance,
4594 const gpr::Observation& training_obs, const double noise_variance)
4595{
4596 OieBandActionAcquisition result;
4597 if (image_dof <= 0 || action_positions.size() == 0 ||
4598 action_positions.size() % image_dof != 0 ||
4599 !action_positions.allFinite()) {
4600 return result;
4601 }
4602 const Eigen::Index query_count = action_positions.size() / image_dof;
4603 const Eigen::Index expected_channels = query_count * (image_dof + 1);
4604 if (posterior_covariance.rows() != expected_channels ||
4605 posterior_covariance.cols() != expected_channels ||
4606 !posterior_covariance.allFinite()) {
4607 return result;
4608 }
4609
4610 std::vector<Eigen::Index> target_queries(
4611 static_cast<std::size_t>(query_count));
4612 std::iota(target_queries.begin(), target_queries.end(), Eigen::Index{0});
4613 double best_reduction = -std::numeric_limits<double>::infinity();
4614 for (Eigen::Index query = 0; query < query_count; ++query) {
4615 const Eigen::VectorXd positions =
4616 action_positions.segment(query * image_dof, image_dof);
4617 if (hasPosition(training_obs, positions)) continue;
4618 const auto reduction = gpr::jointObservationForceVarianceReduction(
4619 posterior_covariance, query_count, image_dof, query, target_queries,
4620 noise_variance);
4621 if (!reduction || !std::isfinite(reduction->variance_reduction) ||
4622 reduction->variance_reduction < 0.0 ||
4623 reduction->variance_reduction <= best_reduction) {
4624 continue;
4625 }
4626 best_reduction = reduction->variance_reduction;
4627 result.target.image_index = static_cast<int>(query + 1);
4628 result.target.positions = positions;
4629 result.force_variance_reduction = reduction->variance_reduction;
4630 result.target_force_variance = reduction->target_variance;
4631 }
4632 return result;
4633}
4634
4635OieInnerProposalDecision decideOieInnerProposal(
4636 const OieBandPosteriorReadiness& readiness,
4637 const Eigen::VectorXd& proposal_positions, Eigen::Index image_dof,
4638 const gpr::Observation& training_obs)
4639{
4640 OieInnerProposalDecision decision;
4641 if (readiness.resolved()) return decision;
4642
4643 decision.accept = false;
4644 if (readiness.acquisition_image <= 0) return decision;
4645
4646 const std::vector<char> eligible(readiness.per_image_deficit.size(), 1);
4647 decision.acquisition = selectRejectedProposalAcquisitionTarget(
4648 proposal_positions, image_dof, readiness.per_image_deficit, eligible,
4649 training_obs, readiness.acquisition_image);
4650 return decision;
4651}
4652
4653bool usesClassicOieRelaxation(AcquisitionType acquisition) noexcept
4654{
4655 return acquisition == AcquisitionType::MaxVariance;
4656}
4657
4658bool shouldSkipOieInnerForPendingAcquisition(
4659 const ProposalAcquisitionTarget& pending_acquisition,
4660 bool candidate_applied, int current_band_acquisition_image,
4661 bool force_posterior_unresolved, bool activation_stencil_pending)
4662{
4663 return static_cast<bool>(pending_acquisition) || candidate_applied ||
4664 current_band_acquisition_image > 0 || force_posterior_unresolved ||
4665 activation_stencil_pending;
4666}
4667
4668bool shouldPreemptOieInnerForPosteriorAction(
4669 AcquisitionType acquisition, bool ci_active, bool force_posterior_resolved,
4670 const ProposalAcquisitionTarget& posterior_action) noexcept
4671{
4672 return acquisition == AcquisitionType::PSBAX && ci_active &&
4673 !force_posterior_resolved && static_cast<bool>(posterior_action);
4674}
4675
4676bool shouldSkipOieInnerForUnresolvedForcePosterior(
4677 bool force_resolved, int current_band_acquisition_image) noexcept
4678{
4679 // When acquisition_image > 0 the pending-acquisition path already skips
4680 // for a joint current-chain row. Assess only leaves force_resolved false
4681 // when an unobserved interior still exceeds the joint ceiling; if that
4682 // target is missing, skip so the planner can still route PS-BAX / recovery
4683 // without deterministic GP motion on an uncertified field.
4684 return !force_resolved && current_band_acquisition_image <= 0;
4685}
4686
4687namespace {
4688
4689double reparametrizationSupportScore(
4690 int image_index, const Eigen::VectorXd& positions,
4691 const std::vector<ReparametrizationSupportMetric>& support_metrics)
4692{
4693 double score =
4694 support_metrics.empty() ? std::numeric_limits<double>::infinity() : 0.0;
4695 for (const auto& metric: support_metrics) {
4696 double ratio = std::numeric_limits<double>::infinity();
4697 if (metric.limit >= 0.0 && std::isfinite(metric.limit) &&
4698 metric.evaluate) {
4699 const double value = metric.evaluate(image_index, positions);
4700 if (value >= 0.0 && std::isfinite(value)) {
4701 if (metric.limit > 0.0) {
4702 ratio = value / metric.limit;
4703 } else if (value == 0.0) {
4704 ratio = 0.0;
4705 }
4706 }
4707 }
4708 score = std::max(score, ratio);
4709 if (!std::isfinite(score)) break;
4710 }
4711 return score;
4712}
4713
4714} // namespace
4715
4716ProposalAcquisitionTarget selectUnobservedReparametrizationTarget(
4717 const std::vector<Eigen::VectorXd>& proposed_positions,
4718 const std::vector<ReparametrizationSupportMetric>& support_metrics,
4719 const ReparametrizationObservationPredicate& is_observed)
4720{
4721 ProposalAcquisitionTarget target;
4722 if (proposed_positions.size() <= 2) return target;
4723
4724 double largest_score = -std::numeric_limits<double>::infinity();
4725 for (std::size_t i = 1; i + 1 < proposed_positions.size(); ++i) {
4726 const Eigen::VectorXd& positions = proposed_positions[i];
4727 if (positions.size() == 0) continue;
4728 if (is_observed && is_observed(static_cast<int>(i), positions)) {
4729 continue;
4730 }
4731
4732 const double score = reparametrizationSupportScore(
4733 static_cast<int>(i), positions, support_metrics);
4734 if (!target || !std::isfinite(score) || score > largest_score) {
4735 target.image_index = static_cast<int>(i);
4736 target.positions = positions;
4737 largest_score = score;
4738 if (!std::isfinite(score)) break;
4739 }
4740 }
4741 return target;
4742}
4743
4744ProposalAcquisitionTarget selectUnobservedBandProposalTarget(
4745 const std::vector<Eigen::VectorXd>& proposed_positions, int preferred_image,
4746 const std::vector<ReparametrizationSupportMetric>& support_metrics,
4747 const ReparametrizationObservationPredicate& is_observed)
4748{
4749 ProposalAcquisitionTarget preferred;
4750 if (preferred_image > 0 &&
4751 preferred_image + 1 < static_cast<int>(proposed_positions.size())) {
4752 const Eigen::VectorXd& positions =
4753 proposed_positions[static_cast<std::size_t>(preferred_image)];
4754 if (positions.size() > 0 &&
4755 !(is_observed && is_observed(preferred_image, positions))) {
4756 preferred.image_index = preferred_image;
4757 preferred.positions = positions;
4758 return preferred;
4759 }
4760 }
4761 return selectUnobservedReparametrizationTarget(
4762 proposed_positions, support_metrics, is_observed);
4763}
4764
4765ProposalAcquisitionTarget selectUnsupportedReparametrizationTarget(
4766 const std::vector<Eigen::VectorXd>& proposed_positions,
4767 const std::vector<ReparametrizationSupportMetric>& support_metrics)
4768{
4769 ProposalAcquisitionTarget target;
4770 if (proposed_positions.size() <= 2) return target;
4771
4772 double largest_relative_violation =
4773 -std::numeric_limits<double>::infinity();
4774 for (std::size_t i = 1; i + 1 < proposed_positions.size(); ++i) {
4775 const Eigen::VectorXd& positions = proposed_positions[i];
4776 if (positions.size() == 0) continue;
4777
4778 const double relative_violation = reparametrizationSupportScore(
4779 static_cast<int>(i), positions, support_metrics);
4780 if (relative_violation <= 1.0) continue;
4781
4782 if (!target || !std::isfinite(relative_violation) ||
4783 relative_violation > largest_relative_violation) {
4784 target.image_index = static_cast<int>(i);
4785 target.positions = positions;
4786 largest_relative_violation = relative_violation;
4787 if (!std::isfinite(relative_violation)) break;
4788 }
4789 }
4790 return target;
4791}
4792
4793bool hasMeasuredReparametrizationNeed(const NEBPath& path, int protected_image)
4794{
4795 if (path.numImages() <= 2) return false;
4796
4797 NEBPath measured = path;
4798 for (int i = 0; i < measured.numImages(); ++i) {
4799 const Image& image = measured.image(i);
4800 if (!std::isfinite(image.energy) || !image.positions.allFinite()) {
4801 return false;
4802 }
4803 if (i > 0 && i < measured.numImages() - 1 &&
4804 (!image.evaluated ||
4805 image.gradient.size() != image.positions.size() ||
4806 !image.gradient.allFinite())) {
4807 return false;
4808 }
4809 }
4810 measured.computeNEBForces();
4811
4812 double max_parallel_spring = 0.0;
4813 double max_perpendicular_force = 0.0;
4814 bool has_unprotected_image = false;
4815 for (int i = 1; i < measured.numImages() - 1; ++i) {
4816 if (i == protected_image || measured.image(i).is_climbing) continue;
4817 const Eigen::VectorXd tangent = measured.tangentAt(i);
4818 const Eigen::VectorXd& force = measured.nebForce(i);
4819 if (tangent.size() != force.size() || !tangent.allFinite() ||
4820 !force.allFinite()) {
4821 return false;
4822 }
4823 const double parallel = force.dot(tangent);
4824 max_parallel_spring = std::max(max_parallel_spring, std::abs(parallel));
4825 max_perpendicular_force = std::max(max_perpendicular_force,
4826 (force - parallel * tangent).norm());
4827 has_unprotected_image = true;
4828 }
4829 return has_unprotected_image &&
4830 max_parallel_spring > max_perpendicular_force;
4831}
4832
4833bool shouldLaunchFixedPointReparametrization(
4834 const NEBPath& path, const std::vector<Eigen::VectorXd>& proposed_positions,
4835 const std::vector<ReparametrizationSupportMetric>& support_metrics,
4836 int protected_image)
4837{
4838 if (!hasMeasuredReparametrizationNeed(path, protected_image) ||
4839 proposed_positions.size() !=
4840 static_cast<std::size_t>(path.numImages())) {
4841 return false;
4842 }
4843
4844 bool proposal_moves_band = false;
4845 for (int i = 1; i < path.numImages() - 1; ++i) {
4846 const Eigen::VectorXd& proposed =
4847 proposed_positions[static_cast<std::size_t>(i)];
4848 if (proposed.size() != path.image(i).positions.size() ||
4849 !proposed.allFinite()) {
4850 return false;
4851 }
4852 proposal_moves_band =
4853 proposal_moves_band ||
4854 !positionsCoincide(path.image(i).positions, proposed);
4855 }
4856 return proposal_moves_band && !selectUnsupportedReparametrizationTarget(
4857 proposed_positions, support_metrics);
4858}
4859
4860ProposalAcquisitionTarget selectUnsupportedReparametrizationTarget(
4861 const std::vector<Eigen::VectorXd>& proposed_positions,
4862 double trust_threshold,
4863 const ReparametrizationTrustDistance& distance_to_training)
4864{
4865 return selectUnsupportedReparametrizationTarget(
4866 proposed_positions, {{trust_threshold, distance_to_training}});
4867}
4868
4869ProposalAcquisitionTarget selectUnsupportedReparametrizationTarget(
4870 const std::vector<Eigen::VectorXd>& proposed_positions,
4871 const gpr::Observation& training_obs, const gpr::TrustRadius& trust,
4872 double trust_threshold)
4873{
4874 return selectUnsupportedReparametrizationTarget(
4875 proposed_positions, trust_threshold,
4876 [&](int, const Eigen::VectorXd& positions) {
4877 if (hasPosition(training_obs, positions)) return 0.0;
4878 if (training_obs.R.rows() == 0 ||
4879 training_obs.R.cols() != positions.size()) {
4880 return std::numeric_limits<double>::infinity();
4881 }
4882 return trust.distanceToTraining(positions);
4883 });
4884}
4885
4886int findRestorableObservationRow(const gpr::Observation& obs,
4887 const Image& image)
4888{
4889 const int observed_row = detail::findPositionIndex(obs, image.positions);
4890 if (observed_row < 0 || observed_row >= obs.E.rows() ||
4891 observed_row >= obs.G.rows() || obs.E.cols() <= 0 ||
4892 obs.G.cols() != image.positions.size()) {
4893 return -1;
4894 }
4895 return observed_row;
4896}
4897
4898bool refreshOieImage(Image& image, const gpr::Observation& observations,
4899 bool preserve_evaluated,
4900 const std::function<void(Image&)>& predict)
4901{
4902 if (preserve_evaluated && image.evaluated) return true;
4903 if (preserve_evaluated &&
4904 restoreObservedImageIfPresent(observations, image))
4905 return true;
4906 predict(image);
4907 image.evaluated = false;
4908 return std::isfinite(image.energy) && image.gradient.allFinite();
4909}
4910
4911bool restoreObservedImageIfPresent(const gpr::Observation& obs, Image& image)
4912{
4913 const int observed_row = findRestorableObservationRow(obs, image);
4914 if (observed_row < 0) return false;
4915 image.energy = obs.E(observed_row, 0);
4916 image.gradient = obs.G.row(observed_row).transpose();
4917 image.evaluated = true;
4918 return true;
4919}
4920
4921bool restoreObservedImagesAndRefreshForces(
4922 const gpr::Observation& obs, NEBPath& path,
4923 std::vector<char>& image_observed_current,
4924 std::vector<char>& image_evaluated)
4925{
4926 const int n_images = path.numImages();
4927 image_observed_current.assign(n_images, 0);
4928 image_evaluated.assign(n_images, 0);
4929
4930 bool restored_any = false;
4931 for (int i = 0; i < n_images; ++i) {
4932 if (restoreObservedImageIfPresent(obs, path.image(i))) {
4933 image_observed_current[i] = 1;
4934 restored_any = true;
4935 }
4936 image_evaluated[i] = path.image(i).evaluated ? 1 : 0;
4937 }
4938 if (restored_any) {
4939 path.computeNEBForces();
4940 }
4941 return restored_any;
4942}
4943
4954bool measuredClimbRefutesHandover(const NEBPath& path, int candidate_idx,
4955 int incumbent_idx,
4956 const OieClimbingEnergyChange& climb_change)
4957{
4958 const int n = path.numImages();
4959 if (!climb_change || candidate_idx <= 0 || candidate_idx >= n - 1 ||
4960 incumbent_idx <= 0 || incumbent_idx >= n - 1 ||
4961 candidate_idx == incumbent_idx) {
4962 return false;
4963 }
4964 const Image& candidate = path.image(candidate_idx);
4965 const Image& incumbent = path.image(incumbent_idx);
4966 if (!candidate.evaluated || !incumbent.evaluated ||
4967 !std::isfinite(candidate.energy) || !std::isfinite(incumbent.energy)) {
4968 return false;
4969 }
4970 const double candidate_change = climb_change(path, candidate_idx);
4971 const double incumbent_change = climb_change(path, incumbent_idx);
4972 if (!std::isfinite(candidate_change) || !std::isfinite(incumbent_change)) {
4973 return false;
4974 }
4975 return candidate.energy + candidate_change <=
4976 incumbent.energy + incumbent_change;
4977}
4978
4979double oieClimbingStepEnergyChange(const NEBPath& path, int image_idx,
4980 ActiveLearningSession& session,
4981 bool project_rotations, double radius)
4982{
4983 const double nan = std::numeric_limits<double>::quiet_NaN();
4984 if (image_idx <= 0 || image_idx >= path.numImages() - 1) return nan;
4985 const Image& image = path.image(image_idx);
4986 const Eigen::Index dof = image.positions.size();
4987 if (!image.evaluated || dof == 0 || dof % 3 != 0 ||
4988 image.gradient.size() != dof || !image.gradient.allFinite() ||
4989 !image.positions.allFinite() ||
4990 !(std::isfinite(radius) && radius > 0.0))
4991 return nan;
4992 gpr::Observation probe;
4993 probe.R.resize(1, dof);
4994 probe.R.row(0) = image.positions.transpose();
4995 // The physical subspace: the complement of the rigid motions.
4996 const Eigen::MatrixXd rigid =
4997 dimer::rigid_motion_basis(probe.R, project_rotations);
4998 Eigen::MatrixXd Q;
4999 if (rigid.cols() > 0 && rigid.cols() < dof) {
5000 Eigen::HouseholderQR<Eigen::MatrixXd> qr(rigid);
5001 const Eigen::MatrixXd full = qr.householderQ();
5002 Q = full.rightCols(dof - rigid.cols());
5003 } else if (rigid.cols() == 0) {
5004 Q = Eigen::MatrixXd::Identity(dof, dof);
5005 } else {
5006 return nan;
5007 }
5008 auto model = session.acquireGlobalModel();
5009 gpr::GaussianProcessRegression::PreparedHssvdHessianVector prepared;
5010 const bool have_prepared =
5011 model.gp().prepareMeanHessianVectorHssvd(probe.R, prepared);
5012 Eigen::MatrixXd HQ;
5013 const bool have_block =
5014 have_prepared &&
5015 model.gp().applyMeanHessianBlockHssvd(prepared, Q, HQ) &&
5016 HQ.rows() == dof && HQ.cols() == Q.cols() && HQ.allFinite();
5017 if (!have_block) {
5018 HQ.resize(dof, Q.cols());
5019 for (Eigen::Index c = 0; c < Q.cols(); ++c) {
5020 Eigen::VectorXd hv;
5021 const Eigen::VectorXd q = Q.col(c);
5022 const bool ok =
5023 have_prepared
5024 ? model.gp().applyMeanHessianVectorHssvd(prepared, q, hv)
5025 : model.gp().calculateMeanHessianVectorDispatched(probe.R,
5026 q, hv);
5027 if (!ok || hv.size() != dof || !hv.allFinite()) return nan;
5028 HQ.col(c) = hv;
5029 }
5030 }
5031 Eigen::MatrixXd Hsub = Q.transpose() * HQ;
5032 Hsub = (0.5 * (Hsub + Hsub.transpose())).eval();
5033 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(Hsub);
5034 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0 ||
5035 !(es.eigenvalues()(0) < 0.0))
5036 return nan;
5037 // The climbing step of applyOieMeasuredClimbingImageStep, and the change
5038 // the unmodified quadratic model gives along it.
5039 const gpr::optim::SpectralTrustRegionStep solved =
5041 es.eigenvalues(), Eigen::MatrixXd(Q * es.eigenvectors()), 0,
5042 Eigen::VectorXd(-image.gradient), radius, {});
5043 if (!solved.valid || solved.step.size() != dof) return nan;
5044 const Eigen::VectorXd reduced = Q.transpose() * solved.step;
5045 return image.gradient.dot(solved.step) +
5046 0.5 * solved.step.dot(HQ * reduced);
5047}
5048
5049bool hasTrueClimbingImageHandoverCertificate(
5050 const NEBPath& path, int candidate_idx, int incumbent_idx,
5051 const OieClimbingEnergyChange& climb_change)
5052{
5053 if (candidate_idx <= 0 || candidate_idx >= path.numImages() - 1) {
5054 return false;
5055 }
5056 const auto& candidate = path.image(candidate_idx);
5057 const auto& left = path.image(candidate_idx - 1);
5058 const auto& right = path.image(candidate_idx + 1);
5059 if (!candidate.evaluated || !left.evaluated || !right.evaluated ||
5060 !std::isfinite(candidate.energy) || !std::isfinite(left.energy) ||
5061 !std::isfinite(right.energy)) {
5062 return false;
5063 }
5064 // Measured energy ordering identifies the peak that must climb. Its
5065 // perpendicular force belongs to relaxation and terminal convergence,
5066 // except through the saddle energy its climb predicts.
5067 return candidate.energy > left.energy && candidate.energy > right.energy &&
5068 isTruePesSaddleEnergyCandidate(
5069 candidate.energy, path.image(0).energy,
5070 path.image(path.numImages() - 1).energy) &&
5071 !measuredClimbRefutesHandover(path, candidate_idx, incumbent_idx,
5072 climb_change);
5073}
5074
5075void refreshOieClimbingImageAfterRefit(
5076 const GPNEBConfig& config, NEBPath& path, bool ci_active,
5077 int posterior_candidate_idx, int previous_ci_idx, int protected_ci_idx,
5078 const std::vector<double>& posterior_energy_variance,
5079 double variance_ceiling, const OieClimbingEnergyChange& climb_change)
5080{
5081 const int candidate_after_refit =
5082 protected_ci_idx > 0 ? protected_ci_idx
5083 : previous_ci_idx > 0 && posterior_candidate_idx != previous_ci_idx &&
5084 !hasTrueClimbingImageHandoverCertificate(
5085 path, posterior_candidate_idx, previous_ci_idx,
5086 climb_change)
5087 ? previous_ci_idx
5088 : posterior_candidate_idx;
5089 refreshOieClimbingImageMarkerFromPosteriorCandidate(
5090 ci_active, path, candidate_after_refit, posterior_energy_variance,
5091 config.ucb_kappa, variance_ceiling,
5092 protected_ci_idx > 0 ? protected_ci_idx : previous_ci_idx);
5093}
5094
5095OieCurrentObservationState restoreOieCurrentObservationsAndMarker(
5096 const gpr::Observation& obs, NEBPath& path, bool ci_active,
5097 int posterior_candidate_idx, int certified_ci_idx,
5098 const std::vector<double>& posterior_energy_variance,
5099 double confidence_width, double variance_ceiling,
5100 std::vector<char>& image_observed_current,
5101 std::vector<char>& image_evaluated, bool require_true_handover_certificate,
5102 int protected_ci_idx, const OieClimbingEnergyChange& climb_change)
5103{
5104 OieCurrentObservationState state;
5105 state.restored_current_observations = restoreObservedImagesAndRefreshForces(
5106 obs, path, image_observed_current, image_evaluated);
5107 if (ci_active) {
5108 int refresh_candidate_idx = posterior_candidate_idx;
5109 int refresh_previous_idx = certified_ci_idx;
5110 const bool retain_protected_ci =
5111 protected_ci_idx > 0 && protected_ci_idx < path.numImages() - 1;
5112 const bool candidate_changes_marker =
5113 certified_ci_idx > 0 && posterior_candidate_idx != certified_ci_idx;
5114 if (retain_protected_ci) {
5115 refresh_candidate_idx = protected_ci_idx;
5116 refresh_previous_idx = protected_ci_idx;
5117 } else if (require_true_handover_certificate &&
5118 candidate_changes_marker &&
5119 !hasTrueClimbingImageHandoverCertificate(
5120 path, posterior_candidate_idx, certified_ci_idx,
5121 climb_change)) {
5122 refresh_candidate_idx = certified_ci_idx;
5123 }
5124 refreshOieClimbingImageMarkerFromPosteriorCandidate(
5125 ci_active, path, refresh_candidate_idx, posterior_energy_variance,
5126 confidence_width, variance_ceiling, refresh_previous_idx);
5127 path.computeNEBForces();
5128 }
5129 state.ci_idx =
5130 selectOieClimbingImageIndex(ci_active, path, posterior_energy_variance,
5131 confidence_width, variance_ceiling);
5132 return state;
5133}
5134
5135bool oieClimbingImageActivationCertificate(bool band_force_gate_ready,
5136 bool saddle_exists) noexcept
5137{
5138 // Canonical activation: the band is roughly relaxed (eOn force gate)
5139 // and the surrogate shows an interior maximum. Activation is cheap and
5140 // self-correcting (the climbing marker reassigns every outer), so the
5141 // rigor lives on the ACCEPT path (force tolerance, mountain-pass,
5142 // band-maximum, path ceiling, adjacent-perpendicular MEP certificate).
5143 // Peak-confidence, triplet-at-current-geometry, and band-variance
5144 // conjuncts starve activation on a moving band: a physically converged
5145 // system (CI true force under tolerance, barrier in the reference
5146 // range) sat unactivated for whole runs while the candidate index
5147 // alternated between two competing peaks and the triplet rows went
5148 // stale each refit.
5149 return band_force_gate_ready && saddle_exists;
5150}
5151
5152OieClimbingImageActivationState updateOieClimbingImageActivation(
5153 const GPNEBConfig& config, NEBPath& path, bool ci_active,
5154 const std::vector<double>& posterior_energy_variance,
5155 double confidence_width, double variance_ceiling, int certified_ci_idx,
5156 bool band_force_gate_ready)
5157{
5158 OieClimbingImageActivationState state;
5159 state.ci_active = ci_active;
5160 for (int i = 0; i < path.numImages(); ++i) {
5161 if (i < static_cast<int>(posterior_energy_variance.size())) {
5162 path.image(i).posterior_variance = posterior_energy_variance[i];
5163 }
5164 }
5165 const bool retain_certified_ci = ci_active && certified_ci_idx > 0 &&
5166 certified_ci_idx < path.numImages() - 1 &&
5167 path.image(certified_ci_idx).evaluated &&
5168 path.image(certified_ci_idx).is_climbing;
5169 if (retain_certified_ci) {
5170 state.ci_idx = certified_ci_idx;
5171 path.computeNEBForces();
5172 return state;
5173 }
5174 const int activation_candidate_idx = selectOieClimbingImageIndex(
5175 /*ci_active=*/false, path, posterior_energy_variance, confidence_width,
5176 variance_ceiling);
5177 const bool posterior_peak_confident = detail::ciPosteriorConfident(
5178 path, activation_candidate_idx, confidence_width);
5179 const bool local_triplet_evaluated =
5180 oieActivationCandidateTripletEvaluated(path, activation_candidate_idx);
5181 bool saddle_exists = false;
5182 if (!ci_active && config.climbing_image && activation_candidate_idx > 0) {
5183 std::vector<double> energies(static_cast<std::size_t>(path.numImages()),
5184 0.0);
5185 for (int i = 0; i < path.numImages(); ++i)
5186 energies[static_cast<std::size_t>(i)] = path.image(i).energy;
5187 saddle_exists = oie::saddleExists(energies);
5188 }
5189 double max_band_posterior_variance = 0.0;
5190 for (int i = 1; i < path.numImages() - 1; ++i) {
5191 if (i >= static_cast<int>(posterior_energy_variance.size()) ||
5192 !std::isfinite(posterior_energy_variance[i]) ||
5193 posterior_energy_variance[i] < 0.0) {
5194 max_band_posterior_variance =
5195 std::numeric_limits<double>::infinity();
5196 break;
5197 }
5198 max_band_posterior_variance =
5199 std::max(max_band_posterior_variance, posterior_energy_variance[i]);
5200 }
5201 // Resolved means resolved at any band length: the absolute bar, plus a
5202 // spread test the design density cannot flatter. See
5203 // posteriorVarianceResolvedAcrossBand.
5204 std::vector<double> per_image_var;
5205 per_image_var.reserve(static_cast<std::size_t>(path.numImages()));
5206 for (int i = 0; i < path.numImages(); ++i) {
5207 per_image_var.push_back(path.image(i).posterior_variance);
5208 }
5209 const bool band_posterior_resolved = posteriorVarianceResolvedAcrossBand(
5210 max_band_posterior_variance, medianPositive(per_image_var),
5211 variance_ceiling, config.variance_spread_factor);
5212 const bool activation_certified = oieClimbingImageActivationCertificate(
5213 band_force_gate_ready, saddle_exists);
5214 if (!ci_active && config.climbing_image && !activation_certified) {
5215 neb_log() << "[oie-activation] cand=" << activation_candidate_idx
5216 << " force_gate=" << band_force_gate_ready
5217 << " peak_conf=" << posterior_peak_confident
5218 << " triplet=" << local_triplet_evaluated
5219 << " saddle=" << saddle_exists
5220 << " band_res=" << band_posterior_resolved
5221 << " max_band_var=" << max_band_posterior_variance
5222 << " ceiling=" << variance_ceiling << std::endl;
5223 }
5224 if (activation_certified) {
5225 state.ci_active = true;
5226 refreshOieClimbingImageMarker(state.ci_active, path,
5227 posterior_energy_variance,
5228 confidence_width, variance_ceiling);
5229 path.computeNEBForces();
5230 }
5231 state.ci_idx = selectOieClimbingImageIndex(
5232 state.ci_active, path, posterior_energy_variance, confidence_width,
5233 variance_ceiling);
5234 return state;
5235}
5236
5237bool posteriorCertifiesCurrentImage(bool ci_active, int ci_idx, int image_idx,
5238 double neb_force, double variance,
5239 double variance_threshold, double conv_tol)
5240{
5241 if (ci_active && image_idx == ci_idx) return false;
5242 if (!(std::isfinite(conv_tol) && conv_tol >= 0.0)) return false;
5243 if (!(std::isfinite(neb_force) && neb_force < conv_tol)) return false;
5244 if (!(variance_threshold > 0.0 && std::isfinite(variance_threshold))) {
5245 return false;
5246 }
5247 return posteriorVarianceConverged(variance, variance_threshold);
5248}
5249
5250bool shouldStartTerminalSweep(double relaxed_gp_force, double max_chain_var,
5251 double uncertainty_threshold,
5252 bool has_true_force_eval,
5253 double max_true_force_eval, double conv_tol,
5254 bool ci_force_confident,
5255 bool ci_only_convergence_active)
5256{
5257 if (!(std::isfinite(conv_tol) && conv_tol >= 0.0)) return false;
5258 const bool relaxed_force_ok =
5259 std::isfinite(relaxed_gp_force) && relaxed_gp_force < conv_tol;
5260 if (!ci_force_confident && !relaxed_force_ok) {
5261 return false;
5262 }
5263 // A local posterior certificate at the saddle can arm the full-band sweep
5264 // while non-CI images carry large forces or variances when whole-band
5265 // convergence semantics apply. CI-only convergence uses its own true-PES
5266 // saddle and adjacent-perpendicular certificates.
5267 if (ci_force_confident && ci_only_convergence_active) return false;
5268 if (ci_force_confident) return true;
5269 if (!ci_force_confident &&
5270 !posteriorVarianceConverged(max_chain_var, uncertainty_threshold)) {
5271 return false;
5272 }
5273 if (!has_true_force_eval) return true;
5274 return std::isfinite(max_true_force_eval) && max_true_force_eval < conv_tol;
5275}
5276
5277const char* oieOracleSelectionArmName(OieOracleSelectionArm arm) noexcept
5278{
5279 switch (arm) {
5280 case OieOracleSelectionArm::None:
5281 return "none";
5282 case OieOracleSelectionArm::ActivationPriority:
5283 return "activation";
5284 case OieOracleSelectionArm::RejectedProposal:
5285 return "rejected";
5286 case OieOracleSelectionArm::CurrentChainPriority:
5287 return "current_chain";
5288 case OieOracleSelectionArm::CertificateDeficit:
5289 return "certificate_deficit";
5290 case OieOracleSelectionArm::AcceptedDrift:
5291 return "accepted_drift";
5292 case OieOracleSelectionArm::PredictionKernelDrift:
5293 return "prediction_kernel_drift";
5294 case OieOracleSelectionArm::FrozenSweep:
5295 return "frozen_sweep";
5296 case OieOracleSelectionArm::CurrentClimbingImage:
5297 return "current_ci";
5298 case OieOracleSelectionArm::Variance:
5299 return "variance";
5300 case OieOracleSelectionArm::FirstUnobserved:
5301 return "first_unobserved";
5302 case OieOracleSelectionArm::RecoveryModelGrowth:
5303 return "recovery_growth";
5304 case OieOracleSelectionArm::TPE:
5305 return "tpe";
5306 case OieOracleSelectionArm::PSBAX:
5307 return "psbax";
5308 case OieOracleSelectionArm::ExpectedImprovement:
5309 return "ei";
5310 }
5311 return "unknown";
5312}
5313
5314bool oieSelectionArmUsesPosteriorAcquisition(OieOracleSelectionArm arm) noexcept
5315{
5316 switch (arm) {
5317 case OieOracleSelectionArm::Variance:
5318 case OieOracleSelectionArm::FirstUnobserved:
5319 case OieOracleSelectionArm::TPE:
5320 case OieOracleSelectionArm::PSBAX:
5321 case OieOracleSelectionArm::ExpectedImprovement:
5322 return true;
5323 case OieOracleSelectionArm::None:
5324 case OieOracleSelectionArm::ActivationPriority:
5325 case OieOracleSelectionArm::RejectedProposal:
5326 case OieOracleSelectionArm::CurrentChainPriority:
5327 case OieOracleSelectionArm::CertificateDeficit:
5328 case OieOracleSelectionArm::AcceptedDrift:
5329 case OieOracleSelectionArm::PredictionKernelDrift:
5330 case OieOracleSelectionArm::FrozenSweep:
5331 case OieOracleSelectionArm::CurrentClimbingImage:
5332 case OieOracleSelectionArm::RecoveryModelGrowth:
5333 return false;
5334 }
5335 return false;
5336}
5337
5338namespace {
5339
5340bool oieSelectionArmRequestsForceQuality(OieOracleSelectionArm arm)
5341{
5342 switch (arm) {
5343 case OieOracleSelectionArm::ActivationPriority:
5344 case OieOracleSelectionArm::RejectedProposal:
5345 case OieOracleSelectionArm::CurrentChainPriority:
5346 case OieOracleSelectionArm::CertificateDeficit:
5347 case OieOracleSelectionArm::AcceptedDrift:
5348 case OieOracleSelectionArm::PredictionKernelDrift:
5349 case OieOracleSelectionArm::FrozenSweep:
5350 case OieOracleSelectionArm::CurrentClimbingImage:
5351 case OieOracleSelectionArm::RecoveryModelGrowth:
5352 case OieOracleSelectionArm::TPE:
5353 case OieOracleSelectionArm::PSBAX:
5354 case OieOracleSelectionArm::ExpectedImprovement:
5355 return true;
5356 case OieOracleSelectionArm::None:
5357 case OieOracleSelectionArm::Variance:
5358 case OieOracleSelectionArm::FirstUnobserved:
5359 return false;
5360 }
5361 return false;
5362}
5363
5364bool isPosteriorAcquisitionArm(OieOracleSelectionArm arm)
5365{
5366 return arm == OieOracleSelectionArm::TPE ||
5367 arm == OieOracleSelectionArm::PSBAX ||
5368 arm == OieOracleSelectionArm::ExpectedImprovement;
5369}
5370
5371bool isPosteriorAcquisitionReplaceableArm(OieOracleSelectionArm arm)
5372{
5373 return arm == OieOracleSelectionArm::Variance ||
5374 arm == OieOracleSelectionArm::FirstUnobserved ||
5375 arm == OieOracleSelectionArm::CertificateDeficit;
5376}
5377
5378bool isPosteriorActionReplaceableArm(OieOracleSelectionArm arm)
5379{
5380 // A fully observed current band can leave the planner idle while its force
5381 // posterior remains unresolved. PS-BAX may replace that idle decision with
5382 // a trust-certified off-path action geometry.
5383 return arm == OieOracleSelectionArm::None ||
5384 isPosteriorAcquisitionReplaceableArm(arm) ||
5385 arm == OieOracleSelectionArm::PredictionKernelDrift;
5386}
5387
5388} // namespace
5389
5390bool OieOracleTargetDecision::selectedByRejectedProposal() const
5391{
5392 return arm == OieOracleSelectionArm::RejectedProposal;
5393}
5394
5395bool OieOracleTargetDecision::selectedByPosteriorAcquisition() const
5396{
5397 return isPosteriorAcquisitionArm(arm);
5398}
5399
5400bool OieOracleTargetDecision::replaceableByPosteriorAcquisition() const
5401{
5402 return isPosteriorAcquisitionReplaceableArm(arm);
5403}
5404
5405bool OieOracleTargetDecision::replaceableByPosteriorActionAcquisition() const
5406{
5407 return isPosteriorActionReplaceableArm(arm);
5408}
5409
5410OieOracleTargetPlanner::OieOracleTargetPlanner(
5411 int n_images, bool frozen_sweep, bool ci_active, int ci_idx,
5412 const std::vector<char>& image_evaluated,
5413 const std::vector<char>& image_observed_current,
5414 const std::vector<char>& image_posterior_certified_current,
5415 const std::vector<double>& per_image_var, double acquisition_noise_floor,
5416 int local_recovery_image, bool allow_replaceable_acquisition,
5417 bool climbing_image_converged_only,
5418 std::vector<char> image_acquisition_unavailable)
5419 : n_images_(n_images),
5420 frozen_sweep_(frozen_sweep),
5421 ci_active_(ci_active),
5422 ci_idx_(ci_idx),
5423 image_evaluated_(image_evaluated),
5424 image_observed_current_(image_observed_current),
5425 image_posterior_certified_current_(image_posterior_certified_current),
5426 per_image_var_(per_image_var),
5427 acquisition_noise_floor_(acquisition_noise_floor),
5428 local_recovery_image_(local_recovery_image),
5429 allow_replaceable_acquisition_(allow_replaceable_acquisition),
5430 climbing_image_converged_only_(climbing_image_converged_only),
5431 image_acquisition_unavailable_(std::move(image_acquisition_unavailable))
5432{
5433}
5434
5435bool OieOracleTargetPlanner::isInterior(int idx) const
5436{
5437 return idx > 0 && idx < n_images_ - 1;
5438}
5439
5440bool OieOracleTargetPlanner::isCurrentAcquisitionAvailable(int idx) const
5441{
5442 return isInterior(idx) &&
5443 (idx >= static_cast<int>(image_acquisition_unavailable_.size()) ||
5444 !image_acquisition_unavailable_[idx]);
5445}
5446
5447bool OieOracleTargetPlanner::isEvaluated(int idx) const
5448{
5449 return idx >= 0 && idx < static_cast<int>(image_evaluated_.size()) &&
5450 image_evaluated_[idx] != 0;
5451}
5452
5453bool OieOracleTargetPlanner::isObservedCurrent(int idx) const
5454{
5455 return idx >= 0 && idx < static_cast<int>(image_observed_current_.size()) &&
5456 image_observed_current_[idx] != 0;
5457}
5458
5459bool OieOracleTargetPlanner::isPosteriorCertified(int idx) const
5460{
5461 return idx >= 0 &&
5462 idx < static_cast<int>(image_posterior_certified_current_.size()) &&
5463 image_posterior_certified_current_[idx] != 0 &&
5464 !(ci_active_ && idx == ci_idx_);
5465}
5466
5467bool OieOracleTargetPlanner::hasTrueCurrentOracleData(int idx) const
5468{
5469 return isEvaluated(idx) || isObservedCurrent(idx);
5470}
5471
5472bool OieOracleTargetPlanner::hasCurrentOracleData(int idx) const
5473{
5474 return hasTrueCurrentOracleData(idx) || isPosteriorCertified(idx);
5475}
5476
5477bool OieOracleTargetPlanner::clearsNoiseFloor(int idx) const
5478{
5479 if (!(acquisition_noise_floor_ > 0.0)) return true;
5480 if (idx < 0 || idx >= static_cast<int>(per_image_var_.size())) return true;
5481 const double variance = per_image_var_[idx];
5482 return gpr::numerics::exceedsThreshold(variance, acquisition_noise_floor_);
5483}
5484
5485int OieOracleTargetPlanner::firstUnobservedInterior() const
5486{
5487 for (int i = 1; i < n_images_ - 1; ++i) {
5488 if (isCurrentAcquisitionAvailable(i) && !hasCurrentOracleData(i) &&
5489 clearsNoiseFloor(i))
5490 return i;
5491 }
5492 return -1;
5493}
5494
5495int OieOracleTargetPlanner::bestVarianceTarget(int max_var_idx) const
5496{
5497 if (isCurrentAcquisitionAvailable(max_var_idx) &&
5498 !hasCurrentOracleData(max_var_idx) && clearsNoiseFloor(max_var_idx)) {
5499 return max_var_idx;
5500 }
5501 double best = -std::numeric_limits<double>::infinity();
5502 int best_idx = -1;
5503 for (int i = 1; i < n_images_ - 1; ++i) {
5504 if (!isCurrentAcquisitionAvailable(i) || hasCurrentOracleData(i))
5505 continue;
5506 if (!clearsNoiseFloor(i)) continue;
5507 const double variance = i < static_cast<int>(per_image_var_.size())
5508 ? per_image_var_[i]
5509 : -std::numeric_limits<double>::infinity();
5510 if (gpr::numerics::clearlyGreater(variance, best)) {
5511 best = variance;
5512 best_idx = i;
5513 }
5514 }
5515 return isInterior(best_idx) ? best_idx : firstUnobservedInterior();
5516}
5517
5518OieOracleTargetDecision OieOracleTargetPlanner::decision(
5519 int image_index, OieOracleSelectionArm arm) const
5520{
5521 OieOracleTargetDecision out;
5522 out.image_index = isInterior(image_index) ? image_index : -1;
5523 out.arm = out.image_index >= 0 ? arm : OieOracleSelectionArm::None;
5524 out.requires_force_quality = oieSelectionArmRequestsForceQuality(out.arm);
5525 return out;
5526}
5527
5528OieOracleTargetDecision OieOracleTargetPlanner::selectPriorityTarget(
5529 const ProposalAcquisitionTarget& rejected_proposal_acquisition,
5530 bool variance_exceeded, int max_var_idx, int current_chain_priority_idx,
5531 OieAcceptedDriftTarget accepted_drift, bool current_chain_required,
5532 const ProposalAcquisitionTarget& pending_band_action) const
5533{
5534 const int variance_target = bestVarianceTarget(max_var_idx);
5535
5536 // Certificate arms are subject to the same noise-floor information
5537 // gate as the exploration arms: a target whose predictive variance
5538 // sits at the likelihood floor has a determined outcome and cannot
5539 // change any certificate, so re-measuring it is informationless. A
5540 // quasi-periodic outer map (band alternating between two geometries
5541 // that drift below exact-match resolution) otherwise re-fires the
5542 // current-chain arm every outer forever while the variance arm
5543 // starves.
5544 // The activation stencil is exempt from the noise-floor gate: while it
5545 // is pending the inner relaxation is skipped, so refusing the purchase
5546 // leaves nothing else to change and the outer map is the identity
5547 // (measured on the HEAD Baker board: 1000 outers at arm=none, 0 oracle
5548 // calls). Each activation purchase either stores a row at the stencil
5549 // member or is refused by the session's resolution gate, and the
5550 // observation mask counts both as observed, so the pending set shrinks
5551 // by one per outer: the arm fires at most three times per candidate.
5552 // A prediction-kernel boundary outranks the certificate arms. The held
5553 // image needs data at its current point or its boundary query to extend
5554 // the region where the motion policy permits surrogate relaxation.
5555 // Ordinary geometric drift retains its lower acquisition priority.
5556 if (accepted_drift.kind == OieAcceptedDriftKind::PredictionKernelBoundary &&
5557 isInterior(accepted_drift.image_index)) {
5558 if (isCurrentAcquisitionAvailable(accepted_drift.image_index) &&
5559 !hasTrueCurrentOracleData(accepted_drift.image_index)) {
5560 return decision(accepted_drift.image_index,
5561 OieOracleSelectionArm::PredictionKernelDrift);
5562 }
5563 // A measured current image can still have an unmeasured proposal
5564 // beyond its kernel support. That proposal restores room to relax.
5565 if (rejected_proposal_acquisition &&
5566 rejected_proposal_acquisition.image_index ==
5567 accepted_drift.image_index) {
5568 return decision(accepted_drift.image_index,
5569 OieOracleSelectionArm::RejectedProposal);
5570 }
5571 }
5572
5573 // A supported band needs a resolved posterior to activate its CI.
5574 if (!ci_active_ && variance_exceeded &&
5575 isCurrentAcquisitionAvailable(variance_target)) {
5576 return decision(variance_target, OieOracleSelectionArm::Variance);
5577 }
5578
5579 const bool activation_priority =
5580 !ci_active_ &&
5581 isCurrentAcquisitionAvailable(current_chain_priority_idx) &&
5582 !hasTrueCurrentOracleData(current_chain_priority_idx);
5583 if (activation_priority) {
5584 return decision(current_chain_priority_idx,
5585 OieOracleSelectionArm::ActivationPriority);
5586 }
5587
5588 if (current_chain_required &&
5589 isCurrentAcquisitionAvailable(current_chain_priority_idx) &&
5590 !hasTrueCurrentOracleData(current_chain_priority_idx) &&
5591 clearsNoiseFloor(current_chain_priority_idx)) {
5592 if (climbing_image_converged_only_ && ci_active_ &&
5593 current_chain_priority_idx == ci_idx_) {
5594 return decision(ci_idx_,
5595 OieOracleSelectionArm::CurrentClimbingImage);
5596 }
5597 return decision(current_chain_priority_idx,
5598 OieOracleSelectionArm::CurrentChainPriority);
5599 }
5600
5601 // A fixed whole-band action owns its own off-path information campaign.
5602 // It remains an action-level PS-BAX query before and after CI activation;
5603 // current-chain activation and convergence certificates retain priority.
5604 if (!frozen_sweep_ && pending_band_action &&
5605 isInterior(pending_band_action.image_index) &&
5606 pending_band_action.positions.allFinite()) {
5607 return decision(pending_band_action.image_index,
5608 OieOracleSelectionArm::PSBAX);
5609 }
5610
5611 if (rejected_proposal_acquisition &&
5612 isInterior(rejected_proposal_acquisition.image_index)) {
5613 return decision(rejected_proposal_acquisition.image_index,
5614 OieOracleSelectionArm::RejectedProposal);
5615 }
5616
5617 if (frozen_sweep_) {
5618 if (ci_active_ && isCurrentAcquisitionAvailable(ci_idx_) &&
5619 !hasTrueCurrentOracleData(ci_idx_)) {
5620 return decision(ci_idx_,
5621 OieOracleSelectionArm::CurrentClimbingImage);
5622 }
5623 double best = -std::numeric_limits<double>::infinity();
5624 int best_idx = -1;
5625 for (int i = 1; i < n_images_ - 1; ++i) {
5626 if (!isCurrentAcquisitionAvailable(i) ||
5627 hasTrueCurrentOracleData(i))
5628 continue;
5629 const double variance =
5630 i < static_cast<int>(per_image_var_.size())
5631 ? per_image_var_[i]
5632 : -std::numeric_limits<double>::infinity();
5633 if (gpr::numerics::clearlyGreater(variance, best)) {
5634 best = variance;
5635 best_idx = i;
5636 }
5637 }
5638 if (isInterior(best_idx)) {
5639 return decision(best_idx, OieOracleSelectionArm::FrozenSweep);
5640 }
5641 for (int i = 1; i < n_images_ - 1; ++i) {
5642 if (isCurrentAcquisitionAvailable(i) &&
5643 !hasTrueCurrentOracleData(i)) {
5644 return decision(i, OieOracleSelectionArm::FrozenSweep);
5645 }
5646 }
5647 return decision(-1, OieOracleSelectionArm::None);
5648 }
5649
5650 // A confident fixed-image recovery owns the local saddle until its MMF
5651 // hook consumes the current certificate. Unrelated posterior sampling can
5652 // change the fitted saddle identity before that hook runs. Missing
5653 // current-chain data and rejected proposals retain their higher priority.
5654 if (oieLocalRecoverySuppressesReplaceableWork(
5655 oieLocalRecoveryOwnsReplaceableWork(
5656 n_images_, local_recovery_image_, image_evaluated_,
5657 image_observed_current_),
5658 allow_replaceable_acquisition_)) {
5659 return decision(-1, OieOracleSelectionArm::None);
5660 }
5661
5662 // A geometric frontier blocks the surrogate solve independently of its
5663 // variance. Ordinary CI samples cannot release a distant frontier;
5664 // measurements owned by activation or convergence retain priority.
5665 if (climbing_image_converged_only_ && ci_active_ &&
5666 !current_chain_required &&
5667 accepted_drift.kind == OieAcceptedDriftKind::GeometricTrustBoundary &&
5668 isCurrentAcquisitionAvailable(accepted_drift.image_index) &&
5669 !hasTrueCurrentOracleData(accepted_drift.image_index)) {
5670 return decision(accepted_drift.image_index,
5671 OieOracleSelectionArm::AcceptedDrift);
5672 }
5673
5674 // The convergence target needs its measured force before ordinary
5675 // uncertainty elsewhere can decide which data the supported band needs.
5676 // A current CI measurement releases this priority to the band certificate.
5677 if (climbing_image_converged_only_ && ci_active_ &&
5678 isCurrentAcquisitionAvailable(ci_idx_)) {
5679 if (!hasTrueCurrentOracleData(ci_idx_)) {
5680 return decision(ci_idx_,
5681 OieOracleSelectionArm::CurrentClimbingImage);
5682 }
5683 if (isCurrentAcquisitionAvailable(current_chain_priority_idx) &&
5684 !hasTrueCurrentOracleData(current_chain_priority_idx) &&
5685 clearsNoiseFloor(current_chain_priority_idx)) {
5686 return decision(current_chain_priority_idx,
5687 OieOracleSelectionArm::CertificateDeficit);
5688 }
5689 }
5690
5691 if (variance_exceeded && isCurrentAcquisitionAvailable(variance_target)) {
5692 return decision(variance_target, OieOracleSelectionArm::Variance);
5693 }
5694
5695 // A geometric trust-boundary stop is a distance-to-data bound: the band
5696 // cannot move past the frontier image until an oracle row exists there,
5697 // and no other observation changes that distance. The posterior-variance
5698 // floor therefore does not gate it (ioykF 04_ch3o: 295 of 419 inner
5699 // exits were drift stops, the frontier failed the floor, and the
5700 // climbing image was re-evaluated 267 times within 0.03 A of rows it
5701 // already had). A drift of any other kind keeps the floor.
5702 if (isCurrentAcquisitionAvailable(accepted_drift.image_index) &&
5703 !hasTrueCurrentOracleData(accepted_drift.image_index) &&
5704 (accepted_drift.kind == OieAcceptedDriftKind::GeometricTrustBoundary ||
5705 clearsNoiseFloor(accepted_drift.image_index))) {
5706 // Kernel-boundary drift targets are consumed at the dedicated
5707 // top-ranked kernel arm; any drift reaching here takes the
5708 // fallback arm.
5709 return decision(accepted_drift.image_index,
5710 OieOracleSelectionArm::AcceptedDrift);
5711 }
5712
5713 // Ordinary force/variance deficits are useful fallback evidence, but they
5714 // do not certify an action that consumes the row immediately. Posterior
5715 // policies may replace this target with a higher-value information query.
5716 if (isCurrentAcquisitionAvailable(current_chain_priority_idx) &&
5717 !hasTrueCurrentOracleData(current_chain_priority_idx) &&
5718 clearsNoiseFloor(current_chain_priority_idx)) {
5719 return decision(current_chain_priority_idx,
5720 OieOracleSelectionArm::CertificateDeficit);
5721 }
5722
5723 const bool ci_needs_current_data = ci_active_ &&
5724 isCurrentAcquisitionAvailable(ci_idx_) &&
5725 !hasTrueCurrentOracleData(ci_idx_);
5726 if (ci_needs_current_data) {
5727 return decision(ci_idx_, OieOracleSelectionArm::CurrentClimbingImage);
5728 }
5729 if (isCurrentAcquisitionAvailable(variance_target)) {
5730 return decision(variance_target, OieOracleSelectionArm::Variance);
5731 }
5732 return decision(firstUnobservedInterior(),
5733 OieOracleSelectionArm::FirstUnobserved);
5734}
5735
5736OieOracleTargetDecision
5737OieOracleTargetPlanner::selectPosteriorAcquisitionTarget(
5738 const OieOracleTargetDecision& fallback, int image_index,
5739 OieOracleSelectionArm arm) const
5740{
5741 if (!isPosteriorAcquisitionArm(arm)) return fallback;
5742 if (frozen_sweep_ || fallback.selectedByRejectedProposal() ||
5743 !isPosteriorAcquisitionReplaceableArm(fallback.arm) ||
5744 !isCurrentAcquisitionAvailable(image_index) ||
5745 hasTrueCurrentOracleData(image_index)) {
5746 return fallback;
5747 }
5748 return decision(image_index, arm);
5749}
5750
5751OieOracleTargetDecision OieOracleTargetPlanner::selectPosteriorActionTarget(
5752 const OieOracleTargetDecision& fallback,
5753 const ProposalAcquisitionTarget& target,
5754 const bool target_within_training_trust, double posterior_force_variance,
5755 double force_noise_floor, OieOracleSelectionArm arm) const
5756{
5757 if (!isPosteriorAcquisitionArm(arm)) return fallback;
5758 if (frozen_sweep_ || !ci_active_ || fallback.selectedByRejectedProposal() ||
5759 !isPosteriorActionReplaceableArm(fallback.arm) || !target ||
5760 !target_within_training_trust || !isInterior(target.image_index) ||
5761 !target.positions.allFinite() ||
5762 !std::isfinite(posterior_force_variance) ||
5763 posterior_force_variance <= std::max(0.0, force_noise_floor)) {
5764 return fallback;
5765 }
5766 return decision(target.image_index, arm);
5767}
5768
5769OieOracleTargetDecision
5770OieOracleTargetPlanner::selectRequiredCurrentChainMeasurementTarget(
5771 const OieOracleTargetDecision& fallback, int image_index,
5772 OieAcceptedDriftTarget blocking_drift) const
5773{
5774 if (!isCurrentAcquisitionAvailable(image_index)) return fallback;
5775 if (climbing_image_converged_only_ && ci_active_ &&
5776 blocking_drift.kind == OieAcceptedDriftKind::GeometricTrustBoundary &&
5777 isInterior(blocking_drift.image_index) &&
5778 fallback.image_index == blocking_drift.image_index &&
5779 fallback.arm == OieOracleSelectionArm::AcceptedDrift) {
5780 return fallback;
5781 }
5782 if (blocking_drift.kind == OieAcceptedDriftKind::PredictionKernelBoundary &&
5783 isInterior(blocking_drift.image_index) &&
5784 fallback.image_index == blocking_drift.image_index &&
5785 (fallback.arm == OieOracleSelectionArm::PredictionKernelDrift ||
5786 fallback.selectedByRejectedProposal())) {
5787 return fallback;
5788 }
5789 if (climbing_image_converged_only_ && ci_active_ &&
5790 fallback.arm == OieOracleSelectionArm::CurrentClimbingImage &&
5791 fallback.image_index == ci_idx_ && !hasTrueCurrentOracleData(ci_idx_)) {
5792 return fallback;
5793 }
5794 return decision(image_index, OieOracleSelectionArm::CurrentChainPriority);
5795}
5796
5797OieOracleTargetDecision OieOracleTargetPlanner::selectExpectedImprovementTarget(
5798 const OieOracleTargetDecision& fallback, int image_index) const
5799{
5800 if (!isCurrentAcquisitionAvailable(image_index) ||
5801 hasTrueCurrentOracleData(image_index)) {
5802 return fallback;
5803 }
5804 const bool replaceable =
5805 fallback.arm == OieOracleSelectionArm::None ||
5806 isPosteriorAcquisitionReplaceableArm(fallback.arm) ||
5807 fallback.arm == OieOracleSelectionArm::AcceptedDrift ||
5808 fallback.arm == OieOracleSelectionArm::CurrentChainPriority;
5809 if (frozen_sweep_ || !replaceable) {
5810 return fallback;
5811 }
5812 return decision(image_index, OieOracleSelectionArm::ExpectedImprovement);
5813}
5814
5815OieOracleTargetDecision OieOracleTargetPlanner::selectSurrogateRepairTarget(
5816 const OieOracleTargetDecision& fallback, const char* inner_exit,
5817 const OieBandPosteriorReadiness& readiness, bool measurement_owned) const
5818{
5819 const int target = readiness.acquisition_image;
5820 if (measurement_owned || frozen_sweep_ || !ci_active_ ||
5821 !climbing_image_converged_only_ || readiness.resolved() ||
5822 fallback.arm != OieOracleSelectionArm::CurrentClimbingImage ||
5823 fallback.image_index != ci_idx_ ||
5824 !isCurrentAcquisitionAvailable(target) || target == ci_idx_ ||
5825 hasTrueCurrentOracleData(target) || inner_exit == nullptr ||
5826 oieLocalRecoverySuppressesReplaceableWork(
5827 oieLocalRecoveryOwnsReplaceableWork(
5828 n_images_, local_recovery_image_, image_evaluated_,
5829 image_observed_current_),
5830 allow_replaceable_acquisition_)) {
5831 return fallback;
5832 }
5833 const bool exhausted = std::strcmp(inner_exit, "condition") == 0 ||
5834 std::strcmp(inner_exit, "itercap") == 0 ||
5835 std::strcmp(inner_exit, "cycle") == 0 ||
5836 std::strcmp(inner_exit, "stationary") == 0 ||
5837 std::strcmp(inner_exit, "optimizer_stop") == 0;
5838 if (!exhausted) return fallback;
5839 // The joint force deficit already includes its likelihood floor. An
5840 // energy-only noise gate cannot decide whether this row resolves force.
5841 return decision(target, OieOracleSelectionArm::CurrentChainPriority);
5842}
5843
5844OieOracleTargetDecision OieOracleTargetPlanner::selectRecoveryModelGrowthTarget(
5845 const OieOracleTargetDecision& fallback, int image_index) const
5846{
5847 // Recovery growth is the MMF joint-[E,F] evidence campaign. It must
5848 // replace idle/replaceable arms AND rejected path-coincident thrash:
5849 // rejected re-oracles already-trained geometries and freezes ntrain while
5850 // recovery_proposal stays proposed (Baker 04: F stuck 0.178 after a
5851 // recovery trial reject, ntrain frozen at 138, arm=rejected forever).
5852 // A current-chain row on another image does not outrank the recovery
5853 // that owns the band. The owner freezes the band around its image, so
5854 // that arm fires again on every outer and the growth proposal never
5855 // runs (adatom OCINEB: image 5 on 139 of 149 outers, 202 oracle calls
5856 // for 27 measured geometries).
5857 const bool owner_holds_band =
5858 fallback.arm == OieOracleSelectionArm::CurrentChainPriority &&
5859 fallback.image_index != image_index &&
5860 oieLocalRecoverySuppressesReplaceableWork(
5861 oieLocalRecoveryOwnsReplaceableWork(
5862 n_images_, local_recovery_image_, image_evaluated_,
5863 image_observed_current_),
5864 allow_replaceable_acquisition_);
5865 const bool replaceable =
5866 fallback.arm == OieOracleSelectionArm::None ||
5867 isPosteriorAcquisitionReplaceableArm(fallback.arm) ||
5868 fallback.selectedByRejectedProposal() || owner_holds_band;
5869 if (frozen_sweep_ || !replaceable || !isInterior(image_index)) {
5870 return fallback;
5871 }
5872 return decision(image_index, OieOracleSelectionArm::RecoveryModelGrowth);
5873}
5874
5875OieOracleTargetDecision
5876OieOracleTargetPlanner::selectForceResidualRemeasureTarget(
5877 const OieOracleTargetDecision& fallback, int max_force_image,
5878 double max_band_force, double force_tolerance) const
5879{
5880 if (frozen_sweep_ || !isCurrentAcquisitionAvailable(max_force_image))
5881 return fallback;
5882 if (!shouldPreferForceResidualRemeasure(fallback, max_band_force,
5883 force_tolerance)) {
5884 return fallback;
5885 }
5886 // Residual already known on the current max-force geometry: do not
5887 // re-oracle the same row every outer (that blocked acquisition_idle OCI).
5888 // Clear rejected thrash only when the thrash target itself is already a
5889 // current true row (or is the residual image). Fixed-point / rejected
5890 // targets that still need measurement must be preserved.
5891 //
5892 // Never clear RecoveryModelGrowth here: that arm is the MMF recovery
5893 // off-path growth campaign. Clearing it while residual force is open
5894 // freezes exhausted-recovery OCI (Baker 01 under trust-only residual:
5895 // 952 identical outers at F=1.78, recovery_proposal=proposed but
5896 // arm=none, final extractable F stuck at dimer handback 0.109718).
5897 if (hasTrueCurrentOracleData(max_force_image)) {
5898 if (fallback.selectedByRejectedProposal()) {
5899 const int thrash_idx = fallback.image_index;
5900 if (thrash_idx < 0 || thrash_idx == max_force_image ||
5901 hasTrueCurrentOracleData(thrash_idx)) {
5902 return decision(-1, OieOracleSelectionArm::None);
5903 }
5904 return fallback;
5905 }
5906 return fallback;
5907 }
5908 // Missing current-chain true force at the residual image: measure it once.
5909 return selectRequiredCurrentChainMeasurementTarget(fallback,
5910 max_force_image);
5911}
5912
5913bool protectUnmeasuredOffBandProposal(
5914 OffBandResidualGuard& guard, bool selected_by_rejected,
5915 bool proposal_has_positions, bool coincides_with_band,
5916 bool proposal_in_training, const Eigen::VectorXd& proposal,
5917 double residual_force, double force_tolerance)
5918{
5919 if (!(std::isfinite(residual_force) && std::isfinite(force_tolerance) &&
5920 residual_force > force_tolerance)) {
5921 guard.armed = false;
5922 return false;
5923 }
5924 if (!selected_by_rejected || !proposal_has_positions ||
5925 coincides_with_band || proposal_in_training) {
5926 return false;
5927 }
5928 if (!guard.armed) {
5929 guard.armed = true;
5930 guard.positions = proposal;
5931 return true;
5932 }
5933 return positionsCoincide(guard.positions, proposal);
5934}
5935
5936bool keepProposalWithoutRemeasure(bool proposal_has_positions,
5937 bool proposal_in_training,
5938 int remeasure_image) noexcept
5939{
5940 return proposal_has_positions && !proposal_in_training &&
5941 remeasure_image < 0;
5942}
5943
5944bool releaseTrainedPendingAcquisition(ProposalAcquisitionTarget& acquisition,
5945 const gpr::Observation& training,
5946 bool residual_force_open)
5947{
5948 if (!residual_force_open || !acquisition ||
5949 acquisition.positions.size() == 0 ||
5950 !hasPosition(training, acquisition.positions)) {
5951 return false;
5952 }
5953 acquisition.clear();
5954 return true;
5955}
5956
5957bool shouldPreferForceResidualRemeasure(const OieOracleTargetDecision& decision,
5958 double max_band_force,
5959 double force_tolerance) noexcept
5960{
5961 if (!(force_tolerance > 0.0) || !std::isfinite(force_tolerance) ||
5962 !std::isfinite(max_band_force) || !(max_band_force > force_tolerance)) {
5963 return false;
5964 }
5965 // Idle picker, rejected-proposal thrash, or recovery-growth off-path rows
5966 // while true force is still above problem tolerance.
5967 if (decision.image_index < 0) return true;
5968 return decision.selectedByRejectedProposal() ||
5969 decision.arm == OieOracleSelectionArm::RecoveryModelGrowth;
5970}
5971
5972int selectOieOracleTarget(
5973 int n_images, bool frozen_sweep, bool ci_active, int ci_idx,
5974 const std::vector<char>& image_evaluated,
5975 const std::vector<char>& image_observed_current,
5976 const std::vector<double>& per_image_var,
5977 const ProposalAcquisitionTarget& rejected_proposal_acquisition,
5978 bool variance_exceeded, int max_var_idx, int current_chain_priority_idx,
5979 bool* selected_by_rejected_proposal)
5980{
5981 const std::vector<char> no_posterior_certificate;
5982 return selectOieOracleTarget(
5983 n_images, frozen_sweep, ci_active, ci_idx, image_evaluated,
5984 image_observed_current, no_posterior_certificate, per_image_var,
5985 rejected_proposal_acquisition, variance_exceeded, max_var_idx,
5986 current_chain_priority_idx, selected_by_rejected_proposal);
5987}
5988
5989int selectOieOracleTarget(
5990 int n_images, bool frozen_sweep, bool ci_active, int ci_idx,
5991 const std::vector<char>& image_evaluated,
5992 const std::vector<char>& image_observed_current,
5993 const std::vector<char>& image_posterior_certified_current,
5994 const std::vector<double>& per_image_var,
5995 const ProposalAcquisitionTarget& rejected_proposal_acquisition,
5996 bool variance_exceeded, int max_var_idx, int current_chain_priority_idx,
5997 bool* selected_by_rejected_proposal)
5998{
5999 const OieOracleTargetPlanner planner(
6000 n_images, frozen_sweep, ci_active, ci_idx, image_evaluated,
6001 image_observed_current, image_posterior_certified_current,
6002 per_image_var);
6003 const OieOracleTargetDecision decision = planner.selectPriorityTarget(
6004 rejected_proposal_acquisition, variance_exceeded, max_var_idx,
6005 current_chain_priority_idx);
6006 if (selected_by_rejected_proposal) {
6007 *selected_by_rejected_proposal = decision.selectedByRejectedProposal();
6008 }
6009 return decision.image_index;
6010}
6011
6012double maxBandMotion(const Eigen::VectorXd& step, Eigen::Index image_dof)
6013{
6014 if (step.size() == 0) return 0.0;
6015 if (image_dof <= 0) return step.norm();
6016
6017 double max_motion = 0.0;
6018 for (Eigen::Index offset = 0; offset < step.size(); offset += image_dof) {
6019 const Eigen::Index count = std::min(image_dof, step.size() - offset);
6020 const Eigen::VectorXd image_step = step.segment(offset, count);
6021 if (count >= 3 && count % 3 == 0) {
6022 for (Eigen::Index atom = 0; atom < count; atom += 3) {
6023 max_motion =
6024 std::max(max_motion, image_step.segment(atom, 3).norm());
6025 }
6026 } else {
6027 max_motion = std::max(max_motion, image_step.norm());
6028 }
6029 }
6030 return max_motion;
6031}
6032
6033Eigen::VectorXd limitBandMotion(const Eigen::VectorXd& step,
6034 Eigen::Index image_dof, double max_move)
6035{
6036 if (!(max_move > 0.0) || !std::isfinite(max_move)) {
6037 return Eigen::VectorXd::Zero(step.size());
6038 }
6039 const double max_motion = maxBandMotion(step, image_dof);
6040 if (max_motion > max_move && max_motion > 0.0) {
6041 return step * (max_move / max_motion);
6042 }
6043 return step;
6044}
6045
6046Eigen::VectorXd GlobalLBFGSObjective::difference(const Eigen::VectorXd& a,
6047 const Eigen::VectorXd& b) const
6048{
6049 return a - b;
6050}
6051
6052Eigen::VectorXd GlobalLBFGSObjective::stepPositions(
6053 const Eigen::VectorXd& positions, const Eigen::VectorXd& step) const
6054{
6055 return positions + step;
6056}
6057
6058double GlobalLBFGSObjective::maxMotion(const Eigen::VectorXd& step) const
6059{
6060 return maxBandMotion(step, imageDof());
6061}
6062
6063Eigen::VectorXd GlobalLBFGSObjective::limitMotion(const Eigen::VectorXd& step,
6064 double max_move) const
6065{
6066 return limitBandMotion(step, imageDof(), max_move);
6067}
6068
6069NEBBandObjective::NEBBandObjective(NEBPath& path, std::function<bool()> refresh,
6070 NEBBandObjectiveGeodesicOptions geodesic,
6071 int fixed_image_index,
6072 std::vector<char> active_images)
6073 : path_(path),
6074 refresh_(std::move(refresh)),
6075 geodesic_(std::move(geodesic)),
6076 fixed_image_index_(fixed_image_index),
6077 active_images_(std::move(active_images))
6078{
6079 if ((geodesic_.n_atoms > 1 || hasFrozenContacts()) &&
6080 geodesic_.min_distance_ratio_limit > 0.0 &&
6081 geodesic_.min_distance_ratio_limit < 1.0) {
6082 const auto endpoint_distance = [&](const Eigen::VectorXd& moving) {
6083 if (!hasFrozenContacts())
6084 return geometry::minimumPairDistance(moving, geodesic_.cell);
6085 Eigen::VectorXd positions(moving.size() +
6086 geodesic_.frozen_positions.size());
6087 positions << moving, geodesic_.frozen_positions;
6088 return geometry::minimumPairDistance(positions, geodesic_.cell,
6089 geodesic_.n_atoms);
6090 };
6091 const double endpoint_floor =
6092 geodesic_.min_distance_ratio_limit *
6093 std::min(endpoint_distance(path_.image(0).positions),
6094 endpoint_distance(
6095 path_.image(path_.numImages() - 1).positions));
6096 std::vector<int> floor_numbers;
6097 if (static_cast<int>(geodesic_.atomic_numbers.size()) ==
6098 geodesic_.n_atoms) {
6099 floor_numbers = geodesic_.atomic_numbers;
6100 // The fixed atoms follow the moving ones, so the floor's
6101 // moving_count marks the boundary and frozen-frozen pairs stay
6102 // out of it.
6103 if (hasFrozenContacts())
6104 floor_numbers.insert(floor_numbers.end(),
6105 geodesic_.frozen_atomic_numbers.begin(),
6106 geodesic_.frozen_atomic_numbers.end());
6107 }
6108 contact_floor_ =
6109 geometry::ElementPairContactFloor(endpoint_floor, floor_numbers);
6110 // The endpoints are geometries the potential treats as ordinary; a
6111 // pair type they hold inside its covalent onset (a Lennard-Jones
6112 // solid under a chemical label) takes its floor from them.
6113 const auto endpoint_frame = [&](const Eigen::VectorXd& moving) {
6114 if (!hasFrozenContacts()) return moving;
6115 Eigen::VectorXd positions(moving.size() +
6116 geodesic_.frozen_positions.size());
6117 positions << moving, geodesic_.frozen_positions;
6118 return positions;
6119 };
6120 contact_floor_.calibrateToGeometries(
6121 {endpoint_frame(path_.image(0).positions),
6122 endpoint_frame(path_.image(path_.numImages() - 1).positions)},
6123 geodesic_.cell, geodesic_.n_atoms);
6124 }
6125}
6126
6127bool NEBBandObjective::hasFrozenContacts() const noexcept
6128{
6129 return !geodesic_.frozen_atomic_numbers.empty() &&
6130 geodesic_.frozen_positions.size() ==
6131 3 * static_cast<Eigen::Index>(
6132 geodesic_.frozen_atomic_numbers.size()) &&
6133 static_cast<int>(geodesic_.atomic_numbers.size()) ==
6134 geodesic_.n_atoms;
6135}
6136
6137void NEBBandObjective::setActiveImages(std::vector<char> active_images)
6138{
6139 active_images_ = std::move(active_images);
6140}
6141
6142ProposalAcquisitionTarget holdOieUnsupportedImages(
6143 NEBBandObjective& objective, const Eigen::VectorXd& accepted_positions,
6144 const std::vector<char>& blocked_images)
6145{
6146 const Eigen::Index dof = objective.imageDof();
6147 if (dof <= 0 || accepted_positions.size() != objective.positions().size() ||
6148 blocked_images.size() !=
6149 static_cast<std::size_t>(accepted_positions.size() / dof + 2)) {
6150 throw std::invalid_argument("invalid OIE image hold geometry");
6151 }
6152 std::vector<char> relaxable = objective.activeImages();
6153 if (relaxable.empty()) relaxable.assign(blocked_images.size(), 1);
6154 Eigen::VectorXd held_positions = objective.positions();
6155 ProposalAcquisitionTarget boundary;
6156 for (std::size_t i = 0; i < blocked_images.size() && i < relaxable.size();
6157 ++i) {
6158 if (!blocked_images[i]) continue;
6159 if (i > 0 && i + 1 < blocked_images.size()) {
6160 const Eigen::Index offset = static_cast<Eigen::Index>(i - 1) * dof;
6161 if (!boundary && relaxable[i] &&
6162 (held_positions.segment(offset, dof).array() !=
6163 accepted_positions.segment(offset, dof).array())
6164 .any()) {
6165 boundary.image_index = static_cast<int>(i);
6166 boundary.positions = held_positions.segment(offset, dof);
6167 }
6168 held_positions.segment(offset, dof) =
6169 accepted_positions.segment(offset, dof);
6170 }
6171 relaxable[i] = 0;
6172 }
6173 // Rollback uses the original motion mask; a held image cannot move.
6174 objective.setPositions(held_positions);
6175 objective.setActiveImages(std::move(relaxable));
6176 return boundary;
6177}
6178
6179bool NEBBandObjective::imageIsActive(int image_idx) const
6180{
6181 if (image_idx == fixed_image_index_) return false;
6182 if (active_images_.empty()) return true;
6183 return image_idx >= 0 &&
6184 image_idx < static_cast<int>(active_images_.size()) &&
6185 active_images_[static_cast<std::size_t>(image_idx)] != 0;
6186}
6187
6188Eigen::VectorXd NEBBandObjective::positions() const
6189{
6190 const int n_interior = path_.numImages() - 2;
6191 if (n_interior <= 0) return Eigen::VectorXd();
6192 const Eigen::Index per = path_.image(1).positions.size();
6193 Eigen::VectorXd r(static_cast<Eigen::Index>(n_interior) * per);
6194 for (int i = 1; i < path_.numImages() - 1; ++i) {
6195 r.segment(static_cast<Eigen::Index>(i - 1) * per, per) =
6196 path_.image(i).positions;
6197 }
6198 return r;
6199}
6200
6201Eigen::VectorXd NEBBandObjective::force() const
6202{
6203 const int n_interior = path_.numImages() - 2;
6204 if (n_interior <= 0) return Eigen::VectorXd();
6205 const Eigen::Index per = path_.image(1).positions.size();
6206 Eigen::VectorXd f(static_cast<Eigen::Index>(n_interior) * per);
6207 for (int i = 1; i < path_.numImages() - 1; ++i) {
6208 f.segment(static_cast<Eigen::Index>(i - 1) * per, per) =
6209 path_.nebForce(i);
6210 path_.maskFixedForce(
6211 f.segment(static_cast<Eigen::Index>(i - 1) * per, per));
6212 }
6213 for (int i = 1; i < path_.numImages() - 1; ++i) {
6214 if (!imageIsActive(i)) {
6215 f.segment(static_cast<Eigen::Index>(i - 1) * per, per).setZero();
6216 }
6217 }
6218 // The NEB force combines perpendicular PES force with tangential spring
6219 // force. Internal coordinates constrain and retract trial steps in
6220 // stepPositions(); force-space preconditioning would alter NEB fixed
6221 // points and mix the two components.
6222 return f;
6223}
6224
6225void NEBBandObjective::setPositions(const Eigen::VectorXd& positions)
6226{
6227 const int n_interior = path_.numImages() - 2;
6228 if (n_interior <= 0) return;
6229 const Eigen::Index per = path_.image(1).positions.size();
6230 const Eigen::VectorXd canonical_positions =
6231 detail::broadcastRootVector(positions);
6232 if (canonical_positions.size() !=
6233 static_cast<Eigen::Index>(n_interior) * per) {
6234 return;
6235 }
6236 for (int i = 1; i < path_.numImages() - 1; ++i) {
6237 if (!imageIsActive(i)) continue;
6238 path_.image(i).positions = canonical_positions.segment(
6239 static_cast<Eigen::Index>(i - 1) * per, per);
6240 path_.pinFixedAtoms(path_.image(i).positions);
6241 path_.image(i).evaluated = false;
6242 }
6243 clean_ = false;
6244}
6245
6246bool NEBBandObjective::stepAdmissible(const Eigen::VectorXd& from,
6247 const Eigen::VectorXd& to) const
6248{
6249 const Eigen::Index per = imageDof();
6250 if (!from.allFinite() || !to.allFinite() || per <= 0 ||
6251 from.size() != (path_.numImages() - 2) * per ||
6252 to.size() != from.size())
6253 return false;
6254 if (!contact_floor_.active()) return true;
6255 for (int i = 1; i < path_.numImages() - 1; ++i) {
6256 const Eigen::Index offset = static_cast<Eigen::Index>(i - 1) * per;
6257 auto ratio = [&](const Eigen::VectorXd& positions) {
6258 if (hasFrozenContacts()) {
6259 Eigen::VectorXd frame(per + geodesic_.frozen_positions.size());
6260 frame << positions.segment(offset, per),
6261 geodesic_.frozen_positions;
6262 return contact_floor_.minimumRatio(frame, geodesic_.cell,
6263 per / 3);
6264 }
6265 return contact_floor_.minimumRatio(positions.segment(offset, per),
6266 geodesic_.cell);
6267 };
6268 // minimumRatio is capped at one. A feasible image stays feasible;
6269 // a compressed seed can separate its atoms but cannot compress more.
6270 if (ratio(to) < ratio(from)) return false;
6271 }
6272 return true;
6273}
6274
6275double NEBBandObjective::merit() const
6276{
6277 double sum = 0.0;
6278 bool any = false;
6279 for (int i = 1; i < path_.numImages() - 1; ++i) {
6280 if (!imageIsActive(i)) continue;
6281 const double e = path_.image(i).energy;
6282 if (!std::isfinite(e)) return std::numeric_limits<double>::quiet_NaN();
6283 sum += e;
6284 any = true;
6285 }
6286 return any ? sum : std::numeric_limits<double>::quiet_NaN();
6287}
6288
6289Eigen::VectorXd NEBBandObjective::projectPerpendicular(
6290 const Eigen::VectorXd& v) const
6291{
6292 const int n_interior = path_.numImages() - 2;
6293 if (n_interior <= 0) return v;
6294 const Eigen::Index per = path_.image(1).positions.size();
6295 if (v.size() != static_cast<Eigen::Index>(n_interior) * per) return v;
6296 Eigen::VectorXd out = v;
6297 for (int i = 1; i < path_.numImages() - 1; ++i) {
6298 if (!imageIsActive(i)) continue;
6299 Eigen::VectorXd tau = path_.tangentAt(i);
6300 const double nt = tau.norm();
6301 if (!(nt > 0.0) || tau.size() != per) continue;
6302 tau /= nt;
6303 auto seg = out.segment(static_cast<Eigen::Index>(i - 1) * per, per);
6304 seg -= tau.dot(seg) * tau;
6305 }
6306 return out;
6307}
6308
6309void NEBBandObjective::respace()
6310{
6311 if (path_.numImages() < 3) return;
6312 (void)path_.reparametrizeByArcLength();
6313 for (int i = 1; i < path_.numImages() - 1; ++i) {
6314 path_.image(i).evaluated = false;
6315 }
6316 clean_ = false;
6317}
6318
6319bool NEBBandObjective::refresh(bool finite_difference_step)
6320{
6321 if (!finite_difference_step && clean_) return true;
6322 const bool ok = refresh_ ? refresh_() : (path_.computeNEBForces(), true);
6323 if (ok && !finite_difference_step) clean_ = true;
6324 return ok;
6325}
6326
6327Eigen::Index NEBBandObjective::imageDof() const
6328{
6329 if (path_.numImages() <= 2) return 0;
6330 return path_.image(1).positions.size();
6331}
6332
6333Eigen::VectorXd internalTrustFromPathSpacing(
6334 const NEBPath& path,
6335 const gpr::geometry::InternalCoordinateSet& internal_coordinates)
6336{
6337 const int n_images = path.numImages();
6338 if (n_images < 2) return Eigen::VectorXd();
6339 std::vector<Eigen::VectorXd> q(static_cast<std::size_t>(n_images));
6340 Eigen::Index n_primitives = -1;
6341 try {
6342 for (int i = 0; i < n_images; ++i) {
6343 q[static_cast<std::size_t>(i)] =
6344 internal_coordinates.values(path.image(i).positions);
6345 if (n_primitives < 0)
6346 n_primitives = q[static_cast<std::size_t>(i)].size();
6347 if (q[static_cast<std::size_t>(i)].size() != n_primitives)
6348 return Eigen::VectorXd();
6349 }
6350 } catch (const std::invalid_argument&) {
6351 return Eigen::VectorXd();
6352 } catch (const std::runtime_error&) {
6353 return Eigen::VectorXd();
6354 }
6355 if (n_primitives <= 0) return Eigen::VectorXd();
6356 Eigen::VectorXd trust = Eigen::VectorXd::Zero(n_primitives);
6357 std::vector<double> spacing(static_cast<std::size_t>(n_images - 1));
6358 for (Eigen::Index k = 0; k < n_primitives; ++k) {
6359 bool finite = true;
6360 for (int i = 0; i + 1 < n_images; ++i) {
6361 const double dq = std::abs(q[static_cast<std::size_t>(i + 1)](k) -
6362 q[static_cast<std::size_t>(i)](k));
6363 if (!std::isfinite(dq)) {
6364 finite = false;
6365 break;
6366 }
6367 spacing[static_cast<std::size_t>(i)] = dq;
6368 }
6369 if (!finite) continue;
6370 auto mid = spacing.begin() + spacing.size() / 2;
6371 std::nth_element(spacing.begin(), mid, spacing.end());
6372 trust(k) = *mid;
6373 }
6374 // Kind-median floor: a spectator primitive with a tiny-but-nonzero
6375 // median spacing otherwise annihilates the whole step (the scale test
6376 // divides by its radius; Baker 20 accepted 300 zero-length steps per
6377 // outer and deadlocked with the acquisition seeing no new geometry).
6378 // Each primitive's radius is floored at the median radius of its own
6379 // KIND (bond/angle/dihedral), so spectators inherit the traversal
6380 // scale of their kind while staying unit-consistent. Kinds the band
6381 // does not traverse at all keep zero radii and stay unconstrained.
6382 const auto& prims = internal_coordinates.primitives();
6383 if (static_cast<Eigen::Index>(prims.size()) == n_primitives) {
6384 for (int kind = 0; kind < 3; ++kind) {
6385 std::vector<double> kind_radii;
6386 for (Eigen::Index k = 0; k < n_primitives; ++k) {
6387 if (static_cast<int>(prims[static_cast<std::size_t>(k)].kind) ==
6388 kind &&
6389 trust(k) > 0.0) {
6390 kind_radii.push_back(trust(k));
6391 }
6392 }
6393 if (kind_radii.empty()) continue;
6394 auto mid = kind_radii.begin() + kind_radii.size() / 2;
6395 std::nth_element(kind_radii.begin(), mid, kind_radii.end());
6396 const double kind_median = *mid;
6397 for (Eigen::Index k = 0; k < n_primitives; ++k) {
6398 if (static_cast<int>(prims[static_cast<std::size_t>(k)].kind) ==
6399 kind &&
6400 trust(k) > 0.0 && trust(k) < kind_median) {
6401 trust(k) = kind_median;
6402 }
6403 }
6404 }
6405 }
6406 return trust;
6407}
6408
6409Eigen::VectorXd NEBBandObjective::stepPositions(
6410 const Eigen::VectorXd& positions, const Eigen::VectorXd& step) const
6411{
6412 Eigen::VectorXd physical_step;
6413 const Eigen::VectorXd* effective_step = &step;
6414 const Eigen::Index image_dof = imageDof();
6415 if (path_.molecularRigidMotion() && positions.size() == step.size() &&
6416 image_dof > 0 && positions.size() % image_dof == 0) {
6417 physical_step = step;
6418 for (Eigen::Index offset = 0; offset < positions.size();
6419 offset += image_dof) {
6420 path_.projectPhysicalVector(
6421 positions.segment(offset, image_dof),
6422 physical_step.segment(offset, image_dof));
6423 }
6424 effective_step = &physical_step;
6425 }
6426 const auto preserve_inactive_images = [&](Eigen::VectorXd trial) {
6427 const Eigen::Index per = imageDof();
6428 if (per > 0 && trial.size() == positions.size()) {
6429 for (int i = 1; i < path_.numImages() - 1; ++i) {
6430 const Eigen::Index offset =
6431 static_cast<Eigen::Index>(i - 1) * per;
6432 if (imageIsActive(i)) {
6433 if (contact_floor_.active() && hasFrozenContacts()) {
6434 // The fixed atoms ride along unchanged in both
6435 // geometries, so they bound the moving ones and
6436 // never move themselves.
6437 const Eigen::Index n_frozen =
6438 geodesic_.frozen_positions.size();
6439 Eigen::VectorXd from(per + n_frozen);
6440 Eigen::VectorXd to(per + n_frozen);
6441 from << positions.segment(offset, per),
6442 geodesic_.frozen_positions;
6443 to << trial.segment(offset, per),
6444 geodesic_.frozen_positions;
6445 trial.segment(offset, per) =
6446 contact_floor_
6447 .limitStep(from, to, geodesic_.cell, per / 3)
6448 .head(per);
6449 } else if (contact_floor_.active()) {
6450 trial.segment(offset, per) = contact_floor_.limitStep(
6451 positions.segment(offset, per),
6452 trial.segment(offset, per), geodesic_.cell);
6453 }
6454 if (path_.molecularRigidMotion()) {
6455 trial.segment(offset, per) =
6456 path_.alignMolecularGeometry(
6457 positions.segment(offset, per),
6458 trial.segment(offset, per));
6459 }
6460 path_.pinFixedAtoms(trial.segment(offset, per));
6461 continue;
6462 }
6463 trial.segment(offset, per) = positions.segment(offset, per);
6464 }
6465 }
6466 return trial;
6467 };
6468 // Internal-coordinate constrained step (Sella
6469 // restricted_step.MaxInternalStep
6470 // + retraction). Limits the per-image step so the largest linearised
6471 // internal-coordinate change (bond/angle) stays within an internal trust
6472 // radius, then retracts the (possibly scaled) step back onto the
6473 // internal-coordinate manifold. This keeps the band/dimer relaxation from
6474 // stepping into broken geometries that the GP then learns (the silylene
6475 // force blow-up / sub-reactant collapses). The trust radii are the band's
6476 // own per-primitive inter-image spacings (internalTrustFromPathSpacing),
6477 // so the constraint is parameter-free and unit-consistent per primitive.
6478 const bool derived_trust =
6479 geodesic_.internal_trust_per_primitive.size() > 0 &&
6480 geodesic_.internal_trust_per_primitive.maxCoeff() > 0.0;
6481 const bool constrained_step =
6482 derived_trust && geodesic_.internal_coordinates != nullptr;
6483
6484 const bool min_distance_capped = geodesic_.min_distance_ratio_limit > 0.0 &&
6485 geodesic_.min_distance_ratio_limit < 1.0 &&
6486 geodesic_.n_atoms > 1;
6487
6488 if (!geodesic_.enabled && !constrained_step && !min_distance_capped) {
6489 return preserve_inactive_images(positions + *effective_step);
6490 }
6491 if (positions.size() != step.size())
6492 return preserve_inactive_images(positions + step);
6493 const Eigen::Index per = imageDof();
6494 if (per <= 0 || per != static_cast<Eigen::Index>(3 * geodesic_.n_atoms) ||
6495 positions.size() % per != 0) {
6496 return preserve_inactive_images(positions + *effective_step);
6497 }
6498
6499 // Minimum-distance cap (Eq. 5.3). It does not evaluate primitives, so a
6500 // collinear angle or a non-finite step cannot throw from here.
6501 const auto capMinDistance = [&](const Eigen::VectorXd& p,
6502 Eigen::VectorXd s) {
6503 if (min_distance_capped) {
6504 // Cap every atom's displacement at 0.5 * (1 - r_limit) * d_min
6505 // so one step cannot close any interatomic contact below
6506 // r_limit * d_min. This is the anti-clash brake the
6507 // feature-space trust radius cannot provide: a wall geometry
6508 // oracled once poisons the amplitude fit for the rest of the run.
6509 const double d_min =
6510 geometry::minimumPairDistance(p, geodesic_.cell);
6511 if (std::isfinite(d_min) && d_min > 0.0) {
6512 const double cap =
6513 0.5 * (1.0 - geodesic_.min_distance_ratio_limit) * d_min;
6514 double max_disp = 0.0;
6515 for (int a = 0; a < geodesic_.n_atoms; ++a) {
6516 max_disp = std::max(max_disp, s.segment(3 * a, 3).norm());
6517 }
6518 if (max_disp > cap && cap > 0.0) s *= cap / max_disp;
6519 }
6520 }
6521 return s;
6522 };
6523 // Per-primitive internal trust. linearizedChange throws
6524 // UndefinedInternalCoordinate for a collinear angle and
6525 // std::invalid_argument for a non-finite step. The try below turns
6526 // those into one fallback. The fallback itself must not call this
6527 // unguarded: it already logged that fallback and bumped the counter.
6528 const auto scaleInternalTrust = [&](const Eigen::VectorXd& p,
6529 Eigen::VectorXd s) {
6530 if (constrained_step) {
6531 // MaxInternalStep trust region: scale the Cartesian step so no
6532 // linearised internal-coordinate change exceeds its trust
6533 // radius. The derived radii test each primitive against its own
6534 // inter-image spacing.
6535 const Eigen::VectorXd ds_int =
6536 geodesic_.internal_coordinates->linearizedChange(p, s);
6537 if (ds_int.size() > 0) {
6538 double worst_ratio = 1.0;
6539 for (Eigen::Index k = 0; k < ds_int.size(); ++k) {
6540 const double radius =
6541 k < geodesic_.internal_trust_per_primitive.size()
6542 ? geodesic_.internal_trust_per_primitive(k)
6543 : 0.0;
6544 if (!(radius > 0.0)) continue;
6545 const double change = std::abs(ds_int(k));
6546 if (std::isfinite(change) && change / radius > worst_ratio)
6547 worst_ratio = change / radius;
6548 }
6549 if (worst_ratio > 1.0) s /= worst_ratio;
6550 }
6551 }
6552 return s;
6553 };
6554 // Distance cap, then internal-trust scaling, for the attempt inside
6555 // the try. The fallback does not use this combined step: it always
6556 // applies the distance cap, and it keeps that capped step when trust
6557 // scaling throws.
6558 const auto scaleImageStep = [&](const Eigen::VectorXd& p,
6559 Eigen::VectorXd s) {
6560 return scaleInternalTrust(p, capMinDistance(p, std::move(s)));
6561 };
6562 const auto reported_cartesian_fallback =
6563 [&](const char* reason) -> Eigen::VectorXd {
6564 ++geodesic_retraction_fallbacks_;
6565 std::cerr << "[gpneb] geodesic retraction fallback #"
6566 << geodesic_retraction_fallbacks_ << ": " << reason
6567 << "; using the Cartesian trial" << std::endl;
6568 Eigen::VectorXd fallback = positions;
6569 for (Eigen::Index offset = 0; offset < positions.size();
6570 offset += per) {
6571 const Eigen::VectorXd image = positions.segment(offset, per);
6572 // The distance cap always applies. Trust scaling is skipped for
6573 // this image only when the primitive is undefined or the step is
6574 // not finite; any other error still leaves stepPositions.
6575 Eigen::VectorXd s =
6576 capMinDistance(image, effective_step->segment(offset, per));
6577 if (constrained_step) {
6578 try {
6579 s = scaleInternalTrust(image, s);
6581 // Keep the distance-capped step for this image.
6582 } catch (const std::invalid_argument&) {
6583 // Keep the distance-capped step for this image.
6584 }
6585 }
6586 fallback.segment(offset, per) = image + s;
6587 }
6588 return preserve_inactive_images(std::move(fallback));
6589 };
6590
6591 Eigen::VectorXd trial(positions.size());
6592 try {
6593 for (Eigen::Index offset = 0; offset < positions.size();
6594 offset += per) {
6595 const Eigen::VectorXd p = positions.segment(offset, per);
6596 const Eigen::VectorXd s =
6597 scaleImageStep(p, effective_step->segment(offset, per));
6598 if (!geodesic_.enabled && !constrained_step) {
6599 // Min-distance cap only: plain Cartesian step, no
6600 // geodesic retraction semantics were requested.
6601 trial.segment(offset, per) = p + s;
6602 } else if (geodesic_.internal_coordinates) {
6603 trial.segment(offset, per) =
6604 geodesic_.internal_coordinates->retractLinearized(p, s);
6605 } else {
6606 const std::array<double, 9>* geodesic_cell =
6607 gpr::geometry::cellIsMicLattice(geodesic_.cell.data())
6608 ? &geodesic_.cell
6609 : nullptr;
6610 trial.segment(offset, per) =
6611 NEBPath::inverseDistanceGeodesicStep(geodesic_.n_atoms,
6612 geodesic_.moving_atoms,
6613 p, s, geodesic_cell);
6614 }
6615 }
6617 return reported_cartesian_fallback("internal-coordinate solve failed");
6619 return reported_cartesian_fallback(
6620 "an internal-coordinate primitive is undefined");
6621 } catch (const std::invalid_argument&) {
6622 return reported_cartesian_fallback(
6623 "the geodesic trial has an invalid argument");
6624 } catch (const std::runtime_error&) {
6625 return reported_cartesian_fallback(
6626 "the geodesic trial raised a runtime error");
6627 }
6628 if (!trial.allFinite())
6629 return reported_cartesian_fallback(
6630 "the geodesic trial produced non-finite coordinates");
6631 return preserve_inactive_images(std::move(trial));
6632}
6633
6634GlobalLBFGSOptimizer::GlobalLBFGSOptimizer(GlobalLBFGSOptions options)
6635 : options_(options)
6636{
6637}
6638
6639void emitMaxMoveTrustRegionWarning(double max_move, bool& warned)
6640{
6641 // 0.2 A is the eOn default and the practical upper bound where
6642 // the L-BFGS quadratic model still holds. One-shot per
6643 // (optimizer, max_move) pair.
6644 if (max_move > 0.2 && !warned) {
6645 std::cerr << "[gpneb] WARNING: max_move=" << max_move
6646 << " exceeds 0.2 A" << std::endl;
6647 warned = true;
6648 }
6649}
6650
6651void GlobalLBFGSOptimizer::warnIfMaxMoveExceedsTrustRegion(double max_move)
6652{
6653 emitMaxMoveTrustRegionWarning(max_move, max_move_warned_);
6654}
6655
6656void GlobalLBFGSOptimizer::clearHistory()
6657{
6658 s_history_.clear();
6659 y_history_.clear();
6660 rho_history_.clear();
6661}
6662
6663void GlobalLBFGSOptimizer::reset()
6664{
6665 clearHistory();
6666 iteration_ = 0;
6667 r_prev_.resize(0);
6668 f_prev_.resize(0);
6669 last_curvature_dot_ = 0.0;
6670 curvature_cap_.reset();
6671 sketched_h0_.reset();
6672}
6673
6674void GlobalLBFGSOptimizer::rebuildSketchedH0(
6675 const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>& hvp,
6676 int n_dof)
6677{
6678 if (options_.sketch_h0_rank <= 0 || n_dof <= 0) return;
6679 const int k = std::min(options_.sketch_h0_rank, n_dof);
6680 if (!sketched_h0_ || sketched_h0_->n_dof() != n_dof ||
6681 sketched_h0_->sketch_rank() != k) {
6682 sketched_h0_ = std::make_unique<gpr::optim::SketchedHessianH0>(
6683 n_dof, k, options_.sketch_seed != 0 ? options_.sketch_seed : 1ULL);
6684 }
6685 sketched_h0_->rebuild(hvp);
6686}
6687
6688bool GlobalLBFGSOptimizer::update(const GlobalLBFGSObjective& objective,
6689 const Eigen::VectorXd& r1,
6690 const Eigen::VectorXd& r0,
6691 const Eigen::VectorXd& f1,
6692 const Eigen::VectorXd& f0)
6693{
6694 Eigen::VectorXd s0 = objective.difference(r1, r0);
6695 Eigen::VectorXd y0 = f0 - f1;
6697 s0, y0, curvature_exclude_offset_, curvature_exclude_len_);
6698 last_curvature_dot_ = s0.dot(y0);
6699 // A nonfinite or degenerate secant cannot define rho. getStep applies
6700 // the same block policy before rejecting a nonpositive full pair.
6701 if (!std::isfinite(last_curvature_dot_) ||
6702 std::abs(last_curvature_dot_) < 1e-30) {
6703 return false;
6704 }
6705
6706 s_history_.push_back(s0);
6707 y_history_.push_back(y0);
6708 rho_history_.push_back(1.0 / last_curvature_dot_);
6709
6710 const int memory = std::max(
6711 1, std::min(options_.memory,
6712 static_cast<int>(std::max<Eigen::Index>(1, s0.size()))));
6713 while (static_cast<int>(s_history_.size()) > memory) {
6714 s_history_.pop_front();
6715 y_history_.pop_front();
6716 rho_history_.pop_front();
6717 }
6718 return true;
6719}
6720
6721Eigen::VectorXd GlobalLBFGSOptimizer::getStep(
6722 GlobalLBFGSObjective& objective, double max_move,
6723 const Eigen::VectorXd& force, const Eigen::VectorXd& positions,
6724 std::optional<double> initial_inverse_curvature)
6725{
6726 double H0 = options_.inverse_curvature;
6727 if (!(H0 > 0.0) || !std::isfinite(H0)) H0 = 0.01;
6728 const bool use_measured_curvature =
6729 iteration_ == 0 && initial_inverse_curvature.has_value() &&
6730 std::isfinite(*initial_inverse_curvature) &&
6731 *initial_inverse_curvature > 0.0;
6732 if (use_measured_curvature) H0 = *initial_inverse_curvature;
6733
6734 if (iteration_ > 0 && r_prev_.size() == positions.size() &&
6735 f_prev_.size() == force.size()) {
6736 Eigen::VectorXd dr = objective.difference(positions, r_prev_);
6737 Eigen::VectorXd df = f_prev_ - force;
6739 dr, df, curvature_exclude_offset_, curvature_exclude_len_);
6740 const double denom = dr.dot(df);
6741 const double df_norm2 = df.squaredNorm();
6742 // A non-positive force secant gives a non-positive inverse-Hessian
6743 // scale. The reference eOn L-BFGS discards that curvature model and
6744 // takes a bounded force step, preserving descent orientation without
6745 // introducing a second displacement scale.
6746 if (!(denom > 0.0) || !std::isfinite(denom) || !(df_norm2 > 0.0) ||
6747 !std::isfinite(df_norm2)) {
6748 clearHistory();
6749 return objective.limitMotion(1000.0 * force, max_move);
6750 }
6751 if (options_.auto_scale) {
6753 }
6754 }
6755
6756 if (iteration_ == 0 && !use_measured_curvature && options_.auto_scale &&
6757 options_.finite_difference > 0.0) {
6758 const double force_norm = force.norm();
6759 if (force_norm > 0.0 && std::isfinite(force_norm)) {
6760 const Eigen::VectorXd unit = force / force_norm;
6761 objective.setPositions(objective.stepPositions(
6762 positions, options_.finite_difference * unit));
6763 if (!objective.refresh(true)) {
6764 objective.setPositions(positions);
6765 (void)objective.refresh(false);
6766 return objective.limitMotion(H0 * force, max_move);
6767 }
6768 const Eigen::VectorXd gradient_delta = -objective.force() + force;
6769 const double C =
6770 gradient_delta.dot(unit) / options_.finite_difference;
6771 objective.setPositions(positions);
6772 if (!objective.refresh(false)) {
6773 return objective.limitMotion(H0 * force, max_move);
6774 }
6775 H0 = (std::abs(C) < 1e-300) ? -1.0 : 1.0 / C;
6776 if (!(H0 > 0.0) || !std::isfinite(H0)) {
6777 clearHistory();
6778 return objective.limitMotion(1000.0 * force, max_move);
6779 }
6780 }
6781 }
6782
6783 // Shared Nocedal two-loop recursion (gpr::optim::twoLoopRecursion).
6784 //
6785 // Sketched L-BFGS (Gower-Richtarik 2015 sketch-and-project view):
6786 // when sketch_history > 0 and < |s_history_|, uniformly sub-sample
6787 // sketch_history pairs from the history and call the kernel on
6788 // the sketched deques. Equivalent to a {0,1}-sketch matrix
6789 // selecting which curvature pairs participate in the H_k apply.
6790 // The sketch RNG (splitmix64) is seeded once from sketch_seed on
6791 // the first call. When sketch_history == 0 or >= history size,
6792 // this is a no-op and the standard full-history L-BFGS runs.
6793 const int k_sketch = options_.sketch_history;
6794 Eigen::VectorXd z;
6795 if (k_sketch > 0 && k_sketch < static_cast<int>(s_history_.size())) {
6796 if (sketch_rng_state_ == 0) {
6797 sketch_rng_state_ =
6798 options_.sketch_seed != 0 ? options_.sketch_seed : 1ULL;
6799 }
6800 const std::size_t m = s_history_.size();
6801 std::vector<std::size_t> idx(m);
6802 std::iota(idx.begin(), idx.end(), std::size_t{0});
6803 // Fisher-Yates partial shuffle using splitmix64.
6804 for (std::size_t i = 0; i < static_cast<std::size_t>(k_sketch); ++i) {
6805 sketch_rng_state_ += 0x9E3779B97F4A7C15ULL;
6806 uint64_t z64 = sketch_rng_state_;
6807 z64 = (z64 ^ (z64 >> 30)) * 0xBF58476D1CE4E5B9ULL;
6808 z64 = (z64 ^ (z64 >> 27)) * 0x94D049BB133111EBULL;
6809 z64 = z64 ^ (z64 >> 31);
6810 const std::size_t pick = i + (z64 % (m - i));
6811 std::swap(idx[i], idx[pick]);
6812 }
6813 // Sketched pairs must remain in original (chronological) order
6814 // so the two-loop's most-recent-first / oldest-first iteration
6815 // semantics stay correct after sub-sampling.
6816 std::sort(idx.begin(), idx.begin() + k_sketch);
6817 std::deque<Eigen::VectorXd> s_sk, y_sk;
6818 std::deque<double> rho_sk;
6819 for (int i = 0; i < k_sketch; ++i) {
6820 s_sk.push_back(s_history_[idx[i]]);
6821 y_sk.push_back(y_history_[idx[i]]);
6822 rho_sk.push_back(rho_history_[idx[i]]);
6823 }
6824 z = gpr::optim::twoLoopRecursion(s_sk, y_sk, rho_sk, force, H0);
6825 } else {
6826 // Sketched-Nystrom H0 if a SketchedHessianH0 has data for the current
6827 // rebuild epoch; otherwise use scalar H0 = gamma * I.
6828 if (sketched_h0_ && sketched_h0_->ready()) {
6829 auto apply_h0 = [this,
6830 H0](const Eigen::VectorXd& v) -> Eigen::VectorXd {
6831 return sketched_h0_->apply(v, H0);
6832 };
6833 z = gpr::optim::twoLoopRecursion(s_history_, y_history_,
6834 rho_history_, force, apply_h0);
6835 } else {
6836 z = gpr::optim::twoLoopRecursion(s_history_, y_history_,
6837 rho_history_, force, H0);
6838 }
6839 }
6840
6841 const Eigen::VectorXd proposed = -z;
6842 // max_move bounds the region where the quasi-Newton model is trusted.
6843 // The reference eOn distance reset discards a model whose proposal
6844 // reaches that boundary and retries with the scalar H0 force step.
6845 const double proposed_motion = objective.maxMotion(proposed);
6846 if (options_.distance_reset && max_move > 0.0 && std::isfinite(max_move) &&
6847 std::isfinite(proposed_motion) && proposed_motion >= max_move) {
6848 clearHistory();
6849 return objective.limitMotion(H0 * force, max_move);
6850 }
6851
6852 const double proposed_norm = proposed.norm();
6853 const double force_norm = force.norm();
6854 if (proposed_norm > 0.0 && force_norm > 0.0 && options_.angle_reset) {
6855 double cos_angle = proposed.dot(force) / (proposed_norm * force_norm);
6856 cos_angle = std::clamp(cos_angle, -1.0, 1.0);
6857 constexpr double pi = 3.14159265358979323846;
6858 const double angle = std::acos(cos_angle) * 180.0 / pi;
6859 if (angle > 90.0) {
6860 clearHistory();
6861 return objective.limitMotion(H0 * force, max_move);
6862 }
6863 }
6864
6865 return objective.limitMotion(proposed, max_move);
6866}
6867
6868bool GlobalLBFGSOptimizer::step(GlobalLBFGSObjective& objective,
6869 double max_move,
6870 std::optional<double> initial_inverse_curvature)
6871{
6872 warnIfMaxMoveExceedsTrustRegion(max_move);
6873 if (!objective.refresh(false)) return false;
6874 const Eigen::VectorXd r = objective.positions();
6875 const Eigen::VectorXd f = objective.force();
6876 if (r.size() == 0 || f.size() != r.size()) return false;
6877
6878 if (iteration_ > 0 && r_prev_.size() == r.size() &&
6879 f_prev_.size() == f.size()) {
6880 (void)update(objective, r, r_prev_, f, f_prev_);
6881 }
6882
6883 const double configured_move = max_move;
6884 const double used_move = curvature_cap_.resolve(
6885 configured_move, lastCurvatureScale(), objective.maxMotion(f),
6886 options_.newton_agreement);
6887 const Eigen::VectorXd dr =
6888 getStep(objective, used_move, f, r, initial_inverse_curvature);
6889 curvature_cap_.observe(objective.maxMotion(dr), configured_move,
6890 objective.maxMotion(f));
6891 objective.setPositions(objective.stepPositions(r, dr));
6892 r_prev_ = r;
6893 f_prev_ = f;
6894 ++iteration_;
6895 return true;
6896}
6897
6898std::vector<int> pathAwareTopologyImageIndices(const NEBPath& path)
6899{
6900 const int n = path.numImages();
6901 std::vector<int> out;
6902 if (n <= 0) return out;
6903 out.reserve(static_cast<std::size_t>(n));
6904 std::vector<char> seen(static_cast<std::size_t>(n), 0);
6905 const auto push = [&](int i) {
6906 if (i < 0 || i >= n) return;
6907 char& flag = seen[static_cast<std::size_t>(i)];
6908 if (flag != 0) return;
6909 flag = 1;
6910 out.push_back(i);
6911 };
6912 push(0);
6913 if (n >= 2) push(n - 1);
6914 for (int i = 0; i < n; ++i) {
6915 if (path.image(i).is_climbing) push(i);
6916 }
6917 for (int i = 0; i < n; ++i)
6918 push(i);
6919 return out;
6920}
6921
6922std::shared_ptr<const gpr::geometry::InternalCoordinateSet>
6923makeMolecularInternalCoordinatesForPath(const NEBPath& path,
6924 const GPNEBConfig& config)
6925{
6926 if (!(config.n_atoms > 0 && path.numImages() > 0)) {
6927 return {};
6928 }
6929 const Eigen::Index dof = path.image(0).positions.size();
6930 if (dof != static_cast<Eigen::Index>(3 * config.n_atoms)) {
6931 return {};
6932 }
6933
6934 const auto kind = config.use_relative_neighborhood_graph
6937 try {
6938 std::vector<Eigen::VectorXd> geometries;
6939 geometries.reserve(static_cast<std::size_t>(path.numImages()));
6940 for (const int i: pathAwareTopologyImageIndices(path)) {
6941 if (path.image(i).positions.size() != dof ||
6942 !path.image(i).positions.allFinite()) {
6943 return {};
6944 }
6945 geometries.push_back(path.image(i).positions);
6946 }
6947 // Path-union: endpoints, CI, and current images. A forming or
6948 // breaking pair that is a Gabriel (or RNG) edge at either
6949 // endpoint stays in the redundant set so the SVD chart rank
6950 // does not jump at the TS.
6951 const std::array<double, 9> lattice =
6952 gpr::geometry::micLattice(config.cell);
6953 const auto union_bonds = gpr::geometry::unionBondGraph(
6954 config.n_atoms, geometries, config.moving_atoms, kind, lattice);
6955 return std::make_shared<gpr::geometry::InternalCoordinateSet>(
6956 config.n_atoms, config.moving_atoms,
6959 union_bonds),
6960 geometries, lattice),
6961 lattice);
6962 } catch (const std::invalid_argument&) {
6963 return {};
6964 }
6965}
6966
6967std::shared_ptr<const gpr::geometry::InternalCoordinateSet>
6968makeGeodesicInternalCoordinatesForPath(const NEBPath& path,
6969 const GPNEBConfig& config)
6970{
6971 if (!config.sidpp_geodesic || !config.geodesic_retraction) return {};
6972 return makeMolecularInternalCoordinatesForPath(path, config);
6973}
6974
6975std::shared_ptr<const gpr::geometry::InternalCoordinateChart>
6976makeImageInternalCoordinateChart(
6977 std::shared_ptr<const gpr::geometry::InternalCoordinateSet> internals,
6978 const Eigen::VectorXd& positions)
6979{
6980 if (!internals || positions.size() <= 0 || !positions.allFinite()) {
6981 return {};
6982 }
6983 try {
6984 auto chart = std::make_shared<gpr::geometry::InternalCoordinateChart>(
6985 std::move(internals), positions);
6986 if (!chart->valid()) return {};
6987 return chart;
6988 } catch (const std::invalid_argument&) {
6989 return {};
6990 }
6991}
6992
6993bool attachImageManifoldChart(
6994 ActiveLearningSession& session, int i,
6995 const std::shared_ptr<const gpr::geometry::InternalCoordinateSet>&
6996 internals,
6997 const Eigen::VectorXd& positions)
6998{
6999 if (i < 0 || i >= static_cast<int>(session.image_models.size())) {
7000 return false;
7001 }
7002 const auto& existing = session.image_models[i].internalCoordinateChart();
7003 std::shared_ptr<const gpr::geometry::InternalCoordinateChart> chart;
7004 if (existing && internals && existing->valid() &&
7005 existing->internalCoordinates().hasSameDefinition(*internals) &&
7006 existing->anchor().size() == positions.size() &&
7007 existing->anchor().isApprox(positions, 0.0)) {
7008 chart = existing;
7009 } else {
7010 chart = makeImageInternalCoordinateChart(internals, positions);
7011 }
7012 if (!session.setImageInternalCoordinateChart(i, std::move(chart))) {
7013 session.image_models[i].clearInternalCoordinateChart();
7014 return false;
7015 }
7016 return true;
7017}
7018
7019bool attachGlobalManifoldChart(
7020 ActiveLearningSession& session,
7021 const std::shared_ptr<const gpr::geometry::InternalCoordinateSet>&
7022 internals,
7023 const Eigen::VectorXd& positions)
7024{
7025 const auto& existing = session.globalInternalCoordinateChart();
7026 std::shared_ptr<const gpr::geometry::InternalCoordinateChart> chart;
7027 if (existing && internals && existing->valid() &&
7028 existing->internalCoordinates().hasSameDefinition(*internals) &&
7029 existing->anchor().size() == positions.size() &&
7030 existing->anchor().isApprox(positions, 0.0)) {
7031 chart = existing;
7032 } else {
7033 chart = makeImageInternalCoordinateChart(internals, positions);
7034 }
7035 return session.setGlobalInternalCoordinateChart(std::move(chart));
7036}
7037
7038bool attachGlobalManifoldChart(
7039 gpr::GaussianProcessRegression& gp, const gpr::Observation* training_obs,
7040 const std::shared_ptr<const gpr::geometry::InternalCoordinateSet>&
7041 internals,
7042 const Eigen::VectorXd& positions)
7043{
7044 auto& covariance = gp.getSexpAtCovarianceFunction();
7045 const bool had_chart = covariance.usesManifoldChart();
7046 auto rematerialize = [&]() {
7047 if (training_obs && training_obs->R.rows() > 0) {
7048 gp.updateModelWithFullData(*training_obs);
7049 }
7050 };
7051 auto chart = makeImageInternalCoordinateChart(internals, positions);
7052 if (!chart) {
7053 if (had_chart) {
7054 covariance.clearManifoldChart();
7055 rematerialize();
7056 }
7057 return false;
7058 }
7059 const std::optional<double> length_scale =
7061 if (!length_scale) {
7062 if (had_chart) {
7063 covariance.clearManifoldChart();
7064 rematerialize();
7065 }
7066 return false;
7067 }
7068 gp.setInternalCoordinateChart(std::move(chart), *length_scale);
7069 rematerialize();
7070 return true;
7071}
7072
7073void attachClassicGlobalManifoldChart(const GPNEBConfig& config,
7074 const NEBPath& path,
7075 ActiveLearningSession* session,
7076 gpr::GaussianProcessRegression& gp,
7077 const gpr::Observation& training_obs)
7078{
7079 if (config.atomic_environments || !config.attach_manifold_chart ||
7080 !usesClassicJointEnergyForcePrior(config.model_profile) ||
7081 path.numImages() <= 0) {
7082 return;
7083 }
7084 const auto internals =
7085 makeMolecularInternalCoordinatesForPath(path, config);
7086 const Eigen::VectorXd& anchor = path.image(path.numImages() / 2).positions;
7087 if (session) {
7088 (void)attachGlobalManifoldChart(*session, internals, anchor);
7089 } else {
7090 (void)attachGlobalManifoldChart(gp, &training_obs, internals, anchor);
7091 }
7092}
7093
7094const char* measuredNebStepStatusName(MeasuredNebStepStatus status) noexcept
7095{
7096 switch (status) {
7097 case MeasuredNebStepStatus::NotRequested:
7098 return "not_requested";
7099 case MeasuredNebStepStatus::Proposed:
7100 return "proposed";
7101 case MeasuredNebStepStatus::InvalidPath:
7102 return "invalid_path";
7103 case MeasuredNebStepStatus::InvalidSelection:
7104 return "invalid_selection";
7105 case MeasuredNebStepStatus::InvalidImageState:
7106 return "invalid_image_state";
7107 case MeasuredNebStepStatus::InvalidPosteriorSample:
7108 return "invalid_posterior_sample";
7109 case MeasuredNebStepStatus::MissingMeasurement:
7110 return "missing_measurement";
7111 case MeasuredNebStepStatus::NonFiniteForce:
7112 return "nonfinite_force";
7113 case MeasuredNebStepStatus::Stationary:
7114 return "stationary";
7115 case MeasuredNebStepStatus::OptimizerRejected:
7116 return "optimizer_rejected";
7117 }
7118 return "unknown";
7119}
7120
7121std::vector<Eigen::VectorXd> proposePsBaxSampledNebStep(
7122 const NEBPath& path, const Eigen::VectorXd& interior_observation_sample,
7123 const GPNEBConfig& config, MeasuredNebStepStatus* status)
7124{
7125 const int n_interior = path.numImages() - 2;
7126 const Eigen::Index image_dof =
7127 path.numImages() > 0 ? path.image(0).positions.size() : 0;
7128 const Eigen::Index expected_channels =
7129 static_cast<Eigen::Index>(n_interior) * (image_dof + 1);
7130 if (n_interior <= 0 || image_dof <= 0 ||
7131 interior_observation_sample.size() != expected_channels ||
7132 !interior_observation_sample.allFinite()) {
7133 if (status) *status = MeasuredNebStepStatus::InvalidPosteriorSample;
7134 return {};
7135 }
7136
7137 NEBPath sampled_path = path;
7138 for (int image = 1; image < sampled_path.numImages() - 1; ++image) {
7139 const Eigen::Index interior = image - 1;
7140 auto& sampled_image = sampled_path.image(image);
7141 sampled_image.energy = interior_observation_sample(interior);
7142 sampled_image.gradient.resize(image_dof);
7143 for (Eigen::Index dimension = 0; dimension < image_dof; ++dimension) {
7144 sampled_image.gradient(dimension) = interior_observation_sample(
7145 n_interior + dimension * n_interior + interior);
7146 }
7147 sampled_image.evaluated = true;
7148 }
7149 return proposeMeasuredNebStep(sampled_path, config, -1, status);
7150}
7151
7152PsBaxActionProposal proposePsBaxActionAcquisition(
7153 const NEBPath& path, gpr::GaussianProcessRegression& gp,
7154 const gpr::Observation& training_obs, const GPNEBConfig& config,
7155 std::uint64_t posterior_seed, const PsBaxTrustProjector& project_to_trust,
7156 const PsBaxTrustCertificate& is_trust_certified)
7157{
7158 PsBaxActionProposal result;
7159 const int n_images = path.numImages();
7160 if (n_images <= 2) {
7161 result.status = MeasuredNebStepStatus::InvalidPath;
7162 return result;
7163 }
7164
7165 const int n_interior = n_images - 2;
7166 const Eigen::Index image_dof = path.image(0).positions.size();
7167 if (image_dof <= 0) {
7168 result.status = MeasuredNebStepStatus::InvalidImageState;
7169 return result;
7170 }
7171
7172 EigenMatrix chain_positions(n_interior, image_dof);
7173 Eigen::VectorXd posterior_mean(n_interior * (image_dof + 1));
7174 for (int image = 1; image < n_images - 1; ++image) {
7175 const Eigen::Index interior = image - 1;
7176 const auto& state = path.image(image);
7177 if (state.gradient.size() != image_dof ||
7178 !std::isfinite(state.energy) || !state.positions.allFinite() ||
7179 !state.gradient.allFinite()) {
7180 result.status = MeasuredNebStepStatus::InvalidImageState;
7181 return result;
7182 }
7183 chain_positions.row(interior) = state.positions.transpose();
7184 posterior_mean(interior) = state.energy;
7185 for (Eigen::Index dimension = 0; dimension < image_dof; ++dimension) {
7186 posterior_mean(n_interior + dimension * n_interior + interior) =
7187 state.gradient(dimension);
7188 }
7189 }
7190
7191 EigenMatrix posterior_covariance;
7192 gp.calculateObservationPosteriorCovariance(chain_positions,
7193 posterior_covariance);
7194 const Eigen::VectorXd posterior_sample =
7195 oie::drawPosteriorObservationSample(
7196 posterior_mean, posterior_covariance, posterior_seed);
7197 std::vector<Eigen::VectorXd> action_positions = proposePsBaxSampledNebStep(
7198 path, posterior_sample, config, &result.status);
7199 if (action_positions.size() != static_cast<std::size_t>(n_images)) {
7200 return result;
7201 }
7202
7203 Eigen::VectorXd flattened_action(n_interior * image_dof);
7204 for (int image = 1; image < n_images - 1; ++image) {
7205 const Eigen::VectorXd& positions =
7206 action_positions[static_cast<std::size_t>(image)];
7207 if (positions.size() != image_dof || !positions.allFinite()) {
7208 result.status = MeasuredNebStepStatus::InvalidImageState;
7209 return result;
7210 }
7211 flattened_action.segment(
7212 static_cast<Eigen::Index>(image - 1) * image_dof, image_dof) =
7213 positions;
7214 }
7215
7216 if (project_to_trust) {
7217 result.trust_projected = project_to_trust(flattened_action);
7218 }
7219 result.trust_certified =
7220 is_trust_certified && is_trust_certified(flattened_action);
7221 if (!result.trust_certified) return result;
7222
7223 EigenMatrix action_query(n_interior, image_dof);
7224 for (int image = 1; image < n_images - 1; ++image) {
7225 const Eigen::Index offset =
7226 static_cast<Eigen::Index>(image - 1) * image_dof;
7227 action_positions[static_cast<std::size_t>(image)] =
7228 flattened_action.segment(offset, image_dof);
7229 action_query.row(image - 1) =
7230 flattened_action.segment(offset, image_dof).transpose();
7231 }
7232
7233 EigenMatrix action_covariance;
7234 gp.calculateObservationPosteriorCovariance(action_query, action_covariance);
7235 const Eigen::Index action_channels = n_interior * (image_dof + 1);
7236 if (action_covariance.rows() != action_channels ||
7237 action_covariance.cols() != action_channels ||
7238 !action_covariance.allFinite()) {
7239 return result;
7240 }
7241
7242 const double force_noise_floor =
7243 static_cast<double>(image_dof) * std::max(0.0, gp.getSigma2());
7244 double best_force_variance = force_noise_floor;
7245 for (int image = 1; image < n_images - 1; ++image) {
7246 const Eigen::Index interior = image - 1;
7247 double force_variance = 0.0;
7248 for (Eigen::Index dimension = 0; dimension < image_dof; ++dimension) {
7249 const Eigen::Index channel =
7250 n_interior + dimension * n_interior + interior;
7251 force_variance +=
7252 std::max(0.0, action_covariance(channel, channel));
7253 }
7254 const Eigen::VectorXd& positions =
7255 action_positions[static_cast<std::size_t>(image)];
7256 if (gpr::numerics::clearlyGreater(force_variance,
7257 best_force_variance) &&
7258 !hasPosition(training_obs, positions)) {
7259 best_force_variance = force_variance;
7260 result.target.image_index = image;
7261 result.target.positions = positions;
7262 result.force_variance = force_variance;
7263 }
7264 }
7265 return result;
7266}
7267
7268std::vector<Eigen::VectorXd> proposeMeasuredNebStep(
7269 const NEBPath& path, const GPNEBConfig& config, int selected_image,
7270 MeasuredNebStepStatus* status)
7271{
7272 const auto fail = [status](MeasuredNebStepStatus reason) {
7273 if (status) *status = reason;
7274 return std::vector<Eigen::VectorXd>{};
7275 };
7276 if (path.numImages() <= 2) {
7277 return fail(MeasuredNebStepStatus::InvalidPath);
7278 }
7279 const bool targeted =
7280 selected_image > 0 && selected_image < path.numImages() - 1;
7281 if (selected_image >= 0 && !targeted) {
7282 return fail(MeasuredNebStepStatus::InvalidSelection);
7283 }
7284 for (int i = 0; i < path.numImages(); ++i) {
7285 const auto& image = path.image(i);
7286 if (!std::isfinite(image.energy) || !image.positions.allFinite()) {
7287 return fail(MeasuredNebStepStatus::InvalidImageState);
7288 }
7289 if (i > 0 && i < path.numImages() - 1 &&
7290 (image.gradient.size() != image.positions.size() ||
7291 !image.gradient.allFinite())) {
7292 return fail(MeasuredNebStepStatus::InvalidImageState);
7293 }
7294 if (i > 0 && i < path.numImages() - 1 && !targeted &&
7295 !image.evaluated) {
7296 return fail(MeasuredNebStepStatus::MissingMeasurement);
7297 }
7298 }
7299 if (targeted) {
7300 for (int i = selected_image - 1; i <= selected_image + 1; ++i) {
7301 if (i > 0 && i < path.numImages() - 1 && !path.image(i).evaluated) {
7302 return fail(MeasuredNebStepStatus::MissingMeasurement);
7303 }
7304 }
7305 }
7306
7307 NEBPath candidate = path;
7308 candidate.computeNEBForces();
7309 bool has_finite_force = false;
7310 for (int i = 1; i < candidate.numImages() - 1; ++i) {
7311 const Eigen::VectorXd& force = candidate.nebForce(i);
7312 if (!force.allFinite()) {
7313 return fail(MeasuredNebStepStatus::NonFiniteForce);
7314 }
7315 if (!targeted || i == selected_image) {
7316 has_finite_force = has_finite_force || force.squaredNorm() > 0.0;
7317 }
7318 }
7319 if (!has_finite_force) return fail(MeasuredNebStepStatus::Stationary);
7320
7321 GlobalLBFGSOptions options;
7322 options.memory = config.lbfgs_memory;
7323 options.inverse_curvature = config.lbfgs_inverse_curvature;
7324 options.finite_difference = 0.0;
7325 options.auto_scale = false;
7326 options.angle_reset = config.lbfgs_angle_reset;
7327 options.distance_reset = config.lbfgs_distance_reset;
7328 options.newton_agreement = config.lbfgs_newton_agreement;
7329
7330 NEBBandObjectiveGeodesicOptions geodesic;
7331 geodesic.enabled = config.sidpp_geodesic && config.geodesic_retraction;
7332 geodesic.n_atoms = config.n_atoms;
7333 geodesic.moving_atoms = config.moving_atoms;
7334 geodesic.internal_coordinates =
7335 makeGeodesicInternalCoordinatesForPath(candidate, config);
7336 if (geodesic.internal_coordinates) {
7337 geodesic.internal_trust_per_primitive = internalTrustFromPathSpacing(
7338 candidate, *geodesic.internal_coordinates);
7339 }
7340 geodesic.min_distance_ratio_limit = config.trust_ratio_at_limit;
7341 geodesic.atomic_numbers = config.atomic_numbers;
7342 geodesic.frozen_positions = config.frozen_positions;
7343 geodesic.frozen_atomic_numbers = config.frozen_atomic_numbers;
7344 geodesic.cell = config.cell;
7345
7346 std::vector<char> active_images;
7347 if (targeted) {
7348 active_images.assign(static_cast<std::size_t>(candidate.numImages()),
7349 0);
7350 active_images[static_cast<std::size_t>(selected_image)] = 1;
7351 }
7352 NEBBandObjective objective(
7353 candidate,
7354 [&candidate]() {
7355 candidate.computeNEBForces();
7356 return true;
7357 },
7358 std::move(geodesic), /*fixed_image_index=*/-1,
7359 std::move(active_images));
7360 GlobalLBFGSOptimizer optimizer(options);
7361 if (!optimizer.step(objective, config.lbfgs_max_move)) {
7362 return fail(MeasuredNebStepStatus::OptimizerRejected);
7363 }
7364
7365 std::vector<Eigen::VectorXd> proposed(candidate.numImages());
7366 bool has_resolved_displacement = false;
7367 for (int i = 0; i < candidate.numImages(); ++i) {
7368 proposed[i] = candidate.image(i).positions;
7369 if (i > 0 && i < candidate.numImages() - 1 &&
7370 (!targeted || i == selected_image)) {
7371 has_resolved_displacement =
7372 has_resolved_displacement ||
7373 !positionsCoincide(path.image(i).positions, proposed[i]);
7374 }
7375 }
7376 if (!has_resolved_displacement) {
7377 if (config.sidpp_geodesic) {
7378 // Path spacing is a geometric preconditioner, not a physical
7379 // constraint. A collapsed chart cannot supply a new training
7380 // point. The measured Cartesian action retains displacement
7381 // and contact limits and requires the caller's trust and oracle
7382 // validation before the band can accept it.
7383 GPNEBConfig cartesian_config = config;
7384 cartesian_config.sidpp_geodesic = false;
7385 return proposeMeasuredNebStep(path, cartesian_config,
7386 selected_image, status);
7387 }
7388 return fail(MeasuredNebStepStatus::OptimizerRejected);
7389 }
7390 if (status) *status = MeasuredNebStepStatus::Proposed;
7391 return proposed;
7392}
7393
7394std::vector<Eigen::VectorXd> proposeCertifiedMeasuredNebStep(
7395 const NEBPath& path, const gpr::Observation& observations,
7396 const GPNEBConfig& config, int selected_image,
7397 MeasuredNebStepStatus* status)
7398{
7399 if (selected_image <= 0 || selected_image >= path.numImages() - 1) {
7400 if (status) *status = MeasuredNebStepStatus::InvalidSelection;
7401 return {};
7402 }
7403 NEBPath measured_path = path;
7404 for (int image = selected_image - 1; image <= selected_image + 1; ++image) {
7405 if (image > 0 && image < measured_path.numImages() - 1 &&
7406 !restoreObservedImageIfPresent(observations,
7407 measured_path.image(image))) {
7408 if (status) *status = MeasuredNebStepStatus::MissingMeasurement;
7409 return {};
7410 }
7411 }
7412 measured_path.computeNEBForces();
7413 return proposeMeasuredNebStep(measured_path, config, selected_image,
7414 status);
7415}
7416
7417std::vector<Eigen::VectorXd> proposeCertifiedMeasuredNebStep(
7418 const NEBPath& path, const ActiveLearningSession& session,
7419 const GPNEBConfig& config, int selected_image,
7420 MeasuredNebStepStatus* status)
7421{
7422 if (selected_image <= 0 || selected_image >= path.numImages() - 1) {
7423 if (status) *status = MeasuredNebStepStatus::InvalidSelection;
7424 return {};
7425 }
7426 NEBPath measured_path = path;
7427 for (int image = selected_image - 1; image <= selected_image + 1; ++image) {
7428 if (image <= 0 || image >= measured_path.numImages() - 1) continue;
7429 const auto observation = session.currentChainObservation(
7430 image, measured_path.image(image).positions);
7431 if (!observation) {
7432 if (status) *status = MeasuredNebStepStatus::MissingMeasurement;
7433 return {};
7434 }
7435 measured_path.image(image).energy = observation->energy;
7436 measured_path.image(image).gradient = observation->gradient;
7437 measured_path.image(image).evaluated = true;
7438 }
7439 measured_path.computeNEBForces();
7440 return proposeMeasuredNebStep(measured_path, config, selected_image,
7441 status);
7442}
7443
7444std::vector<Eigen::VectorXd> oieRecoveryGrowthCandidates(
7445 const Eigen::VectorXd& source, const Eigen::VectorXd& measured_proposal,
7446 const gpr::Observation& local_observations)
7447{
7448 if (source.size() == 0 || measured_proposal.size() != source.size() ||
7449 !source.allFinite() || !measured_proposal.allFinite() ||
7450 positionsCoincide(source, measured_proposal) ||
7451 (local_observations.R.rows() > 0 &&
7452 local_observations.R.cols() != source.size())) {
7453 return {};
7454 }
7455
7456 std::vector<Eigen::VectorXd> candidates;
7457 const auto append_distinct = [&](const Eigen::VectorXd& candidate) {
7458 if (candidate.size() != source.size() || !candidate.allFinite() ||
7459 positionsCoincide(candidate, source)) {
7460 return;
7461 }
7462 const bool duplicate =
7463 std::any_of(candidates.begin(), candidates.end(),
7464 [&](const Eigen::VectorXd& existing) {
7465 return positionsCoincide(existing, candidate);
7466 });
7467 if (!duplicate) candidates.push_back(candidate);
7468 };
7469
7470 const Eigen::VectorXd measured_step = measured_proposal - source;
7471 const double step_norm = measured_step.norm();
7472 if (!(step_norm > 0.0) || !std::isfinite(step_norm)) return {};
7473
7474 append_distinct(measured_proposal);
7475 append_distinct(source - measured_step);
7476 for (Eigen::Index row = 0; row < local_observations.R.rows(); ++row) {
7477 const Eigen::VectorXd observed =
7478 local_observations.R.row(row).transpose();
7479 if (!observed.allFinite() || positionsCoincide(observed, source)) {
7480 continue;
7481 }
7482 const Eigen::VectorXd trajectory = observed - source;
7483 const double trajectory_norm = trajectory.norm();
7484 if (!(trajectory_norm > 0.0) || !std::isfinite(trajectory_norm)) {
7485 continue;
7486 }
7487 const Eigen::VectorXd direction = trajectory / trajectory_norm;
7488 append_distinct(observed + step_norm * direction);
7489 append_distinct(source - step_norm * direction);
7490 }
7491 return candidates;
7492}
7493
7494int selectOieRecoveryGrowthCandidate(const std::vector<char>& admissible,
7495 const std::vector<double>& variances,
7496 const std::vector<double>& trust_distances,
7497 int measured_step_index,
7498 int secant_backtrack_index)
7499{
7500 if (admissible.size() != variances.size() ||
7501 admissible.size() != trust_distances.size()) {
7502 return -1;
7503 }
7504 const auto selectable = [&](int index) {
7505 return index >= 0 && index < static_cast<int>(admissible.size()) &&
7506 admissible[static_cast<std::size_t>(index)] != 0;
7507 };
7508 if (selectable(secant_backtrack_index)) return secant_backtrack_index;
7509 if (selectable(measured_step_index)) return measured_step_index;
7510
7511 int selected = -1;
7512 double best_variance = -std::numeric_limits<double>::infinity();
7513 double best_trust_distance = -std::numeric_limits<double>::infinity();
7514 for (std::size_t index = 0; index < admissible.size(); ++index) {
7515 if (!admissible[index] || !std::isfinite(variances[index]) ||
7516 !std::isfinite(trust_distances[index])) {
7517 continue;
7518 }
7519 if (selected < 0 || variances[index] > best_variance ||
7520 (variances[index] == best_variance &&
7521 trust_distances[index] > best_trust_distance)) {
7522 selected = static_cast<int>(index);
7523 best_variance = variances[index];
7524 best_trust_distance = trust_distances[index];
7525 }
7526 }
7527 return selected;
7528}
7529
7530std::vector<Eigen::VectorXd> isolateBandProposalImage(
7531 const NEBPath& source,
7532 const std::vector<Eigen::VectorXd>& proposed_positions, int selected_image)
7533{
7534 if (selected_image <= 0 || selected_image >= source.numImages() - 1 ||
7535 proposed_positions.size() !=
7536 static_cast<std::size_t>(source.numImages()) ||
7537 proposed_positions[static_cast<std::size_t>(selected_image)].size() !=
7538 source.image(selected_image).positions.size()) {
7539 return {};
7540 }
7541 std::vector<Eigen::VectorXd> candidate(source.numImages());
7542 for (int i = 0; i < source.numImages(); ++i) {
7543 candidate[static_cast<std::size_t>(i)] = source.image(i).positions;
7544 }
7545 candidate[static_cast<std::size_t>(selected_image)] =
7546 proposed_positions[static_cast<std::size_t>(selected_image)];
7547 return candidate;
7548}
7549
7550namespace {
7551
7552std::vector<double> measuredBandForceNorms(const NEBPath& source)
7553{
7554 if (source.numImages() <= 2) return {};
7555 for (int i = 0; i < source.numImages(); ++i) {
7556 const auto& image = source.image(i);
7557 if (!std::isfinite(image.energy) || !image.positions.allFinite()) {
7558 return {};
7559 }
7560 if (i > 0 && i < source.numImages() - 1 &&
7561 (!image.evaluated ||
7562 image.gradient.size() != image.positions.size() ||
7563 !image.gradient.allFinite())) {
7564 return {};
7565 }
7566 }
7567
7568 NEBPath measured = source;
7569 measured.computeNEBForces();
7570 std::vector<double> force_norms;
7571 force_norms.reserve(static_cast<std::size_t>(measured.numImages() - 2));
7572 for (int i = 1; i < measured.numImages() - 1; ++i) {
7573 const double force = measured.nebForceMagnitude(i);
7574 if (!std::isfinite(force)) return {};
7575 force_norms.push_back(force);
7576 }
7577 return force_norms;
7578}
7579
7580} // namespace
7581
7582std::vector<double> measuredBandForceProfile(const NEBPath& source,
7583 int climbing_image)
7584{
7585 if (climbing_image >= 0) {
7586 if (climbing_image == 0 || climbing_image >= source.numImages() - 1) {
7587 return {};
7588 }
7589 const auto& image = source.image(climbing_image);
7590 if (!image.is_climbing || !image.evaluated ||
7591 !std::isfinite(image.energy) || image.positions.size() == 0 ||
7592 !image.positions.allFinite() ||
7593 image.gradient.size() != image.positions.size() ||
7594 !image.gradient.allFinite()) {
7595 return {};
7596 }
7597 const double force = source.saddleForce(climbing_image);
7598 if (!std::isfinite(force)) return {};
7599 return {force};
7600 }
7601 std::vector<double> profile = measuredBandForceNorms(source);
7602 std::sort(profile.begin(), profile.end(), std::greater<double>());
7603 return profile;
7604}
7605
7606MeasuredResidualStepAssessment assessMeasuredClimbingStep(
7607 const NEBPath& source, const NEBPath& candidate, int climbing_image)
7608{
7609 if (climbing_image <= 0 || climbing_image >= source.numImages() - 1 ||
7610 source.numImages() != candidate.numImages() ||
7611 measuredBandForceProfile(source, climbing_image).empty() ||
7612 measuredBandForceProfile(candidate, climbing_image).empty()) {
7613 return {};
7614 }
7615 for (int i = 0; i < source.numImages(); ++i) {
7616 if (source.image(i).positions.size() !=
7617 candidate.image(i).positions.size() ||
7618 (i != climbing_image &&
7619 !positionsCoincide(source.image(i).positions,
7620 candidate.image(i).positions))) {
7621 return {};
7622 }
7623 }
7624 const auto& source_image = source.image(climbing_image);
7625 const auto& candidate_image = candidate.image(climbing_image);
7626 if (positionsCoincide(source_image.positions, candidate_image.positions)) {
7627 return {};
7628 }
7629 MeasuredResidualStepAssessment assessment;
7630 const double source_residual = source_image.gradient.norm();
7631 const double candidate_residual = candidate_image.gradient.norm();
7632 if (std::isfinite(source_residual) && std::isfinite(candidate_residual) &&
7633 candidate_residual < source_residual) {
7634 assessment.action = MeasuredResidualStepAction::Accept;
7635 return assessment;
7636 }
7637
7638 // A climbing reflection preserves the full force norm. The physical
7639 // force secant measures the residual along the actual proposed motion;
7640 // an interior affine minimum supplies another measured trial.
7641 const Eigen::VectorXd difference =
7642 candidate_image.gradient - source_image.gradient;
7643 const double numerator = -source_image.gradient.dot(difference);
7644 const double denominator = difference.squaredNorm();
7645 if (std::isfinite(numerator) && std::isfinite(denominator) &&
7646 numerator > 0.0 && numerator < denominator) {
7647 const double fraction = numerator / denominator;
7648 if (fraction > 0.0 && fraction < 1.0) {
7649 assessment.action = MeasuredResidualStepAction::Backtrack;
7650 assessment.backtrack_fraction = fraction;
7651 }
7652 }
7653 return assessment;
7654}
7655
7656MeasuredBandProposalAssessment assessMeasuredBandProposal(
7657 const NEBPath& source, const NEBPath& candidate)
7658{
7659 MeasuredBandProposalAssessment assessment;
7660 if (source.numImages() <= 2 ||
7661 source.numImages() != candidate.numImages()) {
7662 return assessment;
7663 }
7664
7665 const std::vector<double> source_profile = measuredBandForceProfile(source);
7666 const std::vector<double> candidate_profile =
7667 measuredBandForceProfile(candidate);
7668 if (source_profile.empty() ||
7669 source_profile.size() != candidate_profile.size()) {
7670 return assessment;
7671 }
7672
7673 const Eigen::Index image_dof = source.image(0).positions.size();
7674 const Eigen::Index interior_count = source.numImages() - 2;
7675 if (image_dof <= 0) return assessment;
7676 for (int i = 0; i < source.numImages(); ++i) {
7677 if (source.image(i).positions.size() != image_dof ||
7678 candidate.image(i).positions.size() != image_dof) {
7679 return assessment;
7680 }
7681 }
7682
7683 NEBPath measured_source = source;
7684 NEBPath measured_candidate = candidate;
7685 measured_source.computeNEBForces();
7686 measured_candidate.computeNEBForces();
7687 Eigen::VectorXd source_positions(interior_count * image_dof);
7688 Eigen::VectorXd source_forces(interior_count * image_dof);
7689 Eigen::VectorXd candidate_positions(interior_count * image_dof);
7690 Eigen::VectorXd candidate_forces(interior_count * image_dof);
7691 for (Eigen::Index interior = 0; interior < interior_count; ++interior) {
7692 const int image = static_cast<int>(interior) + 1;
7693 const Eigen::Index offset = interior * image_dof;
7694 source_positions.segment(offset, image_dof) =
7695 measured_source.image(image).positions;
7696 source_forces.segment(offset, image_dof) =
7697 measured_source.nebForce(image);
7698 candidate_positions.segment(offset, image_dof) =
7699 measured_candidate.image(image).positions;
7700 candidate_forces.segment(offset, image_dof) =
7701 measured_candidate.nebForce(image);
7702 }
7703
7704 assessment.fully_measured = true;
7705 assessment.accept =
7706 shouldAcceptMeasuredBandCandidate(candidate_profile, source_profile);
7707 assessment.inverse_curvature = oieBbForceStepLength(
7708 source_positions, source_forces, candidate_positions, candidate_forces);
7709 return assessment;
7710}
7711
7712int selectMeasuredBandForceTarget(const NEBPath& source)
7713{
7714 const std::vector<double> force_norms = measuredBandForceNorms(source);
7715 if (force_norms.empty()) return -1;
7716 return static_cast<int>(std::distance(
7717 force_norms.begin(),
7718 std::max_element(force_norms.begin(), force_norms.end()))) +
7719 1;
7720}
7721
7722bool commitMeasuredBandCandidate(NEBPath& accepted_path,
7723 const NEBPath& measured_candidate,
7724 int climbing_image)
7725{
7726 if (accepted_path.numImages() != measured_candidate.numImages() ||
7727 measuredBandForceProfile(measured_candidate, climbing_image).empty()) {
7728 return false;
7729 }
7730
7731 if (climbing_image > 0) {
7732 if (!accepted_path.image(climbing_image).is_climbing) return false;
7733 for (int i = 0; i < accepted_path.numImages(); ++i) {
7734 if (i != climbing_image &&
7735 !positionsCoincide(accepted_path.image(i).positions,
7736 measured_candidate.image(i).positions)) {
7737 return false;
7738 }
7739 }
7740 accepted_path.image(climbing_image) =
7741 measured_candidate.image(climbing_image);
7742 accepted_path.computeNEBForces();
7743 return true;
7744 }
7745 accepted_path = measured_candidate;
7746 accepted_path.computeNEBForces();
7747 return true;
7748}
7749
7750bool shouldAcceptMeasuredBandCandidate(double candidate_max_force,
7751 double anchor_max_force) noexcept
7752{
7753 return std::isfinite(candidate_max_force) &&
7754 candidate_max_force < anchor_max_force;
7755}
7756
7757bool shouldAcceptMeasuredBandCandidate(
7758 const std::vector<double>& candidate_force_profile,
7759 const std::vector<double>& anchor_force_profile) noexcept
7760{
7761 if (candidate_force_profile.empty() ||
7762 candidate_force_profile.size() != anchor_force_profile.size()) {
7763 return false;
7764 }
7765 for (std::size_t i = 0; i < candidate_force_profile.size(); ++i) {
7766 const double candidate = candidate_force_profile[i];
7767 const double anchor = anchor_force_profile[i];
7768 if (!std::isfinite(candidate) || std::isnan(anchor)) return false;
7769 if (candidate < anchor) return true;
7770 if (candidate > anchor) return false;
7771 }
7772 return false;
7773}
7774
7775} // namespace detail
7776
7777namespace {
7778
7779// Helper: evaluate a set of images in parallel across MPI ranks to avoid
7780// rank replication. Returns a vector of results (E, G) for all requested
7781// images on all ranks.
7782struct EvalResult {
7783 double energy;
7784 Eigen::VectorXd gradient;
7785};
7786
7787class ScopedOracleEvaluationContext {
7788public:
7789 ScopedOracleEvaluationContext(
7790 const std::function<void(const NEBOracleEvaluationContext&)>& hook,
7791 const NEBOracleEvaluationContext& context)
7792 : hook_(hook)
7793 {
7794 if (hook_) hook_(context);
7795 }
7796
7797 ~ScopedOracleEvaluationContext()
7798 {
7799 if (hook_) hook_(NEBOracleEvaluationContext{});
7800 }
7801
7802 ScopedOracleEvaluationContext(const ScopedOracleEvaluationContext&) =
7803 delete;
7804 ScopedOracleEvaluationContext& operator=(
7805 const ScopedOracleEvaluationContext&) = delete;
7806
7807private:
7808 const std::function<void(const NEBOracleEvaluationContext&)>& hook_;
7809};
7810
7823std::vector<EvalResult> parallelEvaluate(
7824 const std::vector<Eigen::VectorXd>& points, const NEBOracle& oracle,
7825 const std::vector<NEBOracleEvaluationContext>* contexts = nullptr,
7826 const std::function<void(const NEBOracleEvaluationContext&)>& context_hook =
7827 {},
7828 const std::function<bool()>& session_restart_requested = {},
7829 const NEBBatchOracle* batch_oracle = nullptr, Eigen::Index batch_chunk = 0,
7830 std::vector<char>* accepted = nullptr, std::string* refusal_out = nullptr)
7831{
7832 const auto n_pts = static_cast<Eigen::Index>(points.size());
7833 std::vector<EvalResult> results(static_cast<std::size_t>(n_pts));
7834 if (n_pts == 0) return results;
7835 const auto D = static_cast<Eigen::Index>(points[0].size());
7836
7837 const pot::OracleBatchLayout layout =
7838 pot::OracleBatchLayout::world(batch_chunk);
7839 const bool batched = batch_oracle && *batch_oracle && !context_hook;
7840
7841 std::vector<double> energies(static_cast<std::size_t>(n_pts), 0.0);
7842 Eigen::MatrixXd gradients = Eigen::MatrixXd::Zero(n_pts, D);
7843 const auto store = [&](Eigen::Index i, double energy,
7844 const Eigen::VectorXd& gradient) {
7845 if (gradient.size() != D) {
7846 throw std::runtime_error(
7847 "oracle gradient dimension differs from its position");
7848 }
7849 // A non-finite value is a failed measurement like a raised error:
7850 // it becomes the batch's refusal, and the caller rejects the trial.
7851 if (!std::isfinite(energy) || !gradient.allFinite()) {
7852 throw std::runtime_error(
7853 "oracle returned a non-finite energy or force");
7854 }
7855 energies[static_cast<std::size_t>(i)] = energy;
7856 gradients.row(i) = gradient.transpose();
7857 };
7858 const auto context_of = [&](Eigen::Index i) {
7859 return contexts && i < static_cast<Eigen::Index>(contexts->size())
7860 ? (*contexts)[static_cast<std::size_t>(i)]
7861 : NEBOracleEvaluationContext{};
7862 };
7863
7864 // 1. Each rank records its own refusal. All ranks agree on failure
7865 // before sharing values, so a throwing owner cannot strand its peers.
7866 // A caller that passes `accepted` keeps every geometry this rank
7867 // evaluated. One refused point does not drop the rest of its group,
7868 // and the mask says which rows are real after the union.
7870 std::string refusal;
7871 bool wall_clock_limit = false;
7872 std::vector<char> accepted_local(static_cast<std::size_t>(n_pts), 0);
7873 const auto note_failure = [&](const std::string& message) {
7875 if (refusal.empty()) refusal = message;
7876 };
7877 const auto note_wall_clock_limit = [&]() {
7879 wall_clock_limit = true;
7880 refusal = "wall-clock limit reached";
7881 };
7882 const auto accept_point = [&](Eigen::Index i) {
7883 accepted_local[static_cast<std::size_t>(i)] = 1;
7884 };
7885 for (const auto& group: pot::ownedOracleGroups(n_pts, layout)) {
7886 if (wall_clock_limit) break;
7888 if (accepted == nullptr && status != pot::OracleBatchStatus::Ok) break;
7889 try {
7890 if (batched) {
7891 std::vector<Eigen::VectorXd> owned;
7892 owned.reserve(group.size());
7893 for (const Eigen::Index i: group)
7894 owned.push_back(points[i]);
7895 const auto rows = (*batch_oracle)(owned);
7896 if (rows.size() != group.size()) {
7897 throw std::runtime_error(
7898 "batch oracle returned a different number of rows "
7899 "than points");
7900 }
7901 for (std::size_t k = 0; k < group.size(); ++k) {
7902 store(group[k], rows[k].first, rows[k].second);
7903 accept_point(group[k]);
7904 }
7905 } else if (accepted == nullptr) {
7906 for (const Eigen::Index i: group) {
7907 const ScopedOracleEvaluationContext context_scope(
7908 context_hook, context_of(i));
7909 const auto [e, g] = oracle(points[i]);
7910 store(i, e, g);
7911 accept_point(i);
7912 }
7913 } else {
7914 for (const Eigen::Index i: group) {
7915 try {
7916 const ScopedOracleEvaluationContext context_scope(
7917 context_hook, context_of(i));
7918 const auto [e, g] = oracle(points[i]);
7919 store(i, e, g);
7920 accept_point(i);
7921 } catch (const OracleSessionRestartRequested&) {
7923 break;
7924 } catch (const gpr::WallClockLimitReached&) {
7925 note_wall_clock_limit();
7926 break;
7927 } catch (const std::exception& error) {
7928 note_failure(error.what());
7929 } catch (...) {
7930 note_failure("oracle raised a non-standard exception");
7931 }
7932 }
7933 }
7934 } catch (const OracleSessionRestartRequested&) {
7936 } catch (const gpr::WallClockLimitReached&) {
7937 note_wall_clock_limit();
7938 } catch (const std::exception& error) {
7939 note_failure(error.what());
7940 } catch (...) {
7941 note_failure("oracle raised a non-standard exception");
7942 }
7943 }
7944
7945 const auto outcome = pot::agreeOracleBatchStatus(status, refusal, layout);
7946 if (outcome.status == pot::OracleBatchStatus::WallClockLimit)
7948 if (outcome.status == pot::OracleBatchStatus::Restart)
7949 throw OracleSessionRestartRequested{};
7950 if (accepted == nullptr && outcome.status != pot::OracleBatchStatus::Ok) {
7951 throw std::runtime_error(
7952 outcome.message.empty()
7953 ? "oracle refused a geometry on another rank"
7954 : outcome.message);
7955 }
7956
7957 // 2. Union of the owners' values; a rank that evaluated nothing holds
7958 // positive zeros, so the bitwise union preserves each owner's values.
7959 // The partial path shares the mask in the same step. A refused point
7960 // stays zero and unaccepted on every rank. Callers that throw on any
7961 // failure never reach here with a failed batch, and they do not pay
7962 // for the mask collective.
7963 if (accepted != nullptr)
7964 pot::allreduceOwnedOracleMask(accepted_local, layout);
7965 pot::allreduceOwnedOracleValues(energies, gradients, layout,
7967 if (accepted != nullptr) {
7968 *accepted = std::move(accepted_local);
7969 if (refusal_out != nullptr) *refusal_out = outcome.message;
7970 }
7971 for (Eigen::Index i = 0; i < n_pts; ++i) {
7972 results[static_cast<std::size_t>(i)].energy =
7973 energies[static_cast<std::size_t>(i)];
7974 results[static_cast<std::size_t>(i)].gradient =
7975 gradients.row(i).transpose();
7976 }
7977 detail::throwIfOracleSessionRestartRequested(session_restart_requested);
7978 return results;
7979}
7980
7981// Append one (positions, energy, gradient) triple to a growing
7982// Observation. Each row of obs.R holds positions for one image; obs.E
7983// is shaped (n_obs, 1) and obs.G is shaped (n_obs, D). Layout matches
7984// AtomicDimer's all_obs accumulation pattern (gpr::field::appendRows).
7985void appendObservation(gpr::Observation& obs, const Eigen::VectorXd& positions,
7986 double energy, const Eigen::VectorXd& gradient)
7987{
7988 const Eigen::Index D = positions.size();
7989 const Eigen::Index n0 = obs.R.rows();
7990 if (n0 == 0) {
7991 obs.R.resize(1, D);
7992 obs.E.resize(1, 1);
7993 obs.G.resize(1, D);
7994 } else {
7995 // Append one row in place. Mirror of gpr::field::appendRows
7996 // semantics for the (R, E, G) triple; row-major storage keeps
7997 // the existing rows contiguous after the resize.
7998 obs.R.conservativeResize(n0 + 1, D);
7999 obs.E.conservativeResize(n0 + 1, 1);
8000 obs.G.conservativeResize(n0 + 1, D);
8001 }
8002 const Eigen::Index k = obs.R.rows() - 1;
8003 for (Eigen::Index j = 0; j < D; ++j)
8004 obs.R(k, j) = positions(j);
8005 obs.E(k, 0) = energy;
8006 for (Eigen::Index j = 0; j < D; ++j)
8007 obs.G(k, j) = gradient(j);
8008}
8009
8010int liveOracleCalls(const GPNEBResult& result)
8011{
8012 return result.oracle_calls_endpoints + result.oracle_calls_initial +
8013 result.oracle_calls_outer;
8014}
8015
8016void noteNebPolicyProgress(ActiveLearningSession* session, int iteration,
8017 const GPNEBResult& result, int training_size)
8018{
8019 if (session == nullptr) return;
8020 session->publishPolicyProgress(iteration, liveOracleCalls(result),
8021 result.hyperparameter_refits, training_size);
8022}
8023
8024double probeEnergyVariance(GaussianProcessRegression& gp,
8025 const Eigen::VectorXd& positions)
8026{
8027 try {
8028 gpr::Observation probe;
8029 probe.R.resize(1, positions.size());
8030 probe.R.row(0) = positions.transpose();
8031 gp.calculateVarianceDispatched(probe);
8032 if (probe.E.size() == 0 || !probe.E.allFinite()) {
8033 return std::numeric_limits<double>::quiet_NaN();
8034 }
8035 return std::abs(probe.E(0, 0));
8036 } catch (const std::exception&) {
8037 return std::numeric_limits<double>::quiet_NaN();
8038 }
8039}
8040
8041void filterAcquisitionBatch(
8042 const GPNEBConfig& config, GaussianProcessRegression& gp,
8043 ActiveLearningSession* session, int iteration, const GPNEBResult& result,
8044 const gpr::Observation& training, std::vector<int>& indices,
8045 std::vector<Eigen::VectorXd>& positions, std::vector<char>& off_path,
8046 std::vector<NEBOracleEvaluationContext>& contexts)
8047{
8048 if (config.training_policy == nullptr || positions.empty()) return;
8049 noteNebPolicyProgress(session, iteration, result,
8050 static_cast<int>(training.R.rows()));
8051 std::vector<int> keep;
8052 keep.reserve(positions.size());
8053 for (std::size_t i = 0; i < positions.size(); ++i) {
8054 if (i < contexts.size() && (contexts[i].current_chain_certificate ||
8055 contexts[i].force_stencil)) {
8056 keep.push_back(static_cast<int>(i));
8057 continue;
8058 }
8059 GaussianProcessRegression& model =
8060 session != nullptr ? session->gp : gp;
8061 const double variance = probeEnergyVariance(model, positions[i]);
8062 policy::SearchState state;
8063 state.kind = config.training_search_kind;
8064 state.role = policy::OracleRole::Acquisition;
8065 state.iteration = iteration;
8066 state.oracle_calls = liveOracleCalls(result);
8067 state.training_size = static_cast<int>(training.R.rows());
8068 state.hyperparameter_refits = result.hyperparameter_refits;
8069 state.posterior_variance = variance;
8070 state.engine_would_call_oracle = true;
8071 state.engine_would_retrain = true;
8072 state.engine_would_rebuild_factor = true;
8073 state.positions = positions[i].data();
8074 state.n_coords = static_cast<int>(positions[i].size());
8075 state.image_index = i < indices.size() ? indices[i] : -1;
8076 state.gp = &model;
8077 if (policy::consensusShouldCallOracle(*config.training_policy, state))
8078 keep.push_back(static_cast<int>(i));
8079 }
8080 if (keep.size() == positions.size()) return;
8081 const auto compact = [&](auto& values) {
8082 using Value = typename std::decay<decltype(values)>::type::value_type;
8083 std::vector<Value> next;
8084 next.reserve(keep.size());
8085 for (const int index: keep)
8086 next.push_back(std::move(values[static_cast<std::size_t>(index)]));
8087 values.swap(next);
8088 };
8089 compact(indices);
8090 compact(positions);
8091 compact(off_path);
8092 compact(contexts);
8093}
8094
8095bool policyAdmitsRow(const policy::TrainingPolicy& policy,
8096 const Eigen::VectorXd& positions, double energy,
8097 const Eigen::VectorXd& gradient,
8098 const gpr::Observation& training)
8099{
8100 policy::CandidatePoint candidate;
8101 candidate.positions = positions;
8102 candidate.energy = energy;
8103 candidate.gradient = gradient;
8104 std::vector<Eigen::VectorXd> current;
8105 current.reserve(static_cast<std::size_t>(training.R.rows()));
8106 for (Eigen::Index row = 0; row < training.R.rows(); ++row)
8107 current.emplace_back(training.R.row(row).transpose());
8108 const std::vector<int> indices =
8109 policy::consensusSelectTrainingPoints(policy, {candidate}, current);
8110 return policy::admitsFirstCandidate(indices);
8111}
8112
8113bool retainTrainingObservation(const policy::TrainingPolicy& policy,
8114 gpr::Observation& training,
8115 GaussianProcessRegression& gp,
8116 ActiveLearningSession* session)
8117{
8118 if (session != nullptr) {
8119 return session->retainTrainingRowsForPolicy(policy);
8120 }
8121 const int n = static_cast<int>(training.R.rows());
8122 if (n == 0) return false;
8123 std::vector<Eigen::VectorXd> rows;
8124 rows.reserve(static_cast<std::size_t>(n));
8125 for (Eigen::Index row = 0; row < training.R.rows(); ++row)
8126 rows.emplace_back(training.R.row(row).transpose());
8127 const std::vector<int> keep =
8128 policy::consensusRetainTrainingRows(policy, rows);
8129 const std::vector<int> accepted =
8130 policy::canonicalizeRetainedIndices(keep, n);
8131 if (policy::indexListIsIdentity(accepted, n)) return false;
8132 gpr::Observation next;
8133 const Eigen::Index kept = static_cast<Eigen::Index>(accepted.size());
8134 const Eigen::Index dof = training.R.cols();
8135 next.R.resize(kept, dof);
8136 next.E.resize(kept, training.E.cols() > 0 ? training.E.cols() : 1);
8137 next.G.resize(kept, training.G.cols() > 0 ? training.G.cols() : dof);
8138 for (Eigen::Index out = 0; out < kept; ++out) {
8139 const Eigen::Index row = accepted[static_cast<std::size_t>(out)];
8140 next.R.row(out) = training.R.row(row);
8141 if (training.E.rows() > row) next.E.row(out) = training.E.row(row);
8142 if (training.G.rows() > row) next.G.row(out) = training.G.row(row);
8143 }
8144 training = std::move(next);
8145 const bool had_model =
8146 gp.isDecomposedSuccessfully() || gp.hasBeenOptimized();
8147 gp.clearModeRefitHint();
8148 gp.invalidateTrainingFactorCache();
8149 if (had_model && training.R.rows() > 0) {
8150 gp.updateModelWithFullData(training);
8151 }
8152 return true;
8153}
8154
8155bool optimizeUnlessPolicy(GaussianProcessRegression& gp,
8156 const gpr::Observation& training,
8157 const AtomsConfiguration& atoms, bool reinit,
8158 const GPNEBConfig& config, int iteration,
8159 const GPNEBResult& result,
8160 bool pruned_in_outer = false)
8161{
8162 if (config.training_policy != nullptr) {
8163 const bool unseeded =
8164 !gp.isDecomposedSuccessfully() && !gp.hasBeenOptimized();
8165 if (unseeded && training.R.rows() > 0) {
8166 gp.setHyperparameters(training, atoms, reinit, reinit, reinit);
8167 }
8168 policy::SearchState state;
8169 state.kind = config.training_search_kind;
8170 state.iteration = iteration;
8171 state.oracle_calls = liveOracleCalls(result);
8172 state.training_size = static_cast<int>(training.R.rows());
8173 state.hyperparameter_refits = result.hyperparameter_refits;
8174 state.engine_would_retrain = true;
8175 state.engine_would_rebuild_factor = true;
8176 state.gp = &gp;
8177 if (!policy::consensusShouldRetrainHyperparameters(
8178 *config.training_policy, state)) {
8179 const bool rebuild = policy::consensusShouldRebuildFactor(
8180 *config.training_policy, state);
8181 gp.clearModeRefitHint();
8182 if (training.R.rows() == 0) {
8183 gp.invalidateTrainingFactorCache();
8184 return false;
8185 }
8186 if (pruned_in_outer && !config.attach_manifold_chart &&
8187 gp.isDecomposedSuccessfully()) {
8188 return false;
8189 }
8190 if (!rebuild && gp.trainingFactorAppendable(training.R.rows())) {
8191 gp.updateModelWithFullData(training);
8192 return false;
8193 }
8194 if (rebuild) gp.invalidateTrainingFactorCache();
8195 gp.updateModelWithFullData(training);
8196 return false;
8197 }
8198 if (training.R.rows() == 0) {
8199 gp.invalidateTrainingFactorCache();
8200 return false;
8201 }
8202 if (!unseeded) {
8203 gp.setHyperparameters(training, atoms, reinit, reinit, reinit);
8204 }
8205 gp.optimize(training);
8206 return true;
8207 }
8208 gp.setHyperparameters(training, atoms, reinit, reinit, reinit);
8209 gp.optimize(training);
8210 return true;
8211}
8212
8221std::vector<EvalResult> evaluateTrialPoints(
8222 const std::vector<Eigen::VectorXd>& points, const NEBOracle& oracle,
8223 const std::vector<NEBOracleEvaluationContext>* contexts,
8224 const std::function<void(const NEBOracleEvaluationContext&)>& context_hook,
8225 const std::function<bool()>& session_restart_requested,
8226 const NEBBatchOracle* batch_oracle, Eigen::Index batch_chunk,
8227 std::vector<char>& measured, std::string& failure)
8228{
8229 measured.assign(points.size(), 0);
8230 auto results = parallelEvaluate(points, oracle, contexts, context_hook,
8231 session_restart_requested, batch_oracle,
8232 batch_chunk, &measured, &failure);
8233 for (std::size_t i = 0; i < results.size(); ++i) {
8234 if (measured[i]) continue;
8235 results[i].energy = std::numeric_limits<double>::quiet_NaN();
8236 results[i].gradient = Eigen::VectorXd::Constant(
8237 points[i].size(), std::numeric_limits<double>::quiet_NaN());
8238 }
8239 if (failure.empty() &&
8240 std::find(measured.begin(), measured.end(), 0) != measured.end())
8241 failure = "oracle refused a geometry";
8242 return results;
8243}
8244
8247class OracleFailureBudget {
8248public:
8249 void measured() noexcept
8250 {
8251 consecutive_ = 0;
8252 }
8253 void failed(const char* where, const std::string& what)
8254 {
8255 ++consecutive_;
8256 if (consecutive_ > kMaxConsecutiveOracleFailures)
8257 throw std::runtime_error(
8258 std::string("the oracle failed at ") +
8259 std::to_string(consecutive_) + " consecutive " + where +
8260 " evaluations, past the bound of " +
8261 std::to_string(kMaxConsecutiveOracleFailures) +
8262 "; last: " + what);
8263 }
8264
8265private:
8266 int consecutive_ = 0;
8267};
8268
8269} // namespace
8270
8271std::pair<double, Eigen::VectorXd> detail::evaluateOieOraclePosition(
8272 const Eigen::VectorXd& positions, const NEBOracle& oracle)
8273{
8274 const auto measured =
8275 parallelEvaluate({detail::broadcastRootVector(positions)}, oracle);
8276 return {measured.front().energy, measured.front().gradient};
8277}
8278
8279// Wire layered-chain knobs from a GPNEBConfig onto a constructed
8280// GaussianProcessRegression: hyperparameter mode/objective, uncertainty
8281// mode, HS-SVD, ZBL/nugget/kappa, ScaLAPACK, theta-shift skip, PSIS /
8282// INLA-Delta, and RFF. gprn uses the same GP layering as gprd.
8283// The kernel's pair cutoff. A requested cutoff is kept. Without one, a
8284// periodic band cuts at the radius inside which each pair has a single
8285// nearest image: past it the minimum-image displacement turns
8286// discontinuously, and so do the inverse-distance features and every force
8287// the gradient-enhanced GP predicts from them. Molecules keep unbounded
8288// features.
8289static double bandPairCutoff(const GPNEBConfig& config)
8290{
8291 return config.pair_cutoff > 0.0
8292 ? config.pair_cutoff
8294}
8295
8296void applyConfigToGP(const GPNEBConfig& config,
8298{
8300 const double pair_cutoff = bandPairCutoff(config);
8301 const gpr::PairCutoff validate_cutoff(pair_cutoff,
8302 config.pair_cutoff_width);
8303 if (gp.getAtomsConfig().pair_cutoff != pair_cutoff ||
8305 auto atoms = gp.getAtomsConfig();
8306 atoms.pair_cutoff = pair_cutoff;
8307 atoms.pair_cutoff_width = config.pair_cutoff_width;
8308 gp.updateConfiguration(atoms);
8309 }
8310 // Covering energy/gradient layouts reuse pair derivatives in curvature
8311 // assembly, including an open boundary. The cutoff selected above is
8312 // left as it is. A configuration-pair tile has one owner across MPI
8313 // ranks; a layout that does not cover falls back to the channel blocks.
8315 const bool objective_requires_hssvd = config.hyperparameter_objective ==
8317 if (config.rgmin_method_set)
8318 gp.setRgminMethod(static_cast<rgmin_method_t>(config.rgmin_method));
8324 gp.setHssvdBackend(config.use_hssvd_solver || objective_requires_hssvd);
8326 objective_requires_hssvd);
8336 gpr::detail::validateRigidNullDeflationConfiguration(
8338 if (!config.principled_nugget) gp.setPrincipledNugget(false);
8339 if (!config.use_rigid_null_deflation) gp.setRigidNullDeflation(false);
8342 gp.setUseLsPrior(config.use_ls_prior);
8344 if (!config.gp_population_prior.empty()) {
8345 std::ifstream table(config.gp_population_prior);
8347 if (!table || !population.read(table))
8348 throw std::runtime_error("population prior table unreadable: " +
8349 config.gp_population_prior);
8350 gp.setPopulationPrior(std::move(population));
8351 }
8360 gp.setKappaMax(config.kappa_max);
8367 if (config.scalapack_block_size > 0)
8369 if (config.scalapack_nprow > 0)
8371 if (config.theta_shift_skip_tol > 0.0)
8376 gp.setAnnealStage(
8377 config.gp_anneal_stage,
8378 static_cast<std::size_t>(std::max(0, config.gp_anneal_budget)),
8379 static_cast<std::size_t>(std::max(1, config.gp_anneal_replicas)),
8380 static_cast<std::size_t>(std::max(0, config.gp_anneal_every)),
8381 static_cast<std::uint64_t>(config.seed));
8386 }
8387 // RFF request is uncertainty-mode-agnostic: the cutoff-gated
8388 // RFF-replace path (updateModelWithFullData) serves mean AND variance
8389 // from the RFF posterior for every mode (MAP included), so enable it
8390 // unconditionally. Above the design cutoff it replaces the exact
8391 // dual-kernel eigensolve; below it, it leaves the exact path active.
8392 if (config.rff_features == -1) {
8394 } else if (config.rff_features < -1) {
8395 throw std::invalid_argument(
8396 "rff_features must be -1 (auto), 0, or positive");
8397 } else {
8399 }
8400
8401 // Classic profiles select the joint prior, objective and normalization.
8402 // The configured solver optimizes that objective independently.
8403 gp.setModelProfile(config.model_profile);
8404 if (config.rff_features == -1) {
8406 }
8412 // The classic profiles reset the objective to NLML. An objective named
8413 // on the command line is a decision, not a default: re-apply it after
8414 // the profile so `--hyperparameter-objective loo` fits LOO under
8415 // gprd_zbl instead of silently fitting NLML (every downstream switch
8416 // below keys on the effective mode, so it must be settled here).
8419 config.hyperparameter_objective) {
8421 }
8422 {
8423 const auto effective = gp.getHyperparameterObjectiveMode();
8424 const char* name =
8425 effective == gpr::HyperparameterObjectiveMode::LOO ? "loo"
8427 ? "local_loo"
8428 : "nlml";
8429 neb_log() << "GP objective: " << name
8431 ? " (command line)"
8432 : " (model profile default)")
8433 << "\n";
8434 }
8437 }
8438
8439 // Noise fitting follows the effective objective, including an explicit
8440 // command-line choice. The trailing-noise gradient lives in the NLML
8441 // paths; the LOO direction loop has no branch for it.
8443 config.learn_likelihood_noise &&
8446 gp.setRobustNu(config.robust_nu);
8447 gp.setFitStepStop(config.fit_step_stop);
8448
8449 // LOO requires the dual basis. Other objectives honor the requested
8450 // HS-SVD setting independently of the model profile.
8451 const bool effective_objective_requires_hssvd =
8455 effective_objective_requires_hssvd);
8457 effective_objective_requires_hssvd);
8460}
8461
8462namespace {
8463
8464bool isGpOieMode(NEBMode mode)
8465{
8466 return mode == NEBMode::GP_AIE || mode == NEBMode::GP_OIE;
8467}
8468
8469double gpOieTrustThreshold(const GPNEBConfig& config, int n_training,
8470 int n_atoms)
8471{
8472 if (config.trust_metric == DistanceMetricType::MAX_1D_LOG) {
8473 return std::abs(std::log(config.trust_ratio_at_limit));
8474 }
8475 if (!config.use_adaptive_trust) return config.trust_radius;
8476
8477 const double half_life =
8478 std::max(1.0, static_cast<double>(config.trust_half_life));
8479 const double n = std::max(0, n_training);
8480 const double adaptive =
8481 config.trust_t_min +
8482 config.trust_delta_explore *
8483 (1.0 - std::exp(-std::log(2.0) * n / half_life));
8484 const double physical_limit =
8485 std::max(config.trust_adaptive_floor,
8486 config.trust_adaptive_A /
8487 std::sqrt(std::max(1.0, static_cast<double>(n_atoms))));
8488 return std::min(adaptive, physical_limit);
8489}
8490
8491bool reparametrizeGeodesicBandForConfig(NEBPath& path,
8492 const GPNEBConfig& config,
8493 int anchor_idx = -1)
8494{
8495 const bool keep_anchor =
8496 anchor_idx > 0 && anchor_idx < path.numImages() - 1;
8497 if (!(config.sidpp_geodesic && config.n_atoms > 1 &&
8498 path.image(0).positions.size() ==
8499 static_cast<Eigen::Index>(3 * config.n_atoms))) {
8500 return false;
8501 }
8502 try {
8503 if (keep_anchor) {
8504 (void)path
8505 .reparametrizeByInverseDistanceGeodesicArcLengthKeepingImage(
8506 config.n_atoms, config.moving_atoms, anchor_idx);
8507 } else {
8508 (void)path.reparametrizeByInverseDistanceGeodesicArcLength(
8509 config.n_atoms, config.moving_atoms);
8510 }
8511 return true;
8512 } catch (const std::invalid_argument&) {
8513 return false;
8514 }
8515}
8516
8517void reparametrizeBandForConfig(NEBPath& path, const GPNEBConfig& config,
8518 int anchor_idx = -1)
8519{
8520 if (reparametrizeGeodesicBandForConfig(path, config, anchor_idx)) {
8521 return;
8522 }
8523
8524 const bool keep_anchor =
8525 anchor_idx > 0 && anchor_idx < path.numImages() - 1;
8526 // Degenerate inverse-distance coordinates do not define a geodesic
8527 // update. Cartesian arc length remains well-defined.
8528 if (keep_anchor) {
8529 (void)path.reparametrizeByArcLengthKeepingImage(anchor_idx);
8530 } else {
8531 (void)path.reparametrizeByArcLength();
8532 }
8533}
8534
8535} // namespace
8536
8537namespace detail {
8538
8539int bootstrapOracleSessionFromCheckpoint(
8540 const NEBOracleSessionCheckpoint& checkpoint, NEBOracle& oracle,
8541 const std::function<void(const NEBOracleEvaluationContext&)>&
8542 evaluation_context,
8543 ActiveLearningSession& session, OracleSessionBootstrapScope scope)
8544{
8545 const int n_images = static_cast<int>(checkpoint.positions.rows());
8546 const Eigen::Index coordinates = checkpoint.positions.cols();
8547 if (n_images < 2 || coordinates <= 0 || !checkpoint.positions.allFinite()) {
8548 return 0;
8549 }
8550
8551 std::vector<int> image_indices;
8552 const auto append_unique = [&image_indices](int image) {
8553 if (std::find(image_indices.begin(), image_indices.end(), image) ==
8554 image_indices.end()) {
8555 image_indices.push_back(image);
8556 }
8557 };
8558 const int focal = checkpoint.focal_image_index;
8559 if (scope == OracleSessionBootstrapScope::FullPath) {
8560 image_indices.reserve(static_cast<std::size_t>(n_images));
8561 for (int image = 0; image < n_images; ++image) {
8562 append_unique(image);
8563 }
8564 } else {
8565 append_unique(0);
8566 if (focal > 0 && focal < n_images - 1) {
8567 append_unique(focal - 1);
8568 append_unique(focal);
8569 append_unique(focal + 1);
8570 }
8571 append_unique(n_images - 1);
8572 }
8573
8574 std::vector<Eigen::VectorXd> positions;
8575 std::vector<NEBOracleEvaluationContext> contexts;
8576 positions.reserve(image_indices.size());
8577 contexts.reserve(image_indices.size());
8578 for (const int image: image_indices) {
8579 positions.push_back(checkpoint.positions.row(image).transpose());
8580 NEBOracleEvaluationContext context;
8581 context.image_index = image;
8582 const bool force_stencil = focal > 0 && focal < n_images - 1 &&
8583 image >= focal - 1 && image <= focal + 1;
8584 const bool current_chain =
8585 scope == OracleSessionBootstrapScope::FullPath || force_stencil;
8586 context.force_quality = current_chain;
8587 context.current_chain_certificate = current_chain;
8588 context.force_stencil = force_stencil;
8589 contexts.push_back(context);
8590 }
8591
8592 auto results =
8593 parallelEvaluate(positions, oracle, &contexts, evaluation_context);
8594 session.initialise();
8595 session.initializePerImage(n_images);
8596 for (std::size_t i = 0; i < image_indices.size(); ++i) {
8597 const auto& result = results[i];
8598 if (!std::isfinite(result.energy) ||
8599 result.gradient.size() != coordinates ||
8600 !result.gradient.allFinite()) {
8601 throw std::runtime_error(
8602 "oracle session bootstrap returned a non-finite row");
8603 }
8604 const int image = image_indices[i];
8605 if (contexts[i].current_chain_certificate) {
8606 session.appendCurrentChainObservation(
8607 image, positions[i], result.energy, result.gradient);
8608 } else {
8609 session.appendObservation(image, positions[i], result.energy,
8610 result.gradient);
8611 }
8612 }
8613 return static_cast<int>(image_indices.size());
8614}
8615
8616bool activateOracleTransitionFocalClimbingImage(
8617 const GPNEBConfig& config, NEBPath& path,
8618 const ActiveLearningSession& session, int outer_iteration)
8619{
8620 const int focal = config.oracle_transition_focal_image;
8621 if (outer_iteration != 0 || focal <= 0 || focal >= path.numImages() - 1) {
8622 return false;
8623 }
8624 for (const int image: {focal - 1, focal, focal + 1}) {
8625 if (!session.hasCurrentChainCertificate(image,
8626 path.image(image).positions) ||
8627 findRestorableObservationRow(session.training_obs,
8628 path.image(image)) < 0) {
8629 return false;
8630 }
8631 }
8632 for (const int image: {focal - 1, focal, focal + 1}) {
8633 (void)restoreObservedImageIfPresent(session.training_obs,
8634 path.image(image));
8635 }
8636 for (int image = 0; image < path.numImages(); ++image) {
8637 path.image(image).is_climbing = image == focal;
8638 }
8639 path.computeNEBForces();
8640 return true;
8641}
8642
8643std::vector<Eigen::VectorXd> proposeReparametrizedBand(
8644 const NEBPath& accepted_path, const GPNEBConfig& config, int anchor_index)
8645{
8646 NEBPath candidate = accepted_path;
8647 reparametrizeBandForConfig(candidate, config, anchor_index);
8648 std::vector<Eigen::VectorXd> proposed_positions(candidate.numImages());
8649 for (int i = 0; i < candidate.numImages(); ++i) {
8650 proposed_positions[static_cast<std::size_t>(i)] =
8651 candidate.image(i).positions;
8652 }
8653 return proposed_positions;
8654}
8655
8664double evaluatedTrueForce(const NEBPath& path, int index)
8665{
8666 const double none = std::numeric_limits<double>::infinity();
8667 if (index <= 0 || index >= path.numImages() - 1) return none;
8668 const Image& image = path.image(index);
8669 if (!image.evaluated || image.gradient.size() == 0 ||
8670 image.gradient.size() != image.positions.size() ||
8671 !image.gradient.allFinite() || !image.positions.allFinite() ||
8672 !std::isfinite(image.energy))
8673 return none;
8674 const double force = path.saddleForce(index);
8675 return std::isfinite(force) ? force : none;
8676}
8677
8678bool evaluatedTrueForceBelowFinalTolerance(const NEBPath& path, int index,
8679 double tolerance,
8680 bool require_energy_bracket)
8681{
8682 if (!(std::isfinite(tolerance) && tolerance >= 0.0)) return false;
8683 const double force = evaluatedTrueForce(path, index);
8684 if (!std::isfinite(force)) return false;
8685 const Image& image = path.image(index);
8686 if (require_energy_bracket) {
8687 const double left = path.image(0).energy;
8688 const double right = path.image(path.numImages() - 1).energy;
8689 if (!(std::isfinite(left) && std::isfinite(right) &&
8690 image.energy > left && image.energy > right))
8691 return false;
8692 }
8693 return force < tolerance;
8694}
8695
8696bool adoptMeasuredOracleRow(NEBPath& path, int index,
8697 const gpr::Observation& measured, double* force)
8698{
8699 if (index <= 0 || index >= path.numImages() - 1) return false;
8700 Image& image = path.image(index);
8701 if (!image.positions.allFinite()) return false;
8702 const int row = findRestorableObservationRow(measured, image);
8703 if (row < 0 || row >= measured.E.rows() || measured.E.cols() < 1) {
8704 return false;
8705 }
8706 const double energy = measured.E(row, 0);
8707 const Eigen::VectorXd gradient = measured.G.row(row).transpose();
8708 if (!std::isfinite(energy) || gradient.size() != image.positions.size() ||
8709 !gradient.allFinite()) {
8710 return false;
8711 }
8712 image.energy = energy;
8713 image.gradient = gradient;
8714 image.evaluated = true;
8715 const double magnitude = path.forceMagnitude(gradient);
8716 if (force != nullptr) *force = magnitude;
8717 return std::isfinite(magnitude);
8718}
8719
8720bool measuredForceBelowFinalTolerance(NEBPath& path, int index,
8721 double tolerance,
8722 bool require_energy_bracket,
8723 const gpr::Observation& measured,
8724 double* force)
8725{
8726 double magnitude = std::numeric_limits<double>::infinity();
8727 if (!adoptMeasuredOracleRow(path, index, measured, &magnitude)) {
8728 if (force != nullptr) {
8729 *force = std::numeric_limits<double>::infinity();
8730 }
8731 return false;
8732 }
8733 if (force != nullptr) *force = magnitude;
8734 if (!(std::isfinite(tolerance) && tolerance >= 0.0)) return false;
8735 if (require_energy_bracket) {
8736 const double left = path.image(0).energy;
8737 const double right = path.image(path.numImages() - 1).energy;
8738 const double energy = path.image(index).energy;
8739 if (!(std::isfinite(left) && std::isfinite(right) &&
8740 std::isfinite(energy) && energy > left && energy > right)) {
8741 return false;
8742 }
8743 }
8744 return std::isfinite(magnitude) && magnitude <= tolerance;
8745}
8746
8748int bestEvaluatedSaddleCandidate(const NEBPath& path)
8749{
8750 int best = -1;
8751 double best_energy = -std::numeric_limits<double>::infinity();
8752 for (int i = 1; i < path.numImages() - 1; ++i) {
8753 const Image& image = path.image(i);
8754 if (!image.evaluated || !std::isfinite(image.energy)) continue;
8755 if (image.energy > best_energy) {
8756 best_energy = image.energy;
8757 best = i;
8758 }
8759 }
8760 return best;
8761}
8762
8763bool admitRecoveryGrowthObservation(
8764 ActiveLearningSession& session, const policy::TrainingPolicy* policy,
8765 int image_index, const Eigen::VectorXd& positions, double energy,
8766 const Eigen::VectorXd& gradient, bool admitted_this_outer_step)
8767{
8768 // A recovery-growth target is never a row the training set already
8769 // holds, so a row present here came from the acquisition batch, which
8770 // archived it and counted the draw. It is certified and nothing is
8771 // appended: a second append would archive it again and count the result
8772 // as another draw. This holds with or without a training policy.
8773 if (hasPosition(session.training_obs, positions)) {
8774 session.recordCurrentChainCertificate(image_index, positions, energy,
8775 gradient);
8776 return false;
8777 }
8778 // A row the outer step dropped from the training set is admitted again
8779 // for its certificate. Its oracle result is already in the archive.
8780 session.appendCurrentChainObservation(
8781 image_index, positions, energy, gradient,
8782 admitted_this_outer_step ? ObservationRetention::AlreadyRecorded
8783 : ObservationRetention::RecordAcquisition);
8784 if (policy == nullptr) return false;
8785 // Retention already ran on the admitted row. The policy is not asked a
8786 // second time, and the revision is marked so the refit does not ask in
8787 // its place.
8788 if (admitted_this_outer_step) {
8789 session.markCurrentTrainingRevisionRetainedByPolicy(policy);
8790 return false;
8791 }
8792 return session.retainTrainingRowsForPolicy(*policy);
8793}
8794
8795} // namespace detail
8796
8797namespace {
8798
8799thread_local PosteriorFactorizationCounts* posterior_factorization_sink =
8800 nullptr;
8801
8802void add_factorization_delta(gpr::GaussianProcessRegression& model,
8803 std::size_t hssvd_baseline,
8804 std::size_t cholesky_baseline)
8805{
8806 if (posterior_factorization_sink == nullptr) return;
8807 posterior_factorization_sink->hssvd +=
8808 model.hssvdFullFactorizationsForTesting() - hssvd_baseline;
8809 posterior_factorization_sink->cholesky +=
8810 model.fullCholeskyFactorizationsForTesting() - cholesky_baseline;
8811}
8812
8813} // namespace
8814
8817 : previous_(posterior_factorization_sink)
8818{
8819 posterior_factorization_sink = &counts;
8820}
8821
8823{
8824 posterior_factorization_sink = previous_;
8825}
8826
8827namespace {
8828
8829// Post-convergence competing-channel survey (surrogate-only, zero
8830// oracle cost). Re-relaxes perturbed copies of the INITIAL band on the
8831// final GP with a plain steepest-descent NEB and reports where each
8832// copy's highest-energy image lands relative to the certified saddle.
8833// Variant 0 relaxes the untouched initial band on the final surface;
8834// variant 1 mirrors the certified displacement field about the initial
8835// band, probing the basin on the other side of the initial path. A
8836// survey col far from the certified one with a lower predicted barrier
8837// marks a competing channel candidate; the predicted sigma states how
8838// much of that is extrapolation. Report-only: the loop's answer is
8839// unchanged.
8840void runChannelSurvey(gpr::GaussianProcessRegression& gp,
8841 const std::vector<Eigen::VectorXd>& initial_band,
8842 const NEBPath& certified_path, double reactant_energy)
8843{
8844 const int n_im = certified_path.numImages();
8845 if (static_cast<int>(initial_band.size()) != n_im || n_im < 3) return;
8846
8847 auto predictInto = [&gp](const Eigen::VectorXd& x, double& energy,
8848 Eigen::VectorXd& gradient) {
8849 gpr::Observation probe;
8850 probe.R.resize(1, x.size());
8851 probe.R.row(0) = x.transpose();
8853 energy = probe.E.size() > 0 ? probe.E(0, 0)
8854 : std::numeric_limits<double>::quiet_NaN();
8855 gradient = probe.G.size() > 0 ? Eigen::VectorXd(probe.G.row(0))
8856 : Eigen::VectorXd();
8857 };
8858 auto energyVarianceAt = [&gp](const Eigen::VectorXd& x) {
8859 gpr::Observation probe;
8860 probe.R.resize(1, x.size());
8861 probe.R.row(0) = x.transpose();
8863 return probe.E.size() > 0 ? probe.E(0, 0)
8864 : std::numeric_limits<double>::quiet_NaN();
8865 };
8866
8867 const int certified_col = detail::climbingStopImage(certified_path);
8868 const Eigen::VectorXd certified_col_positions =
8869 certified_path.image(certified_col).positions;
8870 constexpr int kMaxSteps = 300;
8871 constexpr double kStepScale = 0.05;
8872 constexpr double kStepCap = 0.1;
8873 constexpr double kForceTol = 0.1;
8874 constexpr double kSpring = 1.0;
8875 constexpr double kDistinctColDistance = 0.3;
8876 // A survey image that travels further than this from its start has
8877 // left any plausibly-supported region; the variant is reported as
8878 // escaped (negative steps) instead of pretending its prior-reverted
8879 // energies rank anything.
8880 constexpr double kMaxImageTravel = 1.5;
8881
8882 for (int variant = 0; variant < 2; ++variant) {
8883 std::vector<Eigen::VectorXd> band(initial_band);
8884 if (variant == 1) {
8885 for (int i = 1; i < n_im - 1; ++i) {
8886 const Eigen::VectorXd displacement =
8887 certified_path.image(i).positions - initial_band[i];
8888 band[static_cast<std::size_t>(i)] =
8889 initial_band[static_cast<std::size_t>(i)] - displacement;
8890 }
8891 }
8892 std::vector<double> energies(static_cast<std::size_t>(n_im), 0.0);
8893 std::vector<Eigen::VectorXd> gradients(static_cast<std::size_t>(n_im));
8894 std::vector<double> travel(static_cast<std::size_t>(n_im), 0.0);
8895 energies[0] = certified_path.image(0).energy;
8896 energies[static_cast<std::size_t>(n_im - 1)] =
8897 certified_path.image(n_im - 1).energy;
8898 int steps = 0;
8899 double max_perp_force = std::numeric_limits<double>::infinity();
8900 for (; steps < kMaxSteps; ++steps) {
8901 for (int i = 1; i < n_im - 1; ++i) {
8902 predictInto(band[static_cast<std::size_t>(i)],
8903 energies[static_cast<std::size_t>(i)],
8904 gradients[static_cast<std::size_t>(i)]);
8905 }
8906 max_perp_force = 0.0;
8907 std::vector<Eigen::VectorXd> forces(static_cast<std::size_t>(n_im));
8908 bool finite = true;
8909 for (int i = 1; i < n_im - 1; ++i) {
8910 const auto& gradient = gradients[static_cast<std::size_t>(i)];
8911 if (gradient.size() == 0 || !gradient.allFinite()) {
8912 finite = false;
8913 break;
8914 }
8915 Eigen::VectorXd tangent =
8916 band[static_cast<std::size_t>(i + 1)] -
8917 band[static_cast<std::size_t>(i - 1)];
8918 const double tangent_norm = tangent.norm();
8919 if (tangent_norm > 0.0) tangent /= tangent_norm;
8920 const Eigen::VectorXd perp_force =
8921 -(gradient - gradient.dot(tangent) * tangent);
8922 const double spring_stretch =
8923 (band[static_cast<std::size_t>(i + 1)] -
8924 band[static_cast<std::size_t>(i)])
8925 .norm() -
8926 (band[static_cast<std::size_t>(i)] -
8927 band[static_cast<std::size_t>(i - 1)])
8928 .norm();
8929 forces[static_cast<std::size_t>(i)] =
8930 perp_force + kSpring * spring_stretch * tangent;
8931 max_perp_force = std::max(max_perp_force, perp_force.norm());
8932 }
8933 if (!finite || max_perp_force < kForceTol) break;
8934 // Adaptive damping: on a surrogate reverting to its prior
8935 // the forces can reach tens of eV/A; a fixed step there
8936 // thrashes against the cap without descending. Scale the
8937 // whole step down so the largest per-image move stays at
8938 // kStepCap.
8939 const double damping =
8940 max_perp_force > 1.0 ? 1.0 / max_perp_force : 1.0;
8941 for (int i = 1; i < n_im - 1; ++i) {
8942 Eigen::VectorXd step =
8943 kStepScale * damping * forces[static_cast<std::size_t>(i)];
8944 const double step_norm = step.norm();
8945 if (step_norm > kStepCap) step *= kStepCap / step_norm;
8946 band[static_cast<std::size_t>(i)] += step;
8947 travel[static_cast<std::size_t>(i)] += step.norm();
8948 }
8949 bool escaped = false;
8950 for (int i = 1; i < n_im - 1; ++i) {
8951 if (travel[static_cast<std::size_t>(i)] > kMaxImageTravel) {
8952 escaped = true;
8953 break;
8954 }
8955 }
8956 if (escaped) {
8957 steps = -steps;
8958 break;
8959 }
8960 }
8961 int survey_col = 1;
8962 for (int i = 2; i < n_im - 1; ++i) {
8963 if (energies[static_cast<std::size_t>(i)] >
8964 energies[static_cast<std::size_t>(survey_col)])
8965 survey_col = i;
8966 }
8967 const double barrier_pred =
8968 energies[static_cast<std::size_t>(survey_col)] - reactant_energy;
8969 const double energy_variance =
8970 energyVarianceAt(band[static_cast<std::size_t>(survey_col)]);
8971 const double col_distance =
8972 (band[static_cast<std::size_t>(survey_col)] -
8973 certified_col_positions)
8974 .norm();
8975 neb_log() << "[channel-survey] variant=" << variant
8976 << " steps=" << steps << " fmax=" << max_perp_force
8977 << " col=" << survey_col << " bar_pred=" << barrier_pred
8978 << " sigma=" << std::sqrt(std::max(0.0, energy_variance))
8979 << " dist_to_certified=" << col_distance << " distinct="
8980 << (col_distance > kDistinctColDistance ? 1 : 0) << "\n";
8981 }
8982}
8983
8984// A fixed-point proposal parked across outer iterations: the acquisition it
8985// waits on, the band positions it proposes, the interior signature of the path
8986// that produced them, and which proposal produced them. Every site that reads
8987// one reads the others, and all four are discarded together, so they travel as
8988// One trial geometry handed to the oracle: whether the measurement happened and
8989// what it returned. An unmeasured trial keeps a NaN energy, so reading it
8990// without first checking measured does not quietly pass for zero.
8991struct TrialMeasurement {
8992 bool measured = false;
8993 double energy = std::numeric_limits<double>::quiet_NaN();
8994 Eigen::VectorXd gradient;
8995 Eigen::VectorXd positions;
8996};
8997// a single value rather than as four parallel locals.
8998enum class FixedPointProposalKind {
8999 None,
9000 MeasuredChainSweep,
9001 MeasuredNebStep,
9002 MeasuredNebStepRejected,
9003 Reparameterization,
9004 ReparameterizationRejected,
9005};
9006
9007struct PendingFixedPointCampaign {
9008 detail::ProposalAcquisitionTarget acquisition;
9009 Eigen::VectorXd source_signature;
9010 std::vector<Eigen::VectorXd> candidate_positions;
9011 FixedPointProposalKind kind = FixedPointProposalKind::None;
9012 int climbing_image = -1;
9013
9014 // A campaign is live exactly while it still names positions to observe.
9015 [[nodiscard]] bool active() const noexcept
9016 {
9017 return !candidate_positions.empty();
9018 }
9019
9020 void clear() noexcept
9021 {
9022 acquisition.clear();
9023 source_signature.resize(0);
9024 candidate_positions.clear();
9025 kind = FixedPointProposalKind::None;
9026 climbing_image = -1;
9027 }
9028};
9029
9030// The concatenated interior-image positions: the value that identifies a
9031// band geometry for the fixed-point campaign, and empty when the band has no
9032// interior or its images disagree on their degree count.
9033Eigen::VectorXd interiorPositionSignature(const NEBPath& path)
9034{
9035 if (path.numImages() <= 2) return Eigen::VectorXd();
9036 const Eigen::Index image_dof = path.image(1).positions.size();
9037 if (image_dof <= 0) return Eigen::VectorXd();
9038 Eigen::VectorXd signature(static_cast<Eigen::Index>(path.numImages() - 2) *
9039 image_dof);
9040 for (int i = 1; i < path.numImages() - 1; ++i) {
9041 if (path.image(i).positions.size() != image_dof) {
9042 return Eigen::VectorXd();
9043 }
9044 signature.segment(static_cast<Eigen::Index>(i - 1) * image_dof,
9045 image_dof) = path.image(i).positions;
9046 }
9047 return signature;
9048}
9049
9050// A fixed-point proposal is resolved once every interior position it named
9051// has been observed: the band either adopts the proposal or the campaign is
9052// abandoned. A campaign whose source geometry has since moved is stale and is
9053// discarded without being applied.
9054void resolvePendingFixedPointCampaign(
9055 NEBPath& path, const GPNEBConfig& config, gpr::Observation& training_obs,
9056 bool ci_active, int log_rank, int outer,
9057 const std::vector<double>& anchor_true_force_profile,
9058 double anchor_true_max_force,
9059 PendingFixedPointCampaign& pending_fixed_point,
9060 FixedPointProposalKind& fixed_point_applied_kind,
9061 detail::MeasuredBandRecoveryState& measured_band_recovery)
9062{
9063 if (!pending_fixed_point.active()) return;
9064 const Eigen::VectorXd current_signature = interiorPositionSignature(path);
9065 const int climbing_image = pending_fixed_point.climbing_image;
9066 if (!detail::positionsCoincide(current_signature,
9067 pending_fixed_point.source_signature) ||
9068 (climbing_image > 0 && (!ci_active || detail::activeClimbingMarkerIndex(
9069 path) != climbing_image))) {
9070 pending_fixed_point.clear();
9071 } else {
9072 bool all_candidates_observed = true;
9073 for (std::size_t i = 1;
9074 i + 1 < pending_fixed_point.candidate_positions.size(); ++i) {
9075 if (climbing_image > 0 &&
9076 (static_cast<int>(i) < climbing_image - 1 ||
9077 static_cast<int>(i) > climbing_image + 1)) {
9078 continue;
9079 }
9080 all_candidates_observed =
9081 all_candidates_observed &&
9082 detail::hasPosition(training_obs,
9083 pending_fixed_point.candidate_positions[i]);
9084 }
9085 if (all_candidates_observed) {
9086 bool candidate_followup_scheduled = false;
9087 if (pending_fixed_point.kind ==
9088 FixedPointProposalKind::MeasuredChainSweep) {
9089 (void)detail::restoreOiePathPositions(
9090 path, pending_fixed_point.candidate_positions,
9091 /*preserve_climbing_marker=*/ci_active);
9092 fixed_point_applied_kind =
9093 FixedPointProposalKind::MeasuredChainSweep;
9094 } else {
9095 std::vector<double> recovery_anchor_profile =
9096 anchor_true_force_profile;
9097 if (climbing_image > 0) {
9098 for (int i = std::max(1, climbing_image - 1);
9099 i < std::min(path.numImages() - 1, climbing_image + 2);
9100 ++i) {
9101 (void)detail::restoreObservedImageIfPresent(
9102 training_obs, path.image(i));
9103 }
9104 recovery_anchor_profile =
9105 detail::measuredBandForceProfile(path, climbing_image);
9106 }
9107 NEBPath measured_candidate = path;
9108 bool candidate_observations_restored = true;
9109 for (int i = 1; i < measured_candidate.numImages() - 1; ++i) {
9110 measured_candidate.image(i).positions =
9111 pending_fixed_point
9112 .candidate_positions[static_cast<std::size_t>(i)];
9113 measured_candidate.image(i).evaluated = false;
9114 const bool observed = detail::restoreObservedImageIfPresent(
9115 training_obs, measured_candidate.image(i));
9116 if (climbing_image < 0 ||
9117 std::abs(i - climbing_image) <= 1) {
9118 candidate_observations_restored =
9119 observed && candidate_observations_restored;
9120 }
9121 }
9122 const std::vector<double> candidate_force_profile =
9123 candidate_observations_restored
9124 ? detail::measuredBandForceProfile(measured_candidate,
9125 climbing_image)
9126 : std::vector<double>{};
9127 const double candidate_max_force =
9128 candidate_force_profile.empty()
9129 ? std::numeric_limits<double>::infinity()
9130 : candidate_force_profile.front();
9131 int moved_image = -1;
9132 if (pending_fixed_point.kind ==
9133 FixedPointProposalKind::MeasuredNebStep) {
9134 for (int i = 1; i < path.numImages() - 1; ++i) {
9135 if (detail::positionsCoincide(
9136 path.image(i).positions,
9137 pending_fixed_point.candidate_positions
9138 [static_cast<std::size_t>(i)])) {
9139 continue;
9140 }
9141 if (moved_image >= 0) {
9142 moved_image = -1;
9143 break;
9144 }
9145 moved_image = i;
9146 }
9147 }
9148 if (moved_image > 0) {
9149 path.computeNEBForces();
9150 measured_candidate.computeNEBForces();
9151 }
9152 const bool measured_climbing_step =
9153 moved_image > 0 && moved_image == climbing_image;
9154 const auto climbing_step =
9155 measured_climbing_step
9156 ? detail::assessMeasuredClimbingStep(
9157 path, measured_candidate, climbing_image)
9158 : detail::MeasuredResidualStepAssessment{};
9159 const bool candidate_improves_anchor =
9160 measured_climbing_step
9161 ? climbing_step.action ==
9162 detail::MeasuredResidualStepAction::Accept
9163 : !candidate_force_profile.empty() &&
9164 ((climbing_image < 0 &&
9165 recovery_anchor_profile.empty()) ||
9166 detail::shouldAcceptMeasuredBandCandidate(
9167 candidate_force_profile,
9168 recovery_anchor_profile));
9169 if (candidate_improves_anchor) {
9170 if (moved_image > 0) {
9171 (void)measured_band_recovery.observeAcceptedStep(
9172 moved_image, path.image(moved_image).positions,
9173 path.nebForce(moved_image),
9174 measured_candidate.image(moved_image).positions,
9175 measured_candidate.nebForce(moved_image));
9176 } else {
9177 measured_band_recovery.reset();
9178 }
9179 if (detail::commitMeasuredBandCandidate(
9180 path, measured_candidate, climbing_image)) {
9181 fixed_point_applied_kind = pending_fixed_point.kind;
9182 }
9183 } else {
9184 if (moved_image > 0) {
9185 const auto fraction =
9186 measured_climbing_step
9187 ? climbing_step.backtrack_fraction
9188 : detail::measuredSecantBacktrackFraction(
9189 path.image(moved_image).positions,
9190 path.nebForce(moved_image),
9191 measured_candidate.image(moved_image)
9192 .positions,
9193 measured_candidate.nebForce(moved_image));
9194 if (fraction) {
9195 const Eigen::VectorXd backtracked =
9196 path.image(moved_image).positions +
9197 *fraction *
9198 (measured_candidate.image(moved_image)
9199 .positions -
9200 path.image(moved_image).positions);
9201 if (backtracked.allFinite() &&
9202 !detail::hasPosition(training_obs,
9203 backtracked)) {
9204 pending_fixed_point.candidate_positions
9205 [static_cast<std::size_t>(moved_image)] =
9206 backtracked;
9207 pending_fixed_point.acquisition.image_index =
9208 moved_image;
9209 pending_fixed_point.acquisition.positions =
9210 backtracked;
9211 candidate_followup_scheduled = true;
9212 if (config.verbose && log_rank == 0) {
9213 neb_log() << "[gp_oie] outer=" << outer
9214 << " fixed-point: "
9215 "backtracking measured "
9216 "NEB step at image "
9217 << moved_image
9218 << " fraction=" << *fraction
9219 << std::endl;
9220 }
9221 }
9222 }
9223 }
9224 if (!candidate_followup_scheduled) {
9225 fixed_point_applied_kind =
9226 pending_fixed_point.kind ==
9227 FixedPointProposalKind::MeasuredNebStep
9228 ? FixedPointProposalKind::
9229 MeasuredNebStepRejected
9230 : FixedPointProposalKind::
9231 ReparameterizationRejected;
9232 if (config.verbose && log_rank == 0) {
9233 const char* candidate_name =
9234 pending_fixed_point.kind ==
9235 FixedPointProposalKind::MeasuredNebStep
9236 ? "measured NEB step"
9237 : "reparameterization";
9238 neb_log()
9239 << "[gp_oie] outer=" << outer
9240 << " fixed-point: rejecting " << candidate_name
9241 << " max_true_F=" << candidate_max_force
9242 << " anchor_F="
9243 << (climbing_image > 0 &&
9244 !recovery_anchor_profile.empty()
9245 ? recovery_anchor_profile.front()
9246 : anchor_true_max_force)
9247 << std::endl;
9248 }
9249 }
9250 }
9251 }
9252 if (!candidate_followup_scheduled) {
9253 pending_fixed_point.clear();
9254 }
9255 }
9256 }
9257}
9258
9259class PosteriorFactorizationGuard {
9260public:
9261 PosteriorFactorizationGuard(gpr::GaussianProcessRegression& gp,
9262 ActiveLearningSession* session)
9263 : gp_(gp),
9264 session_(session),
9265 hssvd0_(gp.hssvdFullFactorizationsForTesting()),
9266 cholesky0_(gp.fullCholeskyFactorizationsForTesting())
9267 {
9268 }
9269
9270 ~PosteriorFactorizationGuard()
9271 {
9272 add_factorization_delta(gp_, hssvd0_, cholesky0_);
9273 if (session_ == nullptr) return;
9274 for (auto& slot: session_->image_models) {
9275 gpr::GaussianProcessRegression* model = slot.gp();
9276 if (model == nullptr || model == &gp_) continue;
9277 add_factorization_delta(*model, 0, 0);
9278 }
9279 }
9280
9281 PosteriorFactorizationGuard(const PosteriorFactorizationGuard&) = delete;
9282 PosteriorFactorizationGuard& operator=(const PosteriorFactorizationGuard&) =
9283 delete;
9284
9285private:
9286 gpr::GaussianProcessRegression& gp_;
9287 ActiveLearningSession* session_;
9288 std::size_t hssvd0_;
9289 std::size_t cholesky0_;
9290};
9291
9292} // namespace
9293
9294void detail::installSecantClimbingDirection(NEBPath& path,
9295 ActiveLearningSession* session,
9296 const GPNEBConfig& config)
9297{
9298 if (!config.secant_hessian.seed_curvature) return;
9299 if (session == nullptr)
9300 throw std::logic_error(
9301 "secant curvature seed requested but the band has no session");
9302 const int climb = detail::activeClimbingMarkerIndex(path);
9303 if (climb <= 0 || climb >= path.numImages() - 1) {
9304 path.clearClimbingCurvatureDirection();
9305 return;
9306 }
9307 const optim::SecantHessian* secant = session->imageSecantHessian(climb);
9308 if (secant == nullptr) {
9309 path.clearClimbingCurvatureDirection();
9310 return;
9311 }
9312 const optim::SecantSeed seed =
9313 optim::secantSeedDirection(*secant, path.tangentAt(climb));
9314 // Any other status carries the tangent of this call, which would freeze
9315 // the climb axis while the band moves.
9316 if (seed.status != optim::SecantSeedStatus::Seeded) {
9317 path.clearClimbingCurvatureDirection();
9318 return;
9319 }
9320 path.setClimbingCurvatureDirection(seed.direction);
9321}
9322
9323namespace {
9324
9325std::optional<double> secantBandInverseCurvature(ActiveLearningSession* session,
9326 const GPNEBConfig& config)
9327{
9328 if (!config.secant_hessian.seed_curvature) return std::nullopt;
9329 if (session == nullptr)
9330 throw std::logic_error(
9331 "secant curvature seed requested but the band has no session");
9332 return optim::secantPositiveInverseScale(session->globalSecantHessian());
9333}
9334
9335void noteMeasuredSecant(ActiveLearningSession* session,
9336 const GPNEBConfig& config, int image_index,
9337 const Eigen::VectorXd& positions, double energy,
9338 const Eigen::VectorXd& gradient)
9339{
9340 if (!config.secant_hessian.enabled()) return;
9341 if (session == nullptr)
9342 throw std::logic_error(
9343 "secant options requested but the band has no session");
9344 session->noteTrueForceSecant(image_index, positions, energy, gradient);
9345}
9346
9347// The GP-OIE driver: the outer acquisition loop, the inner GP relaxation, the
9348// climbing-image certification and the hook protocol. It shares nothing with
9349// the standard and AIE branches beyond the initial path and the values threaded
9350// in here, and it always returns rather than falling through to them, so it is
9351// a separate function rather than the first two thirds of gpNEB's body.
9352GPNEBResult runGpOieNeb(
9353 NEBOracle& oracle, const GPNEBConfig& config,
9354 ActiveLearningSession* session, std::unique_ptr<NEBPath>& path_ptr,
9355 NEBPath& path, GPNEBResult& result,
9356 OracleForceProgressTracker& oracle_force_progress,
9357 std::vector<Eigen::VectorXd>& anchor_positions,
9358 std::vector<double>& anchor_true_force_profile,
9359 double anchor_true_max_force,
9360 const std::vector<Eigen::VectorXd>& ceiling_witness_positions,
9361 bool ci_active, double connecting_path_energy_ceiling,
9362 bool had_preexisting_session_rows)
9363{
9364 ActiveLearningSession::PolicyScope policy_scope(
9365 session, config.training_policy, config.training_search_kind);
9366 // Routing: if the caller supplied an ActiveLearningSession,
9367 // use its gp / training_obs / atoms_config (shared across NEB
9368 // + Dimer phases). Otherwise allocate local stack copies and
9369 // run a local, single-phase GP.
9370 gpr::InputParameters parameters;
9371 gpr::AtomsConfiguration local_atoms_config;
9372 gpr::AtomsConfiguration& atoms_config =
9373 session ? session->atoms_config : local_atoms_config;
9374 // Atomic numbers for the band's contact domain: the config's frame, or
9375 // the session's atoms when a caller left the config without them.
9376 std::vector<int> domain_atomic_numbers = config.atomic_numbers;
9377 if (static_cast<int>(domain_atomic_numbers.size()) != config.n_atoms &&
9378 atoms_config.atomicNrs.size() == config.n_atoms) {
9379 domain_atomic_numbers.resize(static_cast<std::size_t>(config.n_atoms));
9380 for (int a = 0; a < config.n_atoms; ++a)
9381 domain_atomic_numbers[static_cast<std::size_t>(a)] =
9382 static_cast<int>(atoms_config.atomicNrs(0, a));
9383 }
9384
9385 gpr::GaussianProcessRegression local_gp;
9386 gpr::GaussianProcessRegression& gp = session ? session->gp : local_gp;
9387 PosteriorFactorizationGuard factorization_guard(gp, session);
9388
9389 gpr::Observation local_training_obs;
9390 gpr::Observation& training_obs =
9391 session ? session->training_obs : local_training_obs;
9392 // Set only when this entry's seed hook installed a kernel, before
9393 // the initial fit (which also marks the model optimized). A reused
9394 // session is already optimized, and a hook that ran and refused
9395 // must not keep that stale kernel: hasBeenOptimized() alone cannot
9396 // tell the two apart.
9397 bool preserve_imported_kernel = false;
9398
9399 if (session) {
9400 // Session owns gp_setup; ensure it has run once. If the
9401 // caller's session.gp_setup is empty, fall back to the
9402 // config's gp_setup so a freshly-constructed session can
9403 // still bootstrap.
9404 if (!session->gp_setup) session->gp_setup = config.gp_setup;
9405 session->setLikelihoodNoiseFloorRms(
9406 detail::oracleEnergyNoiseRmsPtr(config));
9407 session->setResolutionDedup(config.use_resolution_dedup);
9408 session->setEvidenceRefitTrigger(config.evidence_refit_trigger);
9409 if (config.refit_training_revisions > 0) {
9410 session->setRefitTrainingRevisions(
9411 static_cast<std::uint64_t>(config.refit_training_revisions));
9412 }
9413 session->initialise();
9414 atoms_config.pair_cutoff = bandPairCutoff(config);
9415 atoms_config.pair_cutoff_width = config.pair_cutoff_width;
9416 session->refreshLikelihoodNoiseFloor();
9417 applyConfigToGP(config, gp);
9418 session->min_per_image_n_train = config.per_image_min_train;
9419 session->per_image_knn = config.per_image_knn;
9420 // Allocate per-image local GPs aligned with the NEB chain
9421 // length. The session bookkeeping is idempotent across
9422 // calls -- only the first hit allocates -- so callers that
9423 // re-enter ~gpNEB~ on the same path size hit the no-op
9424 // branch.
9425 session->initializePerImage(path.numImages());
9426 for (auto& model: session->image_models) {
9427 if (auto* local_gp = model.gp()) applyConfigToGP(config, *local_gp);
9428 }
9429 if (gpr::geometry::copyMicLattice(atoms_config.cell,
9430 config.cell.data())) {
9431 gp.updateConfiguration(atoms_config);
9432 for (auto& model: session->image_models) {
9433 if (auto* local_gp = model.gp()) {
9434 local_gp->updateConfiguration(atoms_config);
9435 }
9436 }
9437 }
9438 preserve_imported_kernel =
9439 session->applySeededModel() && gp.hasBeenOptimized();
9440 } else {
9441 config.gp_setup(parameters, local_atoms_config);
9442 atoms_config.pair_cutoff = bandPairCutoff(config);
9443 atoms_config.pair_cutoff_width = config.pair_cutoff_width;
9444 gpr::geometry::copyMicLattice(atoms_config.cell, config.cell.data());
9445 gp.initialize(parameters, atoms_config);
9446 applyConfigToGP(config, gp);
9447 local_training_obs.clear();
9448 }
9449
9450 const auto update_frozen_environment = [&]() {
9451 if (atoms_config.atoms_froz_active.type.size() == 0 &&
9452 atoms_config.atoms_froz_inactive.type.size() == 0)
9453 return false;
9454 gpr::Coord band(path.numImages(), path.image(0).positions.size());
9455 for (int i = 0; i < path.numImages(); ++i)
9456 band.row(i) = path.image(i).positions.transpose();
9457 if (session) return session->updateFrozenEnvironment(band);
9458 aux::ProblemSetUp setup;
9459 const bool changed = setup.activateFrozenAtoms(
9460 band, parameters.actdist_fro.value, atoms_config);
9461 if (changed) gp.updateConfiguration(atoms_config);
9462 return changed;
9463 };
9464 (void)update_frozen_environment();
9465
9466 // Per-image prediction: an always-on precision-weighted
9467 // partial pool of the global GP and image i's per-image GP.
9468 // Each posterior is weighted by its inverse variance, so where
9469 // the per-image GP is confident (image i near its own
9470 // neighbourhood data) the pool leans local -- the global GP,
9471 // fit across the whole reaction path, carries little signal at
9472 // an individual image's stationary point -- and where the
9473 // per-image GP extrapolates (large local variance) the pool
9474 // leans global. The global posterior is therefore always a
9475 // valid base: the prediction degrades gracefully to the global
9476 // trend rather than running away. No regime thresholds -- the
9477 // inverse-variance weights are continuous in the data.
9478 auto localEligible = [&](int i) {
9479 // Classic joint [E,F] profiles run ONE global posterior: the
9480 // per-image local-expert tier dispatches predictions,
9481 // variances, band gradients, and trust envelopes through
9482 // per-image posteriors, and the outer decisions then compare
9483 // quantities across different probability spaces (acquisition
9484 // argmax over mixed local/global variances, force
9485 // certification from a different model than the energy
9486 // probe). The published formulation conditions every decision
9487 // on the single global GP.
9488 if (usesClassicJointEnergyForcePrior(config.model_profile) &&
9489 !config.local_tier_classic) {
9490 return false;
9491 }
9492 return session && session->imageModelEligibleForPrediction(i);
9493 };
9494 int image_state_rank = 0;
9495 int image_state_nprocs = 1;
9496#ifdef GPR_HAVE_MPI
9497 {
9498 int mpi_up = 0;
9499 MPI_Initialized(&mpi_up);
9500 if (mpi_up) {
9501 MPI_Comm_rank(MPI_COMM_WORLD, &image_state_rank);
9502 MPI_Comm_size(MPI_COMM_WORLD, &image_state_nprocs);
9503 }
9504 }
9505#endif
9506 auto ownsImageState = [&](int image_idx) {
9507 return detail::ownerRankForImage(image_idx, image_state_nprocs) ==
9508 image_state_rank;
9509 };
9510
9511 auto makeProbe = [&](int i) {
9512 gpr::Observation probe;
9513 probe.R.resize(1, path.image(i).positions.size());
9514 probe.R.row(0) = path.image(i).positions.transpose();
9515 return probe;
9516 };
9517 // One probe carrying several images. The HS-SVD variance contracts the
9518 // cross-covariance against the whole basis, so the basis is streamed once
9519 // per call regardless of how many images the call covers: asking image by
9520 // image re-streams it for every image of every relaxation step. The
9521 // per-image results are identical either way; only the traffic differs.
9522 auto makeProbeBatch = [&](const std::vector<int>& images) {
9523 gpr::Observation probe;
9524 if (images.empty()) return probe;
9525 const Eigen::Index dof = path.image(images.front()).positions.size();
9526 probe.R.resize(static_cast<Eigen::Index>(images.size()), dof);
9527 for (std::size_t k = 0; k < images.size(); ++k) {
9528 probe.R.row(static_cast<Eigen::Index>(k)) =
9529 path.image(images[k]).positions.transpose();
9530 }
9531 return probe;
9532 };
9533 auto observationEnergy = [](const gpr::Observation& obs) {
9534 return obs.E.size() > 0 ? obs.E(0, 0)
9535 : std::numeric_limits<double>::quiet_NaN();
9536 };
9537 auto observationGradient = [](const gpr::Observation& obs) {
9538 return obs.G.size() > 0 ? obs.G.row(0).transpose() : Eigen::VectorXd();
9539 };
9540 auto computeGlobalPotentials = [&](const std::vector<char>& required,
9541 std::vector<gpr::Observation>&
9542 global_potential) {
9543 const int n_im = path.numImages();
9544 global_potential.clear();
9545 global_potential.resize(n_im);
9546 bool any_required = false;
9547 for (int i = 1; i < n_im - 1; ++i) {
9548 any_required = any_required || required[i] != 0;
9549 }
9550 if (!any_required) return;
9551 if (gp.hasReusableHssvdPosterior()) {
9552 const int dof = static_cast<int>(path.image(0).positions.size());
9553 detail::OwnedImageState local_state;
9554 local_state.valid.assign(static_cast<std::size_t>(n_im), 0);
9555 local_state.energy.assign(static_cast<std::size_t>(n_im), 0.0);
9556 local_state.gradient = Eigen::MatrixXd::Zero(n_im, dof);
9557 auto compute_owned = [&](gpr::GaussianProcessRegression& model) {
9558 for (int i = 1; i < n_im - 1; ++i) {
9559 if (!required[i] || !ownsImageState(i)) {
9560 continue;
9561 }
9562 gpr::Observation potential = makeProbe(i);
9563 model.calculatePotentialDispatched(potential);
9564 local_state.valid[static_cast<std::size_t>(i)] = 1;
9565 local_state.energy[static_cast<std::size_t>(i)] =
9566 observationEnergy(potential);
9567 const Eigen::VectorXd gradient =
9568 observationGradient(potential);
9569 if (gradient.size() == dof) {
9570 local_state.gradient.row(i) = gradient.transpose();
9571 } else {
9572 local_state.energy[static_cast<std::size_t>(i)] =
9573 std::numeric_limits<double>::quiet_NaN();
9574 }
9575 }
9576 };
9577 if (session) {
9578 auto model = session->acquireGlobalModel();
9579 compute_owned(model.gp());
9580 } else {
9581 compute_owned(gp);
9582 }
9583 const auto consensus =
9584 detail::allreduceOwnedImageState(local_state);
9585 for (int i = 1; i < n_im - 1; ++i) {
9586 if (!required[i]) continue;
9587 global_potential[i] = makeProbe(i);
9588 global_potential[i].E.resize(1, 1);
9589 global_potential[i].G.resize(1, dof);
9590 if (consensus.valid[static_cast<std::size_t>(i)] == 0) {
9591 global_potential[i].E(0, 0) =
9592 std::numeric_limits<double>::quiet_NaN();
9593 global_potential[i].G.setConstant(
9594 std::numeric_limits<double>::quiet_NaN());
9595 continue;
9596 }
9597 global_potential[i].E(0, 0) =
9598 consensus.energy[static_cast<std::size_t>(i)];
9599 global_potential[i].G.row(0) = consensus.gradient.row(i);
9600 }
9601 return;
9602 }
9603 // Batched query: one probe carrying every required image
9604 // instead of one call per image. Both predict paths are
9605 // multi-row and do their work as matrix operations over the
9606 // whole probe (HS-SVD projects and predicts the full query
9607 // block at once), so this trades n_im-2 small assemblies
9608 // for one wide one per inner step. The per-image results
9609 // are identical -- the rows do not interact.
9610 std::vector<int> batch;
9611 batch.reserve(static_cast<std::size_t>(n_im));
9612 for (int i = 1; i < n_im - 1; ++i) {
9613 if (required[i]) batch.push_back(i);
9614 }
9615 if (batch.empty()) return;
9616 const Eigen::Index batch_dof = path.image(0).positions.size();
9617 gpr::Observation probe;
9618 probe.R.resize(static_cast<Eigen::Index>(batch.size()), batch_dof);
9619 for (std::size_t b = 0; b < batch.size(); ++b) {
9620 probe.R.row(static_cast<Eigen::Index>(b)) =
9621 path.image(batch[b]).positions.transpose();
9622 }
9623 if (session) {
9624 auto model = session->acquireGlobalModel();
9625 model.gp().calculatePotentialDispatched(probe);
9626 } else {
9628 }
9629 const bool probe_valid =
9630 probe.E.size() == static_cast<Eigen::Index>(batch.size()) &&
9631 probe.G.rows() == static_cast<Eigen::Index>(batch.size()) &&
9632 probe.G.cols() == batch_dof;
9633 for (std::size_t b = 0; b < batch.size(); ++b) {
9634 const int i = batch[b];
9635 global_potential[i] = makeProbe(i);
9636 global_potential[i].E.resize(1, 1);
9637 global_potential[i].G.resize(1, batch_dof);
9638 if (probe_valid) {
9639 global_potential[i].E(0, 0) =
9640 probe.E(0, static_cast<Eigen::Index>(b));
9641 global_potential[i].G.row(0) =
9642 probe.G.row(static_cast<Eigen::Index>(b));
9643 } else {
9644 global_potential[i].E(0, 0) =
9645 std::numeric_limits<double>::quiet_NaN();
9646 global_potential[i].G.setConstant(
9647 std::numeric_limits<double>::quiet_NaN());
9648 }
9649 }
9650 };
9651 // Energy-only posterior variance of every interior image on the global
9652 // model: one batched query for the images this rank owns, then the same
9653 // allreduce as the joint probe. The per-step expected-improvement
9654 // selection reads only the energy channel, so the energy block alone is
9655 // assembled: one column per image against the basis instead of (D+1).
9656 auto computeGlobalEnergyVariances = [&]() {
9657 const int n_im = path.numImages();
9658 std::vector<double> energy_variances(static_cast<std::size_t>(n_im),
9659 0.0);
9660 if (n_im <= 2) return energy_variances;
9661 const int dof = static_cast<int>(path.image(0).positions.size());
9662 auto variancesFor = [&](gpr::GaussianProcessRegression& model,
9663 const std::vector<int>& batch) {
9664 gpr::Observation probe = makeProbeBatch(batch);
9665 Eigen::RowVectorXd energy_variance;
9666 if (model.tryGateEnergyVariance(probe, energy_variance) &&
9667 energy_variance.size() ==
9668 static_cast<Eigen::Index>(batch.size())) {
9669 return Eigen::VectorXd(energy_variance.transpose());
9670 }
9671 model.calculateVarianceDispatched(probe);
9672 Eigen::VectorXd out(static_cast<Eigen::Index>(batch.size()));
9673 for (std::size_t k = 0; k < batch.size(); ++k) {
9674 out(static_cast<Eigen::Index>(k)) =
9675 detail::jointObservationVariance(
9676 probe, static_cast<Eigen::Index>(k))
9677 .energy;
9678 }
9679 return out;
9680 };
9681 auto scatter = [&](const std::vector<int>& batch,
9682 const Eigen::VectorXd& values,
9683 std::vector<double>& target) {
9684 for (std::size_t k = 0; k < batch.size(); ++k) {
9685 target[static_cast<std::size_t>(batch[k])] =
9686 values(static_cast<Eigen::Index>(k));
9687 }
9688 };
9689 if (gp.hasReusableHssvdPosterior()) {
9690 detail::OwnedImageState local_state;
9691 local_state.valid.assign(static_cast<std::size_t>(n_im), 0);
9692 local_state.energy.assign(static_cast<std::size_t>(n_im), 0.0);
9693 local_state.gradient = Eigen::MatrixXd::Zero(n_im, dof);
9694 std::vector<int> batch;
9695 for (int i = 1; i < n_im - 1; ++i) {
9696 if (ownsImageState(i)) batch.push_back(i);
9697 }
9698 auto compute_owned = [&](gpr::GaussianProcessRegression& model) {
9699 if (batch.empty()) return;
9700 scatter(batch, variancesFor(model, batch), local_state.energy);
9701 for (int i: batch) {
9702 local_state.valid[static_cast<std::size_t>(i)] = 1;
9703 }
9704 };
9705 if (session) {
9706 auto model = session->acquireGlobalModel();
9707 compute_owned(model.gp());
9708 } else {
9709 compute_owned(gp);
9710 }
9711 const auto consensus =
9712 detail::allreduceOwnedImageState(local_state);
9713 for (int i = 1; i < n_im - 1; ++i) {
9714 if (consensus.valid[static_cast<std::size_t>(i)] != 0) {
9715 energy_variances[static_cast<std::size_t>(i)] =
9716 consensus.energy[static_cast<std::size_t>(i)];
9717 }
9718 }
9719 return energy_variances;
9720 }
9721 std::vector<int> batch;
9722 for (int i = 1; i < n_im - 1; ++i)
9723 batch.push_back(i);
9724 if (session) {
9725 auto model = session->acquireGlobalModel();
9726 scatter(batch, variancesFor(model.gp(), batch), energy_variances);
9727 } else {
9728 scatter(batch, variancesFor(gp, batch), energy_variances);
9729 }
9730 return energy_variances;
9731 };
9732 auto computeGlobalObservationVariances =
9733 [&](const std::vector<char>& required,
9734 std::vector<ObservationVariance>& global_variances) {
9735 const int n_im = path.numImages();
9736 const int dof = static_cast<int>(path.image(0).positions.size());
9737 global_variances.assign(n_im, ObservationVariance{});
9738 for (auto& variance: global_variances) {
9739 variance.gradient = Eigen::VectorXd::Zero(dof);
9740 }
9741 bool any_required = false;
9742 for (int i = 1; i < n_im - 1; ++i) {
9743 any_required = any_required || required[i] != 0;
9744 }
9745 if (!any_required) return;
9746 if (gp.hasReusableHssvdPosterior()) {
9747 detail::OwnedImageState local_state;
9748 local_state.valid.assign(static_cast<std::size_t>(n_im), 0);
9749 local_state.energy.assign(static_cast<std::size_t>(n_im), 0.0);
9750 local_state.gradient = Eigen::MatrixXd::Zero(n_im, dof);
9751 auto compute_owned =
9752 [&](gpr::GaussianProcessRegression& model) {
9753 std::vector<int> batch;
9754 batch.reserve(static_cast<std::size_t>(n_im));
9755 for (int i = 1; i < n_im - 1; ++i) {
9756 if (!required[i] || !ownsImageState(i)) {
9757 continue;
9758 }
9759 batch.push_back(i);
9760 }
9761 if (batch.empty()) return;
9762 gpr::Observation probe = makeProbeBatch(batch);
9763 // Chain probes always return the complete joint
9764 // energy-and-gradient variance observation.
9765 model.calculateVarianceDispatched(probe);
9766 for (std::size_t k = 0; k < batch.size(); ++k) {
9767 const int i = batch[k];
9768 const auto variance =
9769 detail::jointObservationVariance(
9770 probe, static_cast<Eigen::Index>(k));
9771 if (variance.gradient.size() != dof) {
9772 throw std::logic_error(
9773 "GP variance probe did not return every "
9774 "gradient channel");
9775 }
9776 local_state.valid[static_cast<std::size_t>(i)] = 1;
9777 local_state.energy[static_cast<std::size_t>(i)] =
9778 variance.energy;
9779 local_state.gradient.row(i) =
9780 variance.gradient.transpose();
9781 }
9782 };
9783 if (session) {
9784 auto model = session->acquireGlobalModel();
9785 compute_owned(model.gp());
9786 } else {
9787 compute_owned(gp);
9788 }
9789 const auto consensus =
9790 detail::allreduceOwnedImageState(local_state);
9791 for (int i = 1; i < n_im - 1; ++i) {
9792 if (!required[i]) continue;
9793 if (consensus.valid[static_cast<std::size_t>(i)] == 0) {
9794 continue;
9795 }
9796 global_variances[i].energy =
9797 consensus.energy[static_cast<std::size_t>(i)];
9798 global_variances[i].gradient =
9799 consensus.gradient.row(i).transpose();
9800 }
9801 return;
9802 }
9803 auto compute_with = [&](gpr::GaussianProcessRegression& model) {
9804 std::vector<int> batch;
9805 batch.reserve(static_cast<std::size_t>(n_im));
9806 for (int i = 1; i < n_im - 1; ++i) {
9807 if (required[i]) batch.push_back(i);
9808 }
9809 if (batch.empty()) return;
9810 gpr::Observation probe = makeProbeBatch(batch);
9811 model.calculateVarianceDispatched(probe);
9812 for (std::size_t k = 0; k < batch.size(); ++k) {
9813 const int i = batch[k];
9814 global_variances[i] = detail::jointObservationVariance(
9815 probe, static_cast<Eigen::Index>(k));
9816 if (global_variances[i].gradient.size() != dof) {
9817 throw std::logic_error(
9818 "GP variance probe did not return every gradient "
9819 "channel");
9820 }
9821 }
9822 };
9823 if (session) {
9824 auto model = session->acquireGlobalModel();
9825 compute_with(model.gp());
9826 } else {
9827 compute_with(gp);
9828 }
9829 };
9830
9831 // Initial-design evaluations enter the global corpus at measurement.
9832 // Populate each image's local view, including a refined warm band, without
9833 // recording those same acquisitions twice.
9834 for (int i = 0; i < path.numImages(); ++i) {
9835 if (!path.image(i).evaluated) continue;
9836 if (session) {
9837 const int row = detail::findPositionIndex(session->training_obs,
9838 path.image(i).positions);
9839 if (row >= 0) {
9840 (void)session->attachImageObservation(i, row);
9841 } else {
9842 session->appendObservation(
9843 i, path.image(i).positions, path.image(i).energy,
9844 path.image(i).gradient,
9845 ObservationRetention::AlreadyRecorded);
9846 }
9847 } else {
9848 appendObservation(training_obs, path.image(i).positions,
9849 path.image(i).energy, path.image(i).gradient);
9850 }
9851 }
9852
9853 // Initial training fit: cold start re-derives hyperparam
9854 // seeds from data statistics. With a session that already
9855 // has fitted hyperparams from a previous phase, warm-start
9856 // instead.
9857 // Tell the GP the chain image count for image-count-adaptive
9858 // controls. The count is NOT a length-scale floor: binding the
9859 // SCG length scale at the chain spacing over-smooths the
9860 // surrogate and moves the converged saddle (Baker14 anchor
9861 // 2.36819 eV at free length scales vs 3.7772 eV with the chain
9862 // bound; single-node A/B). The MAP projection domain keeps only
9863 // the collapse guard and the dimer stencil resolution floor.
9864 gp.setChainImageCount(path.numImages());
9865 if (session) session->gp.setChainImageCount(path.numImages());
9866
9867 // Imported observations initialize a fresh model; their count carries no
9868 // information about whether this GP owns fitted hyperparameters.
9869 const bool cold_start = !gp.hasBeenOptimized();
9870 if (!config.atomic_environments && config.attach_manifold_chart &&
9871 usesClassicJointEnergyForcePrior(config.model_profile)) {
9872 // Seed the pair metric before constructing the chart. The selected
9873 // chart covariance owns the initial fit used by band relaxation.
9874 gp.setHyperparameters(training_obs, atoms_config, cold_start,
9875 cold_start, cold_start);
9876 detail::attachClassicGlobalManifoldChart(config, path, session, gp,
9877 training_obs);
9878 }
9879 gpr::Coord initial_heat_reference;
9880 if (!config.atomic_environments && config.use_geodesic_prior &&
9881 path.numImages() > 0) {
9882 initial_heat_reference.resize(path.numImages(),
9883 path.image(0).positions.size());
9884 for (int image = 0; image < path.numImages(); ++image)
9885 initial_heat_reference.row(image) =
9886 path.image(image).positions.transpose();
9887 if (session)
9888 (void)session->setBandGeodesicReferencePath(initial_heat_reference);
9889 }
9890 if (config.training_policy != nullptr)
9891 noteNebPolicyProgress(session, 0, result,
9892 static_cast<int>(training_obs.R.rows()));
9893 bool initial_hyperparameters_refit = true;
9894 if (session) {
9895 if (config.training_policy != nullptr &&
9896 !had_preexisting_session_rows) {
9897 session->retainTrainingRowsForPolicy(*config.training_policy);
9898 }
9899 initial_hyperparameters_refit = session->refitGP(cold_start);
9900 // Amplitude is owned by the hyperparameter objective; early
9901 // training sets can have near-duplicate energies, so a MAD clamp
9902 // would collapse the fitted signal.
9903 } else {
9904 initial_hyperparameters_refit = optimizeUnlessPolicy(
9905 gp, training_obs, atoms_config, cold_start, config, 0, result);
9906 if (initial_heat_reference.rows() > 0)
9907 (void)gp.fitGeodesicHeatPrior(initial_heat_reference, training_obs);
9908 }
9909 if (initial_hyperparameters_refit)
9910 ++result.hyperparameter_refits;
9911 else
9912 ++result.fixed_theta_refreshes;
9913
9914 // Global L-BFGS band optimizer. The whole interior band is a
9915 // single objective vector, matching the eOn NEB optimizer
9916 // contract rather than per-image first-order relaxation.
9917 detail::GlobalLBFGSOptions band_options;
9918 band_options.memory = config.lbfgs_memory;
9919 band_options.inverse_curvature = config.lbfgs_inverse_curvature;
9920 band_options.finite_difference = config.lbfgs_finite_difference;
9921 band_options.auto_scale = config.lbfgs_auto_scale;
9922 band_options.angle_reset = config.lbfgs_angle_reset;
9923 band_options.distance_reset = config.lbfgs_distance_reset;
9924 band_options.newton_agreement = config.lbfgs_newton_agreement;
9925 band_options.sketch_history = config.lbfgs_sketch_history;
9926 band_options.sketch_seed = config.lbfgs_sketch_seed;
9927 band_options.sketch_h0_rank = config.lbfgs_sketch_h0_rank;
9928 // Which image is the higher saddle is a question about a posterior,
9929 // not about two numbers. The marker moves when the rival is higher
9930 // by more than kappa standard deviations of the difference, which is
9931 // the same confidence the acquisition already uses; a strict
9932 // comparison answers a question the data cannot settle and lets the
9933 // marker swap on noise, so the band climbs a different barrier each
9934 // outer and never converges.
9935 {
9936 double energy_noise = 0.0;
9937 if (config.oracle_energy_noise_rms != nullptr &&
9938 std::isfinite(*config.oracle_energy_noise_rms) &&
9939 *config.oracle_energy_noise_rms > 0.0) {
9940 energy_noise = *config.oracle_energy_noise_rms;
9941 }
9942 detail::setClimbingImageReassignConfidence(config.ucb_kappa,
9943 energy_noise);
9944 }
9945 detail::InternalLbfgsEngine band_optimizer(band_options);
9946 // rg-saddle is the linked librgsaddle. The band engine stays
9947 // opt-in; rg-lbfgs and rg-fire are the rgmin engines. Bofill
9948 // records the index-test choice and calls the linked symbol.
9949 if (!config.rgsaddle_library.empty())
9950 optim::setBofillRgsaddleLibrary(config.rgsaddle_library.c_str());
9951 RgsaddleClient rgsaddle_client;
9952 detail::RgsaddleBandEngine rgsaddle_engine;
9953 GprRgsaddleUser rgsaddle_user;
9954 const bool use_rgsaddle = GPNEBConfig::isRgsaddleEngine(config.band_engine);
9955 if (use_rgsaddle) {
9956 if (!rgsaddle_client.load()) {
9957 neb_log() << "rg-saddle requested but the linked rgsaddle "
9958 "ABI stamp was rejected ("
9959 << rgsaddle_client.lastMessage() << ")\n";
9960 return std::move(result);
9961 }
9962 const int n_im = path.numImages();
9963 const Eigen::Index dof = n_im > 0 ? path.image(0).positions.size() : 0;
9964 if (n_im < 3 || dof < 3 || dof % 3 != 0) {
9965 neb_log() << "rg-saddle refused: band too small\n";
9966 return std::move(result);
9967 }
9968 std::vector<double> packed(static_cast<std::size_t>(n_im) *
9969 static_cast<std::size_t>(dof));
9970 for (int i = 0; i < n_im; ++i) {
9971 const Eigen::VectorXd& p = path.image(i).positions;
9972 if (p.size() != dof) {
9973 neb_log() << "rg-saddle refused: image size mismatch\n";
9974 return std::move(result);
9975 }
9976 std::copy(p.data(), p.data() + dof,
9977 packed.begin() + static_cast<std::ptrdiff_t>(i) * dof);
9978 }
9979 detail::RgsaddleBandEngine::Method rg_method =
9980 detail::RgsaddleBandEngine::Method::Fire;
9981 switch (config.band_engine) {
9982 case GPNEBConfig::BandEngineKind::RgsaddleRtr:
9983 rg_method = detail::RgsaddleBandEngine::Method::Rtr;
9984 break;
9985 case GPNEBConfig::BandEngineKind::RgsaddleOde12r:
9986 rg_method = detail::RgsaddleBandEngine::Method::Ode12r;
9987 break;
9988 case GPNEBConfig::BandEngineKind::RgsaddleOde12rExp:
9989 rg_method = detail::RgsaddleBandEngine::Method::Ode12rExp;
9990 break;
9991 default:
9992 break;
9993 }
9994 if (!rgsaddle_engine.bind(rgsaddle_client, n_im, dof / 3, packed.data(),
9995 rg_method)) {
9996 neb_log() << "rg-saddle bind refused\n";
9997 return std::move(result);
9998 }
9999 rgsaddle_user.gp = &gp;
10000 rgsaddle_engine.setSurface(&gprRgsaddleSurface, &rgsaddle_user);
10001 }
10002 detail::RgFireEngine rg_fire_engine;
10003 detail::RgLbfgsEngine rg_lbfgs_engine(band_options);
10004 detail::BandRelaxationEngine& band_stepper =
10005 use_rgsaddle
10006 ? static_cast<detail::BandRelaxationEngine&>(rgsaddle_engine)
10007 : (config.band_engine == GPNEBConfig::BandEngineKind::RgFire)
10008 ? static_cast<detail::BandRelaxationEngine&>(rg_fire_engine)
10009 : (config.band_engine == GPNEBConfig::BandEngineKind::RgLbfgs)
10010 ? static_cast<detail::BandRelaxationEngine&>(rg_lbfgs_engine)
10011 : static_cast<detail::BandRelaxationEngine&>(band_optimizer);
10012 int active_oie_fixed_image = -1;
10013 // The climbing image held through the surrogate relaxation that follows
10014 // a measured climbing-image step, so the oracle measures the step.
10015 int measured_step_hold_image = -1;
10016 // Trust radius of the measured climbing-image step per image.
10017 std::map<int, double> measured_step_radius;
10018 // Geometries the oracle refused (an exception from the potential). A
10019 // refused geometry is a failed measurement, not an abort: it appends
10020 // no row and is not asked again while an image sits on it.
10021 std::vector<Eigen::VectorXd> oracle_refused_geometries;
10022 const geometry::ElementPairContactFloor acquisition_contact_floor = [&] {
10023 if (!(config.n_atoms > 1 && config.trust_ratio_at_limit > 0.0 &&
10024 config.trust_ratio_at_limit < 1.0))
10027 config.trust_ratio_at_limit *
10028 std::min(geometry::minimumPairDistance(path.image(0).positions,
10029 config.cell),
10031 path.image(path.numImages() - 1).positions,
10032 config.cell)),
10033 domain_atomic_numbers);
10034 // Element floors the endpoints themselves violate describe chemical
10035 // bonding, not this potential; the endpoints recalibrate them.
10036 floor.calibrateToGeometries(
10037 {path.image(0).positions,
10038 path.image(path.numImages() - 1).positions},
10039 config.cell);
10040 return floor;
10041 }();
10042 auto oracleGeometryRefused = [&](const Eigen::VectorXd& positions) {
10043 return std::any_of(
10044 oracle_refused_geometries.begin(), oracle_refused_geometries.end(),
10045 [&](const Eigen::VectorXd& refused) {
10046 return detail::positionsCoincide(positions, refused);
10047 });
10048 };
10049 auto oracleGeometryAdmissible = [&](const Eigen::VectorXd& positions) {
10050 return !oracleGeometryRefused(positions) &&
10051 !acquisition_contact_floor.violated(positions, config.cell);
10052 };
10053 auto rememberOracleRefusal = [&](const Eigen::VectorXd& positions) {
10054 if (!oracleGeometryRefused(positions))
10055 oracle_refused_geometries.push_back(positions);
10056 };
10057 // Consecutive refused measurements at band geometries; past
10058 // kMaxConsecutiveOracleFailures the run stops with an error.
10059 OracleFailureBudget oracle_failures;
10060 // Evaluates stencil or certificate targets; a refused target stays
10061 // unevaluated and is remembered, so it is not requested again.
10062 auto evaluateBandTargets =
10063 [&](const std::vector<Eigen::VectorXd>& positions,
10064 const std::vector<NEBOracleEvaluationContext>* contexts,
10065 std::vector<char>& measured) {
10066 std::string failure;
10067 auto results = evaluateTrialPoints(
10068 positions, oracle, contexts, config.oracle_evaluation_context,
10069 config.oracle_session_restart_requested, &config.batch_oracle,
10070 config.oracle_batch_chunk, measured, failure);
10071 bool refused = false;
10072 for (std::size_t k = 0; k < positions.size(); ++k) {
10073 if (measured[k]) continue;
10074 refused = true;
10075 rememberOracleRefusal(positions[k]);
10076 }
10077 if (refused) {
10078 if (config.verbose)
10079 neb_log() << "[oracle-refused] band target what=" << failure
10080 << std::endl;
10081 oracle_failures.failed("band", failure);
10082 } else {
10083 oracle_failures.measured();
10084 }
10085 return results;
10086 };
10087 detail::OieRecoveryStencilAnchor recovery_stencil_anchor;
10088 detail::ProposalAcquisitionTarget recovery_growth_backtrack_target;
10089 // Barrier of the last certified-best snapshot whose restore fired
10090 // the terminal stencil check. Restoring the identical snapshot
10091 // re-measures identical positions, so the check is spent once per
10092 // distinct snapshot.
10093 double last_restore_stencil_barrier =
10094 std::numeric_limits<double>::quiet_NaN();
10095 // Individual L-BFGS steps are capped by the configured displacement.
10096 // Measured model agreement controls the separate geometric trust radius;
10097 // a nonconservative NEB relaxation can increase its residual on one step.
10098 const double band_max_step = config.lbfgs_max_move;
10099
10100 TrustRadius trust;
10101 trust.setAtomsConfiguration(atoms_config);
10102 trust.setDistanceMetric(config.trust_metric);
10103
10104 // Per-image trust. The predictor at image i is its per-image
10105 // GP, fit on image i's own neighbourhood. Proposal
10106 // certification bounds image i to the same training set as the
10107 // model that predicts it.
10108 TrustRadius image_trust;
10109 image_trust.setAtomsConfiguration(atoms_config);
10110 image_trust.setDistanceMetric(config.trust_metric);
10111
10112 // Scale-free trust region (TuRBO/LABCAT fraction-of-spread), behind
10113 // config.scalefree_trust (default OFF -> no regression). The radius is
10114 // anchored to tau * median EMD pairwise spread of the training set,
10115 // so it auto-rescales per system and tau stays a dimensionless O(1)
10116 // knob (config.scalefree_tau sets it for sweeps without a rebuild).
10117 // Re-anchored only on the first outer iteration that has >=2 training
10118 // rows; later outers keep the learned radius (no re-anchor drift).
10119 const bool scalefree_trust_enabled = config.scalefree_trust;
10120 ScaleFreeTrustConfig sftr_cfg;
10121 if (std::isfinite(config.scalefree_tau) && config.scalefree_tau > 0.0)
10122 sftr_cfg.tau = config.scalefree_tau;
10123 ScaleFreeTrustRegion sftr(sftr_cfg);
10124
10125 // Index of the image the convergence gate last oracled. When
10126 // the run converges this is the saddle (in Phase 2 it is the
10127 // latched climbing image), and path.image(converged_worst_idx)
10128 // already carries that image's TRUE oracle energy + gradient
10129 // from the gate evaluation -- no separate validation pass is
10130 // needed to get a true-PES barrier.
10131 int converged_worst_idx = -1;
10132 double smallest_oracle_force = std::numeric_limits<double>::infinity();
10133 // Initial-path baseline F0 uses current true oracle rows only.
10134 // Mixed GP/true whole-band force remains the restart and convergence
10135 // merit, but CI activation must not scale itself from GP-only spikes.
10136 double f0_baseline = 0.0;
10137 auto snapshotPathPositions = [&]() {
10138 std::vector<Eigen::VectorXd> positions(path.numImages());
10139 for (int i = 0; i < path.numImages(); ++i) {
10140 positions[i] = path.image(i).positions;
10141 }
10142 return positions;
10143 };
10144 auto restorePathPositions =
10145 [&](const std::vector<Eigen::VectorXd>& positions) {
10146 (void)detail::restoreOiePathPositions(
10147 path, positions,
10148 /*preserve_climbing_marker=*/ci_active);
10149 };
10150 auto updateMeasuredAnchor = [&]() {
10151 std::vector<double> measured_force_profile =
10152 detail::measuredBandForceProfile(path);
10153 if (measured_force_profile.empty() ||
10154 (!anchor_true_force_profile.empty() &&
10155 !detail::shouldAcceptMeasuredBandCandidate(
10156 measured_force_profile, anchor_true_force_profile))) {
10157 return false;
10158 }
10159
10160 anchor_true_force_profile = std::move(measured_force_profile);
10161 anchor_true_max_force = anchor_true_force_profile.front();
10162 anchor_positions = snapshotPathPositions();
10163 return true;
10164 };
10165 const std::vector<Eigen::VectorXd> initial_relaxation_positions =
10166 snapshotPathPositions();
10167 // Best-path recovery is available only through its explicit
10168 // force-merit gate. The live trust-accepted band otherwise carries
10169 // across outer iterations.
10170 std::vector<Eigen::VectorXd> best_path_positions =
10171 initial_relaxation_positions;
10172 std::vector<Eigen::VectorXd> latest_equal_positions =
10173 initial_relaxation_positions;
10174 std::vector<Eigen::VectorXd> latest_climb_positions =
10175 initial_relaxation_positions;
10176 std::vector<Eigen::VectorXd> best_climb_positions =
10177 initial_relaxation_positions;
10178 bool have_latest_equal_positions = false;
10179 bool have_latest_climb_positions = false;
10180 bool have_best_climb_positions = false;
10181 bool latest_climb_from_drift = false;
10182 // A force-improving, fully measured reparametrized band owns the
10183 // restart anchor. Surrogate-only snapshots cannot displace it.
10184 bool measured_reparam_restart_protected = false;
10185 bool hook_reparam_pending = false;
10186 bool skip_next_inner_after_rejected_hook = false;
10187 int hook_reparam_anchor_idx = -1;
10188 Eigen::VectorXd hook_reparam_source_signature;
10189 detail::AdjacentMepRecoveryState adjacent_mep_recovery;
10190 int latest_climb_ci_idx = -1;
10191 int best_climb_ci_idx = -1;
10192 double latest_climb_barrier = std::numeric_limits<double>::infinity();
10193 double best_climb_barrier = std::numeric_limits<double>::infinity();
10194 double best_oracle_force = std::numeric_limits<double>::infinity();
10195 double best_climb_oracle_force = std::numeric_limits<double>::infinity();
10196 double last_outer_oracle_force = std::numeric_limits<double>::infinity();
10197 // The best climb's own measurement travels with its snapshot so the
10198 // band can return to that measured point within an outer.
10199 double best_climb_ci_energy = std::numeric_limits<double>::quiet_NaN();
10200 Eigen::VectorXd best_climb_ci_gradient;
10201 // Restore and continue receive rewards in [0, 1]: relative improvements
10202 // of the best measured climbing force. A decision waits for its measured
10203 // outcome; returning to the retained best alone earns zero. Each arm
10204 // uses Beta(1 + sum(rewards), 1 + pulls - sum(rewards)), the fractional
10205 // update discussed by Agrawal and Goyal (COLT 2012, section 1.2). The
10206 // uniform prior retains uncertainty for repeated zero rewards. This is
10207 // a sampling rule for state-dependent rewards, without a stationary
10208 // bandit regret guarantee.
10209 detail::OieContinuationRewards continuation_rewards;
10210 std::mt19937_64 continuation_rng(
10211 static_cast<std::uint64_t>(config.acquisition_seed_offset) + 1U);
10212 const auto continuationMerit = [&]() {
10213 return detail::oieContinuationMerit(
10214 ci_active, config.climbing_image_converged_only, path);
10215 };
10216 auto decideRestoreByThompson = [&](detail::OieLowerBarrierAction action,
10217 double merit_now) {
10218 if (action != detail::OieLowerBarrierAction::RestoreCertifiedBest)
10219 return action;
10220 if (continuation_rewards.pending())
10221 return detail::OieLowerBarrierAction::KeepCurrent;
10222 const auto& continue_arm = continuation_rewards.arm(false);
10223 const auto& restore_arm = continuation_rewards.arm(true);
10224 bool restore;
10225 if (continue_arm.pulls < 2 || restore_arm.pulls < 2) {
10226 // Both arms receive two measured outcomes before sampling.
10227 restore = restore_arm.pulls <= continue_arm.pulls;
10228 } else {
10229 const double restore_draw = detail::sampleOieContinuationReward(
10230 restore_arm, continuation_rng);
10231 const double continue_draw = detail::sampleOieContinuationReward(
10232 continue_arm, continuation_rng);
10233 restore = restore_draw > continue_draw;
10234 }
10235 if (!continuation_rewards.begin(restore, merit_now))
10236 return detail::OieLowerBarrierAction::KeepCurrent;
10237 if (config.verbose)
10238 neb_log() << "[gp_oie] continuation: "
10239 << (restore ? "restore" : "continue")
10240 << " (restore pulls=" << restore_arm.pulls << " mean="
10241 << (restore_arm.pulls
10242 ? restore_arm.reward_sum / restore_arm.pulls
10243 : 0.0)
10244 << ", continue pulls=" << continue_arm.pulls << " mean="
10245 << (continue_arm.pulls
10246 ? continue_arm.reward_sum / continue_arm.pulls
10247 : 0.0)
10248 << ")\n";
10249 return restore ? action : detail::OieLowerBarrierAction::KeepCurrent;
10250 };
10251 auto climbRestartBarrier = [&](int climb_idx) {
10252 if (!(ci_active && climb_idx > 0 && climb_idx < path.numImages() - 1)) {
10253 return std::numeric_limits<double>::infinity();
10254 }
10255 const double saddle_energy = path.image(climb_idx).energy;
10256 const double e0 = path.image(0).energy;
10257 const double en = path.image(path.numImages() - 1).energy;
10258 if (!std::isfinite(saddle_energy) || !std::isfinite(e0) ||
10259 !std::isfinite(en)) {
10260 return std::numeric_limits<double>::infinity();
10261 }
10262 return saddle_energy - std::min(e0, en);
10263 };
10264 auto certifiedClimbIndex = [&](int climb_idx) {
10265 if (detail::hasTruePesSaddleEnergyCertificate(path, climb_idx,
10266 config.conv_tol)) {
10267 return climb_idx;
10268 }
10269 return -1;
10270 };
10271 auto clearLatestClimbRestartSnapshot = [&]() {
10272 have_latest_climb_positions = false;
10273 latest_climb_from_drift = false;
10274 latest_climb_ci_idx = -1;
10275 latest_climb_barrier = std::numeric_limits<double>::infinity();
10276 };
10277 auto recordLatestClimbRestartSnapshot = [&](int climb_idx,
10278 bool from_drift) {
10279 latest_climb_positions = snapshotPathPositions();
10280 have_latest_climb_positions = true;
10281 latest_climb_from_drift = from_drift;
10282 latest_climb_ci_idx = certifiedClimbIndex(climb_idx);
10283 latest_climb_barrier = climbRestartBarrier(latest_climb_ci_idx);
10284 };
10285 auto recordBestClimbRestartSnapshot = [&](int climb_idx) {
10286 best_climb_positions = snapshotPathPositions();
10287 have_best_climb_positions = true;
10288 // The step radius describes the model at the previous best climb.
10289 measured_step_radius.erase(climb_idx);
10290 best_climb_ci_idx = certifiedClimbIndex(climb_idx);
10291 best_climb_barrier = climbRestartBarrier(best_climb_ci_idx);
10292 best_climb_ci_energy = std::numeric_limits<double>::quiet_NaN();
10293 best_climb_ci_gradient.resize(0);
10294 if (climb_idx > 0 && climb_idx < path.numImages() - 1 &&
10295 path.image(climb_idx).evaluated &&
10296 path.image(climb_idx).gradient.size() ==
10297 path.image(climb_idx).positions.size() &&
10298 path.image(climb_idx).gradient.allFinite() &&
10299 std::isfinite(path.image(climb_idx).energy)) {
10300 best_climb_ci_energy = path.image(climb_idx).energy;
10301 best_climb_ci_gradient = path.image(climb_idx).gradient;
10302 }
10303 };
10304 std::optional<Eigen::VectorXd> previous_ci_oracle_position;
10305 std::optional<Eigen::VectorXd> previous_ci_oracle_force;
10306 std::optional<int> previous_ci_oracle_index;
10307
10308 // Canonical OIE control (Koistinen 2017 J.Chem.Phys.147.152720 /
10309 // Koistinen 2019 JCTC 10.1021/acs.jctc.9b00692 atomic_GP_NEB_OIE.m;
10310 // Garrido-Torres 2019 PRL 122.156001 CatLearn AcqUME). The outer
10311 // loop has two regimes:
10312 //
10313 // EXPLORE (frozen_sweep == false): relax the whole band on the
10314 // GP, then oracle the single UN-EVALUATED image with the largest
10315 // posterior ENERGY variance (the acquisition pick). Relaxing
10316 // moves every intermediate image, so every image is marked
10317 // un-evaluated at the top of the next round -- the oracle calls
10318 // spread across the chain instead of latching one image.
10319 //
10320 // SWEEP (frozen_sweep == true): freeze the band after the GP-side
10321 // force and uncertainty certificates are met, then evaluate the
10322 // remaining current-geometry images on the true PES one per round:
10323 // climbing image first, then by descending variance. Sweep-mode
10324 // convergence requires true oracle data at every intermediate image
10325 // current geometry (N_uneval == 0) and a true max NEB force below
10326 // conv_tol. The CI-only OIE exit above is the cheaper saddle-focused
10327 // convergence path; this sweep is a full-band validation regime.
10328 //
10329 // path.image(i).evaluated is the per-image "evaluated at current
10330 // position" flag: refreshAllGpPath (the inner-loop refresh) clears
10331 // it for every image it GP-predicts, and the oracle sets it true
10332 // for the image it evaluates -- so it already tracks the MATLAB
10333 // reference's `uneval` mask.
10334 bool frozen_sweep = false;
10335
10336 auto restoreInteriorPositionSignature =
10337 [&](const Eigen::VectorXd& signature) {
10338 if (path.numImages() <= 2) return false;
10339 const Eigen::Index image_dof = path.image(1).positions.size();
10340 const Eigen::Index expected =
10341 static_cast<Eigen::Index>(path.numImages() - 2) * image_dof;
10342 if (image_dof <= 0 || signature.size() != expected ||
10343 !signature.allFinite()) {
10344 return false;
10345 }
10346 std::vector<Eigen::VectorXd> positions = snapshotPathPositions();
10347 for (int i = 1; i < path.numImages() - 1; ++i) {
10348 positions[static_cast<std::size_t>(i)] = signature.segment(
10349 static_cast<Eigen::Index>(i - 1) * image_dof, image_dof);
10350 }
10351 return detail::restoreOiePathPositions(
10352 path, positions, /*preserve_climbing_marker=*/ci_active);
10353 };
10354 PendingFixedPointCampaign pending_fixed_point;
10355 detail::OiePendingBandAction pending_band_action;
10356 detail::ProposalAcquisitionTarget pending_band_action_acquisition;
10357 detail::MeasuredBandRecoveryState measured_band_recovery(path.numImages());
10358 // Interior-position signatures of fixed points seen since the
10359 // training set last changed. A recurring signature after a completed
10360 // acquisition or redistribution attempt means the outer map remains
10361 // unchanged. New information resets the set.
10362 detail::OieFixedPointHistory fixed_point_history;
10363 auto& fixed_point_signatures = fixed_point_history.resolutions;
10364 // Brent's doubling windows retain one band state while detecting a
10365 // recurrent outer relaxation without an iteration-count cutoff.
10366 Eigen::VectorXd outer_cycle_anchor;
10367 std::vector<std::uint64_t> outer_cycle_epoch;
10368 Eigen::Vector3d outer_cycle_parameters = Eigen::Vector3d::Zero();
10369 std::size_t outer_cycle_power = 1;
10370 std::size_t outer_cycle_steps = 0;
10371 // Fixed-point signatures whose one-shot MMF grant is spent. A stalled
10372 // outer map (recurring signature, or a fixed point whose
10373 // redistribution has no measured need or GP support) authorizes one
10374 // dimer burst before the honest non-convergence exit: the stall is
10375 // structural evidence that band relaxation alone cannot progress,
10376 // and the burst carries its own certificates, so this changes
10377 // liveness, never acceptance. The spent set resets with the
10378 // signature set when new training information arrives.
10379 auto& fixed_point_mmf_grants = fixed_point_history.mmf_grants;
10380 bool fixed_point_requests_mmf = false;
10381 // The empirical gradient-fidelity radius persists across outer iterations.
10382 // Its numerical floor is independent of the exploration schedule.
10383 double rho_trust_radius = config.trust_radius;
10384 // Empirical calibration of the posterior variance: the squared error
10385 // of the surrogate's force prediction at the latest oracle target over
10386 // the variance it reported there (with the likelihood noise), floored
10387 // at one. The same rule the dimer applies to its stop test. Every
10388 // consumer of the chain's posterior variance (readiness, acquisition,
10389 // trust certificates) sees the variance scaled by it, so a surrogate
10390 // that was wrong by many standard deviations is not trusted at the
10391 // next outer as though it had been right; a surrogate that predicted
10392 // the measurement is unaffected.
10393 double measured_variance_calibration = 1.0;
10394 double measured_variance_error = std::numeric_limits<double>::quiet_NaN();
10395 double measured_variance_reported =
10396 std::numeric_limits<double>::quiet_NaN();
10397 double rho_last_fidelity = std::numeric_limits<double>::quiet_NaN();
10398 const auto gpneb_wall_t0 = std::chrono::steady_clock::now();
10399 auto previous_outer_wall_t0 = gpneb_wall_t0;
10400 double longest_outer_seconds = 0.0;
10401 bool wall_clock_stopped = false;
10402 const auto wallClockReached = [&]() {
10403 if (!gpr::collectiveWallClockLimitReached(config.wall_clock_limit))
10404 return false;
10405 wall_clock_stopped = true;
10406 result.converged = false;
10407 result.stop_reason = GPNEBStopReason::WallClockLimit;
10408 return true;
10409 };
10410 // The probe is an oracle call like any other: it waits for the wall-clock
10411 // limit, counts toward the consecutive-failure bound, and an oracle that
10412 // refuses it leaves the probe unbought.
10413 const auto apply_secant_consistency = [&]() {
10414 if (!config.secant_hessian.consistency_check) return;
10415 if (session == nullptr)
10416 throw std::logic_error(
10417 "secant consistency requested but the band has no session");
10418 const bool bought = session->purchaseSecantConsistencyProbe(
10419 [&](const Eigen::VectorXd& probe) {
10420 if (wallClockReached()) return false;
10421 std::vector<char> measured;
10422 const auto results =
10423 evaluateBandTargets({probe}, nullptr, measured);
10424 ++result.oracle_calls;
10425 ++result.oracle_calls_outer;
10426 if (!measured.front()) return false;
10427 session->appendObservation(probe, results.front().energy,
10428 results.front().gradient);
10429 return true;
10430 });
10431 if (bought) (void)session->refitGP(false);
10432 };
10433 apply_secant_consistency();
10434 // Initial band snapshot for the post-convergence channel
10435 // survey: the survey re-relaxes perturbed copies of THIS band
10436 // on the final surrogate, so it must predate any GP-driven
10437 // relaxation.
10438 // Seed rows are exempt from the first prune window: the counter
10439 // starts at the seeded size so pruning first arms only after
10440 // adaptive_prune_growth ACQUIRED rows, past the activation
10441 // bootstrap.
10442 Eigen::Index last_prune_ntrain = training_obs.R.rows();
10443 // Oracle count at the last hand-off bypass of the inner relaxation.
10444 // A bypass is honoured once per burst: when no oracle call followed
10445 // the previous bypass, the prepared hand-off was declined and the
10446 // band relaxes instead of replaying the same bypass.
10447 long handoff_bypass_oracle_calls = -1;
10448 std::vector<Eigen::VectorXd> channel_survey_initial_band;
10449 if (config.channel_survey) {
10450 channel_survey_initial_band.resize(path.numImages());
10451 for (int i = 0; i < path.numImages(); ++i) {
10452 channel_survey_initial_band[i] = path.image(i).positions;
10453 }
10454 }
10455 // Outer budget, optionally per image. The acquisition oracles about
10456 // one image per outer iteration, so a band of n images needs n outers
10457 // to be covered once; read absolutely, the same number gives a longer
10458 // band less chance per image, and a setting tuned at one image count
10459 // is silently wrong at another.
10460 const int outer_budget =
10461 (config.outer_budget_per_image && path.numImages() > 0)
10462 ? static_cast<int>(std::min<long>(
10463 static_cast<long>(config.max_outer_iter) * path.numImages(),
10464 std::numeric_limits<int>::max()))
10465 : config.max_outer_iter;
10466 detail::OffBandResidualGuard off_band_residual_guard;
10467 double logged_prev_predicted_energy =
10468 std::numeric_limits<double>::quiet_NaN();
10469 double logged_prev_actual_energy = std::numeric_limits<double>::quiet_NaN();
10470 struct AccumulateWallTime {
10471 double& total;
10472 std::chrono::steady_clock::time_point start =
10473 std::chrono::steady_clock::now();
10474 bool running = true;
10475
10476 explicit AccumulateWallTime(double& target) : total(target) { }
10477 AccumulateWallTime(const AccumulateWallTime&) = delete;
10478 AccumulateWallTime& operator=(const AccumulateWallTime&) = delete;
10479 void stop() noexcept
10480 {
10481 if (!running) return;
10482 total += std::chrono::duration<double>(
10483 std::chrono::steady_clock::now() - start)
10484 .count();
10485 running = false;
10486 }
10487 ~AccumulateWallTime()
10488 {
10489 stop();
10490 }
10491 };
10492 struct AccumulateBandPhases {
10493 double& inner;
10494 double& refit;
10495 double& path;
10496 double& predict;
10497 long& predict_count;
10498 double& certificate;
10499 double& drift;
10500
10501 ~AccumulateBandPhases()
10502 {
10507 gpr::PhaseTimers::band_predict_count += predict_count;
10510 }
10511 };
10512 for (int outer = 0; outer < outer_budget; ++outer) {
10513 if (wallClockReached()) break;
10514 if (config.training_policy != nullptr)
10515 noteNebPolicyProgress(session, outer, result,
10516 static_cast<int>(training_obs.R.rows()));
10517 // Per-outer phase attribution, reported next to dt= so a slow
10518 // outer names its owner (inner relaxation, hyperparameter
10519 // refit, band posterior refresh) instead of one opaque total.
10520 double phase_inner_seconds = 0.0;
10521 double phase_refit_seconds = 0.0;
10522 double phase_path_seconds = 0.0;
10523 double phase_predict_seconds = 0.0;
10524 double phase_cert_seconds = 0.0;
10525 double phase_drift_seconds = 0.0;
10526 long phase_predict_count = 0;
10527 const AccumulateBandPhases accumulate_band_phases{
10528 phase_inner_seconds, phase_refit_seconds, phase_path_seconds,
10529 phase_predict_seconds, phase_predict_count, phase_cert_seconds,
10530 phase_drift_seconds};
10531 // Set when this outer kept a certified drift and the oracle
10532 // gradient at that geometry has a squared error outside the
10533 // posterior that proposed the step. A drift the certifier already
10534 // refused is back on the last accepted band; rewinding that band
10535 // to the outer start would drop the steps this outer kept.
10536 bool drift_left_posterior = false;
10537 bool kept_certified_drift = false;
10538 if (update_frozen_environment()) {
10539 AccumulateWallTime refit_wall(phase_refit_seconds);
10540 if (config.training_policy != nullptr)
10541 noteNebPolicyProgress(session, outer, result,
10542 static_cast<int>(training_obs.R.rows()));
10543 const bool refit =
10544 session ? session->refitGP(true)
10545 : optimizeUnlessPolicy(gp, training_obs, atoms_config,
10546 true, config, outer, result);
10547 if (refit)
10548 ++result.hyperparameter_refits;
10549 else
10550 ++result.fixed_theta_refreshes;
10551 trust.setAtomsConfiguration(atoms_config);
10552 image_trust.setAtomsConfiguration(atoms_config);
10553 measured_variance_calibration = 1.0;
10554 if (scalefree_trust_enabled && training_obs.R.rows() >= 2)
10555 sftr.initFromTrainingSpread(detail::emdMedianPairwiseDistance(
10556 training_obs.R, atoms_config));
10557 }
10558 if (wallClockReached()) break;
10559 // Soft geodesic heat prior: hand the session the live band
10560 // as the reference path; the next cadence refit
10561 // evidence-fits the additive amplitude against the current
10562 // atomistic model (zero optimum = exact fallback). The
10563 // setter dedups unchanged paths, so this is free on outers
10564 // where the band did not move.
10565 if (!config.atomic_environments &&
10566 (config.use_geodesic_prior || config.use_chem_factorized_hyper ||
10567 config.use_adaptive_prune) &&
10568 session) {
10569 const Eigen::Index band_dof = path.image(0).positions.size();
10570 gpr::Coord band_reference(path.numImages(), band_dof);
10571 for (int i = 0; i < path.numImages(); ++i) {
10572 band_reference.row(i) = path.image(i).positions.transpose();
10573 }
10574 if (config.use_geodesic_prior) {
10575 (void)session->setBandGeodesicReferencePath(band_reference);
10576 }
10577 if (config.use_chem_factorized_hyper) {
10578 // The live band is the physics collocation set for
10579 // the constrained empirical-Bayes filter in
10580 // optimizeChemistryFactorized.
10581 auto model = session->acquireGlobalModel();
10582 model.gp().setPhysicsCollocationPath(band_reference);
10583 }
10584 // Adaptive pruning on the refit cadence: rows that
10585 // cannot move any band energy by one noise sigma are
10586 // dead weight in every later O(n^3) refit.
10587 // The prune waits for a refit point. Between refits the
10588 // rematerialize is a suffix append onto the cached
10589 // factor, and dropping rows makes the training matrix
10590 // stop being an extension of the one that factor was
10591 // built on, which turns every later refresh back into a
10592 // full O(n^3) rebuild (measured: 40 s of a 100 s outer on
10593 // Baker 21 at inner=0). At a refit point the factor is
10594 // rebuilt regardless, so the same prune is free there.
10595 if (config.use_adaptive_prune &&
10596 (session == nullptr || session->wouldRefitAtNextRefresh())) {
10597 const Eigen::Index ntrain = training_obs.R.rows();
10598 if (ntrain - last_prune_ntrain >=
10599 static_cast<Eigen::Index>(config.adaptive_prune_growth)) {
10600 const int dropped =
10601 session->pruneTrainingObservationsAdaptive(
10602 band_reference);
10603 // Double-GP contract: the global set prunes against
10604 // the whole band, and every activated single-image
10605 // GP additionally prunes its own local set against
10606 // its own band point.
10607 const int image_dropped =
10608 session->pruneImageModelsAdaptive(band_reference);
10609 const int budget_dropped =
10610 config.adaptive_prune_max_observations > 0
10611 ? session->boundActiveSetToBand(
10612 band_reference,
10613 config.adaptive_prune_max_observations)
10614 : 0;
10615 last_prune_ntrain = training_obs.R.rows();
10616 if (dropped > 0 || image_dropped > 0 ||
10617 budget_dropped > 0) {
10618 neb_log()
10619 << "[prune] outer=" << outer
10620 << " dropped=" << dropped
10621 << " budget_dropped=" << budget_dropped
10622 << " image_dropped=" << image_dropped
10623 << " ntrain=" << training_obs.R.rows() << "\n";
10624 }
10625 }
10626 }
10627 }
10628 // Reduce the rank-owned oracle noise floor here, at the one point
10629 // in the iteration every rank reaches unconditionally. The
10630 // materialise paths that consume it (ensureSingletonForImage,
10631 // ensureSingletonForGlobal) sit behind rank-local early returns,
10632 // so they cannot host the reduction themselves.
10633 if (session) session->refreshLikelihoodNoiseFloor();
10634 const auto outer_wall_t0 = std::chrono::steady_clock::now();
10635 if (outer > 0) {
10636 longest_outer_seconds =
10637 std::max(longest_outer_seconds,
10638 std::chrono::duration<double>(outer_wall_t0 -
10639 previous_outer_wall_t0)
10640 .count());
10641 }
10642 previous_outer_wall_t0 = outer_wall_t0;
10643 const double elapsed_seconds =
10644 std::chrono::duration<double>(outer_wall_t0 - gpneb_wall_t0)
10645 .count();
10646 if (!config.wall_clock_limit &&
10647 detail::oieAttemptWallBudgetExhausted(
10648 elapsed_seconds, longest_outer_seconds,
10649 config.attempt_wall_seconds)) {
10650 break;
10651 }
10652 int log_rank = 0;
10653#ifdef GPR_HAVE_MPI
10654 int log_mpi_up = 0;
10655 MPI_Initialized(&log_mpi_up);
10656 if (log_mpi_up) MPI_Comm_rank(MPI_COMM_WORLD, &log_rank);
10657#endif
10658 FixedPointProposalKind fixed_point_applied_kind =
10659 FixedPointProposalKind::None;
10660 // Every required candidate must be measurable. A refused candidate
10661 // cannot acquire the evidence needed to apply a pending band.
10662 for (int i = 1;
10663 i + 1 <
10664 static_cast<int>(pending_fixed_point.candidate_positions.size());
10665 ++i) {
10666 if (pending_fixed_point.climbing_image > 0 &&
10667 std::abs(i - pending_fixed_point.climbing_image) > 1)
10668 continue;
10669 const auto& candidate = pending_fixed_point.candidate_positions[i];
10670 if (!detail::hasPosition(training_obs, candidate) &&
10671 !oracleGeometryAdmissible(candidate)) {
10672 pending_fixed_point.clear();
10673 break;
10674 }
10675 }
10676 if (pending_band_action.active() &&
10677 !pending_band_action.sourceMatches(
10678 interiorPositionSignature(path))) {
10679 pending_band_action.clear();
10680 pending_band_action_acquisition.clear();
10681 }
10682 if (session) {
10683 session->ci_active_at_outer_start = ci_active;
10684 if (ci_active)
10685 ++session->ci_stable_outer_count;
10686 else
10687 session->ci_stable_outer_count = 0;
10688 }
10689 // The full-band confirmation sweep (frozen_sweep) holds the band
10690 // geometry fixed and oracles one un-evaluated image per outer
10691 // until every intermediate image carries a true gradient
10692 // (n_uneval == 0), at which point the sweep-mode force gate fires.
10693 // restorePathPositions resets every image's evaluated flag to
10694 // false, so running it during the sweep wipes the accumulated
10695 // confirmations each outer -- the picker then re-oracles the same
10696 // image forever, n_uneval never reaches 0, and the run freezes
10697 // until the iteration cap. Skip the restore (and the
10698 // reparametrization, which also perturbs the held geometry) while
10699 // the sweep is in progress; the cascade resumes once the sweep
10700 // rejects the current band on the true PES or reaches convergence.
10701 if (!frozen_sweep) {
10702 if (pending_band_action.active() &&
10703 !restoreInteriorPositionSignature(
10704 pending_band_action.sourcePositions())) {
10705 pending_band_action.clear();
10706 pending_band_action_acquisition.clear();
10707 }
10708 // Carry the live trust-accepted band by default. Explicit
10709 // certified climb and force-merit recovery states may replace
10710 // it; the interpolation seed is not recovery evidence. A
10711 // pending measured campaign owns its source band until its
10712 // acquisition and candidate assessment resolve.
10713 const bool surrogate_restart_allowed =
10714 !measured_reparam_restart_protected &&
10715 !pending_band_action.active() && !pending_fixed_point.active();
10716 const bool use_drift_climb_restart =
10717 surrogate_restart_allowed &&
10718 detail::shouldPreferLatestOieClimbRestart(
10719 ci_active, have_latest_climb_positions,
10720 latest_climb_from_drift);
10721 const bool use_best_climb_restart =
10722 surrogate_restart_allowed && !use_drift_climb_restart &&
10723 detail::shouldUseOieBestClimbRestart(
10724 ci_active, have_best_climb_positions,
10725 best_climb_oracle_force, last_outer_oracle_force,
10726 best_climb_ci_idx, best_climb_barrier, latest_climb_ci_idx,
10727 latest_climb_barrier);
10728 if (use_drift_climb_restart) {
10729 latest_climb_from_drift = false;
10730 }
10731 // Force-ratio best-path restarts are off; the restore
10732 // chain below prefers latest_climb then latest_equal /
10733 // best_path when climb restart is inactive.
10734 const bool use_best_restart = false;
10735 const bool use_latest_climb =
10736 surrogate_restart_allowed &&
10737 (use_drift_climb_restart ||
10738 (!use_best_climb_restart && !use_best_restart && ci_active &&
10739 have_latest_climb_positions));
10740 const bool use_latest_equal = !use_latest_climb && ci_active &&
10741 surrogate_restart_allowed &&
10742 have_latest_equal_positions;
10743 const detail::OieRelaxationRestartSource restart_source =
10744 pending_band_action.active()
10745 ? detail::OieRelaxationRestartSource::CurrentPath
10746 : detail::selectOieRelaxationRestartSource(
10747 frozen_sweep, use_best_climb_restart,
10748 use_best_restart, use_latest_climb, use_latest_equal);
10749 switch (restart_source) {
10750 case detail::OieRelaxationRestartSource::BestClimb:
10751 restorePathPositions(best_climb_positions);
10752 break;
10753 case detail::OieRelaxationRestartSource::BestPath:
10754 restorePathPositions(best_path_positions);
10755 break;
10756 case detail::OieRelaxationRestartSource::LatestClimb:
10757 restorePathPositions(latest_climb_positions);
10758 break;
10759 case detail::OieRelaxationRestartSource::LatestEqual:
10760 restorePathPositions(latest_equal_positions);
10761 break;
10762 case detail::OieRelaxationRestartSource::CurrentPath:
10763 break;
10764 }
10765 // Hook redistribution is opportunistic: it may reorganize
10766 // exact-supported images, but it does not open an acquisition
10767 // campaign away from the measured path. Fixed-point recovery
10768 // owns deliberate support expansion for a stalled band.
10769 if (hook_reparam_pending) {
10770 const Eigen::VectorXd current_signature =
10771 interiorPositionSignature(path);
10772 const bool source_matches =
10773 surrogate_restart_allowed &&
10774 (hook_reparam_source_signature.size() == 0 ||
10775 detail::positionsCoincide(current_signature,
10776 hook_reparam_source_signature));
10777 if (source_matches && !pending_fixed_point.active()) {
10778 std::vector<Eigen::VectorXd> proposed_positions =
10779 detail::proposeReparametrizedBand(
10780 path, config, hook_reparam_anchor_idx);
10781 bool proposal_moves_band = false;
10782 bool all_candidate_images_observed = true;
10783 for (int i = 1; i < path.numImages() - 1; ++i) {
10784 proposal_moves_band =
10785 proposal_moves_band ||
10786 !detail::positionsCoincide(
10787 path.image(i).positions,
10788 proposed_positions[static_cast<std::size_t>(
10789 i)]);
10790 all_candidate_images_observed =
10791 all_candidate_images_observed &&
10792 detail::hasPosition(
10793 training_obs,
10794 proposed_positions[static_cast<std::size_t>(
10795 i)]);
10796 }
10797 if (detail::shouldQueueOieHookReparamCandidate(
10798 proposal_moves_band,
10799 all_candidate_images_observed)) {
10800 pending_fixed_point.source_signature =
10801 current_signature;
10802 pending_fixed_point.candidate_positions =
10803 std::move(proposed_positions);
10804 pending_fixed_point.kind =
10805 FixedPointProposalKind::Reparameterization;
10806 }
10807 }
10808 hook_reparam_pending = false;
10809 hook_reparam_anchor_idx = -1;
10810 hook_reparam_source_signature.resize(0);
10811 }
10812 } // end if (!frozen_sweep): restore/reparam skipped during sweep
10813 if (adjacent_mep_recovery.targetImage() > 0) {
10814 // The target sits at its measured source while its trial is
10815 // pending; the rest of the interior keeps its own state.
10816 (void)adjacent_mep_recovery.restoreTargetSource(path);
10817 }
10818 resolvePendingFixedPointCampaign(
10819 path, config, training_obs, ci_active, log_rank, outer,
10820 anchor_true_force_profile, anchor_true_max_force,
10821 pending_fixed_point, fixed_point_applied_kind,
10822 measured_band_recovery);
10823 if (ci_active && config.climbing_image_converged_only &&
10824 (fixed_point_applied_kind ==
10825 FixedPointProposalKind::MeasuredNebStep ||
10826 fixed_point_applied_kind ==
10827 FixedPointProposalKind::Reparameterization)) {
10828 // The measured CI stencil certifies this accepted recovery.
10829 // Unmeasured tail images cannot revoke its restart ownership.
10830 recordLatestClimbRestartSnapshot(
10831 detail::selectOieClimbingImageIndex(ci_active, path),
10832 /*from_drift=*/false);
10833 measured_reparam_restart_protected = true;
10834 }
10835 const bool transition_focal_handoff =
10836 session && detail::activateOracleTransitionFocalClimbingImage(
10837 config, path, *session, outer);
10838 if (transition_focal_handoff) {
10839 ci_active = true;
10840 }
10841 // An explicit energy limit applies to each acceptance branch.
10842 const auto belowPathCeiling = [&](int saddle_idx) {
10843 if (!std::isfinite(connecting_path_energy_ceiling)) {
10844 return true;
10845 }
10846 if (saddle_idx <= 0 || saddle_idx >= path.numImages() - 1 ||
10847 !std::isfinite(path.image(saddle_idx).energy)) {
10848 return false;
10849 }
10850 const double slack =
10851 (config.oracle_energy_noise_rms &&
10852 std::isfinite(*config.oracle_energy_noise_rms) &&
10853 *config.oracle_energy_noise_rms > 0.0)
10854 ? *config.oracle_energy_noise_rms
10855 : 0.0;
10856 return path.image(saddle_idx).energy <=
10857 connecting_path_energy_ceiling + slack;
10858 };
10859 const int certified_ci_idx_at_outer_start =
10860 ci_active ? detail::activeClimbingMarkerIndex(path) : -1;
10861 band_stepper.reset();
10862 trust.setTrainingData(training_obs.R);
10863 double trust_threshold =
10864 config.rho_trust
10865 ? rho_trust_radius
10866 : gpOieTrustThreshold(config,
10867 static_cast<int>(training_obs.R.rows()),
10868 config.n_atoms);
10869
10870 // Scale-free override: replace the fixed/adaptive EMD radius with
10871 // tau * median EMD pairwise spread, anchored once (first outer with
10872 // >=2 training rows). sftr.radius() == 0.0 means not yet anchored.
10873 if (scalefree_trust_enabled && training_obs.R.rows() >= 2) {
10874 if (sftr.radius() <= 0.0) {
10875 const double emd_median = detail::emdMedianPairwiseDistance(
10876 training_obs.R, atoms_config);
10877 if (std::isfinite(emd_median) && emd_median > 0.0) {
10878 sftr.initFromTrainingSpread(emd_median);
10879 }
10880 }
10881 if (sftr.radius() > 0.0) {
10882 trust_threshold = sftr.radius();
10883 }
10884 }
10885 // The kernel-drift budget under the measured variance calibration:
10886 // the predictive spread grows linearly with the kernel distance
10887 // near the data, so a surrogate whose spread was measured kappa
10888 // times its report reaches a given tolerance at 1/sqrt(kappa) of
10889 // the distance (scripts/derive_calibrated_trust_radius.py). A
10890 // surrogate that predicted its measurement keeps the full budget.
10891 if (measured_variance_calibration > 1.0 &&
10892 std::isfinite(measured_variance_calibration) &&
10893 std::isfinite(trust_threshold) && trust_threshold > 0.0) {
10894 trust_threshold /= std::sqrt(measured_variance_calibration);
10895 }
10896 // Refresh each intermediate image's local GP neighbourhood:
10897 // the EMD k-nearest global observations to that image's
10898 // current position. Recomputed every outer iteration so the
10899 // per-image surrogate tracks the moving chain. The global
10900 // GP, fit on the whole reaction path, has no usable signal
10901 // at an individual image's stationary point; the per-image
10902 // GP is the production surrogate, and its training set must
10903 // be image i's geometric neighbourhood, not the picker
10904 // index it happened to be assigned. setImageNeighborhood is
10905 // a no-op when the membership is unchanged, so a per-image
10906 // refit fires only when the neighbourhood turns over.
10907 // A global chart changes on the refit boundary, so every band
10908 // step uses the coordinate map whose parameters were fitted.
10909 if (session && !config.atomic_environments &&
10910 usesClassicJointEnergyForcePrior(config.model_profile) &&
10911 config.local_tier_classic && !config.attach_manifold_chart &&
10912 !config.use_geodesic_image_prior) {
10913 // Local tier without a composed prior uses per-image models of
10914 // the k nearest rows (no chart, no geodesic prior), and the
10915 // global posterior becomes a random-feature regulariser once
10916 // every interior image has its own model. Its feature count is
10917 // the capacity of one local model, k (1 + dof) design rows.
10918 bool all_local = path.numImages() > 2;
10919 for (int i = 1; i < path.numImages() - 1; ++i) {
10920 const std::vector<int> neigh = trust.kNearestIndices(
10921 path.image(i).positions, session->per_image_knn);
10922 session->setImageNeighborhood(i, neigh,
10923 &path.image(i).positions);
10924 // "Enough points at each image" means rows bought at that
10925 // image, not the k nearest rows of the global set, which
10926 // every image has from the first outer iteration.
10927 all_local = all_local && localEligible(i) &&
10928 session->image_models[i].directObservationCount() >=
10929 session->min_per_image_n_train;
10930 }
10931 const auto& global_kernel = gp.getSexpAtCovarianceFunction();
10932 if (all_local && gp.getRFFFeaturesRequested() <= 0 &&
10934 !global_kernel.usesManifoldChart() &&
10935 !global_kernel.usesGeodesicHeatKernel()) {
10936 const int dof =
10937 static_cast<int>(path.image(0).positions.size());
10938 const int d_rff = session->per_image_knn * (1 + dof);
10939 gp.setRFFFeaturesRequested(d_rff);
10940 if (log_rank == 0) {
10941 neb_log() << "[local-tier] outer=" << outer
10942 << " every interior image is local; global "
10943 "model promoted to RFF regulariser, D_rff="
10944 << d_rff << std::endl;
10945 }
10946 }
10947 } else if (session && !config.atomic_environments &&
10948 (!usesClassicJointEnergyForcePrior(config.model_profile) ||
10949 config.local_tier_classic)) {
10950 gpr::Coord geodesic_reference_path;
10951 bool path_is_finite =
10952 config.use_geodesic_image_prior && path.numImages() > 0;
10953 if (path_is_finite) {
10954 const Eigen::Index dimensions = path.image(0).positions.size();
10955 path_is_finite = dimensions > 0;
10956 geodesic_reference_path.resize(path.numImages(), dimensions);
10957 for (int image = 0; path_is_finite && image < path.numImages();
10958 ++image) {
10959 const Eigen::VectorXd& positions =
10960 path.image(image).positions;
10961 path_is_finite =
10962 positions.size() == dimensions && positions.allFinite();
10963 if (path_is_finite) {
10964 geodesic_reference_path.row(image) =
10965 positions.transpose();
10966 }
10967 }
10968 }
10969 bool needs_image_chart = false;
10970 for (int i = 1; i < path.numImages() - 1; ++i) {
10971 const std::vector<int> neigh = trust.kNearestIndices(
10972 path.image(i).positions, session->per_image_knn);
10973 session->setImageNeighborhood(i, neigh,
10974 &path.image(i).positions);
10975 needs_image_chart = needs_image_chart || localEligible(i);
10976 }
10977 // Ineligible image models predict through the global posterior.
10978 // Their unused charts require no Wilson-matrix factorization.
10979 const auto molecular_internals =
10980 needs_image_chart
10981 ? detail::makeMolecularInternalCoordinatesForPath(path,
10982 config)
10983 : nullptr;
10984 for (int i = 1; i < path.numImages() - 1; ++i) {
10985 if (path_is_finite) {
10986 (void)session->setImageGeodesicReferencePath(
10987 i, geodesic_reference_path);
10988 } else {
10989 session->image_models[i].clearGeodesicReferencePath();
10990 }
10991 if (localEligible(i)) {
10992 (void)detail::attachImageManifoldChart(
10993 *session, i, molecular_internals,
10994 path.image(i).positions);
10995 } else {
10996 session->image_models[i].clearInternalCoordinateChart();
10997 }
10998 }
10999 }
11000
11001 // ---- Inner GP relaxation ------------------------------------
11002 // Relaxes intermediate images on the GP mean surface. The band
11003 // phase targets the whole path; the CI-only phase targets the
11004 // climbing image. Surrogate convergence requests true-surface
11005 // evaluation before the outer loop can accept the result.
11006 // Optimizer: a global L-BFGS over the concatenated band.
11007 // The whole interior band is one optimization vector; the
11008 // quasi-Newton step carries
11009 // curvature across inner iterations, so it converges the
11010 // GP surface's narrow saddle valleys without the limit
11011 // cycle a per-image first-order method falls into.
11012 int inner = 0;
11013 double max_inner = std::numeric_limits<double>::infinity();
11014 double relaxation_inner = std::numeric_limits<double>::infinity();
11015 // Running minimum of the relaxation force within the current
11016 // doubling window of the inner loop, and the minimum before it.
11017 double window_best_force = std::numeric_limits<double>::infinity();
11018 double window_best_force_before =
11019 std::numeric_limits<double>::infinity();
11020 const double base_inner_conv_tol = detail::oieGpInnerTolerance(
11021 config, smallest_oracle_force, ci_active);
11022 double effective_inner_conv_tol = base_inner_conv_tol;
11023 detail::OieMeasuredForceMargin measured_force_margin;
11024 // Whole-band relaxation uses the adaptive non-CI tolerance. A
11025 // CI-only phase retains neighbours for its tangent without imposing
11026 // their force tolerance on the climbing image's stopping decision.
11027 const double chain_inner_conv_tol = detail::oieGpInnerTolerance(
11028 config, smallest_oracle_force, /*ci_active=*/false);
11029 const int oie_ci_idx =
11030 detail::selectOieClimbingImageIndex(ci_active, path);
11031 const OieFixedImageLease requested_fixed_image_lease =
11032 detail::resolveOieFixedImageLease(config, path, oie_ci_idx, outer);
11033 OieFixedImageLease fixed_image_lease =
11034 detail::arbitrateOieRecoveryBandOwnership(
11035 requested_fixed_image_lease, oie_ci_idx,
11036 adjacent_mep_recovery.ciIndex(),
11037 adjacent_mep_recovery.targetImage());
11038 // The hold lasts until the oracle has measured the stepped image;
11039 // a surrogate relaxation of the image before that undoes the step.
11040 if (measured_step_hold_image > 0 &&
11041 measured_step_hold_image < path.numImages() - 1 &&
11042 path.image(measured_step_hold_image).evaluated)
11043 measured_step_hold_image = -1;
11044 if (measured_step_hold_image > 0 &&
11045 measured_step_hold_image < path.numImages() - 1 &&
11046 fixed_image_lease.image_index <= 0) {
11047 fixed_image_lease.image_index = measured_step_hold_image;
11048 fixed_image_lease.retain_climbing_marker = true;
11049 // The held image is exactly the one to measure: a lease that
11050 // suppressed replaceable acquisition made the local recovery
11051 // own the climbing image and refuse its measurement for
11052 // seventeen outers (10_tetrazine, plain seed).
11053 fixed_image_lease.allow_replaceable_acquisition = true;
11054 }
11055 const int fixed_image = fixed_image_lease.image_index;
11056 const int protected_oie_ci_idx =
11057 fixed_image_lease.retain_climbing_marker ? fixed_image : -1;
11058 const bool recovery_stencil_changed =
11059 recovery_stencil_anchor.update(path, fixed_image_lease);
11060 if (recovery_stencil_changed) {
11061 recovery_growth_backtrack_target.clear();
11062 }
11063 (void)recovery_stencil_anchor.restore(path);
11064 if (fixed_image != active_oie_fixed_image || recovery_stencil_changed) {
11065 band_stepper.reset();
11066 active_oie_fixed_image = fixed_image;
11067 if (config.verbose && log_rank == 0) {
11068 neb_log() << "[gp_oie] fixed-image lease outer=" << outer
11069 << " image=" << fixed_image << " retain_marker="
11070 << fixed_image_lease.retain_climbing_marker
11071 << " model_growth="
11072 << fixed_image_lease.model_growth_required
11073 << " stencil_anchor="
11074 << recovery_stencil_anchor.active() << std::endl;
11075 }
11076 }
11077 auto refreshGpPath = [&](bool preserve_evaluated) {
11078 AccumulateWallTime predict_wall(phase_predict_seconds);
11079 const int n_im = path.numImages();
11080 std::vector<char> local_required(n_im, 0);
11081 std::vector<char> global_required(n_im, 0);
11082 for (int i = 1; i < n_im - 1; ++i) {
11083 const bool observed_current =
11084 preserve_evaluated && detail::findRestorableObservationRow(
11085 training_obs, path.image(i)) >= 0;
11086 const bool needs_prediction =
11087 !preserve_evaluated ||
11088 (!path.image(i).evaluated && !observed_current);
11089 local_required[i] =
11090 needs_prediction && localEligible(i) ? 1 : 0;
11091 global_required[i] =
11092 needs_prediction && !local_required[i] ? 1 : 0;
11093 }
11094 std::vector<gpr::Observation> global_potential;
11095 computeGlobalPotentials(global_required, global_potential);
11096 for (int i = 1; i < n_im - 1; ++i) {
11097 if (global_required[i]) ++phase_predict_count;
11098 }
11099 for (int i = 1; i < path.numImages() - 1; ++i) {
11100 const bool valid = detail::refreshOieImage(
11101 path.image(i), training_obs, preserve_evaluated,
11102 [&](Image& image) {
11103 if (local_required[i]) {
11104 gpr::Observation local_potential = makeProbe(i);
11105 session->withImageModel(
11106 i, [&](gpr::GaussianProcessRegression& local) {
11107 local.calculatePotentialDispatched(
11108 local_potential);
11109 });
11110 ++phase_predict_count;
11111 image.energy = observationEnergy(local_potential);
11112 image.gradient =
11113 observationGradient(local_potential);
11114 } else {
11115 image.energy =
11116 observationEnergy(global_potential[i]);
11117 image.gradient =
11118 observationGradient(global_potential[i]);
11119 }
11121 image.gradient);
11122 });
11123 if (!valid) {
11124 max_inner = std::numeric_limits<double>::infinity();
11125 return false;
11126 }
11127 }
11128 predict_wall.stop();
11129 (void)detail::refreshOieClimbingImageMarkerAndResetHistory(
11130 ci_active, path, band_stepper, protected_oie_ci_idx);
11131 detail::installSecantClimbingDirection(path, session, config);
11132 path.computeNEBForces();
11133 {
11134 // The climbing reflection has positive curvature near an
11135 // aligned index-one saddle. Retain those secants and exclude
11136 // only a nonpositive CI contribution, following the marker.
11137 const int climb_idx = detail::activeClimbingMarkerIndex(path);
11138 const Eigen::Index dof_ex = path.image(1).positions.size();
11139 if (ci_active && climb_idx > 0 &&
11140 climb_idx < path.numImages() - 1 && dof_ex > 0) {
11141 band_stepper.setCurvatureExclusion(
11142 static_cast<Eigen::Index>(climb_idx - 1) * dof_ex,
11143 dof_ex);
11144 } else {
11145 band_stepper.setCurvatureExclusion(-1, 0);
11146 }
11147 }
11148 const int ci_inner_idx =
11149 detail::selectOieClimbingImageIndex(ci_active, path);
11150 const bool ci_saddle_energy_certified =
11151 detail::hasTruePesSaddleEnergyCertificate(path, ci_inner_idx,
11152 config.conv_tol);
11153 const detail::OieRelaxableForceMeasure force_measure =
11154 detail::measureOieRelaxableForces(path, ci_inner_idx,
11155 fixed_image);
11156 max_inner = force_measure.max_force;
11157 // The exponential-metric band converges on the metric
11158 // residual its library reports (RgsaddleBandEngine::
11159 // metricResidual), not on the Euclidean perpendicular force,
11160 // which does not vanish on the metric's minimum energy path.
11161 if (use_rgsaddle) {
11162 if (const auto residual = rgsaddle_engine.metricResidual();
11163 residual.has_value()) {
11164 max_inner = *residual;
11165 }
11166 }
11167 relaxation_inner = detail::oieGpRelaxationForce(
11168 config, ci_active, max_inner, force_measure.climbing_force,
11169 ci_saddle_energy_certified);
11170 // The current climbing image supplies its own stopping margin.
11171 // A marker change or a smaller measured error releases that margin.
11172 effective_inner_conv_tol = base_inner_conv_tol;
11173 if (!preserve_evaluated && ci_active &&
11174 config.climbing_image_converged_only && ci_inner_idx > 0 &&
11175 ci_inner_idx < path.numImages() - 1) {
11176 const Image& image = path.image(ci_inner_idx);
11177 const int row =
11178 detail::findRestorableObservationRow(training_obs, image);
11179 if (row >= 0) {
11180 const Eigen::VectorXd measured =
11181 training_obs.G.row(row).transpose();
11182 const Eigen::VectorXd error = measured - image.gradient;
11183 measured_force_margin.observe(ci_inner_idx,
11184 path.forceMagnitude(measured),
11185 path.forceMagnitude(error));
11186 }
11187 effective_inner_conv_tol = measured_force_margin.tolerance(
11188 config, ci_inner_idx, effective_inner_conv_tol,
11189 path.forceMagnitude(image.gradient));
11190 }
11191 if (std::isfinite(relaxation_inner))
11192 window_best_force =
11193 std::min(window_best_force, relaxation_inner);
11194 return true;
11195 };
11196 auto refreshAllGpPath = [&]() {
11197 // The inner line search uses one differentiable GP surface.
11198 // Oracle observations constrain that surface and certify the
11199 // outer acquisition; mixing their forces into it changes the
11200 // objective whenever an image leaves a measured position.
11201 return refreshGpPath(/*preserve_evaluated=*/false);
11202 };
11203 // probeChainVariance dispatches per-image vs global GPs by
11204 // localEligible. The per-image path acquires an image
11205 // model lease that re-factorises K when the active model
11206 // owner changes. Inside the inner loop we call the probe
11207 // many times; alternating local/global owners triggers a
11208 // full Cholesky refactor per call (gdb trace on
11209 // 06_bicyclobutane tr6 outer 45: main thread spent the
11210 // dominant fraction of 4 hours in
11211 // updateModelWithFullData -> decomposeCovarianceMatrix
11212 // -> SexpatCF::ginput3 because each inner iter's variance
11213 // probe re-leased ~N image models). The force_global_only
11214 // override skips per-image leases: one acquireGlobalModel
11215 // lease covers all N images, so the inner-loop probe cost
11216 // collapses to a single K factorisation reuse per probe.
11217 // Used by the inner-loop unc-halt and trust-certifier
11218 // calls; the post-loop picker still calls with
11219 // force_global_only=false to retain the per-image GP
11220 // refinement for acquisition scoring.
11221 struct ChainObservationVarianceProbe {
11222 std::vector<ObservationVariance> per_image;
11223 std::vector<ObservationVariance> force_certification_per_image;
11224 std::pair<double, int> max_energy{0.0, 1};
11225 std::pair<double, int> max_gradient_trace{0.0, 1};
11226 double max_reported_variance_calibration = 1.0;
11227 };
11228 // A probe is a function of the band geometry, the training set and
11229 // the fitted posterior. Consecutive callers within one inner step
11230 // ask for the same geometry under the same model (the restricted
11231 // variance target and the proposal readiness), and each answer
11232 // costs a solve against every training row; the last answer is
11233 // returned again while its inputs stand.
11234 struct ChainVarianceMemo {
11235 bool force_global_only = false;
11236 Eigen::VectorXd positions;
11237 Eigen::Index training_rows = -1;
11238 std::uint64_t training_revision = 0;
11239 std::uint64_t factor_epoch = 0;
11240 ChainObservationVarianceProbe probe;
11241 };
11242 std::optional<ChainVarianceMemo> chain_variance_memo;
11243 auto probeChainObservationVariance = [&](bool force_global_only =
11244 false) {
11245 const int n_im = path.numImages();
11246 const int dof = static_cast<int>(path.image(0).positions.size());
11247 Eigen::VectorXd memo_positions(static_cast<Eigen::Index>(n_im) *
11248 dof);
11249 for (int i = 0; i < n_im; ++i)
11250 memo_positions.segment(static_cast<Eigen::Index>(i) * dof,
11251 dof) = path.image(i).positions;
11252 const std::uint64_t memo_revision =
11253 session ? session->trainingRevision() : 0;
11254 if (chain_variance_memo &&
11255 chain_variance_memo->force_global_only == force_global_only &&
11256 chain_variance_memo->training_rows == training_obs.R.rows() &&
11257 chain_variance_memo->training_revision == memo_revision &&
11258 chain_variance_memo->factor_epoch == gp.factorEpoch() &&
11259 chain_variance_memo->positions.size() ==
11260 memo_positions.size() &&
11261 chain_variance_memo->positions == memo_positions) {
11262 return chain_variance_memo->probe;
11263 }
11264 ChainObservationVarianceProbe result;
11265 result.per_image.assign(n_im, ObservationVariance{});
11266 result.force_certification_per_image.assign(n_im,
11267 ObservationVariance{});
11268 for (auto& variance: result.per_image) {
11269 variance.gradient = Eigen::VectorXd::Zero(dof);
11270 }
11271 for (auto& variance: result.force_certification_per_image) {
11272 variance.gradient = Eigen::VectorXd::Zero(dof);
11273 }
11274 std::vector<char> local_required(n_im, 0);
11275 std::vector<char> global_required(n_im, 0);
11276 for (int i = 1; i < n_im - 1; ++i) {
11277 const bool eligible_local =
11278 !force_global_only && localEligible(i);
11279 local_required[i] = eligible_local ? 1 : 0;
11280 global_required[i] = local_required[i] ? 0 : 1;
11281 }
11282 // Force certification must see the model that owns the
11283 // observation: global training rows only condition the global
11284 // GP. Local neighbourhood GPs can be eligible for prediction
11285 // without the current band geometry, which left force
11286 // residual at prior scale and deadlocked acquisition once
11287 // every image was "observed" globally.
11288 std::vector<char> global_for_force_cert = global_required;
11289 for (int i = 1; i < n_im - 1; ++i) {
11290 if (detail::findRestorableObservationRow(training_obs,
11291 path.image(i)) >= 0) {
11292 global_for_force_cert[i] = 1;
11293 }
11294 }
11295 // Query columns solve independently against one training factor.
11296 // A shared image contributes the same marginal variance to both
11297 // consumers, so their union requires only one global solve.
11298 const auto global_variances = detail::evaluateOieGlobalVariances(
11299 global_required, global_for_force_cert,
11300 computeGlobalObservationVariances);
11301 const double global_variance_calibration =
11303 for (int i = 1; i < n_im - 1; ++i) {
11304 ObservationVariance variance = global_variances[i];
11305 double variance_calibration = global_variance_calibration;
11306 ObservationVariance force_cert_variance = variance;
11307 double force_cert_calibration = global_variance_calibration;
11308 const bool global_owns_geometry =
11309 detail::findRestorableObservationRow(training_obs,
11310 path.image(i)) >= 0;
11311 if (local_required[i]) {
11312 gpr::Observation local_variance = makeProbe(i);
11313 session->withImageModel(
11314 i, [&](gpr::GaussianProcessRegression& local) {
11315 local.calculateVarianceDispatched(local_variance);
11316 variance_calibration =
11318 });
11319 // Force cert stays on the global GP when that GP owns
11320 // the geometry. Local variance is retained for
11321 // acquisition/energy reporting only.
11322 if (!global_owns_geometry) {
11323 force_cert_calibration = variance_calibration;
11324 }
11325 variance = detail::jointObservationVariance(local_variance);
11326 if (!global_owns_geometry) {
11327 force_cert_variance = variance;
11328 }
11329 }
11330 if (variance.gradient.size() != dof) {
11331 throw std::logic_error(
11332 "GP variance probe did not return every gradient "
11333 "channel");
11334 }
11335 if (force_cert_variance.gradient.size() != dof) {
11336 force_cert_variance = variance;
11337 force_cert_calibration = variance_calibration;
11338 }
11339 if (measured_variance_calibration > 1.0) {
11340 variance.energy *= measured_variance_calibration;
11341 variance.gradient *= measured_variance_calibration;
11342 force_cert_variance.energy *= measured_variance_calibration;
11343 force_cert_variance.gradient *=
11344 measured_variance_calibration;
11345 }
11346 result.per_image[i] = variance;
11347 result.force_certification_per_image[i] =
11348 detail::jointForceCertificationVariance(
11349 force_cert_variance, force_cert_calibration);
11350 result.max_reported_variance_calibration = std::max(
11351 result.max_reported_variance_calibration,
11352 std::max(variance_calibration, force_cert_calibration));
11353 const double energy_variance = result.per_image[i].energy;
11354 if (energy_variance > result.max_energy.first) {
11355 result.max_energy = {energy_variance, i};
11356 }
11357 const double gradient_trace =
11358 detail::observationGradientVarianceTrace(
11359 result.force_certification_per_image[i]);
11360 if (gradient_trace > result.max_gradient_trace.first) {
11361 result.max_gradient_trace = {gradient_trace, i};
11362 }
11363 }
11364 chain_variance_memo = ChainVarianceMemo{
11365 force_global_only, std::move(memo_positions),
11366 training_obs.R.rows(), memo_revision,
11367 gp.factorEpoch(), result};
11368 return result;
11369 };
11370 auto currentBandObservationMask = [&]() {
11371 std::vector<char> observed(path.numImages(), 0);
11372 for (int i = 1; i < path.numImages() - 1; ++i) {
11373 // An image is observed when a row sits at its exact
11374 // position, or when the session's resolution gate would
11375 // refuse to store one there (a row already lies within the
11376 // model's resolution floor). The second case is not
11377 // optional: the gate silently drops such purchases, so a
11378 // stencil that keeps demanding the row never sees it and
11379 // the outer loop spins without moving (HEAD Baker board:
11380 // every cell ran 1000 outers at arm=none).
11381 const bool exact = detail::findRestorableObservationRow(
11382 training_obs, path.image(i)) >= 0;
11383 const bool resolved =
11384 session != nullptr &&
11385 session->withinTrainingResolution(path.image(i).positions);
11386 observed[i] = (exact || resolved) ? 1 : 0;
11387 }
11388 return observed;
11389 };
11390 auto globalGpOwnsCurrentGeometry = [&](int image_idx) {
11391 if (image_idx <= 0 || image_idx >= path.numImages() - 1) {
11392 return false;
11393 }
11394 const EigenMatrix& assembled = gp.getRMatrix();
11395 const Eigen::Index dof = path.image(image_idx).positions.size();
11396 if (dof <= 0 || assembled.cols() != dof + 1 ||
11397 assembled.rows() <= 0 || assembled.rows() % (dof + 1) != 0) {
11398 return false;
11399 }
11400 const Eigen::Index ntrain = assembled.rows() / (dof + 1);
11401 constexpr double kPositionToleranceSquared = 1e-12;
11402 for (Eigen::Index row = 0; row < ntrain; ++row) {
11403 if ((assembled.row(row).head(dof) -
11404 path.image(image_idx).positions.transpose())
11405 .squaredNorm() <= kPositionToleranceSquared) {
11406 return true;
11407 }
11408 }
11409 return false;
11410 };
11411 auto globalGpTrainingConfigurationCount = [&]() {
11412 const EigenMatrix& assembled = gp.getRMatrix();
11413 const Eigen::Index dof = path.image(0).positions.size();
11414 return dof > 0 && assembled.cols() == dof + 1 &&
11415 assembled.rows() % (dof + 1) == 0
11416 ? assembled.rows() / (dof + 1)
11417 : Eigen::Index{-1};
11418 };
11419 const double uncertainty_threshold =
11420 detail::effectivePosteriorVarianceThreshold(
11421 config, std::optional<double>{
11423 detail::NEBBandObjectiveGeodesicOptions geodesic_options;
11424 geodesic_options.enabled =
11425 config.sidpp_geodesic && config.geodesic_retraction;
11426 geodesic_options.n_atoms = config.n_atoms;
11427 geodesic_options.moving_atoms = config.moving_atoms;
11428 geodesic_options.internal_coordinates =
11429 detail::makeGeodesicInternalCoordinatesForPath(path, config);
11430 if (geodesic_options.internal_coordinates) {
11431 geodesic_options.internal_trust_per_primitive =
11432 detail::internalTrustFromPathSpacing(
11433 path, *geodesic_options.internal_coordinates);
11434 }
11435 geodesic_options.min_distance_ratio_limit = config.trust_ratio_at_limit;
11436 geodesic_options.atomic_numbers = domain_atomic_numbers;
11437 geodesic_options.frozen_positions = config.frozen_positions;
11438 geodesic_options.frozen_atomic_numbers = config.frozen_atomic_numbers;
11439 geodesic_options.cell = config.cell;
11440 const int adjacent_mep_live_ci_idx =
11441 detail::selectOieClimbingImageIndex(ci_active, path);
11442 const bool adjacent_mep_recovery_active =
11443 adjacent_mep_recovery.activeFor(path, adjacent_mep_live_ci_idx);
11444 if (!adjacent_mep_recovery_active &&
11445 adjacent_mep_recovery.targetImage() > 0) {
11446 adjacent_mep_recovery.clear();
11447 }
11448 // An armed adjacent-MEP recovery probes where its target image
11449 // relaxes to on the surrogate and restores the path to its
11450 // source afterwards, so the whole interior relaxes during the
11451 // probe: a target relaxed jointly with its neighbours is the
11452 // MEP position the certificate asks about, and no image is
11453 // held still with an open force.
11454 std::vector<char> active_band_images;
11455 recovery_stencil_anchor.applyActiveImageMask(active_band_images,
11456 path.numImages());
11457 detail::NEBBandObjective band_objective(
11458 path, refreshAllGpPath, std::move(geodesic_options), fixed_image,
11459 std::move(active_band_images));
11460 auto calculateBandActionPosteriorCovariance =
11461 [&](const Eigen::VectorXd& action_positions,
11462 EigenMatrix& posterior_covariance) {
11463 const Eigen::Index image_dof = band_objective.imageDof();
11464 if (image_dof <= 0 || action_positions.size() == 0 ||
11465 action_positions.size() % image_dof != 0 ||
11466 !action_positions.allFinite()) {
11467 return false;
11468 }
11469 const Eigen::Index query_count =
11470 action_positions.size() / image_dof;
11471 EigenMatrix query_positions(query_count, image_dof);
11472 for (Eigen::Index query = 0; query < query_count; ++query) {
11473 query_positions.row(query) =
11474 action_positions.segment(query * image_dof, image_dof)
11475 .transpose();
11476 }
11477 if (session) session->ensureSingletonForGlobal();
11479 query_positions, posterior_covariance);
11480 const Eigen::Index expected_channels =
11481 query_count * (image_dof + 1);
11482 return posterior_covariance.rows() == expected_channels &&
11483 posterior_covariance.cols() == expected_channels &&
11484 posterior_covariance.allFinite();
11485 };
11486 // A proposal remains valid while its source band is unchanged.
11487 // Its trial positions can lie off the band, and observing one trial
11488 // leaves the campaign live until every candidate is measured.
11489 // Acquisition selection advances to an unobserved candidate below.
11490 if (pending_fixed_point.active() &&
11491 (!detail::positionsCoincide(interiorPositionSignature(path),
11492 pending_fixed_point.source_signature) ||
11493 (pending_fixed_point.climbing_image > 0 &&
11494 pending_fixed_point.climbing_image !=
11495 detail::activeClimbingMarkerIndex(path)))) {
11496 pending_fixed_point.clear();
11497 }
11498 detail::ProposalAcquisitionTarget rejected_proposal_acquisition =
11499 pending_fixed_point.acquisition;
11500 bool pending_band_action_waiting = false;
11501 bool pending_band_action_applied = false;
11502 if (pending_band_action.active()) {
11503 const Eigen::VectorXd source_positions =
11504 pending_band_action.sourcePositions();
11505 const Eigen::VectorXd trial_positions =
11506 pending_band_action.trialPositions();
11507 band_objective.setPositions(trial_positions);
11508 if (!band_objective.refresh(false)) {
11509 band_objective.setPositions(source_positions);
11510 (void)band_objective.refresh(false);
11511 pending_band_action.clear();
11512 pending_band_action_acquisition.clear();
11513 } else {
11514 const auto action_variance = probeChainObservationVariance(
11515 /*force_global_only=*/true);
11516 const auto action_readiness =
11517 detail::assessOieBandPosteriorReadiness(
11518 action_variance.force_certification_per_image,
11519 uncertainty_threshold,
11520 detail::effectiveModelNoiseTolerance(config),
11522 currentBandObservationMask());
11523 if (action_readiness.resolved()) {
11524 pending_band_action.clear();
11525 pending_band_action_acquisition.clear();
11526 pending_band_action_applied = true;
11527 band_stepper.reset();
11528 } else {
11529 pending_band_action_acquisition.clear();
11530 EigenMatrix action_covariance;
11531 if (calculateBandActionPosteriorCovariance(
11532 trial_positions, action_covariance)) {
11533 pending_band_action_acquisition =
11534 detail::selectOieBandActionAcquisition(
11535 trial_positions, band_objective.imageDof(),
11536 action_covariance, training_obs,
11538 .target;
11539 }
11540 if (!pending_band_action_acquisition) {
11541 const auto fallback = detail::decideOieInnerProposal(
11542 action_readiness, trial_positions,
11543 band_objective.imageDof(), training_obs);
11544 pending_band_action_acquisition = fallback.acquisition;
11545 }
11546 band_objective.setPositions(source_positions);
11547 (void)band_objective.refresh(false);
11548 pending_band_action_waiting = true;
11549 }
11550 }
11551 }
11552 if (pending_band_action_acquisition) {
11553 rejected_proposal_acquisition = pending_band_action_acquisition;
11554 }
11555 const bool adjacent_mep_trial_pending =
11556 adjacent_mep_recovery_active &&
11557 adjacent_mep_recovery.hasPendingTrial();
11558 if (adjacent_mep_trial_pending) {
11559 rejected_proposal_acquisition.image_index =
11560 adjacent_mep_recovery.targetImage();
11561 rejected_proposal_acquisition.positions =
11562 adjacent_mep_recovery.pendingTrialPosition();
11563 }
11564 std::optional<ChainObservationVarianceProbe> pre_inner_variance_probe;
11565 std::optional<detail::OieBandPosteriorReadiness> pre_inner_readiness;
11566 Eigen::VectorXd pre_inner_variance_positions;
11567 int current_band_acquisition_image = -1;
11568 const bool classic_oie_relaxation =
11569 detail::usesClassicOieRelaxation(config.acquisition);
11570 const std::vector<char> pre_inner_current_observed =
11571 classic_oie_relaxation && !ci_active ? currentBandObservationMask()
11572 : std::vector<char>{};
11573 const int pre_inner_ci_candidate_idx =
11574 classic_oie_relaxation && !ci_active
11575 ? path.highestEnergyImageIndex()
11576 : -1;
11577 const bool activation_stencil_pending =
11578 classic_oie_relaxation && !ci_active &&
11579 !detail::selectOieActivationTripletOracleTargets(
11580 pre_inner_ci_candidate_idx, path.numImages(),
11581 pre_inner_current_observed, pre_inner_current_observed,
11582 /*posterior_energy_variance=*/{})
11583 .empty();
11584 // The classic stencil only fires while some triplet member reads
11585 // unobserved. A fully observed band that no longer moves is a fixed
11586 // point it cannot leave, so the band posterior probe supplies the
11587 // variance-driven escape whenever the stencil has nothing pending.
11588 const bool classic_stencil_exhausted =
11589 classic_oie_relaxation && !activation_stencil_pending;
11590 if ((!classic_oie_relaxation || classic_stencil_exhausted) &&
11591 !pending_fixed_point.acquisition && !pending_band_action.active() &&
11592 fixed_point_applied_kind == FixedPointProposalKind::None &&
11593 !adjacent_mep_trial_pending && !frozen_sweep &&
11594 !transition_focal_handoff && !skip_next_inner_after_rejected_hook) {
11595 pre_inner_variance_probe = probeChainObservationVariance();
11596 pre_inner_variance_positions = band_objective.positions();
11597 pre_inner_readiness = detail::assessOieBandPosteriorReadiness(
11598 pre_inner_variance_probe->force_certification_per_image,
11599 uncertainty_threshold,
11600 detail::effectiveModelNoiseTolerance(config),
11602 currentBandObservationMask());
11603 if (!pre_inner_readiness->force_resolved) {
11604 current_band_acquisition_image =
11605 pre_inner_readiness->acquisition_image;
11606 }
11607 }
11608 const double inner_variance_tolerance =
11609 effective_inner_conv_tol * effective_inner_conv_tol;
11610 const Eigen::VectorXd inner_start_positions =
11611 band_objective.positions();
11612 auto flattenedPositionsTrustCertified =
11613 [&](const Eigen::VectorXd& positions) {
11614 const Eigen::Index image_dof = band_objective.imageDof();
11615 const Eigen::Index expected_size =
11616 static_cast<Eigen::Index>(path.numImages() - 2) * image_dof;
11617 if (image_dof <= 0 || positions.size() != expected_size ||
11618 !band_objective.stepAdmissible(inner_start_positions,
11619 positions)) {
11620 return false;
11621 }
11622 // Surrogate motion requires normalized energy covariance
11623 // of at least exp(-1/2) with a global training row. Both
11624 // components participate when the prior is a sum. The
11625 // posterior remains defined outside this motion region.
11626 // Real-surface queries use geometric trust instead, so
11627 // they can extend the region supported by observations.
11628 // The global model gives every image the same motion
11629 // policy despite changes in local neighbour subsets.
11630 // A selected measured radius additionally bounds motion in
11631 // the same neighbourhood used by the line projector.
11632 const auto& band_global_kernel =
11634 for (int i = 1; i < path.numImages() - 1; ++i) {
11635 const Eigen::Index offset =
11636 static_cast<Eigen::Index>(i - 1) * image_dof;
11637 const gpr::Observation* trust_obs = &training_obs;
11638 const gpr::TrustRadius* trust_model = &trust;
11639 if (session && localEligible(i) &&
11640 i < static_cast<int>(session->image_models.size())) {
11641 const auto& image_obs =
11642 session->image_models[i].observations();
11643 if (image_obs.R.rows() > 0) {
11644 image_trust.setTrainingData(image_obs.R);
11645 trust_obs = &image_obs;
11646 trust_model = &image_trust;
11647 }
11648 }
11649 const std::optional<double> measured_radius =
11650 config.use_drift_budget || config.rho_trust
11651 ? std::optional<double>{trust_threshold}
11652 : std::nullopt;
11653 if (!detail::imageWithinSurrogateTrust(
11654 positions.segment(offset, image_dof), atoms_config,
11655 training_obs, band_global_kernel, *trust_obs,
11656 *trust_model, measured_radius)) {
11657 return false;
11658 }
11659 }
11660 return true;
11661 };
11662 auto proposalTrustCertified = [&]() {
11663 return flattenedPositionsTrustCertified(band_objective.positions());
11664 };
11665 auto projectProposalToOuterTrust = [&](Eigen::VectorXd& positions) {
11666 const Eigen::Index image_dof = band_objective.imageDof();
11667 if (image_dof <= 0) return false;
11668 const int n_im = path.numImages();
11669 const Eigen::Index expected_size =
11670 static_cast<Eigen::Index>(n_im - 2) * image_dof;
11671 if (positions.size() != expected_size) return false;
11672 bool clipped = false;
11673 for (int i = 1; i < n_im - 1; ++i) {
11674 const Eigen::Index offset =
11675 static_cast<Eigen::Index>(i - 1) * image_dof;
11676 Eigen::VectorXd image_positions =
11677 positions.segment(offset, image_dof);
11678 const gpr::Observation* trust_obs = &training_obs;
11679 const gpr::TrustRadius* trust_model = &trust;
11680 if (session && localEligible(i) &&
11681 i < static_cast<int>(session->image_models.size())) {
11682 const auto& image_obs =
11683 session->image_models[i].observations();
11684 if (image_obs.R.rows() > 0) {
11685 image_trust.setTrainingData(image_obs.R);
11686 trust_obs = &image_obs;
11687 trust_model = &image_trust;
11688 }
11689 }
11690 if (trust_obs->R.rows() == 0) return false;
11691 if (detail::clipImageToOuterTrust(image_positions, *trust_obs,
11692 *trust_model,
11693 trust_threshold)) {
11694 positions.segment(offset, image_dof) = image_positions;
11695 clipped = true;
11696 }
11697 }
11698 return clipped;
11699 };
11700 const bool force_posterior_resolved =
11701 !pre_inner_readiness.has_value() ||
11702 pre_inner_readiness->force_resolved;
11703 const bool force_posterior_unresolved = !force_posterior_resolved;
11704 std::optional<detail::PsBaxActionProposal> pre_inner_psbax_action;
11705 // An unresolved current force posterior cannot drive a GP-mean
11706 // band step. PS-BAX supplies an informative off-chain target for
11707 // that blocked state. A resolved band advances first and samples
11708 // any action acquisition from its updated geometry below.
11709 if (config.acquisition == AcquisitionType::PSBAX && ci_active &&
11710 force_posterior_unresolved && pre_inner_readiness.has_value()) {
11711 if (session) session->ensureSingletonForGlobal();
11712 const std::uint64_t posterior_seed =
11713 (static_cast<std::uint64_t>(outer + 1 +
11714 config.acquisition_seed_offset)
11715 << 32) ^
11716 static_cast<std::uint64_t>(path.numImages());
11717 detail::PsBaxActionProposal proposal =
11718 detail::proposePsBaxActionAcquisition(
11719 path, gp, training_obs, config, posterior_seed,
11720 projectProposalToOuterTrust,
11721 flattenedPositionsTrustCertified);
11722 if (proposal.target) {
11723 pre_inner_psbax_action = std::move(proposal);
11724 }
11725 }
11726 const bool preempt_inner_for_psbax =
11727 pre_inner_psbax_action.has_value() &&
11728 detail::shouldPreemptOieInnerForPosteriorAction(
11729 config.acquisition, ci_active, force_posterior_resolved,
11730 pre_inner_psbax_action->target);
11731 double residual_band_force_pre_inner = 0.0;
11732 for (int i = 1; i < path.numImages() - 1; ++i) {
11733 const double f = path.nebForceMagnitude(i);
11734 if (std::isfinite(f) && f > residual_band_force_pre_inner) {
11735 residual_band_force_pre_inner = f;
11736 }
11737 }
11738 const double residual_tol_pre_inner =
11739 detail::effectiveModelNoiseTolerance(config);
11740 const bool residual_force_open_pre_inner =
11741 residual_tol_pre_inner > 0.0 &&
11742 residual_band_force_pre_inner > residual_tol_pre_inner;
11743 // Motion-first cadence: while the TRUE band residual force is
11744 // above the problem tolerance, trust-certified GP-mean steps
11745 // always run; the joint force-variance certificate only ranks
11746 // acquisition targets afterwards. The certificate resolves only
11747 // on a static fully re-observed band, so a motion veto
11748 // serializes one acquisition outer (plus an SCG refit) per
11749 // interior image for every band step and the wall budget dies
11750 // in the spin. Wrong-channel slides are the accept path's
11751 // responsibility (saddle-resolution certificate), not a reason
11752 // to freeze the band.
11753 const bool skip_inner_for_force_uncertainty =
11754 !residual_force_open_pre_inner &&
11755 detail::shouldSkipOieInnerForUnresolvedForcePosterior(
11756 force_posterior_resolved, current_band_acquisition_image);
11757 if (detail::releaseTrainedPendingAcquisition(
11758 pending_fixed_point.acquisition, training_obs,
11759 residual_force_open_pre_inner) &&
11760 config.verbose && log_rank == 0) {
11761 neb_log() << "[gp_oie] outer=" << outer
11762 << " fixed-point: trained acquisition released while "
11763 "the band force is open\n";
11764 }
11765 const bool skip_inner_for_pending_acquisition =
11766 detail::shouldSkipOieInnerForPendingAcquisition(
11767 pending_fixed_point.acquisition,
11768 fixed_point_applied_kind != FixedPointProposalKind::None,
11769 residual_force_open_pre_inner ? -1
11770 : current_band_acquisition_image,
11771 force_posterior_unresolved && !residual_force_open_pre_inner,
11772 activation_stencil_pending) ||
11773 pending_band_action_waiting || adjacent_mep_trial_pending ||
11774 preempt_inner_for_psbax || skip_inner_for_force_uncertainty;
11775 // Closed-form maximal certified step for the per-step trust
11776 // gate below: min over interior images of TrustRadius::
11777 // certifiedLineStep(from_image, to_image, trust_threshold),
11778 // mirroring how proposalTrustCertified/projectProposalToOuterTrust
11779 // iterate images and pick the per-image trust model. Replaces
11780 // the acceptTrustCertifiedProposal bisection (12 objective.
11781 // refresh + full-chain trust evaluations) with one closed-form
11782 // evaluation per image.
11783 auto certifiedOuterTrustStep =
11784 [&](const Eigen::VectorXd& from,
11785 const Eigen::VectorXd& to) -> double {
11786 const Eigen::Index image_dof = band_objective.imageDof();
11787 if (image_dof <= 0) return 0.0;
11788 const int n_im = path.numImages();
11789 const Eigen::Index expected_size =
11790 static_cast<Eigen::Index>(n_im - 2) * image_dof;
11791 if (from.size() != expected_size || to.size() != expected_size) {
11792 return 0.0;
11793 }
11794 double min_alpha = 1.0;
11795 for (int i = 1; i < n_im - 1; ++i) {
11796 const Eigen::Index offset =
11797 static_cast<Eigen::Index>(i - 1) * image_dof;
11798 const Eigen::VectorXd from_image =
11799 from.segment(offset, image_dof);
11800 const Eigen::VectorXd to_image = to.segment(offset, image_dof);
11801 const gpr::Observation* trust_obs = &training_obs;
11802 const gpr::TrustRadius* trust_model = &trust;
11803 if (session && localEligible(i) &&
11804 i < static_cast<int>(session->image_models.size())) {
11805 const auto& image_obs =
11806 session->image_models[i].observations();
11807 if (image_obs.R.rows() > 0) {
11808 image_trust.setTrainingData(image_obs.R);
11809 trust_obs = &image_obs;
11810 trust_model = &image_trust;
11811 }
11812 }
11813 if (trust_obs->R.rows() == 0) return 0.0;
11814 min_alpha = std::min(
11815 min_alpha, trust_model->certifiedLineStep(
11816 from_image, to_image, trust_threshold));
11817 }
11818 return min_alpha;
11819 };
11820 // Nystrom-sketched H0 rebuild for the chain L-BFGS (Phase B
11821 // wiring). Builds the rank-k Nystrom approximation of the
11822 // chain Hessian via k Hessian-vector products on the
11823 // GP-mean band force. Cost per HvP: two refresh() calls
11824 // (each predicts GP-mean gradients at all chain images and
11825 // assembles NEB forces). No oracle calls -- the GP-mean is
11826 // already fitted to the chain's training set, so the HvP is
11827 // free of new force evaluations.
11828 //
11829 // FD-on-band-force estimate: H @ v = -(F(x + eps v) - F(x -
11830 // eps v)) / (2 eps), where F is the band NEB force. The
11831 // sign matches the L-BFGS two-loop's H0 application convention
11832 // (apply_H0 multiplies the q built from -force on entry).
11833 //
11834 // The sketch services every chain L-BFGS step inside this
11835 // outer's inner loop. Rebuild is amortised across all inner
11836 // steps; with k = 16 and 8-image Baker chains the total
11837 // HvP work is sub-millisecond per outer iter.
11838 if (!skip_inner_for_pending_acquisition && !transition_focal_handoff &&
11839 config.lbfgs_sketch_h0_rank > 0 &&
11840 band_objective.positions().size() > 0) {
11841 const Eigen::VectorXd x0_band = band_objective.positions();
11842 const double eps = config.lbfgs_sketch_h0_eps > 0.0
11843 ? config.lbfgs_sketch_h0_eps
11844 : 1e-3;
11845 auto hvp = [&band_objective, &x0_band,
11846 eps](const Eigen::VectorXd& v) -> Eigen::VectorXd {
11847 band_objective.setPositions(
11848 band_objective.stepPositions(x0_band, eps * v));
11849 band_objective.refresh(false);
11850 Eigen::VectorXd f_plus = band_objective.force();
11851 band_objective.setPositions(
11852 band_objective.stepPositions(x0_band, -eps * v));
11853 band_objective.refresh(false);
11854 Eigen::VectorXd f_minus = band_objective.force();
11855 band_objective.setPositions(x0_band);
11856 band_objective.refresh(false);
11857 return -(f_plus - f_minus) / (2.0 * eps);
11858 };
11859 band_stepper.rebuildSketchedH0(hvp,
11860 static_cast<int>(x0_band.size()));
11861 }
11862 // Snapshot the chain positions at outer start; per-image
11863 // EMD from this snapshot to the current chain is the
11864 // cumulative drift signal. Break the inner loop when any
11865 // image's cumulative EMD exceeds trust_radius. This is the
11866 // EMD equivalent of Koistinen 2017's max-1d-log cumulative
11867 // stopping criterion, using the threshold already
11868 // calibrated for the EMD metric.
11869 const std::vector<Eigen::VectorXd> outer_start_image_positions = [&] {
11870 std::vector<Eigen::VectorXd> v(path.numImages());
11871 for (int i = 0; i < path.numImages(); ++i) {
11872 v[i] = path.image(i).positions;
11873 }
11874 return v;
11875 }();
11876 const Eigen::Index outer_start_ntrain = training_obs.R.rows();
11877 const long outer_start_oracle_calls =
11878 static_cast<long>(result.oracle_calls);
11879 // Set when the oracle refused this outer's acquisition (directly,
11880 // or at a geometry it refused before); a contact-floor rejection
11881 // is a geometric guard and does not set it.
11882 bool outer_oracle_refusal = false;
11883 std::string outer_oracle_refusal_text;
11884 gpr::TrustRadius drift_metric;
11885 drift_metric.setAtomsConfiguration(atoms_config);
11886 drift_metric.setDistanceMetric(config.trust_metric);
11887 std::vector<double> cumulative_inner_travel(path.numImages(), 0.0);
11888 // SWEEP regime skips the band relaxation: the band is frozen
11889 // at the GP-converged geometry and we only confirm remaining
11890 // un-evaluated images on the true PES. The `!frozen_sweep`
11891 // guard collapses the inner loop to a no-op (inner stays 0)
11892 // without moving any image, so the per-image `evaluated`
11893 // flags persist across sweep rounds.
11894 const char* inner_exit =
11895 config.max_inner_iter_gp > 0 ? "itercap" : "condition";
11896 // The surrogate's climbing force at the walk's endpoint, read when
11897 // the acquisition is planned: whether the walk proposed an
11898 // improvement on the best measured climb or was cut short.
11899 double walk_endpoint_gp_force =
11900 std::numeric_limits<double>::quiet_NaN();
11901 int accepted_inner_steps = pending_band_action_applied ? 1 : 0;
11902 int accepted_drift_priority_idx = -1;
11903 detail::ProposalAcquisitionTarget held_boundary_acquisition;
11904 int ei_acquisition_image = -1;
11905 detail::OieAcceptedDriftKind accepted_drift_kind =
11906 detail::OieAcceptedDriftKind::GeometricTrustBoundary;
11907 int drift_diagnostic_image = -1;
11908 double drift_diagnostic_distance =
11909 std::numeric_limits<double>::quiet_NaN();
11910 bool drift_diagnostic_radius = false;
11911 bool drift_diagnostic_cycle = false;
11912 bool drift_diagnostic_kernel = false;
11913 const bool skip_inner_after_rejected_hook =
11914 skip_next_inner_after_rejected_hook;
11915 skip_next_inner_after_rejected_hook = false;
11916 bool skip_inner_for_handoff = transition_focal_handoff;
11917 //
11918 // Do not early-exit on non-improving force: the NEB force
11919 // (spring + tangent projection) is non-conservative, so ||F||
11920 // is not a merit function. Inner budget remains the configured
11921 // cap; trust / drift bound unproductive motion.
11922 if (skip_inner_after_rejected_hook) {
11923 inner_exit = "hook_reject";
11924 }
11925 if (skip_inner_for_pending_acquisition) {
11926 inner_exit =
11927 pending_band_action_waiting ? "psbax_action"
11928 : preempt_inner_for_psbax ? "psbax_action"
11929 : current_band_acquisition_image > 0 ? "joint_acquisition"
11930 : activation_stencil_pending ? "activation_acquisition"
11931 : skip_inner_for_force_uncertainty ? "force_unresolved"
11932 : adjacent_mep_trial_pending ? "mep_trial"
11933 : fixed_point_applied_kind ==
11934 FixedPointProposalKind::Reparameterization
11935 ? "reparam_apply"
11936 : fixed_point_applied_kind ==
11937 FixedPointProposalKind::MeasuredChainSweep
11938 ? "measured_chain_apply"
11939 : fixed_point_applied_kind ==
11940 FixedPointProposalKind::MeasuredNebStep
11941 ? "measured_step_apply"
11942 : fixed_point_applied_kind ==
11943 FixedPointProposalKind::MeasuredNebStepRejected
11944 ? "measured_step_reject"
11945 : fixed_point_applied_kind ==
11946 FixedPointProposalKind::ReparameterizationRejected
11947 ? "reparam_reject"
11948 : "pending_acquisition";
11949 }
11950 if (frozen_sweep) {
11951 inner_exit = "sweep";
11952 }
11953 if (transition_focal_handoff) {
11954 inner_exit = "transition_handoff";
11955 } else if (!skip_inner_for_pending_acquisition &&
11956 !skip_inner_after_rejected_hook && !frozen_sweep &&
11957 !adjacent_mep_recovery_active &&
11958 config.oie_inner_handoff_priority && ci_active) {
11959 const int handoff_ci_idx =
11960 detail::selectOieClimbingImageIndex(ci_active, path);
11961 if (handoff_ci_idx > 0 && handoff_ci_idx < path.numImages() - 1) {
11962 const double handoff_ci_force =
11963 path.nebForceMagnitude(handoff_ci_idx);
11964 const bool current_chain_certificate =
11965 session &&
11966 session->hasCurrentChainCertificate(
11967 handoff_ci_idx, path.image(handoff_ci_idx).positions);
11968 if (current_chain_certificate) {
11969 const double handoff_threshold =
11970 detail::effectivePosteriorVarianceThreshold(
11971 config, std::optional<double>{
11973 .getMagnSigma2()});
11974 const double handoff_chain_variance =
11975 session->last_max_chain_energy_variance;
11976 const bool planned_current_chain_or_ci = true;
11977 skip_inner_for_handoff =
11978 std::isfinite(handoff_chain_variance) &&
11979 handoff_chain_variance >= 0.0 &&
11980 config.oie_inner_handoff_priority(
11981 path, handoff_ci_idx, outer, handoff_ci_force,
11982 handoff_chain_variance, handoff_threshold,
11983 current_chain_certificate,
11984 planned_current_chain_or_ci, session);
11985 if (skip_inner_for_handoff &&
11986 handoff_bypass_oracle_calls ==
11987 static_cast<long>(result.oracle_calls)) {
11988 skip_inner_for_handoff = false;
11989 if (config.verbose && log_rank == 0) {
11990 neb_log() << "[handoff] outer=" << outer
11991 << " bypass withheld: no oracle call "
11992 "since the previous bypass"
11993 << std::endl;
11994 }
11995 } else if (skip_inner_for_handoff) {
11996 handoff_bypass_oracle_calls =
11997 static_cast<long>(result.oracle_calls);
11998 }
11999 if (skip_inner_for_handoff) inner_exit = "handoff";
12000 }
12001 }
12002 }
12003 // Without the anchored drift budget the inner loop loses
12004 // its distance-based stopping guarantee, and the NEB force
12005 // is non-conservative (surrogate limit cycles spin
12006 // forever, measured: 01_hcn hung its 5th outer for the
12007 // whole 300 s cell). A plain iteration bound restores
12008 // liveness without re-introducing a distance quantum.
12009 //
12010 // The bound is a liveness backstop, so it holds whether or not
12011 // the drift budget is carrying its distance-based stop. Making
12012 // it conditional on use_drift_budget left the default
12013 // configuration with NO bound at all -- iterationAllowedByLimit
12014 // reads a limit of zero as unbounded, and max_inner_iter_gp
12015 // defaults to zero -- which is exactly the case the comment
12016 // above says spins forever. Measured on Baker 02_hcch: one
12017 // outer took 1174 accepted inner steps and 114 s of the cell's
12018 // wall. A backstop that the mechanism it backs up can switch
12019 // off is not a backstop; when the budget does stop the loop
12020 // first this bound never binds, so keeping it costs nothing.
12021 // Liveness comes from Brent's cycle detection (doi:10.1007/bf01933190)
12022 // on the accepted band iterates instead of an iteration count: the
12023 // anchor is moved to the current iterate at every power of two
12024 // accepted steps, and an iterate that coincides with the anchor,
12025 // at the resolution the acquisition uses for one point, closes a
12026 // limit cycle of the non-conservative band force. A configured
12027 // inner limit remains an explicit user bound; zero is unbounded.
12028 const int effective_max_inner_iter = config.max_inner_iter_gp;
12029 // The same doubling windows also bound a quasi-cycle that never
12030 // returns to a point exactly: the relaxation force's running
12031 // minimum must improve within each window, the doubling trick of
12032 // online learning, so a stall is caught over a horizon that grows
12033 // with the relaxation instead of a fixed count.
12034 Eigen::VectorXd cycle_anchor;
12035 int cycle_anchor_step = 0;
12036 int cycle_power = 1;
12037 // The interior images outside the prediction kernel's support at
12038 // the last inner step; none of them can be predicted, so all of
12039 // them join this outer's oracle batch.
12040 std::vector<char> unsupported_images;
12041 window_best_force = std::numeric_limits<double>::infinity();
12042 window_best_force_before = std::numeric_limits<double>::infinity();
12043 AccumulateWallTime inner_wall(phase_inner_seconds);
12044 for (; detail::gpInnerIterationAllowed(inner, effective_max_inner_iter);
12045 ++inner) {
12046 if (wallClockReached()) {
12047 inner_exit = "wall_clock";
12048 break;
12049 }
12050 if (skip_inner_for_pending_acquisition) break;
12051 if (skip_inner_for_handoff) break;
12052 if (skip_inner_after_rejected_hook) break;
12053 if (frozen_sweep) break;
12054 if (!band_objective.refresh(false)) {
12055 inner_exit = "refresh_fail";
12056 break;
12057 }
12058 if (detail::oieGpInnerForceConverged(
12059 ci_active && config.climbing_image_converged_only,
12060 relaxation_inner, max_inner, effective_inner_conv_tol,
12061 chain_inner_conv_tol)) {
12062 inner_exit = "converged";
12063 break;
12064 }
12065 const Eigen::VectorXd accepted_positions =
12066 band_objective.positions();
12067 if (cycle_anchor.size() == accepted_positions.size() &&
12068 inner > cycle_anchor_step &&
12069 detail::positionsCoincide(accepted_positions, cycle_anchor)) {
12070 inner_exit = "cycle";
12071 break;
12072 }
12073 if (inner - cycle_anchor_step >= cycle_power) {
12074 // Progress is judged only over windows at least as long as
12075 // the stepper's memory: shorter than that the quasi-Newton
12076 // model is still being built and a rise in the force is
12077 // not a stall.
12078 if (cycle_power >= config.lbfgs_memory &&
12079 !(window_best_force < window_best_force_before)) {
12080 inner_exit = "cycle";
12081 break;
12082 }
12083 window_best_force_before = window_best_force;
12084 window_best_force = std::numeric_limits<double>::infinity();
12085 cycle_anchor = accepted_positions;
12086 cycle_anchor_step = inner;
12087 cycle_power *= 2;
12088 }
12089 auto measured_inverse_curvature =
12090 adjacent_mep_recovery.takeMeasuredInverseCurvature();
12091 if (!measured_inverse_curvature)
12092 measured_inverse_curvature =
12093 secantBandInverseCurvature(session, config);
12094 if (!band_stepper.step(band_objective, band_max_step,
12095 measured_inverse_curvature)) {
12096 inner_exit = "optimizer_stop";
12097 break;
12098 }
12099 if (!band_objective.refresh(false)) {
12100 inner_exit = "refresh_fail";
12101 break;
12102 }
12103 // A nonconservative NEB step need not decrease the force norm.
12104 // Its displacement is capped, and the geometric trust certifier
12105 // bounds extrapolation independently of residual monotonicity.
12106 const Eigen::VectorXd proposal_positions =
12107 band_objective.positions();
12108 // A proposal below the training-set coordinate resolution
12109 // cannot create a distinct oracle row or measurable band
12110 // progress. Return to acquisition instead of replaying the
12111 // same condition-driven relaxation map indefinitely.
12112 if (detail::shouldStopOieInnerAtCoordinateResolution(
12113 accepted_positions, proposal_positions)) {
12114 band_objective.setPositions(accepted_positions);
12115 (void)band_objective.refresh(false);
12116 band_stepper.reset();
12117 // A surrogate-stationary band with an open force is a
12118 // point the model cannot move away from: measure the image
12119 // that carries the force where it stands, so the next
12120 // outer starts from a corrected surrogate rather than
12121 // replaying the same relaxation (irc 02_hcch triplet: 263
12122 // steps to the same point, 999 outers, force 0.71).
12123 if (!rejected_proposal_acquisition) {
12124 const Eigen::Index image_dof = band_objective.imageDof();
12125 int open_image = -1;
12126 double open_force =
12127 detail::effectiveModelNoiseTolerance(config);
12128 for (int i = 1; i < path.numImages() - 1; ++i) {
12129 const double f =
12130 path.nebForce(i).lpNorm<Eigen::Infinity>();
12131 if (std::isfinite(f) && f > open_force) {
12132 open_force = f;
12133 open_image = i;
12134 }
12135 }
12136 if (open_image > 0 && image_dof > 0) {
12137 const Eigen::VectorXd stationary_point =
12138 accepted_positions.segment(
12139 static_cast<Eigen::Index>(open_image - 1) *
12140 image_dof,
12141 image_dof);
12142 if (stationary_point.allFinite() &&
12143 !detail::hasPosition(training_obs,
12144 stationary_point)) {
12145 rejected_proposal_acquisition.image_index =
12146 open_image;
12147 rejected_proposal_acquisition.positions =
12148 stationary_point;
12149 }
12150 }
12151 }
12152 inner_exit = "stationary";
12153 break;
12154 }
12155 const Eigen::Index travel_image_dof = band_objective.imageDof();
12156 auto imageStepTravelRaw = [&](const Eigen::VectorXd& from,
12157 const Eigen::VectorXd& to) {
12158 std::vector<double> travel(path.numImages(), 0.0);
12159 if (travel_image_dof <= 0 || from.size() != to.size() ||
12160 from.size() % travel_image_dof != 0) {
12161 return travel;
12162 }
12163 const Eigen::Index interior_count =
12164 from.size() / travel_image_dof;
12165 for (Eigen::Index j = 0; j < interior_count; ++j) {
12166 EigenMatrix R_anchor(1, travel_image_dof);
12167 R_anchor.row(0) =
12168 from.segment(j * travel_image_dof, travel_image_dof)
12169 .transpose();
12170 drift_metric.setTrainingData(R_anchor);
12171 const Eigen::VectorXd probe =
12172 to.segment(j * travel_image_dof, travel_image_dof);
12173 const double distance =
12174 drift_metric.distanceToTraining(probe);
12175 if (std::isfinite(distance) && distance >= 0.0)
12176 travel[static_cast<std::size_t>(j + 1)] = distance;
12177 }
12178 return travel;
12179 };
12180 auto imageStepTravel = [&](const Eigen::VectorXd& from,
12181 const Eigen::VectorXd& to) {
12182 AccumulateWallTime drift_wall(phase_drift_seconds);
12183 return imageStepTravelRaw(from, to);
12184 };
12185 const std::vector<double> proposed_step_travel =
12186 imageStepTravel(accepted_positions, proposal_positions);
12187 const bool cumulative_travel_break =
12188 detail::cumulativeTrustTravelExceeded(cumulative_inner_travel,
12189 proposed_step_travel,
12190 trust_threshold);
12191 double max_cumulative_drift = 0.0;
12192 int max_drift_image = -1;
12193 AccumulateWallTime drift_wall(phase_drift_seconds);
12194 for (int i = 1; i < path.numImages() - 1; ++i) {
12195 EigenMatrix R_anchor(1, outer_start_image_positions[i].size());
12196 R_anchor.row(0) = outer_start_image_positions[i].transpose();
12197 drift_metric.setTrainingData(R_anchor);
12198 const double d_i =
12199 drift_metric.distanceToTraining(path.image(i).positions);
12200 if (std::isfinite(d_i) && d_i > max_cumulative_drift) {
12201 max_cumulative_drift = d_i;
12202 max_drift_image = i;
12203 }
12204 }
12205 drift_wall.stop();
12206 if (cumulative_travel_break) {
12207 for (int i = 1; i < path.numImages() - 1; ++i) {
12208 const double travel =
12209 cumulative_inner_travel[i] + proposed_step_travel[i];
12210 if (travel > max_cumulative_drift) {
12211 max_cumulative_drift = travel;
12212 max_drift_image = i;
12213 }
12214 }
12215 }
12216 // The support policy bounds surrogate motion using normalized
12217 // prediction covariance, independently of the image count.
12218 // An unsupported image is held while a real-surface query
12219 // extends its local information. Its posterior remains
12220 // defined outside this motion region.
12221 int kernel_support_break_image = -1;
12222 std::vector<char> kernel_blocked_images(
12223 static_cast<std::size_t>(path.numImages()), 0);
12224 int kernel_blocked_count = 0;
12225 const int kernel_interior_count = std::max(0, path.numImages() - 2);
12226 if (training_obs.R.rows() > 0) {
12227 const auto& global_kernel = gp.getSexpAtCovarianceFunction();
12228 for (int i = 1; i < path.numImages() - 1; ++i) {
12229 const gpr::Observation* local_observations = nullptr;
12230 const gpr::SexpatCF* local_kernel = nullptr;
12231 if (session && localEligible(i) &&
12232 i < static_cast<int>(session->image_models.size())) {
12233 const auto& image_model = session->image_models[i];
12234 if (const auto* local_gp = image_model.gp()) {
12235 local_observations = &image_model.observations();
12236 local_kernel =
12237 &local_gp->getSexpAtCovarianceFunction();
12238 }
12239 }
12240 if (!detail::imageWithinPredictionKernelSupport(
12241 path.image(i).positions, atoms_config, training_obs,
12242 global_kernel, local_observations, local_kernel)) {
12243 if (kernel_support_break_image < 0) {
12244 kernel_support_break_image = i;
12245 }
12246 kernel_blocked_images[static_cast<std::size_t>(i)] = 1;
12247 ++kernel_blocked_count;
12248 // The whole scan runs even when the band-wide stop
12249 // is in force: the count decides whether any image
12250 // is left that could relax, which the first
12251 // blocking index alone cannot answer.
12252 continue;
12253 }
12254 }
12255 }
12256 unsupported_images = kernel_blocked_images;
12257 // Blocking images stop the band outright only under the
12258 // band-wide rule, or when no interior image is left that could
12259 // relax. Decided here because the drift bookkeeping below
12260 // rewrites max_drift_image on the strength of it.
12261 const bool kernel_blocks_everything =
12262 kernel_blocked_count > 0 &&
12263 kernel_blocked_count >= kernel_interior_count;
12264 const bool kernel_stops_band =
12265 kernel_support_break_image > 0 &&
12266 (config.kernel_support_freezes_band ||
12267 kernel_blocks_everything);
12268 // A support-blocked image owns the boundary acquisition ahead
12269 // of ordinary geometric drift, so its missing observations
12270 // cannot be displaced by a supported image's longer motion.
12271 if (kernel_stops_band) {
12272 max_drift_image = kernel_support_break_image;
12273 max_cumulative_drift = trust_threshold;
12274 }
12275 // With the anchored budget retired
12276 // (use_drift_budget=false) the inner loop relaxes to
12277 // surrogate convergence bounded by distance-to-data:
12278 // the kernel-support bound and the per-step certifier
12279 // remain the only trust gates, so relaxation is no
12280 // longer quantized into drift-radius installments of
12281 // one oracle each.
12282 // Supported images keep relaxing while the held image retains
12283 // the boundary geometry needed to extend its prediction support.
12284 if (!kernel_stops_band && kernel_blocked_count > 0) {
12285 auto held_boundary = detail::holdOieUnsupportedImages(
12286 band_objective, accepted_positions, kernel_blocked_images);
12287 if (held_boundary && accepted_drift_priority_idx < 0) {
12288 accepted_drift_priority_idx = held_boundary.image_index;
12289 accepted_drift_kind =
12290 detail::OieAcceptedDriftKind::PredictionKernelBoundary;
12291 const Eigen::Index dof = band_objective.imageDof();
12292 const Eigen::Index offset =
12293 static_cast<Eigen::Index>(held_boundary.image_index -
12294 1) *
12295 dof;
12296 Eigen::VectorXd boundary_positions =
12297 band_objective.positions();
12298 boundary_positions.segment(offset, dof) =
12299 held_boundary.positions;
12300 (void)projectProposalToOuterTrust(boundary_positions);
12301 held_boundary.positions =
12302 boundary_positions.segment(offset, dof);
12303 held_boundary_acquisition =
12304 detail::prepareOieBoundaryAcquisition(
12305 std::move(held_boundary), training_obs, trust,
12306 trust_threshold);
12307 if (held_boundary_acquisition) {
12308 rejected_proposal_acquisition =
12309 held_boundary_acquisition;
12310 }
12311 }
12312 // The curvature history was built over a wider set of
12313 // moving images and no longer describes this subspace.
12314 band_stepper.reset();
12315 if (!band_objective.refresh(false)) {
12316 inner_exit = "refresh_fail";
12317 break;
12318 }
12319 }
12320 const bool drift_break =
12321 !config.eon_inner_mode &&
12322 ((config.use_drift_budget && trust_threshold > 0.0 &&
12323 gpr::numerics::exceedsThreshold(max_cumulative_drift,
12324 trust_threshold) &&
12325 max_drift_image > 0) ||
12326 (config.use_drift_budget && cumulative_travel_break) ||
12327 kernel_stops_band);
12328 if (drift_break) {
12329 drift_diagnostic_image = max_drift_image;
12330 drift_diagnostic_distance = max_cumulative_drift;
12331 drift_diagnostic_radius =
12332 gpr::numerics::exceedsThreshold(max_cumulative_drift,
12333 trust_threshold) &&
12334 max_drift_image > 0;
12335 drift_diagnostic_cycle = cumulative_travel_break;
12336 drift_diagnostic_kernel = kernel_stops_band;
12337 // Virtual conjugate constraint at the clip point: the
12338 // drifted image's live geometry is the furthest point
12339 // the band reached beyond internal trust, riding a GP
12340 // mean the certifier just rejected. Pin the posterior
12341 // toward the prior there so the next inner pass does
12342 // not re-launch the same extrapolation fantasy. The
12343 // retire radius keeps the pin clear of the boundary
12344 // oracle row that typically follows a drift break.
12345 if (config.use_virtual_observations && session &&
12346 max_drift_image > 0 && training_obs.R.rows() > 0) {
12347 const Eigen::VectorXd clip_positions =
12348 path.image(max_drift_image).positions;
12349 double nearest_real =
12350 std::numeric_limits<double>::infinity();
12351 for (Eigen::Index r = 0; r < training_obs.R.rows(); ++r) {
12352 const double d =
12353 (training_obs.R.row(r).transpose() - clip_positions)
12354 .norm();
12355 if (d < nearest_real) nearest_real = d;
12356 }
12357 const double retire_radius =
12358 std::max(0.25 * nearest_real, 1e-3);
12359 session->virtual_obs_noise_sigma2 =
12360 config.virtual_obs_noise;
12361 if (session->addVirtualObservation(clip_positions,
12362 retire_radius)) {
12363 session->refreshCovarianceCache();
12364 }
12365 }
12366 }
12367 // The pre-inner joint certificate blocks motion only when an
12368 // unresolved force posterior has a new current-chain row to
12369 // acquire. Once that information is present, the EMD drift
12370 // certifier and per-step trust gate bound motion within the
12371 // surrogate's geometric support.
12372 Eigen::VectorXd rejected_certification_positions;
12373 // Per-step trust gate via proposalTrustCertified. The certifier
12374 // bisects toward the proposal and commits the largest
12375 // trust-certified step (or projects the band onto the trust
12376 // boundary), so the accepted band ADVANCES by a bounded step
12377 // every outer instead of reverting to the outer-start
12378 // geometry.
12379 //
12380 // Net displacement and accumulated travel both use the live
12381 // trust radius. The per-step certifier commits a bounded
12382 // advance before either signal ends the relaxation burst, so a
12383 // cycle cannot consume unbounded inner work and a drift stop
12384 // cannot roll the band back to its outer-start geometry.
12385 AccumulateWallTime certificate_wall(phase_cert_seconds);
12386 const bool certified =
12387 config.eon_inner_mode ||
12388 detail::acceptTrustCertifiedProposal(
12389 band_objective, accepted_positions, proposalTrustCertified,
12390 /*max_bisections=*/12, &rejected_certification_positions,
12391 projectProposalToOuterTrust, [&]() {
12392 return certifiedOuterTrustStep(accepted_positions,
12393 proposal_positions);
12394 });
12395 certificate_wall.stop();
12396 // Restricted-variance acquisition (qog0): probe the proposed
12397 // (geometrically certified) positions. An uncertified
12398 // unobserved image becomes an oracle target. This is not
12399 // AND-ed into proposalTrustCertified, so residual variance
12400 // on already-trained rows cannot freeze the inner loop.
12401 if (certified && !drift_break &&
12402 config.restricted_variance_acquisition) {
12403 const auto proposal_variance_probe =
12404 probeChainObservationVariance(
12405 /*force_global_only=*/true);
12406 std::vector<double> proposal_energy_var(path.numImages(), 0.0);
12407 for (int i = 1; i < path.numImages() - 1; ++i) {
12408 proposal_energy_var[i] =
12409 proposal_variance_probe.per_image[i].energy;
12410 }
12411 const double noise_floor = gp.likelihoodNoiseVariance();
12412 detail::ProposalAcquisitionTarget restricted_var_target =
12413 detail::selectRestrictedVarianceAcquisitionTarget(
12414 band_objective.positions(), band_objective.imageDof(),
12415 proposal_energy_var, noise_floor, training_obs);
12416 if (restricted_var_target) {
12417 rejected_proposal_acquisition =
12418 std::move(restricted_var_target);
12419 band_objective.setPositions(accepted_positions);
12420 (void)band_objective.refresh(false);
12421 band_stepper.reset();
12422 inner_exit = "restricted_var";
12423 break;
12424 }
12425 }
12426 // While the live band force residual is still above problem
12427 // tolerance, commit trust-certified GP steps without the
12428 // posterior-readiness reject. Observed-row joint cert can
12429 // report joint_ready=1 at max_gp_F~7 (variance on unobserved
12430 // rows only); the posterior gate then rejects every step as
12431 // posterior_unresolved and F never moves (Baker 01/02 under
12432 // TPE). Classic MaxVariance already skips this gate.
12433 const double residual_tol_for_inner =
12434 detail::effectiveModelNoiseTolerance(config);
12435 // max_inner excludes an active fixed-image lease (the CI a
12436 // recovery lease pins), so a quiet band around an OPEN pinned
12437 // CI reads as residual-closed and the posterior gate
12438 // hard-stalls the inner loop. Fold the pinned image's own
12439 // force back into the residual probe; without a lease the
12440 // probe is unchanged.
12441 const double fixed_image_force =
12442 (fixed_image > 0 && fixed_image < path.numImages() - 1)
12443 ? path.nebForceMagnitude(fixed_image)
12444 : 0.0;
12445 const double residual_probe =
12446 std::max(max_inner, fixed_image_force);
12447 const bool residual_force_open =
12448 std::isfinite(residual_probe) && residual_tol_for_inner > 0.0 &&
12449 residual_probe > residual_tol_for_inner;
12450 if (certified && !drift_break && !classic_oie_relaxation &&
12451 !residual_force_open) {
12452 const Eigen::VectorXd trial_positions =
12453 band_objective.positions();
12454 auto assessProposalReadiness = [&]() {
12455 const auto proposal_variance =
12456 probeChainObservationVariance(
12457 /*force_global_only=*/true);
12458 return detail::assessOieBandPosteriorReadiness(
12459 proposal_variance.force_certification_per_image,
12460 uncertainty_threshold,
12461 detail::effectiveModelNoiseTolerance(config),
12463 currentBandObservationMask());
12464 };
12465 const auto proposal_readiness = assessProposalReadiness();
12466 auto proposal_decision = detail::decideOieInnerProposal(
12467 proposal_readiness, trial_positions,
12468 band_objective.imageDof(), training_obs);
12469 if (!proposal_decision.accept) {
12470 const bool accepted_posterior_segment =
12471 detail::acceptPosteriorCertifiedProposal(
12472 band_objective, accepted_positions, [&]() {
12473 return assessProposalReadiness().resolved();
12474 });
12475 if (!accepted_posterior_segment) {
12476 pending_band_action_acquisition.clear();
12477 if (pending_band_action.stage(
12478 config.acquisition, accepted_positions,
12479 trial_positions, band_objective.imageDof())) {
12480 EigenMatrix action_covariance;
12481 if (calculateBandActionPosteriorCovariance(
12482 trial_positions, action_covariance)) {
12483 pending_band_action_acquisition =
12484 detail::selectOieBandActionAcquisition(
12485 trial_positions,
12486 band_objective.imageDof(),
12487 action_covariance, training_obs,
12489 .target;
12490 }
12491 if (!pending_band_action_acquisition) {
12492 pending_band_action_acquisition =
12493 std::move(proposal_decision.acquisition);
12494 }
12495 if (pending_band_action_acquisition) {
12496 rejected_proposal_acquisition =
12497 pending_band_action_acquisition;
12498 }
12499 band_objective.setPositions(accepted_positions);
12500 } else {
12501 // The step is trust-certified; the posterior
12502 // readiness only names the image to measure.
12503 // The band keeps the relaxation and that image
12504 // is measured where it now sits: restoring the
12505 // outer's start and measuring an off-band point
12506 // replayed the same relaxation every outer
12507 // (irc 03_h2co under EI: 1000 outers, one
12508 // off-band call each, climbing image at 0.056).
12509 pending_band_action.clear();
12510 rejected_proposal_acquisition =
12511 std::move(proposal_decision.acquisition);
12512 }
12513 (void)band_objective.refresh(false);
12514 band_stepper.reset();
12515 pending_band_action_waiting =
12516 pending_band_action.active();
12517 inner_exit = pending_band_action_acquisition
12518 ? "psbax_action"
12519 : "posterior_unresolved";
12520 break;
12521 }
12522 }
12523 }
12524 if (certified && !drift_break) {
12525 const std::vector<double> accepted_step_travel =
12526 imageStepTravel(accepted_positions,
12527 band_objective.positions());
12528 for (std::size_t i = 0; i < cumulative_inner_travel.size();
12529 ++i) {
12530 cumulative_inner_travel[i] += accepted_step_travel[i];
12531 }
12532 }
12533 // Keep a bounded certified advance on a drift break so the next
12534 // outer starts from a band that has moved toward relaxation;
12535 // the advance is trust-certified by construction and cannot run
12536 // away. Reverting it is what stalled 08/20.
12537 const bool keep_certified_drift_advance =
12538 certified && drift_break && !config.eon_inner_mode;
12539 Eigen::VectorXd certified_drift_positions;
12540 if (keep_certified_drift_advance) {
12541 certified_drift_positions = band_objective.positions();
12542 accepted_drift_priority_idx =
12543 detail::selectAcceptedDriftCurrentChainPriority(
12544 certified, drift_break, max_drift_image,
12545 path.numImages());
12546 if (drift_diagnostic_kernel && !drift_diagnostic_radius &&
12547 !drift_diagnostic_cycle) {
12548 accepted_drift_kind =
12549 detail::OieAcceptedDriftKind::PredictionKernelBoundary;
12550 }
12551 }
12552 if (keep_certified_drift_advance &&
12553 !detail::shouldLatchRejectedProposalAcquisition(certified,
12554 drift_break)) {
12555 // An initial drift stop can return a measured boundary
12556 // geometry. Its current-chain row needs no acquisition, so
12557 // retain a distinct proposal inside the same trust envelope
12558 // to extend the model. Kernel-support stops also acquire the
12559 // proposal when their boundary row is absent.
12560 if (accepted_inner_steps == 0 && max_drift_image > 0 &&
12561 max_drift_image < path.numImages() - 1) {
12562 const Eigen::Index drift_dof = band_objective.imageDof();
12563 const Eigen::Index drift_offset =
12564 static_cast<Eigen::Index>(max_drift_image - 1) *
12565 drift_dof;
12566 if (drift_dof > 0 &&
12567 proposal_positions.size() >= drift_offset + drift_dof &&
12568 (drift_diagnostic_kernel ||
12569 detail::hasPosition(
12570 training_obs,
12571 path.image(max_drift_image).positions))) {
12572 detail::ProposalAcquisitionTarget boundary_target;
12573 boundary_target.image_index = max_drift_image;
12574 boundary_target.positions =
12575 proposal_positions.segment(drift_offset, drift_dof);
12576 const Eigen::VectorXd raw_boundary_positions =
12577 boundary_target.positions;
12578 const gpr::Observation* boundary_observations =
12579 &training_obs;
12580 const gpr::TrustRadius* boundary_trust = &trust;
12581 if (session && localEligible(max_drift_image) &&
12582 max_drift_image <
12583 static_cast<int>(
12584 session->image_models.size())) {
12585 const auto& local_observations =
12586 session->image_models[max_drift_image]
12587 .observations();
12588 if (local_observations.R.rows() > 0) {
12589 image_trust.setTrainingData(
12590 local_observations.R);
12591 boundary_observations = &local_observations;
12592 boundary_trust = &image_trust;
12593 }
12594 }
12595 boundary_target = detail::prepareOieBoundaryAcquisition(
12596 std::move(boundary_target), *boundary_observations,
12597 *boundary_trust, trust_threshold);
12598 if (boundary_target &&
12599 !detail::hasPosition(training_obs,
12600 boundary_target.positions)) {
12601 rejected_proposal_acquisition =
12602 std::move(boundary_target);
12603 }
12604 if (config.verbose && log_rank == 0) {
12605 Eigen::VectorXd query_positions =
12606 raw_boundary_positions;
12607 const bool query_clipped =
12608 detail::clipImageToOuterTrust(
12609 query_positions, *boundary_observations,
12610 *boundary_trust, trust_threshold);
12611 double nearest_coordinates =
12612 std::numeric_limits<double>::infinity();
12613 double query_nearest_coordinates =
12614 std::numeric_limits<double>::infinity();
12615 for (Eigen::Index row = 0;
12616 row < training_obs.R.rows(); ++row) {
12617 const Eigen::VectorXd measured =
12618 training_obs.R.row(row).transpose();
12619 nearest_coordinates = std::min(
12620 nearest_coordinates,
12621 (raw_boundary_positions - measured).norm());
12622 query_nearest_coordinates = std::min(
12623 query_nearest_coordinates,
12624 (query_positions - measured).norm());
12625 }
12626 neb_log()
12627 << "[drift] outer=" << outer
12628 << " boundary image=" << max_drift_image
12629 << " staged="
12630 << static_cast<bool>(
12631 rejected_proposal_acquisition)
12632 << " raw_step="
12633 << (raw_boundary_positions -
12634 accepted_positions.segment(drift_offset,
12635 drift_dof))
12636 .norm()
12637 << " certified_step="
12638 << (path.image(max_drift_image).positions -
12639 accepted_positions.segment(drift_offset,
12640 drift_dof))
12641 .norm()
12642 << " raw_nearest=" << nearest_coordinates
12643 << " raw_trust="
12644 << boundary_trust->distanceToTraining(
12645 raw_boundary_positions)
12646 << " clipped=" << query_clipped
12647 << " query_nearest="
12648 << query_nearest_coordinates << " query_trust="
12649 << boundary_trust->distanceToTraining(
12650 query_positions)
12651 << " query_local_duplicate="
12652 << detail::hasPosition(*boundary_observations,
12653 query_positions)
12654 << " query_global_duplicate="
12655 << detail::hasPosition(training_obs,
12656 query_positions)
12657 << " trust_radius=" << trust_threshold
12658 << " trust_rows="
12659 << boundary_observations->R.rows() << std::endl;
12660 }
12661 }
12662 }
12663 band_objective.setPositions(certified_drift_positions);
12664 (void)band_objective.refresh(false);
12665 band_stepper.reset();
12666 kept_certified_drift = true;
12667 inner_exit = "drift";
12668 break;
12669 }
12670 if (!certified || drift_break) {
12671 // drift_break: oracle the high-drift chain image
12672 // directly (the bisected certifier output is only
12673 // relevant when the per-step certifier rejected).
12674 const bool use_rejected_certification_positions =
12675 !drift_break && rejected_certification_positions.size() ==
12676 proposal_positions.size();
12677 // Kernel-stuck stall: an image outside kernel support
12678 // breaks the inner loop at step zero and the trust
12679 // certifier vetoes even its downhill motion, so the
12680 // band cannot relax the image and its stale force
12681 // poisons the energy-max identity and the whole-band
12682 // gate. Acquire at the band's CURRENT geometry (the
12683 // stuck image's live position, a genuinely occupied
12684 // state, not a GP-mean proposal): its own measured
12685 // row restores kernel support and trust coverage
12686 // there, which re-enables motion on the next outer.
12687 const bool kernel_stuck_stall =
12688 drift_break && drift_diagnostic_kernel &&
12689 accepted_inner_steps == 0 && !certified;
12690 // The blocked image owns the outer's acquisition. While
12691 // it sits outside kernel support the whole band is
12692 // frozen, so a row anywhere else cannot change the
12693 // geometry: only support at the blocking image restores
12694 // motion. Publishing it as the accepted-drift priority
12695 // gives it precedence over the certificate arms, whose
12696 // targets are unreachable until the band can move
12697 // again.
12698 if (drift_break && drift_diagnostic_kernel &&
12699 kernel_support_break_image > 0 &&
12700 kernel_support_break_image < path.numImages() - 1) {
12701 accepted_drift_priority_idx = kernel_support_break_image;
12702 accepted_drift_kind =
12703 detail::OieAcceptedDriftKind::PredictionKernelBoundary;
12704 }
12705 Eigen::VectorXd acquisition_positions =
12706 kernel_stuck_stall ? accepted_positions
12707 : use_rejected_certification_positions
12708 ? rejected_certification_positions
12709 : proposal_positions;
12710 // Acquisition rows share the surrogate's trust
12711 // contract: every training row comes from a
12712 // trust-certified position. Clip the rejected or
12713 // drifted proposal onto the outer trust envelope
12714 // before it can become an oracle target. An
12715 // unclipped proposal driven by a broken GP mean
12716 // can sit arbitrarily far outside the data
12717 // (overlapping atoms, keV-scale energies), and a
12718 // single such row is outside anything a
12719 // stationary kernel with one lengthscale can
12720 // represent: the hyperparameter fit flattens the
12721 // model (lengthscales at the bound, posterior ==
12722 // prior) and the outer loop spins without information gain.
12723 if (!kernel_stuck_stall) {
12724 (void)projectProposalToOuterTrust(acquisition_positions);
12725 }
12726 std::vector<double> acquisition_per_image_var(path.numImages(),
12727 0.0);
12728 std::vector<double> acquisition_energy_var(path.numImages(),
12729 0.0);
12730 int acquisition_var_idx = drift_break ? max_drift_image : -1;
12731 {
12732 band_objective.setPositions(acquisition_positions);
12733 if (band_objective.refresh(false)) {
12734 const auto acquisition_variance_probe =
12735 probeChainObservationVariance(
12736 /*force_global_only=*/true);
12737 for (int i = 1; i < path.numImages() - 1; ++i) {
12738 acquisition_energy_var[i] =
12739 acquisition_variance_probe.per_image[i].energy;
12740 acquisition_per_image_var[i] =
12741 detail::observationGradientVarianceTrace(
12742 acquisition_variance_probe.per_image[i]);
12743 }
12744 if (detail::shouldProbeRejectedProposalVariance(
12745 certified, drift_break)) {
12746 acquisition_var_idx =
12747 acquisition_variance_probe.max_gradient_trace
12748 .second;
12749 }
12750 }
12751 }
12752 const double acquisition_noise_floor =
12753 config.restricted_variance_acquisition
12754 ? std::max(0.0, gp.likelihoodNoiseVariance())
12755 : std::max(0.0, gp.getSigma2());
12756 std::vector<char> proposal_eligible(path.numImages(), 0);
12757 std::vector<double> proposal_acquisition_score =
12758 acquisition_per_image_var;
12759 const double variance_scale =
12760 (inner_variance_tolerance > 0.0 &&
12761 std::isfinite(inner_variance_tolerance))
12762 ? inner_variance_tolerance
12763 : 1.0;
12764 const Eigen::Index image_dof = band_objective.imageDof();
12765 for (int i = 1; i < path.numImages() - 1; ++i) {
12766 proposal_eligible[i] =
12767 config.restricted_variance_acquisition
12768 ? (!detail::posteriorVarianceWithinNoiseFloor(
12769 acquisition_energy_var[i],
12770 acquisition_noise_floor)
12771 ? 1
12772 : 0)
12773 : (gpr::numerics::exceedsThreshold(
12774 detail::sanitizePosteriorVariance(
12775 acquisition_energy_var[i]),
12776 acquisition_noise_floor)
12777 ? 1
12778 : 0);
12779 double variance_margin = detail::sanitizePosteriorVariance(
12780 acquisition_per_image_var[i]) /
12781 variance_scale;
12782 double trust_margin = 0.0;
12783 const Eigen::Index offset =
12784 static_cast<Eigen::Index>(i - 1) * image_dof;
12785 if (image_dof > 0 &&
12786 offset + image_dof <= acquisition_positions.size()) {
12787 const Eigen::VectorXd proposal_image_positions =
12788 acquisition_positions.segment(offset, image_dof);
12789 const gpr::Observation* trust_obs = &training_obs;
12790 const gpr::TrustRadius* trust_model = &trust;
12791 if (session && localEligible(i) &&
12792 i < static_cast<int>(
12793 session->image_models.size())) {
12794 const auto& image_obs =
12795 session->image_models[i].observations();
12796 if (image_obs.R.rows() > 0) {
12797 image_trust.setTrainingData(image_obs.R);
12798 trust_obs = &image_obs;
12799 trust_model = &image_trust;
12800 }
12801 }
12802 if (trust_obs->R.rows() == 0) {
12803 trust_margin =
12804 std::numeric_limits<double>::infinity();
12805 } else {
12806 const double distance =
12807 trust_model->distanceToTraining(
12808 proposal_image_positions);
12809 if (std::isfinite(distance)) {
12810 trust_margin = (trust_threshold > 0.0)
12811 ? distance / trust_threshold
12812 : distance;
12813 }
12814 }
12815 }
12816 proposal_acquisition_score[i] =
12817 std::max(variance_margin, trust_margin);
12818 }
12819 detail::ProposalAcquisitionTarget inner_rejected_target;
12820 if (config.restricted_variance_acquisition) {
12821 inner_rejected_target =
12822 detail::selectRestrictedVarianceAcquisitionTarget(
12823 acquisition_positions, band_objective.imageDof(),
12824 acquisition_energy_var, acquisition_noise_floor,
12825 training_obs);
12826 }
12827 if (!inner_rejected_target) {
12828 inner_rejected_target =
12829 detail::selectRejectedProposalAcquisitionTarget(
12830 acquisition_positions, band_objective.imageDof(),
12831 proposal_acquisition_score, proposal_eligible,
12832 training_obs,
12833 adjacent_mep_recovery_active
12834 ? adjacent_mep_recovery.targetImage()
12835 : acquisition_var_idx);
12836 }
12837 if (!rejected_proposal_acquisition) {
12838 rejected_proposal_acquisition =
12839 std::move(inner_rejected_target);
12840 }
12841 // A kernel-support break on the first step names the
12842 // image that blocks the band; the point just past its
12843 // boundary is the measurement, ahead of any score-ranked
12844 // target (plain 15_hocl: kernel break at image 8 every
12845 // outer, no target; irc 11_trans_butadiene ocineb: break
12846 // at image 12 while the score picked image 1 off-band for
12847 // 950 outers and 1053 calls).
12848 if (drift_break && drift_diagnostic_kernel &&
12849 accepted_inner_steps == 0 && max_drift_image > 0 &&
12850 max_drift_image < path.numImages() - 1) {
12851 const Eigen::Index dof = band_objective.imageDof();
12852 const Eigen::Index off =
12853 static_cast<Eigen::Index>(max_drift_image - 1) * dof;
12854 if (dof > 0 && proposal_positions.size() >= off + dof) {
12855 const Eigen::VectorXd boundary_point =
12856 proposal_positions.segment(off, dof);
12857 if (boundary_point.allFinite() &&
12858 !detail::hasPosition(training_obs,
12859 boundary_point)) {
12860 rejected_proposal_acquisition.image_index =
12861 max_drift_image;
12862 rejected_proposal_acquisition.positions =
12863 boundary_point;
12864 }
12865 }
12866 }
12867 // A failed proposal remains outside the accepted band.
12868 band_objective.setPositions(accepted_positions);
12869 (void)band_objective.refresh(false);
12870 band_stepper.reset();
12871 inner_exit = drift_break ? "drift" : "trust_cert";
12872 break;
12873 }
12874 ++accepted_inner_steps;
12875 if (config.acquisition == AcquisitionType::ExpectedImprovement) {
12876 const std::vector<double> ei_energy_variance =
12877 computeGlobalEnergyVariances();
12878 gpr::PhaseTimers::notePeak("after_variance");
12879 std::vector<double> ei_energy(
12880 path.numImages(), std::numeric_limits<double>::quiet_NaN());
12881 std::vector<double> ei_var(path.numImages(), 0.0);
12882 std::vector<char> ei_eligible(path.numImages(), 0);
12883 const double ei_noise = std::max(0.0, gp.getSigma2());
12884 for (int i = 1; i < path.numImages() - 1; ++i) {
12885 ei_energy[i] = path.image(i).energy;
12886 ei_var[i] = ei_energy_variance[static_cast<std::size_t>(i)];
12887 ei_eligible[i] =
12888 !detail::hasPosition(training_obs,
12889 path.image(i).positions) &&
12891 detail::sanitizePosteriorVariance(ei_var[i]),
12892 ei_noise);
12893 }
12894 const int ei_img = detail::selectExpectedImprovementImage(
12895 ei_energy, ei_var, ei_eligible);
12896 double ei_score = 0.0;
12897 if (ei_img > 0 && ei_img < path.numImages() - 1) {
12898 double mu_best = -std::numeric_limits<double>::infinity();
12899 for (int i = 1; i < path.numImages() - 1; ++i) {
12900 if (gpr::numerics::clearlyGreater(ei_energy[i],
12901 mu_best)) {
12902 mu_best = ei_energy[i];
12903 }
12904 }
12905 ei_score = detail::expectedImprovementScore(
12906 ei_energy[ei_img], mu_best,
12907 std::sqrt(std::max(0.0, ei_var[ei_img])));
12908 }
12909 if (detail::shouldStopOieInnerForExpectedImprovement(
12910 accepted_inner_steps, ei_img, ei_score,
12911 uncertainty_threshold)) {
12912 ei_acquisition_image = ei_img;
12913 inner_exit = "ei";
12914 break;
12915 }
12916 }
12917 }
12918 inner_wall.stop();
12919 if (wall_clock_stopped) break;
12920 if (config.verbose && log_rank == 0) {
12921 // Inner-phase exit trace: what the surrogate relaxation saw
12922 // when it stopped, so a zero step or a stalled image is
12923 // attributable to the force it was handed, the images it was
12924 // allowed to move, or the engine state.
12925 const Eigen::VectorXd exit_force = band_objective.force();
12926 const auto& active = band_objective.activeImages();
12927 int inactive = 0;
12928 for (int i = 1; i < path.numImages() - 1; ++i) {
12929 if (i < static_cast<int>(active.size()) && !active[i])
12930 ++inactive;
12931 }
12932 int max_force_image = -1;
12933 double max_force = 0.0;
12934 for (int i = 1; i < path.numImages() - 1; ++i) {
12935 const double f = path.nebForce(i).lpNorm<Eigen::Infinity>();
12936 if (std::isfinite(f) && f > max_force) {
12937 max_force = f;
12938 max_force_image = i;
12939 }
12940 }
12941 gpr::PhaseTimers::notePeak("after_inner");
12942 neb_log() << "[inner-exit] outer=" << outer
12943 << " exit=" << inner_exit << " inner=" << inner
12944 << " accepted=" << accepted_inner_steps << " force_inf="
12945 << (exit_force.size() > 0
12946 ? exit_force.lpNorm<Eigen::Infinity>()
12947 : std::numeric_limits<double>::quiet_NaN())
12948 << " max_force_image=" << max_force_image
12949 << " max_force=" << max_force << " inactive=" << inactive
12950 << " engine_iter=" << band_stepper.iteration()
12951 << " max_step=" << band_max_step
12952 << " drift_kernel=" << drift_diagnostic_kernel
12953 << " drift_radius=" << drift_diagnostic_radius
12954 << " drift_cycle=" << drift_diagnostic_cycle
12955 << " drift_priority=" << accepted_drift_priority_idx
12956 << " drift_kind=" << static_cast<int>(accepted_drift_kind)
12957 << std::endl;
12958 }
12959 if (adjacent_mep_recovery_active && !held_boundary_acquisition &&
12960 !adjacent_mep_recovery.hasPendingTrial() &&
12961 adjacent_mep_recovery.stageTrial(path)) {
12962 rejected_proposal_acquisition.image_index =
12963 adjacent_mep_recovery.targetImage();
12964 rejected_proposal_acquisition.positions =
12965 adjacent_mep_recovery.pendingTrialPosition();
12966 // Only the target returns to its measured source while its
12967 // trial is measured; the rest of the interior keeps the
12968 // surrogate relaxation it just made, so a climbing image
12969 // that still carries force is not held still by the probe.
12970 (void)adjacent_mep_recovery.restoreTargetSource(path);
12971 accepted_drift_priority_idx = -1;
12972 inner_exit = "mep_trial";
12973 }
12974 // True-force anchor update: the anchor moves ONLY to a band
12975 // whose forces are oracle-measured at every interior image
12976 // and whose true max NEB force strictly beats the anchor's.
12977 // Surrogate claims never move it -- a GP-converged fixed
12978 // point on a wrong surface installed a collapsed band as the
12979 // anchor once (fast01 Baker 01), and GP-force reverts before
12980 // that anchored torn states. The frozen sweeps and full-band
12981 // confirmations produce exactly the fully-true states this
12982 // update consumes.
12983 const bool measured_anchor_improved_before_refit =
12984 updateMeasuredAnchor();
12985 // GP force on the band after the inner relaxation (MATLAB
12986 // normF_R_ae before the oracle eval). Captured here, before
12987 // the oracle + retrain perturbs the GP, so the freeze
12988 // decision tests the relaxed surrogate band rather than the
12989 // post-retrain jump. Stale (carried from the prior round)
12990 // during a frozen sweep, where the inner loop is skipped and
12991 // this value is not consulted.
12992 const double relaxed_gp_force = relaxation_inner;
12993 const bool retain_restart_snapshot =
12994 detail::shouldRetainOieRestartSnapshot(
12995 ci_active, inner_exit, accepted_inner_steps, relaxed_gp_force,
12996 measured_reparam_restart_protected);
12997 if (!ci_active && retain_restart_snapshot) {
12998 latest_equal_positions = snapshotPathPositions();
12999 have_latest_equal_positions = true;
13000 }
13001 if (ci_active && retain_restart_snapshot) {
13002 recordLatestClimbRestartSnapshot(
13003 detail::selectOieClimbingImageIndex(ci_active, path),
13004 std::strcmp(inner_exit, "drift") == 0);
13005 }
13006
13007 // ---- Pick worst image, oracle-eval, retrain -----------------
13008 //
13009 // Compute per-image GP posterior variance, then derive
13010 // triplet-aggregated variance for the acquisition:
13011 // var_triplet(i) = var(i-1) + var(i) + var(i+1)
13012 // (endpoints contribute 0 since they are evaluated)
13013 // The Phase-1 picker chooses argmax var_triplet, which
13014 // sends the oracle to the image whose neighbourhood is
13015 // most uncertain rather than the single most-uncertain
13016 // point. Reduces "lonely spike" oracle waste: a tall
13017 // single-point variance with low-variance neighbours
13018 // is usually a numerical artefact; a triplet-wide
13019 // variance plateau is a genuine GP weakness.
13020 // max_chain_var (= max single-point variance) is still
13021 // used as the Phase-1/2 transition signal and unc-
13022 // convergence gate -- those criteria are about absolute
13023 // confidence, not relative.
13024 double max_chain_var = 0.0;
13025 int max_var_idx = 1;
13026 const int n_im = path.numImages();
13027 double selected_imspe_score = std::numeric_limits<double>::quiet_NaN();
13028 double imspe_chain_trace = std::numeric_limits<double>::quiet_NaN();
13029 std::vector<double> per_image_var(n_im, 0.0);
13030 std::vector<double> per_image_gradient_var(n_im, 0.0);
13031 ChainObservationVarianceProbe variance_probe;
13032 const Eigen::VectorXd post_inner_variance_positions =
13033 band_objective.positions();
13034 const bool pre_inner_probe_matches_band =
13035 pre_inner_variance_probe.has_value() &&
13036 pre_inner_variance_positions.size() ==
13037 post_inner_variance_positions.size() &&
13038 (pre_inner_variance_positions.array() ==
13039 post_inner_variance_positions.array())
13040 .all();
13041 if (pre_inner_probe_matches_band) {
13042 variance_probe = std::move(*pre_inner_variance_probe);
13043 } else {
13044 variance_probe = probeChainObservationVariance();
13045 }
13046 // UA-NEB: give the band the surrogate's per-degree-of-freedom force
13047 // variance, so every computeNEBForces below removes the tangent
13048 // component in the Sigma^{-1} metric rather than the Euclidean one.
13049 //
13050 // Outside the branch above on purpose. Placed in the else arm it was
13051 // skipped on exactly the outers that reused the pre-inner probe, so
13052 // the metric applied on some iterations and not others; placed in the
13053 // inner acquisition block it was reachable only when that block ran,
13054 // and the run came out identical with the flag on.
13055 //
13056 // The metric is refreshed once per outer and held through the inner
13057 // relaxation while the band moves, so it is the uncertainty at the
13058 // start of the iteration rather than at the current geometry. That is
13059 // the same bargain a trust region makes, and it keeps the projection
13060 // off the inner loop's cost.
13061 if (config.uncertainty_aware_projection) {
13062 for (int ua = 1; ua < path.numImages() - 1; ++ua) {
13063 const Eigen::VectorXd& gvar =
13064 variance_probe.per_image[static_cast<std::size_t>(ua)]
13065 .gradient;
13066 if (gvar.size() == path.image(ua).positions.size()) {
13067 path.setForceVariance(ua, gvar);
13068 }
13069 }
13070 path.computeNEBForces();
13071 }
13072 for (int i = 1; i < n_im - 1; ++i) {
13073 per_image_var[i] = variance_probe.per_image[i].energy;
13074 per_image_gradient_var[i] =
13075 detail::observationGradientVarianceTrace(
13076 variance_probe.per_image[i]);
13077 }
13078 max_chain_var = variance_probe.max_energy.first;
13079 max_var_idx = variance_probe.max_energy.second;
13080 const std::vector<char> current_band_observed =
13081 currentBandObservationMask();
13082 const auto joint_readiness = detail::assessOieBandPosteriorReadiness(
13083 variance_probe.force_certification_per_image, uncertainty_threshold,
13084 detail::effectiveModelNoiseTolerance(config),
13085 gp.getPhysicalTotalDiagonalRegularization(), current_band_observed);
13086 const auto reported_joint_readiness =
13087 detail::assessOieBandPosteriorReadiness(
13088 variance_probe.per_image, uncertainty_threshold,
13089 detail::effectiveModelNoiseTolerance(config),
13091 current_band_observed);
13092 auto imageLocalTrustDistance = [&](int image_idx,
13093 const Eigen::VectorXd& positions) {
13094 const gpr::Observation* trust_obs = &training_obs;
13095 const gpr::TrustRadius* trust_model = &trust;
13096 if (session && localEligible(image_idx) &&
13097 image_idx < static_cast<int>(session->image_models.size())) {
13098 const auto& image_obs =
13099 session->image_models[image_idx].observations();
13100 if (image_obs.R.rows() > 0) {
13101 image_trust.setTrainingData(image_obs.R);
13102 trust_obs = &image_obs;
13103 trust_model = &image_trust;
13104 }
13105 }
13106 if (detail::hasPosition(*trust_obs, positions)) return 0.0;
13107 if (trust_obs->R.rows() == 0 ||
13108 trust_obs->R.cols() != positions.size()) {
13109 return std::numeric_limits<double>::infinity();
13110 }
13111 return trust_model->distanceToTraining(positions);
13112 };
13113 auto candidatePosteriorVariance =
13114 [&](int image_idx, const Eigen::VectorXd& positions) {
13115 gpr::Observation probe;
13116 probe.R.resize(1, positions.size());
13117 probe.R.row(0) = positions.transpose();
13118 if (session) {
13119 session->observationVarianceAtImage(image_idx, probe);
13120 } else {
13122 }
13123 if (probe.E.rows() == 0 || probe.E.cols() == 0) {
13124 return std::numeric_limits<double>::infinity();
13125 }
13126 const double variance = probe.E(0, 0);
13127 return variance >= 0.0 && std::isfinite(variance)
13128 ? variance
13129 : std::numeric_limits<double>::infinity();
13130 };
13131 auto fixedPointProposalSupport = [&]() {
13132 std::vector<detail::ReparametrizationSupportMetric> support = {
13133 {trust_threshold, imageLocalTrustDistance},
13134 };
13135 if (uncertainty_threshold > 0.0 &&
13136 std::isfinite(uncertainty_threshold)) {
13137 support.push_back(
13138 {uncertainty_threshold, candidatePosteriorVariance});
13139 }
13140 return support;
13141 };
13142 auto selectFixedPointProposalTarget =
13143 [&](const std::vector<Eigen::VectorXd>& proposed_positions,
13144 int preferred_image, int climbing_image = -1) {
13145 const auto support = fixedPointProposalSupport();
13146 return detail::selectUnobservedBandProposalTarget(
13147 proposed_positions, preferred_image, support,
13148 [&](int i, const Eigen::VectorXd& positions) {
13149 return (climbing_image > 0 &&
13150 std::abs(i - climbing_image) > 1) ||
13151 !oracleGeometryAdmissible(positions) ||
13152 detail::hasPosition(training_obs, positions);
13153 });
13154 };
13155 auto fixedPointTpePreferredImage = [&]() {
13156 if (config.acquisition != AcquisitionType::TPE) return -1;
13157 std::vector<double> energies(path.numImages(), 0.0);
13158 std::vector<double> force_norm(path.numImages(), 0.0);
13159 for (int i = 0; i < path.numImages(); ++i) {
13160 energies[static_cast<std::size_t>(i)] = path.image(i).energy;
13161 if (i > 0 && i < path.numImages() - 1) {
13162 force_norm[static_cast<std::size_t>(i)] =
13163 path.nebForceMagnitude(i);
13164 }
13165 }
13166 return oie::selectTpeOracleTarget(
13167 energies, per_image_var, force_norm,
13168 per_image_gradient_var,
13169 outer + 1 + config.acquisition_seed_offset)
13170 .image_index;
13171 };
13172 if (pending_fixed_point.active()) {
13173 pending_fixed_point.acquisition = selectFixedPointProposalTarget(
13174 pending_fixed_point.candidate_positions,
13175 fixedPointTpePreferredImage(),
13176 pending_fixed_point.climbing_image);
13177 // An empty fixed-point selection must not erase a target the
13178 // inner phase staged (the support-boundary point): that is
13179 // the new information the campaign is looking for.
13180 if (pending_fixed_point.acquisition ||
13181 !rejected_proposal_acquisition) {
13182 rejected_proposal_acquisition = pending_fixed_point.acquisition;
13183 }
13184 if (config.verbose && log_rank == 0) {
13185 neb_log() << "[fixed-point] outer=" << outer << " selection="
13186 << pending_fixed_point.acquisition.image_index
13187 << " rejected_target="
13188 << rejected_proposal_acquisition.image_index
13189 << std::endl;
13190 }
13191 }
13192 const bool variance_exceeded = classic_oie_relaxation
13193 ? !joint_readiness.force_resolved
13194 : !joint_readiness.resolved();
13195 {
13196 // Phase 1 acquisition dispatch. config.acquisition
13197 // picks the interior image to oracle next:
13198 // MaxVariance scores per-image force variance;
13199 // IMSPE scores the joint-observation force-trace
13200 // reduction from calculateObservationPosteriorCovariance;
13201 // EI scores (mu - mu_best) Phi(z) + sigma phi(z);
13202 // unresolved PSBAX uses the joint-readiness deficit;
13203 // every other arm uses UCB, F_NEB + kappa * sigma_F
13204 // on the image triplet (tangent/spring stencil).
13205 std::vector<double> acquisition_score(
13206 n_im, -std::numeric_limits<double>::infinity());
13207 std::vector<char> acquisition_eligible(n_im, 0);
13208 std::vector<Eigen::VectorXd> acquisition_positions(n_im);
13209 for (int i = 1; i < n_im - 1; ++i) {
13210 acquisition_eligible[i] = 1;
13211 acquisition_positions[i] = path.image(i).positions;
13212 }
13213 double best_score = -std::numeric_limits<double>::infinity();
13214 const double kappa = config.ucb_kappa;
13215 const double sigma_n_sq =
13216 std::max(0.0, gp.getLikGaussian().getSigma2());
13217 if (config.acquisition == AcquisitionType::PSBAX &&
13218 !joint_readiness.resolved()) {
13219 acquisition_score = joint_readiness.per_image_deficit;
13220 max_var_idx = joint_readiness.acquisition_image;
13221 } else if (config.acquisition == AcquisitionType::MaxVariance) {
13222 for (int i = 1; i < n_im - 1; ++i) {
13223 const double score = per_image_gradient_var[i];
13224 acquisition_score[i] = score;
13225 if (gpr::numerics::clearlyGreater(score, best_score)) {
13226 best_score = score;
13227 max_var_idx = i;
13228 }
13229 }
13230 } else if (config.acquisition == AcquisitionType::IMSPE) {
13231 // Exact joint-observation IMSPE acquisition. One oracle
13232 // call conditions every energy and Cartesian-gradient
13233 // channel at its geometry. The score is the force-trace
13234 // reduction from that complete D+1 conditioning block
13235 // over the complete interior-band force posterior.
13236 EigenMatrix chain_pos(n_im - 2, path.image(0).positions.size());
13237 for (int i = 1; i < n_im - 1; ++i) {
13238 chain_pos.row(i - 1) = path.image(i).positions.transpose();
13239 }
13240 // Per-image probes earlier this outer iter may have
13241 // switched the DistributedState's active model away
13242 // from the global GP, leaving its distributed
13243 // Cholesky L at 0x0 (cholesky_distributed pitfall,
13244 // see reference_scalapack_state_pitfalls). Refresh
13245 // the global cache before the IMSPE posterior
13246 // covariance solve to avoid the cache-miss abort.
13247 if (session) {
13248 session->ensureSingletonForGlobal();
13249 }
13250 EigenMatrix K_post;
13251 gp.calculateObservationPosteriorCovariance(chain_pos, K_post);
13252 std::vector<Eigen::Index> target_queries(
13253 static_cast<std::size_t>(chain_pos.rows()));
13254 std::iota(target_queries.begin(), target_queries.end(),
13255 Eigen::Index{0});
13256 for (int i = 1; i < n_im - 1; ++i) {
13257 const Eigen::Index ki = i - 1;
13258 const auto reduction =
13260 K_post, chain_pos.rows(), chain_pos.cols(), ki,
13261 target_queries, sigma_n_sq);
13262 if (!reduction) {
13263 continue;
13264 }
13265 imspe_chain_trace = reduction->target_variance;
13266 const double score = reduction->variance_reduction;
13267 acquisition_score[i] = score;
13268 if (gpr::numerics::clearlyGreater(score, best_score)) {
13269 best_score = score;
13270 max_var_idx = i;
13271 }
13272 }
13273 } else if (config.acquisition ==
13274 AcquisitionType::ExpectedImprovement) {
13275 // EI(i) = (mu_i - mu_best) * Phi(z_i)
13276 // + sigma_i * phi(z_i)
13277 // z_i = (mu_i - mu_best) / sigma_i.
13278 // mu_i = path.image(i).energy (post-inner-relax GP
13279 // posterior mean); mu_best = max over chain.
13280 double mu_best = -std::numeric_limits<double>::infinity();
13281 for (int i = 1; i < n_im - 1; ++i) {
13282 if (gpr::numerics::clearlyGreater(path.image(i).energy,
13283 mu_best))
13284 mu_best = path.image(i).energy;
13285 }
13286 for (int i = 1; i < n_im - 1; ++i) {
13287 const double mu = path.image(i).energy;
13288 const double sigma =
13289 std::sqrt(std::max(0.0, per_image_var[i]));
13290 const double score =
13291 detail::expectedImprovementScore(mu, mu_best, sigma);
13292 acquisition_score[i] = score;
13293 if (gpr::numerics::clearlyGreater(score, best_score)) {
13294 best_score = score;
13295 max_var_idx = i;
13296 }
13297 }
13298 } else {
13299 // Default UCB: F_NEB(i) + kappa * sigma_F,triplet(i).
13300 // The exploitation term is a force (eV/A), so the
13301 // exploration term must be a FORCE standard deviation;
13302 // adding sqrt(energy variance) (eV) mixed dimensions
13303 // and mis-weighted exploration by the energy scale.
13304 for (int i = 1; i < n_im - 1; ++i) {
13305 const double v_minus =
13306 (i - 1 >= 1) ? per_image_gradient_var[i - 1] : 0.0;
13307 const double v_plus = (i + 1 <= n_im - 2)
13308 ? per_image_gradient_var[i + 1]
13309 : 0.0;
13310 const double v_triplet =
13311 per_image_gradient_var[i] + v_minus + v_plus;
13312 const double f_neb = path.nebForceMagnitude(i);
13313 const double score =
13314 f_neb + kappa * std::sqrt(std::max(0.0, v_triplet));
13315 acquisition_score[i] = score;
13316 if (gpr::numerics::clearlyGreater(score, best_score)) {
13317 best_score = score;
13318 max_var_idx = i;
13319 }
13320 }
13321 }
13322 if (variance_exceeded && max_var_idx <= 0 &&
13323 config.acquisition != AcquisitionType::PSBAX) {
13324 max_var_idx = variance_probe.max_energy.second;
13325 }
13326 max_var_idx = detail::selectUnobservedAcquisitionIndex(
13327 acquisition_score, acquisition_eligible, acquisition_positions,
13328 training_obs, max_var_idx);
13329 if (config.acquisition == AcquisitionType::IMSPE &&
13330 max_var_idx > 0 && max_var_idx < n_im) {
13331 selected_imspe_score = acquisition_score[max_var_idx];
13332 }
13333 }
13334 // Phase 1 -> Phase 2 (CI activation): before activation the
13335 // GP-energy maximum is the CI candidate. During active CI
13336 // refinement, a candidate image must posterior-dominate the
13337 // latched arm before it becomes the climbing image.
13338 // The climbing-image candidate is the GP posterior-mean energy
13339 // maximum: the predicted saddle image. The acquisition
13340 // confirms it on the true PES every outer iteration; once
13341 // confirmed it enters the evaluated set and the climbing
13342 // marker (highest evaluated energy) climbs it. Keeping the
13343 // candidate on the predicted peak (rather than on the
13344 // evaluated-energy marker) is what feeds the saddle estimate
13345 // into the oracle data on a flat saddle region, where the
13346 // marker would otherwise lag in a lower-energy evaluated
13347 // image and the peak would stay confidently predicted but
13348 // never confirmed.
13349 // The candidate is the strict local maximum. A higher shoulder
13350 // that is not strict would move the climb off the seeded
13351 // coordinate and add oracle calls on a band that had already
13352 // settled. highestEnergyImageIndex remains the global maximum.
13353 const int prev_ci = [&]() {
13354 for (int i = 1; i < path.numImages() - 1; ++i) {
13355 if (path.image(i).is_climbing) return i;
13356 }
13357 return -1;
13358 }();
13359 // An image held at its measured source by the adjacent-MEP recovery
13360 // carries a measured perpendicular force above the climbing image's
13361 // residual (the recovery's arming condition): it lies off the MEP,
13362 // so its energy includes the perpendicular excess and is no
13363 // estimate of a higher point on the path. It cannot be the climbing
13364 // candidate until its trial moves it. 19_hnccs: image 15 held at
13365 // 6 eV/A outranked the climbing image by 0.01 eV, took the marker
13366 // through a handover stencil, and the measurement of its trial was
13367 // displaced by handovers 14 -> 15 -> 13 -> 14 for 12 outers.
13368 const int ci_candidate_idx = [&]() {
13369 if (!(ci_active && prev_ci > 0))
13370 return path.highestLocalMaximumImageIndex();
13371 const int candidate =
13372 path.highestLocalMaximumImageIndexPreferring(prev_ci);
13373 const bool candidate_held_off_path =
13374 candidate != prev_ci &&
13375 adjacent_mep_recovery.targetImage() == candidate &&
13376 adjacent_mep_recovery.ciIndex() == prev_ci;
13377 return candidate_held_off_path ? prev_ci : candidate;
13378 }();
13379 const double ci_candidate_gp_force =
13380 (ci_candidate_idx > 0 && ci_candidate_idx < path.numImages() - 1)
13381 ? path.nebForceMagnitude(ci_candidate_idx)
13382 : std::numeric_limits<double>::infinity();
13383 std::vector<char> image_evaluated(path.numImages(), 0);
13384 std::vector<char> image_observed_current(path.numImages(), 0);
13385 std::vector<char> image_posterior_certified_current(path.numImages(),
13386 0);
13387 const detail::OieClimbingEnergyChange climb_change =
13388 [&](const NEBPath& band, int image_idx) {
13389 return session ? detail::oieClimbingStepEnergyChange(
13390 band, image_idx, *session,
13392 atoms_config.cell),
13393 band_max_step)
13394 : std::numeric_limits<double>::quiet_NaN();
13395 };
13396 auto current_observation_state =
13397 detail::restoreOieCurrentObservationsAndMarker(
13398 training_obs, path, ci_active, ci_candidate_idx,
13399 certified_ci_idx_at_outer_start, per_image_var,
13400 config.ucb_kappa, uncertainty_threshold, image_observed_current,
13401 image_evaluated,
13402 /*require_true_handover_certificate=*/true,
13403 protected_oie_ci_idx, climb_change);
13404 std::vector<char> image_acquisition_unavailable(path.numImages(), 0);
13405 for (int i = 1; i < path.numImages() - 1; ++i) {
13406 image_acquisition_unavailable[i] =
13407 oracleGeometryRefused(path.image(i).positions);
13408 }
13409 int ci_idx = current_observation_state.ci_idx;
13410 if (protected_oie_ci_idx < 1 && session &&
13411 detail::activateOracleTransitionFocalClimbingImage(
13412 config, path, *session, outer)) {
13413 ci_active = true;
13414 ci_idx = config.oracle_transition_focal_image;
13415 }
13416 if (session) {
13417 // Whole-chain max energy variance for MMF noise-floor
13418 // exhaustion. Do NOT restrict to unobserved images: when
13419 // every interior is observed, selectable_max was 0 and
13420 // falsely certified noise-floor exhaustion every outer
13421 // (Baker 01 arm=none freeze: 16+ identical MMF rejects).
13422 double chain_max = 0.0;
13423 bool any_var = false;
13424 for (int i = 1; i < path.numImages() - 1; ++i) {
13425 if (i >= static_cast<int>(per_image_var.size())) break;
13426 const double v =
13427 detail::sanitizePosteriorVariance(per_image_var[i]);
13428 if (!std::isfinite(v) || v < 0.0) continue;
13429 any_var = true;
13430 chain_max = std::max(chain_max, v);
13431 }
13432 session->last_max_chain_energy_variance =
13433 any_var ? chain_max : std::numeric_limits<double>::quiet_NaN();
13434 }
13435 const double current_true_activation_force =
13436 detail::oieCurrentTrueForceCertificate(path, image_evaluated,
13437 image_observed_current);
13438 const double ci_candidate_variance =
13439 ci_candidate_idx >= 0 &&
13440 ci_candidate_idx < static_cast<int>(per_image_var.size())
13441 ? per_image_var[ci_candidate_idx]
13442 : std::numeric_limits<double>::infinity();
13443 const bool ci_band_force_gate_ready =
13444 ci_active ||
13445 detail::shouldActivateClimbingImage(
13446 config, /*ci_active=*/false, outer, relaxation_inner,
13447 f0_baseline, ci_candidate_variance);
13448 const auto activation_state = detail::updateOieClimbingImageActivation(
13449 config, path, ci_active, per_image_var, config.ucb_kappa,
13450 uncertainty_threshold,
13451 protected_oie_ci_idx > 0 ? protected_oie_ci_idx
13452 : transition_focal_handoff ? config.oracle_transition_focal_image
13453 : -1,
13454 ci_band_force_gate_ready);
13455 ci_active = activation_state.ci_active;
13456 ci_idx = activation_state.ci_idx;
13457
13458 // Acquisition. worst_idx is chosen from the frozen sweep,
13459 // trust-certified rejected proposal, or Phase-1 acquisition
13460 // target.
13461 // Three-phase acquisition dispatch. Phase 1 (exploration):
13462 // pick argmax IMSPE score (the image whose oracle evaluation
13463 // maximally reduces summed chain posterior variance, R&W
13464 // sec. 5.4.2 via joint observation covariance). Phase 2
13465 // (climbing image): oracle the highest-energy image to drive
13466 // saddle convergence. Phase 3 (dimer): handed off via
13467 // outer_iter_hook once the dimer reports converged.
13468 //
13469 // Per-image local GPs inside refreshGpPath deliver inner-loop
13470 // prediction; predictAtImage falls back to the global GP when
13471 // an image has fewer than min_per_image_n_train neighborhood
13472 // rows. EMD k-nearest neighbourhood keeps each bead's
13473 // training set close to evaluated points, preventing
13474 // extrapolation.
13475 // Canonical OIE acquisition (Koistinen 2017 / Koistinen 2019
13476 // atomic_GP_NEB_OIE.m; Garrido-Torres 2019 CatLearn AcqUME).
13477 // One oracle evaluation per outer iteration. The image chosen
13478 // depends on the regime:
13479 //
13480 // EXPLORE: the acquisition pick max_var_idx (max posterior
13481 // energy variance for the MaxVar baseline; the IMSPE / EI /
13482 // UCB score when those opt-in modes are selected). The inner
13483 // relaxation has just moved every image, so every image is
13484 // un-evaluated and max_var_idx is the right target.
13485 //
13486 // SWEEP: confirm remaining un-evaluated images on the true
13487 // PES. The climbing image goes first (Koistinen eval_next_CI
13488 // override) so the saddle is checked before its neighbours;
13489 // then descending posterior energy variance over images that
13490 // still lack a true evaluation at their current geometry.
13491 //
13492 // The oracle-data mask spreads the oracle across the chain. In
13493 // sweep mode, every CI image is confirmed on the true PES while
13494 // ordinary images either carry a true gradient or satisfy the
13495 // same scale-free force/variance certificate used by the selector.
13496 int secondary_idx = -1; // canonical OIE: one oracle per round
13497 for (int i = 0; i < path.numImages(); ++i) {
13498 const double variance =
13499 i < static_cast<int>(per_image_var.size())
13500 ? per_image_var[i]
13501 : std::numeric_limits<double>::infinity();
13502 const double force = (i > 0 && i < path.numImages() - 1)
13503 ? path.nebForceMagnitude(i)
13504 : std::numeric_limits<double>::infinity();
13505 if (detail::posteriorCertifiesCurrentImage(
13506 ci_active, ci_idx, i, force, variance,
13507 uncertainty_threshold, config.conv_tol)) {
13508 image_posterior_certified_current[i] = 1;
13509 }
13510 // Publish the posterior variance onto the image so the OCINEB
13511 // dimer-handover gate can read the GP's confidence at the
13512 // climbing image directly (replaces an iteration counter).
13513 path.image(i).posterior_variance = variance;
13514 }
13515 path.setPosteriorVarianceThreshold(uncertainty_threshold);
13516 // Anchor the activation/CI-handoff oracle on the CI candidate (the
13517 // energy-peak triplet whose peak-1/peak/peak+1 images gate climbing
13518 // image activation). The activation triplet must keep oracling this
13519 // triplet so the peak variance drops and the peak becomes
13520 // posterior-confident; diverting it to the acquisition pick is
13521 // self-reinforcing and starves CI activation on the systems that
13522 // converge via CI.
13523 // Same observation predicate as the pre-inner stencil gate
13524 // (currentBandObservationMask: a stored row at this exact position,
13525 // or a position the session's resolution gate would refuse to
13526 // store). The per-image evaluated/observed flags can disagree with
13527 // it (a flag survives a GP-side refresh; the mask does not), and a
13528 // gate that blocks the inner loop on one predicate while the selector
13529 // buys on another has no fixed point (ioykB 09_parentdielsalder:
13530 // 300 outers at arm=none, calls frozen at 16).
13531 const std::vector<char> activation_observation_mask =
13532 !ci_active ? currentBandObservationMask() : std::vector<char>{};
13533 const auto ci_activation_triplet_targets =
13534 !ci_active ? detail::selectOieActivationTripletOracleTargets(
13535 ci_candidate_idx, path.numImages(),
13536 activation_observation_mask,
13537 activation_observation_mask, per_image_var)
13538 : std::vector<int>{};
13539 const int ci_activation_triplet_idx =
13540 ci_activation_triplet_targets.empty()
13541 ? -1
13542 : ci_activation_triplet_targets.front();
13543 // The activation stencil is binding: while a triplet member reads
13544 // unobserved the inner relaxation is skipped
13545 // (activation_stencil_pending
13546 // -> shouldSkipOieInnerForPendingAcquisition), so the only action that
13547 // changes the outer state is to buy that member. The eOn-style
13548 // activation-force rule alone left the selector at -1 whenever the
13549 // stencil was pending but the force rule was quiet, and the outer map
13550 // became the identity (HEAD Baker board: every cell spent 1000 outers
13551 // at arm=none with zero oracle calls). Buying the stencil member
13552 // terminates: each purchase converts one unobserved member to observed,
13553 // and a triplet has three.
13554 const bool ci_activation_stencil_needs_oracle =
13555 !ci_active && ci_activation_triplet_idx > 0;
13556 const bool ci_activation_needs_oracle =
13557 ci_activation_stencil_needs_oracle ||
13558 detail::shouldSampleCurrentChainForCiActivation(
13559 config, ci_active, outer, current_true_activation_force,
13560 f0_baseline);
13561 const int ci_activation_priority_idx = [&]() {
13562 if (ci_activation_triplet_idx > 0) return ci_activation_triplet_idx;
13563 // Without a predicted barrier, the energy maximum can be an
13564 // arbitrary image on a flat prior. Acquire information about
13565 // the path before giving that image the climbing priority.
13566 if (!ci_active && ci_candidate_idx > 0 &&
13567 ci_candidate_idx < path.numImages() - 1 && max_var_idx > 0 &&
13568 max_var_idx < path.numImages() - 1 &&
13569 path.image(ci_candidate_idx).energy <=
13570 std::max(path.image(0).energy,
13571 path.image(path.numImages() - 1).energy)) {
13572 return max_var_idx;
13573 }
13574 return ci_candidate_idx;
13575 }();
13576 const bool valid_current_ci =
13577 ci_active && ci_idx > 0 && ci_idx < path.numImages() - 1;
13578 const double current_ci_gp_force =
13579 valid_current_ci ? path.nebForceMagnitude(ci_idx)
13580 : std::numeric_limits<double>::quiet_NaN();
13581 walk_endpoint_gp_force = current_ci_gp_force;
13582 const bool saddle_handoff_needs_ci_oracle = [&]() {
13583 if (!valid_current_ci) {
13584 return false;
13585 }
13586 bool controller_requests_handoff =
13587 config.outer_iter_hook != nullptr;
13588 if (config.current_ci_oracle_priority) {
13589 controller_requests_handoff = config.current_ci_oracle_priority(
13590 path, ci_idx, outer, current_ci_gp_force);
13591 }
13592 return detail::shouldPrioritizeCurrentCiOracleForOciMmfHandoff(
13593 controller_requests_handoff, ci_active, ci_idx,
13594 path.numImages(), current_ci_gp_force, config.conv_tol,
13595 max_chain_var, uncertainty_threshold);
13596 }();
13597 double ci_certificate_deficit = detail::oieSaddleCertificateDeficit(
13598 ci_candidate_idx, path, per_image_var, config.conv_tol,
13599 uncertainty_threshold);
13600 const bool ci_candidate_posterior_confident =
13601 detail::ciPosteriorConfident(path, ci_candidate_idx,
13602 config.ucb_kappa);
13603 const bool ci_convergence_needs_oracle =
13604 valid_current_ci && config.climbing_image_converged_only &&
13605 ci_candidate_idx == ci_idx && ci_candidate_posterior_confident &&
13606 detail::shouldRequestOieSaddleForceConfirmation(
13607 detail::oieSaddleForceLowerConfidenceBound(
13608 current_ci_gp_force,
13609 ci_candidate_idx >= 0 &&
13610 ci_candidate_idx <
13611 static_cast<int>(per_image_gradient_var.size())
13612 ? per_image_gradient_var[ci_candidate_idx]
13613 : 0.0,
13614 config.ucb_kappa),
13615 detail::effectiveModelNoiseTolerance(config));
13616 const bool ci_candidate_observed =
13617 ci_candidate_idx >= 0 &&
13618 ci_candidate_idx <
13619 static_cast<int>(image_observed_current.size()) &&
13620 image_observed_current[static_cast<std::size_t>(ci_candidate_idx)];
13621 const bool ci_candidate_handover_certified =
13622 detail::hasTrueClimbingImageHandoverCertificate(
13623 path, ci_candidate_idx, ci_active ? ci_idx : -1, climb_change);
13624 const int recovery_candidate_certificate_image =
13625 detail::selectOieRecoveryCandidateCertificateImage(
13626 path.numImages(), fixed_image,
13627 fixed_image_lease.model_growth_required, ci_candidate_idx,
13628 ci_candidate_handover_certified);
13629 std::vector<int> ci_candidate_handover_targets;
13630 // A measured candidate already refuted by its perpendicular residual
13631 // stays refuted whatever its neighbours measure: the stencil would
13632 // buy rows for a handover the measurement has decided against.
13633 const bool ci_candidate_handover_refuted =
13634 ci_active && detail::measuredClimbRefutesHandover(
13635 path, ci_candidate_idx, ci_idx, climb_change);
13636 if (ci_active && ci_candidate_idx != ci_idx &&
13637 (ci_candidate_posterior_confident ||
13638 recovery_candidate_certificate_image == ci_candidate_idx) &&
13639 !ci_candidate_handover_certified &&
13640 !ci_candidate_handover_refuted) {
13641 ci_candidate_handover_targets =
13642 session ? detail::selectOciHandoffCertificateOracleTargets(
13643 ci_candidate_idx, path, *session)
13644 : detail::selectOciHandoffStencilOracleTargets(
13645 ci_candidate_idx, path.numImages(),
13646 image_evaluated, image_observed_current);
13647 }
13648 const bool ci_candidate_handover_needs_oracle =
13649 !ci_candidate_handover_targets.empty();
13650 detail::ProposalAcquisitionTarget recovery_model_growth_target;
13651 std::size_t recovery_growth_candidate_count = 0;
13652 std::size_t recovery_growth_admissible_count = 0;
13653 double recovery_growth_variance =
13654 std::numeric_limits<double>::quiet_NaN();
13655 double recovery_growth_trust_distance =
13656 std::numeric_limits<double>::quiet_NaN();
13657 detail::MeasuredNebStepStatus recovery_proposal_status =
13658 detail::MeasuredNebStepStatus::NotRequested;
13659 int recovery_stencil_measurement_image = -1;
13660 if (detail::shouldAcquireOieOwnerModelGrowth(
13661 fixed_image_lease.model_growth_required) &&
13662 recovery_candidate_certificate_image < 0 && fixed_image > 0 &&
13663 fixed_image < path.numImages() - 1) {
13664 if (session) {
13665 const auto missing_measurements =
13666 detail::selectOciHandoffCertificateOracleTargets(
13667 fixed_image, path, *session);
13668 if (!missing_measurements.empty()) {
13669 recovery_stencil_measurement_image =
13670 missing_measurements.front();
13671 recovery_proposal_status =
13672 detail::MeasuredNebStepStatus::MissingMeasurement;
13673 }
13674 }
13675 const std::vector<Eigen::VectorXd> measured_proposal =
13676 recovery_stencil_measurement_image < 0
13677 ? session ? detail::proposeCertifiedMeasuredNebStep(
13678 path, *session, config, fixed_image,
13679 &recovery_proposal_status)
13680 : detail::proposeCertifiedMeasuredNebStep(
13681 path, training_obs, config, fixed_image,
13682 &recovery_proposal_status)
13683 : std::vector<Eigen::VectorXd>{};
13684 const std::vector<Eigen::VectorXd> isolated_proposal =
13685 detail::isolateBandProposalImage(path, measured_proposal,
13686 fixed_image);
13687 if (!isolated_proposal.empty()) {
13688 gpr::Observation empty_local_observations;
13689 const gpr::Observation* local_observations =
13690 &empty_local_observations;
13691 const gpr::Observation* trust_obs = &training_obs;
13692 const gpr::TrustRadius* trust_model = &trust;
13693 if (session &&
13694 fixed_image <
13695 static_cast<int>(session->image_models.size())) {
13696 const auto& local_obs =
13697 session->image_models[fixed_image].observations();
13698 local_observations = &local_obs;
13699 if (local_obs.R.rows() > 0) {
13700 image_trust.setTrainingData(local_obs.R);
13701 trust_obs = &local_obs;
13702 trust_model = &image_trust;
13703 }
13704 }
13705 if (trust_obs->R.rows() > 0) {
13706 auto candidates = detail::oieRecoveryGrowthCandidates(
13707 path.image(fixed_image).positions,
13708 isolated_proposal[static_cast<std::size_t>(
13709 fixed_image)],
13710 *local_observations);
13711 const int measured_step_index = candidates.empty() ? -1 : 0;
13712 int secant_backtrack_index = -1;
13713 if (recovery_growth_backtrack_target &&
13714 recovery_growth_backtrack_target.image_index ==
13715 fixed_image) {
13716 const auto existing = std::find_if(
13717 candidates.begin(), candidates.end(),
13718 [&](const Eigen::VectorXd& candidate) {
13719 return detail::positionsCoincide(
13720 candidate,
13721 recovery_growth_backtrack_target.positions);
13722 });
13723 if (existing == candidates.end()) {
13724 secant_backtrack_index =
13725 static_cast<int>(candidates.size());
13726 candidates.push_back(
13727 recovery_growth_backtrack_target.positions);
13728 } else {
13729 secant_backtrack_index = static_cast<int>(
13730 std::distance(candidates.begin(), existing));
13731 }
13732 }
13733 recovery_growth_candidate_count = candidates.size();
13734 std::vector<Eigen::VectorXd> admissible_candidates;
13735 std::vector<Eigen::VectorXd> proposed_candidates(
13736 candidates.size());
13737 std::vector<char> admissible(candidates.size(), 0);
13738 std::vector<double> candidate_variances(
13739 candidates.size(),
13740 std::numeric_limits<double>::quiet_NaN());
13741 std::vector<double> candidate_trust_distances(
13742 candidates.size(),
13743 std::numeric_limits<double>::quiet_NaN());
13744 for (std::size_t index = 0; index < candidates.size();
13745 ++index) {
13746 const Eigen::VectorXd& candidate = candidates[index];
13747 Eigen::VectorXd proposed = candidate;
13748 (void)detail::clipImageToOuterTrust(
13749 proposed, *trust_obs, *trust_model,
13750 trust_threshold);
13751 const bool trusted = detail::isImageWithinTrainingTrust(
13752 proposed, *trust_obs, *trust_model,
13753 trust_threshold);
13754 const bool distinct_from_chain =
13755 !detail::positionsCoincide(
13756 proposed, path.image(fixed_image).positions);
13757 const bool duplicate_candidate =
13758 std::any_of(admissible_candidates.begin(),
13759 admissible_candidates.end(),
13760 [&](const Eigen::VectorXd& existing) {
13761 return detail::positionsCoincide(
13762 existing, proposed);
13763 });
13764 if (!trusted || !distinct_from_chain ||
13765 duplicate_candidate ||
13766 detail::hasPosition(training_obs, proposed)) {
13767 continue;
13768 }
13769 const double variance =
13770 candidatePosteriorVariance(fixed_image, proposed);
13771 const double trust_distance =
13772 trust_model->distanceToTraining(proposed);
13773 if (!std::isfinite(variance) ||
13774 !std::isfinite(trust_distance)) {
13775 continue;
13776 }
13777 admissible_candidates.push_back(proposed);
13778 proposed_candidates[index] = std::move(proposed);
13779 admissible[index] = 1;
13780 candidate_variances[index] = variance;
13781 candidate_trust_distances[index] = trust_distance;
13782 ++recovery_growth_admissible_count;
13783 }
13784 const int selected_candidate =
13785 detail::selectOieRecoveryGrowthCandidate(
13786 admissible, candidate_variances,
13787 candidate_trust_distances, measured_step_index,
13788 secant_backtrack_index);
13789 if (selected_candidate >= 0) {
13790 recovery_model_growth_target.image_index = fixed_image;
13791 recovery_model_growth_target.positions =
13792 proposed_candidates[static_cast<std::size_t>(
13793 selected_candidate)];
13794 recovery_growth_variance =
13795 candidate_variances[static_cast<std::size_t>(
13796 selected_candidate)];
13797 recovery_growth_trust_distance =
13798 candidate_trust_distances[static_cast<std::size_t>(
13799 selected_candidate)];
13800 }
13801 if (secant_backtrack_index >= 0 &&
13802 selected_candidate != secant_backtrack_index) {
13803 recovery_growth_backtrack_target.clear();
13804 }
13805 }
13806 }
13807 }
13808 if (ci_active && ci_candidate_idx > 0 &&
13809 ci_candidate_idx < path.numImages() - 1) {
13810 const double candidate_force =
13811 path.nebForceMagnitude(ci_candidate_idx);
13812 const double force_confirmation_tol =
13813 detail::effectiveModelNoiseTolerance(config);
13814 if (detail::shouldRequestOieSaddleForceConfirmation(
13815 candidate_force, force_confirmation_tol)) {
13816 ci_certificate_deficit = std::max(
13817 ci_certificate_deficit,
13818 detail::oieSaddleForceConfirmationDeficit(
13819 ci_candidate_idx, path, force_confirmation_tol));
13820 }
13821 }
13822 const detail::OieChainCertificateTarget current_chain_certificate =
13823 detail::selectCurrentOieChainCertificateTarget(
13824 saddle_handoff_needs_ci_oracle, ci_active ? ci_idx : -1,
13825 config.climbing_image_converged_only, path, per_image_var,
13826 detail::effectiveModelNoiseTolerance(config),
13827 uncertainty_threshold,
13828 adjacent_mep_recovery_active
13829 ? adjacent_mep_recovery.targetImage()
13830 : -1,
13831 adjacent_mep_recovery_active ? adjacent_mep_recovery.deficit()
13832 : 0.0);
13833 const double current_chain_certificate_deficit =
13834 current_chain_certificate.deficit;
13835 const int certificate_chain_priority_idx =
13836 detail::selectCurrentChainPriorityForOieOracle(
13837 ci_active, ci_idx, ci_activation_needs_oracle,
13838 ci_candidate_handover_needs_oracle
13839 ? ci_candidate_handover_targets.front()
13840 : ci_activation_priority_idx,
13841 ci_certificate_deficit, current_chain_certificate_deficit,
13842 saddle_handoff_needs_ci_oracle,
13843 ci_candidate_handover_needs_oracle, ci_convergence_needs_oracle,
13844 current_chain_certificate.image_index,
13845 detail::isAcceptedDriftCurrentChainPriorityPending(
13846 accepted_drift_priority_idx, path.numImages(),
13847 image_evaluated, image_observed_current));
13848 const bool classic_ci_current_row_required =
13849 classic_oie_relaxation && valid_current_ci;
13850 // The held image keys the measurement, not the climbing marker: an
13851 // image without an evaluated energy can lose the marker to a
13852 // neighbour for the outer in which it must be measured.
13853 const bool measured_step_needs_ci_oracle =
13854 measured_step_hold_image > 0 &&
13855 measured_step_hold_image < path.numImages() - 1 &&
13856 !path.image(measured_step_hold_image).evaluated;
13857 const int oracle_chain_priority_idx =
13858 measured_step_needs_ci_oracle ? measured_step_hold_image
13859 : classic_ci_current_row_required ? ci_idx
13860 : certificate_chain_priority_idx;
13861 const int local_recovery_image =
13862 fixed_image_lease.model_growth_required
13863 ? fixed_image
13864 : detail::resolveOieLocalRecoveryImage(
13865 fixed_image, ci_candidate_idx,
13866 ci_candidate_posterior_confident);
13867 const bool local_recovery_owns_replaceable_work =
13868 detail::oieLocalRecoveryOwnsReplaceableWork(
13869 path.numImages(), local_recovery_image, image_evaluated,
13870 image_observed_current);
13871 const bool local_recovery_suppresses_replaceable_work =
13872 detail::oieLocalRecoverySuppressesReplaceableWork(
13873 local_recovery_owns_replaceable_work,
13874 fixed_image_lease.allow_replaceable_acquisition);
13875 const bool local_recovery_acquisition_hold =
13876 local_recovery_suppresses_replaceable_work;
13877 const detail::OieOracleTargetPlanner oracle_target_planner(
13878 path.numImages(), frozen_sweep, ci_active, ci_idx, image_evaluated,
13879 image_observed_current, image_posterior_certified_current,
13880 per_image_var, std::max(0.0, gp.getSigma2()), local_recovery_image,
13881 fixed_image_lease.allow_replaceable_acquisition,
13882 config.climbing_image_converged_only,
13883 image_acquisition_unavailable);
13884 // A held image's boundary query retains ownership while supported
13885 // images relax and propose other acquisitions.
13886 if (held_boundary_acquisition) {
13887 rejected_proposal_acquisition = held_boundary_acquisition;
13888 accepted_drift_priority_idx = held_boundary_acquisition.image_index;
13889 accepted_drift_kind =
13890 detail::OieAcceptedDriftKind::PredictionKernelBoundary;
13891 }
13892 const detail::ProposalAcquisitionTarget no_rejected_action;
13893 const detail::ProposalAcquisitionTarget& planner_rejected_target =
13894 pending_band_action_acquisition ? no_rejected_action
13895 : rejected_proposal_acquisition;
13896 auto local_oracle_decision = oracle_target_planner.selectPriorityTarget(
13897 planner_rejected_target, variance_exceeded, max_var_idx,
13898 oracle_chain_priority_idx,
13899 detail::OieAcceptedDriftTarget{accepted_drift_priority_idx,
13900 accepted_drift_kind},
13901 ci_activation_needs_oracle || saddle_handoff_needs_ci_oracle ||
13902 ci_candidate_handover_needs_oracle ||
13903 ci_convergence_needs_oracle ||
13904 classic_ci_current_row_required ||
13905 measured_step_needs_ci_oracle,
13906 pending_band_action_acquisition);
13907 if (current_band_acquisition_image > 0) {
13908 local_oracle_decision =
13909 oracle_target_planner
13910 .selectRequiredCurrentChainMeasurementTarget(
13911 local_oracle_decision, current_band_acquisition_image,
13912 detail::OieAcceptedDriftTarget{
13913 accepted_drift_priority_idx, accepted_drift_kind});
13914 }
13915 if (recovery_stencil_measurement_image >= 0) {
13916 local_oracle_decision =
13917 oracle_target_planner
13918 .selectRequiredCurrentChainMeasurementTarget(
13919 local_oracle_decision,
13920 recovery_stencil_measurement_image);
13921 } else if (recovery_model_growth_target) {
13922 local_oracle_decision =
13923 oracle_target_planner.selectRecoveryModelGrowthTarget(
13924 local_oracle_decision,
13925 recovery_model_growth_target.image_index);
13926 }
13927 int surrogate_repair_image = -1;
13928 {
13929 const bool measurement_owned =
13930 ci_activation_needs_oracle || saddle_handoff_needs_ci_oracle ||
13931 ci_candidate_handover_needs_oracle ||
13932 ci_convergence_needs_oracle || measured_step_needs_ci_oracle ||
13933 pending_band_action.active() || planner_rejected_target ||
13934 local_recovery_image > 0 ||
13935 recovery_stencil_measurement_image >= 0 ||
13936 recovery_model_growth_target ||
13937 detail::oieGpInnerForceConverged(
13938 ci_active && config.climbing_image_converged_only,
13939 relaxed_gp_force, max_inner, effective_inner_conv_tol,
13940 chain_inner_conv_tol);
13941 const auto before_repair = local_oracle_decision;
13942 local_oracle_decision =
13943 oracle_target_planner.selectSurrogateRepairTarget(
13944 local_oracle_decision, inner_exit, joint_readiness,
13945 measurement_owned);
13946 if (local_oracle_decision.image_index != before_repair.image_index)
13947 surrogate_repair_image = local_oracle_decision.image_index;
13948 }
13949 // True force residual on the live band (not GP variance): when the
13950 // picker is idle or thrashing rejected/off-path rows while
13951 // max_oracle_F still exceeds problem tolerance, re-measure the
13952 // max-force current-chain image.
13953 const double force_residual_tol =
13954 detail::effectiveModelNoiseTolerance(config);
13955 int residual_max_force_image = -1;
13956 double residual_max_band_force = 0.0;
13957 double measured_current_force = 0.0;
13958 bool has_measured_current_force = false;
13959 for (int i = 1; i < path.numImages() - 1; ++i) {
13960 const double f = path.nebForceMagnitude(i);
13961 if (std::isfinite(f) && f > residual_max_band_force) {
13962 residual_max_band_force = f;
13963 residual_max_force_image = i;
13964 }
13965 if (image_evaluated[static_cast<std::size_t>(i)] ||
13966 image_observed_current[static_cast<std::size_t>(i)]) {
13967 has_measured_current_force = true;
13968 measured_current_force =
13969 std::isfinite(f) ? std::max(measured_current_force, f)
13970 : std::numeric_limits<double>::infinity();
13971 }
13972 }
13973 const bool force_residual_unresolved =
13974 residual_max_force_image > 0 && std::isfinite(force_residual_tol) &&
13975 force_residual_tol > 0.0 &&
13976 residual_max_band_force > force_residual_tol;
13977 // The force-residual remeasure carries an anti-thrash rule that
13978 // drops a rejected proposal whose image already holds current
13979 // true data. That rule reasons about the band geometry, so it
13980 // cannot see that an off-band proposal asks for a DIFFERENT,
13981 // never-measured position: the adjacent-MEP recovery stages a
13982 // trial away from the band and restores the band to its measured
13983 // source, so the image reads as known while the requested
13984 // geometry is not. Letting it fire there discards the trial every
13985 // outer and the recovery restages forever, which is what makes
13986 // climbing_image_converged_only=false hang (994 of 1000 outers
13987 // exit "mep_trial" on 23 oracle calls with arm=none).
13988 // The anti-thrash rule reasons from the per-image observed flag,
13989 // which survives pruning and band motion; the ledger is the
13990 // authority on whether the requested geometry was ever measured.
13991 // A proposal the ledger lacks is a new measurement, whether or
13992 // not it coincides with the band image, and is never dropped.
13993 const int rejected_decision_idx = local_oracle_decision.image_index;
13994 const bool rejected_has_positions =
13995 local_oracle_decision.selectedByRejectedProposal() &&
13996 rejected_proposal_acquisition.positions.size() > 0 &&
13997 rejected_decision_idx > 0 &&
13998 rejected_decision_idx < path.numImages() - 1;
13999 const bool rejected_coincides =
14000 rejected_has_positions &&
14001 detail::positionsCoincide(
14002 rejected_proposal_acquisition.positions,
14003 path.image(rejected_decision_idx).positions);
14004 const bool rejected_in_training =
14005 rejected_has_positions &&
14006 detail::hasPosition(training_obs,
14007 rejected_proposal_acquisition.positions);
14008 const bool protect_off_band = detail::protectUnmeasuredOffBandProposal(
14009 off_band_residual_guard,
14010 local_oracle_decision.selectedByRejectedProposal(),
14011 rejected_has_positions, rejected_coincides, rejected_in_training,
14012 rejected_proposal_acquisition.positions, residual_max_band_force,
14013 force_residual_tol);
14014 const auto priority_decision_for_log = local_oracle_decision;
14015 if (!protect_off_band) {
14016 const auto remeasure =
14017 oracle_target_planner.selectForceResidualRemeasureTarget(
14018 local_oracle_decision, residual_max_force_image,
14019 residual_max_band_force, force_residual_tol);
14020 if (!detail::keepProposalWithoutRemeasure(rejected_has_positions,
14021 rejected_in_training,
14022 remeasure.image_index))
14023 local_oracle_decision = remeasure;
14024 }
14025 // An idle exploration picker can still owe true-force confirmation
14026 // of a confident band. Enter the terminal sweep before spending an
14027 // outer iteration on the unchanged posterior.
14028 if (local_oracle_decision.image_index < 0 &&
14029 !local_recovery_acquisition_hold && !pending_band_action.active() &&
14030 detail::shouldStartTerminalSweep(
14031 detail::oieTerminalSweepReferenceForce(
14032 relaxed_gp_force, residual_max_band_force,
14033 has_measured_current_force),
14034 max_chain_var, uncertainty_threshold,
14035 has_measured_current_force, measured_current_force,
14036 std::max(config.conv_tol, force_residual_tol), false,
14037 config.climbing_image_converged_only && ci_active)) {
14038 const detail::OieOracleTargetPlanner confirmation_planner(
14039 path.numImages(), true, ci_active, ci_idx, image_evaluated,
14040 image_observed_current, image_posterior_certified_current,
14041 per_image_var, std::max(0.0, gp.getSigma2()),
14042 local_recovery_image,
14043 fixed_image_lease.allow_replaceable_acquisition,
14044 config.climbing_image_converged_only,
14045 image_acquisition_unavailable);
14046 local_oracle_decision = confirmation_planner.selectPriorityTarget(
14047 no_rejected_action, false, -1, -1, {}, false);
14048 frozen_sweep = local_oracle_decision.image_index >= 0;
14049 }
14050 if (config.verbose && log_rank == 0) {
14051 // Planner stage trace: which stage produced the target and
14052 // whether the residual remeasure rule replaced it.
14053 neb_log()
14054 << "[acq-plan] outer=" << outer
14055 << " priority=" << priority_decision_for_log.image_index << "/"
14056 << detail::oieOracleSelectionArmName(
14057 priority_decision_for_log.arm)
14058 << " after_residual=" << local_oracle_decision.image_index
14059 << "/"
14060 << detail::oieOracleSelectionArmName(local_oracle_decision.arm)
14061 << " surrogate_repair=" << surrogate_repair_image
14062 << " rejected_target="
14063 << rejected_proposal_acquisition.image_index
14064 << " off_band=" << protect_off_band
14065 << " residual_image=" << residual_max_force_image
14066 << " residual_force=" << residual_max_band_force
14067 << " mep_pending=" << adjacent_mep_trial_pending
14068 << " mep_trained="
14069 << (rejected_proposal_acquisition.positions.size() > 0 &&
14070 detail::hasPosition(
14071 training_obs, rejected_proposal_acquisition.positions))
14072 << std::endl;
14073 }
14074 int tpe_candidate_idx = -1;
14075 int tpe_eligible_count = 0;
14077 bool tpe_objective_evaluated = false;
14078 detail::PsBaxActionProposal psbax_action;
14079 if (pre_inner_psbax_action.has_value()) {
14080 psbax_action = std::move(*pre_inner_psbax_action);
14081 }
14082 // TPE acquisition (opt-in). Only unobserved interiors are eligible
14083 // (standard). Do NOT re-oracle already-observed high-force images
14084 // via TPE: that produced 10k oracles/120s thrash on Baker 01/02.
14085 // Force residual is handled above (remeasure once, else idle→OCI).
14086 // When residual force is open under rejected thrash, allow TPE if
14087 // replaceable or idle so unobserved picks can still run.
14088 const bool tpe_open_under_residual =
14089 force_residual_unresolved &&
14090 (local_oracle_decision.replaceableByPosteriorAcquisition() ||
14091 local_oracle_decision.image_index < 0 ||
14092 local_oracle_decision.selectedByRejectedProposal());
14093 if (config.acquisition == AcquisitionType::TPE && !frozen_sweep &&
14094 !local_recovery_acquisition_hold &&
14095 (local_oracle_decision.replaceableByPosteriorAcquisition() ||
14096 tpe_open_under_residual)) {
14097 const int n_im_tpe = path.numImages();
14098 std::vector<double> tpe_energies(n_im_tpe, 0.0);
14099 std::vector<double> tpe_force(n_im_tpe, 0.0);
14100 for (int i = 0; i < n_im_tpe; ++i) {
14101 tpe_energies[i] = path.image(i).energy;
14102 if (i >= 1 && i < n_im_tpe - 1) {
14103 const double f = path.nebForceMagnitude(i);
14104 tpe_force[i] = std::isfinite(f) ? f : 0.0;
14105 }
14106 }
14107 const double tpe_noise_floor = std::max(0.0, gp.getSigma2());
14108 std::vector<char> tpe_eligible(static_cast<std::size_t>(n_im_tpe),
14109 0);
14110 for (int i = 1; i < n_im_tpe - 1; ++i) {
14111 const bool clears_noise_floor =
14112 !(tpe_noise_floor > 0.0) ||
14114 detail::sanitizePosteriorVariance(per_image_var[i]),
14115 tpe_noise_floor);
14116 // Unobserved only — never re-target current true rows.
14117 const bool informative =
14118 !image_evaluated[static_cast<std::size_t>(i)] &&
14119 !image_observed_current[static_cast<std::size_t>(i)] &&
14120 clears_noise_floor;
14121 tpe_eligible[static_cast<std::size_t>(i)] = informative ? 1 : 0;
14122 if (informative) ++tpe_eligible_count;
14123 }
14124 tpe_objective = oie::tpeObjectiveForSaddleState(
14125 ci_active, ci_candidate_posterior_confident,
14127 current_chain_certificate_deficit, 1.0));
14128 tpe_objective_evaluated = true;
14129 const oie::AcquisitionPolicy tpe_policy(std::move(tpe_eligible),
14130 tpe_objective);
14131 const oie::TpePickResult tpe = tpe_policy.selectTpeOracleTarget(
14132 tpe_energies, per_image_var, tpe_force, per_image_gradient_var,
14133 outer + 1 + config.acquisition_seed_offset);
14134 tpe_candidate_idx = tpe.image_index;
14135 if (tpe.image_index >= 1 &&
14136 tpe.image_index < path.numImages() - 1) {
14137 local_oracle_decision =
14138 oracle_target_planner.selectPosteriorAcquisitionTarget(
14139 local_oracle_decision, tpe.image_index,
14140 detail::OieOracleSelectionArm::TPE);
14141 }
14142 }
14143 if (config.acquisition == AcquisitionType::ExpectedImprovement) {
14144 std::vector<double> ei_energy(
14145 path.numImages(), std::numeric_limits<double>::quiet_NaN());
14146 std::vector<char> ei_eligible(path.numImages(), 0);
14147 const double ei_noise = std::max(0.0, gp.getSigma2());
14148 for (int i = 1; i < path.numImages() - 1; ++i) {
14149 ei_energy[i] = path.image(i).energy;
14150 ei_eligible[i] =
14151 !image_observed_current[static_cast<std::size_t>(i)] &&
14153 detail::sanitizePosteriorVariance(per_image_var[i]),
14154 ei_noise);
14155 }
14156 if (ei_acquisition_image <= 0) {
14157 ei_acquisition_image = detail::selectExpectedImprovementImage(
14158 ei_energy, per_image_var, ei_eligible);
14159 }
14160 if (ei_acquisition_image > 0 &&
14161 ei_acquisition_image < path.numImages() - 1) {
14162 local_oracle_decision =
14163 oracle_target_planner.selectExpectedImprovementTarget(
14164 local_oracle_decision, ei_acquisition_image);
14165 }
14166 }
14167 // Action-level PS-BAX draws one joint posterior E/G realization,
14168 // executes the production NEB action on that sampled surface, and
14169 // queries the trust-certified action-output geometry with the
14170 // largest latent force variance. Geometric trust boundaries,
14171 // certificates, and rejected proposals retain priority. Full-band
14172 // force readiness is not required: the sampled action itself
14173 // identifies the unresolved trust-certified output.
14174 if (config.acquisition == AcquisitionType::PSBAX && ci_active &&
14175 !frozen_sweep && !local_recovery_acquisition_hold &&
14176 local_oracle_decision.replaceableByPosteriorActionAcquisition()) {
14177 if (!psbax_action.target) {
14178 if (session) session->ensureSingletonForGlobal();
14179 const std::uint64_t posterior_seed =
14180 (static_cast<std::uint64_t>(outer + 1 +
14181 config.acquisition_seed_offset)
14182 << 32) ^
14183 static_cast<std::uint64_t>(path.numImages());
14184 psbax_action = detail::proposePsBaxActionAcquisition(
14185 path, gp, training_obs, config, posterior_seed,
14186 projectProposalToOuterTrust,
14187 flattenedPositionsTrustCertified);
14188 }
14189 if (psbax_action.target) {
14190 const Eigen::Index image_dof = path.image(0).positions.size();
14191 const double force_noise_floor =
14192 static_cast<double>(image_dof) *
14193 std::max(0.0, gp.getSigma2());
14194 local_oracle_decision =
14195 oracle_target_planner.selectPosteriorActionTarget(
14196 local_oracle_decision, psbax_action.target,
14197 psbax_action.trust_certified,
14198 psbax_action.force_variance, force_noise_floor,
14199 detail::OieOracleSelectionArm::PSBAX);
14200 }
14201 }
14202 // The stepped climbing image is measured next, whatever the
14203 // certificate and noise-floor arms would pick: its measurement is
14204 // the acceptance of a step, not an information purchase, and the
14205 // noise-floor gate refuses a point one step from a measured row
14206 // (10_tetrazine: four outers of chain measurements after the step).
14207 if (measured_step_needs_ci_oracle) {
14208 const detail::OieOracleTargetDecision planned =
14209 local_oracle_decision;
14210 local_oracle_decision =
14211 oracle_target_planner
14212 .selectRequiredCurrentChainMeasurementTarget(
14213 local_oracle_decision, measured_step_hold_image,
14214 detail::OieAcceptedDriftTarget{});
14215 if (config.verbose && log_rank == 0) {
14216 neb_log() << "[oie-measured-step] outer=" << outer
14217 << " measure held image=" << measured_step_hold_image
14218 << " ci_idx=" << ci_idx
14219 << " planned=" << planned.image_index << "/"
14220 << detail::oieOracleSelectionArmName(planned.arm)
14221 << " forced=" << local_oracle_decision.image_index
14222 << "/"
14223 << detail::oieOracleSelectionArmName(
14224 local_oracle_decision.arm)
14225 << std::endl;
14226 }
14227 }
14228 const int local_worst_idx = local_oracle_decision.image_index;
14229 const bool local_oracle_target_from_rejected_arm =
14230 local_oracle_decision.selectedByRejectedProposal();
14231 const bool local_oracle_target_from_recovery_growth =
14232 local_oracle_decision.arm ==
14233 detail::OieOracleSelectionArm::RecoveryModelGrowth;
14234 const bool local_oracle_performed = local_worst_idx >= 0;
14235 const bool local_oracle_uses_rejected_proposal =
14236 local_oracle_performed && local_oracle_target_from_rejected_arm &&
14237 rejected_proposal_acquisition &&
14238 local_worst_idx == rejected_proposal_acquisition.image_index;
14239 const bool local_oracle_uses_recovery_growth_proposal =
14240 local_oracle_performed &&
14241 local_oracle_target_from_recovery_growth &&
14242 recovery_model_growth_target &&
14243 local_worst_idx == recovery_model_growth_target.image_index;
14244 const bool local_oracle_uses_psbax_action =
14245 local_oracle_performed &&
14246 local_oracle_decision.arm == detail::OieOracleSelectionArm::PSBAX &&
14247 psbax_action.target &&
14248 local_worst_idx == psbax_action.target.image_index;
14249 const bool local_oracle_uses_pending_band_action =
14250 local_oracle_performed &&
14251 local_oracle_decision.arm == detail::OieOracleSelectionArm::PSBAX &&
14252 pending_band_action_acquisition &&
14253 local_worst_idx == pending_band_action_acquisition.image_index;
14254 Eigen::VectorXd local_oracle_positions;
14255 if (local_oracle_performed) {
14256 local_oracle_positions =
14257 local_oracle_uses_rejected_proposal
14258 ? rejected_proposal_acquisition.positions
14259 : local_oracle_uses_recovery_growth_proposal
14260 ? recovery_model_growth_target.positions
14261 : local_oracle_uses_pending_band_action
14262 ? pending_band_action_acquisition.positions
14263 : local_oracle_uses_psbax_action
14264 ? psbax_action.target.positions
14265 : path.image(local_worst_idx).positions;
14266 }
14267 const bool local_oracle_uses_off_path_proposal =
14268 local_oracle_uses_rejected_proposal ||
14269 local_oracle_uses_recovery_growth_proposal ||
14270 local_oracle_uses_pending_band_action ||
14271 local_oracle_uses_psbax_action;
14272 const auto oracle_consensus = detail::broadcastOieOracleConsensus(
14273 local_worst_idx, local_oracle_uses_off_path_proposal,
14274 local_oracle_positions);
14275 const int worst_idx = oracle_consensus.image_index;
14276 const bool oracle_uses_off_path_proposal =
14277 oracle_consensus.from_rejected;
14278 const bool oracle_uses_rejected_proposal =
14279 oracle_uses_off_path_proposal &&
14280 local_oracle_decision.selectedByRejectedProposal();
14281 const bool oracle_uses_pending_band_action =
14282 oracle_uses_off_path_proposal &&
14283 local_oracle_uses_pending_band_action &&
14284 worst_idx == pending_band_action_acquisition.image_index &&
14285 detail::positionsCoincide(
14286 oracle_consensus.positions,
14287 pending_band_action_acquisition.positions);
14288 const bool oracle_uses_recovery_growth_proposal =
14289 oracle_uses_off_path_proposal &&
14290 local_oracle_target_from_recovery_growth;
14291 const bool model_boundary_evidence =
14292 accepted_drift_priority_idx > 0 &&
14293 worst_idx == accepted_drift_priority_idx &&
14294 !oracle_uses_off_path_proposal &&
14295 detail::positionsCoincide(
14296 oracle_consensus.positions,
14297 path.image(accepted_drift_priority_idx).positions);
14298 if (oracle_uses_rejected_proposal) {
14299 rejected_proposal_acquisition.clear();
14300 }
14301 if (oracle_uses_pending_band_action) {
14302 pending_band_action_acquisition.clear();
14303 // The observation updates the posterior used to define the
14304 // action. Replan from the unchanged accepted band instead of
14305 // exhaustively certifying a stale multi-image trial.
14306 pending_band_action.clear();
14307 }
14308 const bool oracle_performed = worst_idx >= 0;
14309 if (config.verbose) {
14310 int log_rank_dbg = 0;
14311#ifdef GPR_HAVE_MPI
14312 int log_mpi_dbg = 0;
14313 MPI_Initialized(&log_mpi_dbg);
14314 if (log_mpi_dbg) MPI_Comm_rank(MPI_COMM_WORLD, &log_rank_dbg);
14315#endif
14316 if (log_rank_dbg == 0) {
14317 std::cerr
14318 << "[acq-pick] outer=" << outer
14319 << " sweep=" << (frozen_sweep ? 1 : 0)
14320 << " ci_active=" << ci_active << " worst=" << worst_idx
14321 << " arm="
14322 << detail::oieOracleSelectionArmName(
14323 local_oracle_decision.arm)
14324 << " recovery_hold=" << local_recovery_acquisition_hold
14325 << " recovery_owns=" << local_recovery_owns_replaceable_work
14326 << " recovery_suppresses="
14327 << local_recovery_suppresses_replaceable_work
14328 << " recovery_allows_replaceable="
14329 << fixed_image_lease.allow_replaceable_acquisition
14330 << " recovery_growth="
14331 << fixed_image_lease.model_growth_required
14332 << " recovery_image=" << local_recovery_image
14333 << " recovery_candidate_cert="
14334 << recovery_candidate_certificate_image
14335 << " recovery_measurement="
14336 << recovery_stencil_measurement_image
14337 << " recovery_proposal="
14338 << (recovery_model_growth_target ? 1 : 0)
14339 << " recovery_proposal_status="
14340 << detail::measuredNebStepStatusName(
14341 recovery_proposal_status)
14342 << " recovery_candidates="
14343 << recovery_growth_candidate_count
14344 << " recovery_admissible="
14345 << recovery_growth_admissible_count
14346 << " recovery_variance=" << recovery_growth_variance
14347 << " recovery_trust_distance="
14348 << recovery_growth_trust_distance << " ci_marker=" << ci_idx
14349 << " ci_cand=" << ci_candidate_idx
14350 << " cand_confident=" << ci_candidate_posterior_confident
14351 << " cand_observed=" << ci_candidate_observed
14352 << " handover_cert=" << ci_candidate_handover_certified
14353 << " handover_targets="
14354 << ci_candidate_handover_targets.size()
14355 << " ci_deficit=" << ci_certificate_deficit
14356 << " chain_deficit=" << current_chain_certificate_deficit
14357 << " chain_priority=" << oracle_chain_priority_idx
14358 << " chain_certificate_image="
14359 << current_chain_certificate.image_index
14360 << " adjacent_mep_priority="
14361 << (adjacent_mep_recovery_active
14362 ? adjacent_mep_recovery.targetImage()
14363 : -1)
14364 << " drift_priority=" << accepted_drift_priority_idx
14365 << " tpe_idx=" << tpe_candidate_idx
14366 << " tpe_eligible=" << tpe_eligible_count << " tpe_obj="
14367 << oie::tpeObjectiveLogName(tpe_objective_evaluated,
14368 tpe_objective)
14369 << " psbax_status="
14370 << detail::measuredNebStepStatusName(psbax_action.status)
14371 << " psbax_image=" << psbax_action.target.image_index
14372 << " psbax_force_variance=" << psbax_action.force_variance
14373 << " psbax_trust_projected=" << psbax_action.trust_projected
14374 << " psbax_trust_certified=" << psbax_action.trust_certified
14375 << " band_action_pending=" << pending_band_action.active()
14376 << " band_action_waiting=" << pending_band_action_waiting
14377 << " band_action_applied=" << pending_band_action_applied
14378 << " band_action_oracle=" << oracle_uses_pending_band_action
14379 << " model_boundary=" << model_boundary_evidence
14380 << " maxVar=" << max_chain_var
14381 << " uncTol=" << uncertainty_threshold
14382 << " joint_energy_ratio="
14383 << joint_readiness.max_energy_ratio
14384 << " joint_force_ratio=" << joint_readiness.max_force_ratio
14385 << " reported_force_ratio="
14386 << reported_joint_readiness.max_force_ratio
14387 << " variance_calibration="
14388 << variance_probe.max_reported_variance_calibration
14389 << " force_cert_image="
14390 << variance_probe.max_gradient_trace.second
14391 << " force_cert_observed="
14392 << (variance_probe.max_gradient_trace.second >= 0 &&
14393 variance_probe.max_gradient_trace.second <
14394 static_cast<int>(
14395 current_band_observed.size())
14396 ? static_cast<int>(
14397 current_band_observed[variance_probe
14398 .max_gradient_trace
14399 .second])
14400 : 0)
14401 << " force_cert_gp_row="
14402 << globalGpOwnsCurrentGeometry(
14403 variance_probe.max_gradient_trace.second)
14404 << " global_gp_ntrain="
14405 << globalGpTrainingConfigurationCount()
14406 << " joint_ready=" << joint_readiness.resolved()
14407 << " joint_acquisition_target="
14408 << current_band_acquisition_image
14409 << " max_var_idx=" << max_var_idx << std::endl;
14410 }
14411 }
14412 // Canonical OIE pays one oracle image per outer iteration. OCI
14413 // handoff additionally fills the missing current true rows in the
14414 // CI force stencil because the dimer consumes that local NEB
14415 // force certificate directly.
14416 // Off-path positions are sampled by rejected-proposal,
14417 // recovery-growth, and posterior-action arms. A certificate arm
14418 // that lands on the same image index needs the chain position: the
14419 // saddle handoff, MMF hook, and convergence gates trade in
14420 // chain-position certificates, and an off-path row cannot mark the
14421 // image evaluated.
14422 bool oracle_updates_current_path = false;
14423 bool any_oracle_path_update = false;
14424 bool current_ci_oracle_updates_path = false;
14425 double current_ci_oracle_force =
14426 std::numeric_limits<double>::infinity();
14427 Eigen::VectorXd current_ci_oracle_force_vector;
14428 Eigen::VectorXd current_ci_oracle_position;
14429 // Posterior comparison diagnostics for the climbing image's
14430 // measured row, before that row enters the refit.
14431 double ci_walk_force_error = std::numeric_limits<double>::quiet_NaN();
14432 double ci_walk_force_sd = std::numeric_limits<double>::quiet_NaN();
14433 TrialMeasurement adjacent_mep_trial;
14434 TrialMeasurement recovery_growth_trial;
14435 std::vector<int> oracle_indices;
14436 std::vector<Eigen::VectorXd> oracle_positions_batch;
14437 Observation refit_oracle_batch;
14438 std::vector<char> oracle_off_path_position;
14439 std::vector<NEBOracleEvaluationContext> oracle_context_batch;
14440 bool acquisition_refused =
14441 std::any_of(image_acquisition_unavailable.begin(),
14442 image_acquisition_unavailable.end(),
14443 [](char unavailable) { return unavailable != 0; });
14444 auto appendOracleTarget = [&](int image_idx,
14445 const Eigen::VectorXd& positions,
14446 bool off_path_position,
14447 bool force_quality = false,
14448 bool posterior_acquisition = false,
14449 bool current_chain_certificate = false,
14450 bool force_stencil = false) {
14451 if (image_idx <= 0 || image_idx >= path.numImages() - 1) {
14452 return;
14453 }
14454 if (!oracleGeometryAdmissible(positions)) {
14455 const bool contact_violation =
14456 acquisition_contact_floor.violated(positions, config.cell);
14457 rememberOracleRefusal(positions);
14458 acquisition_refused = true;
14459 if (!contact_violation) {
14460 outer_oracle_refusal = true;
14461 outer_oracle_refusal_text =
14462 "acquisition at a geometry the oracle refused";
14463 }
14464 if (log_rank == 0) {
14465 neb_log() << (contact_violation ? "[contact-domain]"
14466 : "[oracle-refused]")
14467 << " image=" << image_idx
14468 << " acquisition rejected before evaluation";
14469 if (contact_violation)
14470 neb_log() << " min_contact_ratio="
14471 << acquisition_contact_floor.minimumRatio(
14472 positions, config.cell);
14473 neb_log() << std::endl;
14474 }
14475 return;
14476 }
14477 for (std::size_t i = 0; i < oracle_positions_batch.size(); ++i) {
14478 if (detail::positionsCoincide(oracle_positions_batch[i],
14479 positions)) {
14480 auto& context = oracle_context_batch[i];
14481 context.force_quality =
14482 context.force_quality || force_quality;
14483 context.posterior_acquisition =
14484 context.posterior_acquisition || posterior_acquisition;
14485 context.current_chain_certificate =
14486 context.current_chain_certificate ||
14487 current_chain_certificate;
14488 context.force_stencil =
14489 context.force_stencil || force_stencil;
14490 return;
14491 }
14492 }
14493 oracle_indices.push_back(image_idx);
14494 oracle_positions_batch.push_back(positions);
14495 oracle_off_path_position.push_back(off_path_position ? 1 : 0);
14497 context.image_index = image_idx;
14498 context.rejected_position = off_path_position;
14499 context.force_quality = force_quality;
14500 context.posterior_acquisition = posterior_acquisition;
14501 context.current_chain_certificate = current_chain_certificate;
14502 context.force_stencil = force_stencil;
14503 oracle_context_batch.push_back(context);
14504 };
14505 // Every image outside the kernel's support is measured in this
14506 // round: the surrogate has no prediction for it, an oracle call is
14507 // cheap next to an outer round, and a band held there otherwise
14508 // waits one round per image (grignard: 21 atoms, one acquisition
14509 // per five-second round with the whole band unsupported).
14510 if (oracle_performed) {
14511 for (int i = 1; i < path.numImages() - 1; ++i) {
14512 if (i == worst_idx) continue;
14513 if (static_cast<std::size_t>(i) >= unsupported_images.size() ||
14514 !unsupported_images[static_cast<std::size_t>(i)])
14515 continue;
14516 if (path.image(i).evaluated) continue;
14517 appendOracleTarget(i, path.image(i).positions,
14518 /*off_path_position=*/false,
14519 /*force_quality=*/false,
14520 /*posterior_acquisition=*/true);
14521 }
14522 }
14523 if (oracle_performed) {
14524 appendOracleTarget(
14525 worst_idx, oracle_consensus.positions,
14526 oracle_uses_off_path_proposal,
14527 local_oracle_decision.requires_force_quality,
14528 detail::oieSelectionArmUsesPosteriorAcquisition(
14529 local_oracle_decision.arm),
14530 local_oracle_decision.arm ==
14531 detail::OieOracleSelectionArm::CurrentChainPriority ||
14532 local_oracle_decision.arm ==
14533 detail::OieOracleSelectionArm::AcceptedDrift ||
14534 local_oracle_decision.arm ==
14535 detail::OieOracleSelectionArm::CurrentClimbingImage ||
14536 local_oracle_decision.arm ==
14537 detail::OieOracleSelectionArm::FrozenSweep,
14538 /*force_stencil=*/false);
14539 // Triplet lever: the chosen image's on-path neighbours are
14540 // measured in the same round, so the round returns the
14541 // local tangent and curvature rather than one point.
14542 if (config.use_triplet && !oracle_uses_off_path_proposal) {
14543 for (const int neighbour: {worst_idx - 1, worst_idx + 1}) {
14544 if (neighbour <= 0 || neighbour >= path.numImages() - 1) {
14545 continue;
14546 }
14547 if (image_observed_current[static_cast<std::size_t>(
14548 neighbour)]) {
14549 continue;
14550 }
14551 appendOracleTarget(neighbour,
14552 path.image(neighbour).positions,
14553 /*rejected_position=*/false,
14554 /*force_quality=*/true,
14555 /*posterior_acquisition=*/false,
14556 /*current_chain_certificate=*/true,
14557 /*force_stencil=*/true);
14558 }
14559 }
14560 }
14561 if (ci_activation_needs_oracle) {
14562 for (const int stencil_idx: ci_activation_triplet_targets) {
14563 appendOracleTarget(stencil_idx,
14564 path.image(stencil_idx).positions,
14565 /*rejected_position=*/false,
14566 /*force_quality=*/true,
14567 /*posterior_acquisition=*/false,
14568 /*current_chain_certificate=*/true,
14569 /*force_stencil=*/true);
14570 }
14571 }
14572 for (const int stencil_idx: ci_candidate_handover_targets) {
14573 appendOracleTarget(stencil_idx, path.image(stencil_idx).positions,
14574 /*rejected_position=*/false,
14575 /*force_quality=*/true,
14576 /*posterior_acquisition=*/false,
14577 /*current_chain_certificate=*/true,
14578 /*force_stencil=*/true);
14579 }
14580 if (detail::shouldExpandOciHandoffStencil(
14581 ci_active, saddle_handoff_needs_ci_oracle,
14582 current_chain_certificate_deficit)) {
14583 const auto stencil_targets =
14584 session ? detail::selectOciHandoffCertificateOracleTargets(
14585 ci_idx, path, *session)
14586 : detail::selectOciHandoffStencilOracleTargets(
14587 ci_idx, path.numImages(), image_evaluated,
14588 image_observed_current);
14589 for (const int stencil_idx: stencil_targets) {
14590 appendOracleTarget(stencil_idx,
14591 path.image(stencil_idx).positions,
14592 /*rejected_position=*/false,
14593 /*force_quality=*/true,
14594 /*posterior_acquisition=*/false,
14595 /*current_chain_certificate=*/true,
14596 /*force_stencil=*/true);
14597 }
14598 }
14599 // GP-AIE measures the complete current band in the oracle batch.
14600 // The frozen sweep confirms remaining images on the true PES
14601 // with the band frozen, so confirmation order cannot matter.
14602 // Confirm every missing interior image in one batched outer:
14603 // one image per outer pays a full probe + refit cycle per
14604 // confirmation, which is pure certification latency on a band
14605 // that has already physically converged.
14606 const bool evaluate_all_images = config.mode == NEBMode::GP_AIE;
14607 if (evaluate_all_images || frozen_sweep) {
14608 for (int i = 1; i < path.numImages() - 1; ++i) {
14609 if (!evaluate_all_images &&
14610 image_observed_current[static_cast<std::size_t>(i)]) {
14611 continue;
14612 }
14613 appendOracleTarget(i, path.image(i).positions,
14614 /*rejected_position=*/false,
14615 /*force_quality=*/true,
14616 /*posterior_acquisition=*/false,
14617 /*current_chain_certificate=*/true,
14618 /*force_stencil=*/false);
14619 }
14620 }
14621 // CI-only acceptance requires a this-outer oracle at the climbing
14622 // image (shouldAcceptOieCiOnlyConvergence), but an active climbing
14623 // image is moved each outer and so carries no true gradient when the
14624 // certificate is tested. Spend one oracle call at the climbing
14625 // image whenever the surrogate already places it inside the requested
14626 // tolerance, so the criterion is evaluated on the true PES rather
14627 // than skipped.
14628 //
14629 // The condition is "not oracled THIS outer", which is what the accept
14630 // tests. Keying on image.evaluated instead leaves a hole: restoring a
14631 // row from training marks the image evaluated while its gradient
14632 // belongs to a previous position, so the append would skip exactly
14633 // when the stale-gradient case needs it.
14634 if (ci_active && ci_idx > 0 && ci_idx < path.numImages() - 1 &&
14635 !current_ci_oracle_updates_path) {
14636 const auto ci_surrogate_force = path.nebForce(ci_idx);
14637 const double ci_surrogate_force_magnitude =
14638 ci_surrogate_force.size() > 0
14639 ? path.saddleForce(ci_idx)
14640 : std::numeric_limits<double>::infinity();
14641 if (std::isfinite(ci_surrogate_force_magnitude) &&
14642 ci_surrogate_force_magnitude <
14643 detail::effectiveModelNoiseTolerance(config)) {
14644 appendOracleTarget(ci_idx, path.image(ci_idx).positions,
14645 /*rejected_position=*/false,
14646 /*force_quality=*/true,
14647 /*posterior_acquisition=*/false,
14648 /*current_chain_certificate=*/true,
14649 /*force_stencil=*/false);
14650 }
14651 }
14652 if (config.training_policy != nullptr)
14653 filterAcquisitionBatch(
14654 config, gp, session, outer, result, training_obs,
14655 oracle_indices, oracle_positions_batch,
14656 oracle_off_path_position, oracle_context_batch);
14657 bool pruned_in_outer = false;
14658 bool recovery_row_admitted_in_outer = false;
14659 if (!oracle_positions_batch.empty()) {
14660 if (wallClockReached()) break;
14661 (void)detail::publishOracleSessionPathCheckpoint(config, path);
14662 // CGT fidelity probe: predict the gradient at the
14663 // acquisition target with the CURRENT surrogate, before
14664 // the fresh row retrains it. The comparison against the
14665 // oracle gradient below is the agreement signal that
14666 // drives the rho-controlled trust radius.
14667 Eigen::VectorXd rho_pred_gradient;
14668 double fidelity_force_variance =
14669 std::numeric_limits<double>::quiet_NaN();
14670 {
14671 gpr::Observation fidelity_probe;
14672 fidelity_probe.R.resize(1, oracle_positions_batch[0].size());
14673 fidelity_probe.R.row(0) = oracle_positions_batch[0].transpose();
14674 gpr::Observation fidelity_variance = fidelity_probe;
14675 if (session) {
14676 auto model = session->acquireGlobalModel();
14677 model.gp().calculatePotentialDispatched(fidelity_probe);
14678 model.gp().calculateVarianceDispatched(fidelity_variance);
14679 } else {
14680 gp.calculatePotentialDispatched(fidelity_probe);
14681 gp.calculateVarianceDispatched(fidelity_variance);
14682 }
14683 if (fidelity_probe.G.size() > 0) {
14684 rho_pred_gradient = fidelity_probe.G.row(0).transpose();
14685 }
14686 const ObservationVariance reported =
14687 detail::jointObservationVariance(fidelity_variance);
14688 if (reported.gradient.size() == rho_pred_gradient.size()) {
14689 fidelity_force_variance =
14690 detail::observationGradientVarianceTrace(reported);
14691 }
14692 }
14693 gpr::PhaseTimers::notePeak("before_oracle");
14694 // The potential can refuse a geometry (the UMA graph raised an
14695 // index error on a band image of 10_tetrazine and the process
14696 // aborted). A refusal is a failed measurement: the outer keeps
14697 // its band, records that geometry so it is not asked again, and
14698 // the acquisition moves on. The other geometries in the same
14699 // step stay. One refused image does not drop the measurements
14700 // that returned. Single-rank contract: every rank
14701 // evaluates its own points, so a refusal on one rank of a
14702 // multi-rank run still propagates through the agreed mask.
14703 std::vector<EvalResult> oracle_results;
14704 bool oracle_refused = false;
14705 std::vector<char> oracle_accepted(oracle_positions_batch.size(), 0);
14706 std::string oracle_refusal;
14707 try {
14708 oracle_results = parallelEvaluate(
14709 oracle_positions_batch, oracle, &oracle_context_batch,
14710 config.oracle_evaluation_context,
14711 config.oracle_session_restart_requested,
14712 &config.batch_oracle, config.oracle_batch_chunk,
14713 &oracle_accepted, &oracle_refusal);
14714 } catch (const OracleSessionRestartRequested&) {
14715 throw;
14716 } catch (const gpr::WallClockLimitReached&) {
14717 wallClockReached();
14718 break;
14719 } catch (const std::exception& error) {
14720 oracle_accepted.assign(oracle_positions_batch.size(), 0);
14721 oracle_refusal = error.what();
14722 }
14723 if (oracle_accepted.size() != oracle_positions_batch.size())
14724 oracle_accepted.assign(oracle_positions_batch.size(), 0);
14725 int oracle_kept = 0;
14726 int oracle_refused_count = 0;
14727 for (std::size_t i = 0; i < oracle_positions_batch.size(); ++i) {
14728 if (oracle_accepted[i]) {
14729 ++oracle_kept;
14730 continue;
14731 }
14732 ++oracle_refused_count;
14733 rememberOracleRefusal(oracle_positions_batch[i]);
14734 }
14735 if (oracle_refused_count > 0 && log_rank == 0) {
14736 neb_log() << "[oracle-refused] outer=" << outer
14737 << " geometries=" << oracle_refused_count;
14738 if (oracle_kept > 0) neb_log() << " kept=" << oracle_kept;
14739 neb_log() << " what=" << oracle_refusal << std::endl;
14740 }
14741 if (oracle_refused_count > 0) {
14742 outer_oracle_refusal = true;
14743 outer_oracle_refusal_text = oracle_refusal;
14744 }
14745 if (oracle_kept > 0) oracle_failures.measured();
14746 if (oracle_kept == 0) {
14747 oracle_refused = true;
14748 acquisition_refused = true;
14749 } else if (oracle_refused_count > 0) {
14750 std::vector<int> kept_indices;
14751 std::vector<Eigen::VectorXd> kept_positions;
14752 std::vector<char> kept_off_path;
14753 std::vector<NEBOracleEvaluationContext> kept_contexts;
14754 std::vector<EvalResult> kept_results;
14755 kept_indices.reserve(static_cast<std::size_t>(oracle_kept));
14756 kept_positions.reserve(static_cast<std::size_t>(oracle_kept));
14757 kept_off_path.reserve(static_cast<std::size_t>(oracle_kept));
14758 kept_contexts.reserve(static_cast<std::size_t>(oracle_kept));
14759 kept_results.reserve(static_cast<std::size_t>(oracle_kept));
14760 for (std::size_t i = 0; i < oracle_positions_batch.size();
14761 ++i) {
14762 if (!oracle_accepted[i]) continue;
14763 kept_indices.push_back(oracle_indices[i]);
14764 kept_positions.push_back(oracle_positions_batch[i]);
14765 kept_off_path.push_back(oracle_off_path_position[i]);
14766 kept_contexts.push_back(oracle_context_batch[i]);
14767 kept_results.push_back(oracle_results[i]);
14768 }
14769 oracle_indices.swap(kept_indices);
14770 oracle_positions_batch.swap(kept_positions);
14771 oracle_off_path_position.swap(kept_off_path);
14772 oracle_context_batch.swap(kept_contexts);
14773 oracle_results.swap(kept_results);
14774 }
14775 // The fidelity probe was taken at the original first geometry.
14776 // A refusal of that geometry leaves the probe pointing at a
14777 // row the kept batch no longer starts with.
14778 if (oracle_accepted.empty() || !oracle_accepted[0])
14779 rho_pred_gradient.resize(0);
14780 gpr::PhaseTimers::notePeak("after_oracle");
14781 if (!oracle_refused) {
14782 if (config.active_posterior_refits) {
14783 const Eigen::Index count = oracle_positions_batch.size();
14784 const Eigen::Index dof =
14785 oracle_positions_batch.front().size();
14786 refit_oracle_batch.R.resize(count, dof);
14787 refit_oracle_batch.G.resize(count, dof);
14788 for (Eigen::Index row = 0; row < count; ++row) {
14789 refit_oracle_batch.R.row(row) =
14790 oracle_positions_batch[row].transpose();
14791 refit_oracle_batch.G.row(row) =
14792 oracle_results[row].gradient.transpose();
14793 }
14794 for (Eigen::Index row = 0; row < count; ++row) {
14795 if (!ci_active || oracle_indices[row] != ci_idx ||
14796 oracle_off_path_position[row] != 0)
14797 continue;
14798 gpr::Observation measured;
14799 measured.R = refit_oracle_batch.R.middleRows(row, 1);
14800 measured.G = refit_oracle_batch.G.middleRows(row, 1);
14802 measured, path.convergenceForceNorm(dof),
14803 &ci_walk_force_error, &ci_walk_force_sd);
14804 break;
14805 }
14806 }
14807 result.oracle_calls +=
14808 static_cast<int>(oracle_positions_batch.size());
14809 result.oracle_calls_outer +=
14810 static_cast<int>(oracle_positions_batch.size());
14811 if (config.rho_trust && !oracle_results.empty() &&
14812 rho_pred_gradient.size() > 0 &&
14813 rho_pred_gradient.size() ==
14814 oracle_results[0].gradient.size()) {
14815 // Relative gradient error at the frontier row. The
14816 // scale floors at conv_tol so a near-stationary true
14817 // gradient cannot inflate the ratio into a spurious
14818 // shrink. The radius uses the shared trust-region update
14819 // with quality 1 - fidelity; this empirical error measure
14820 // is separate from an actual/predicted merit ratio.
14821 const double err =
14822 (rho_pred_gradient - oracle_results[0].gradient).norm();
14823 const double scale = std::max(
14824 oracle_results[0].gradient.norm(), config.conv_tol);
14825 const double fidelity = err / scale;
14826 rho_last_fidelity = fidelity;
14827 rho_trust_radius = detail::gradientFidelityTrustRadius(
14828 config, rho_trust_radius, fidelity);
14829 }
14830 if (!oracle_results.empty() && rho_pred_gradient.size() > 0 &&
14831 rho_pred_gradient.size() ==
14832 oracle_results[0].gradient.size() &&
14833 std::isfinite(fidelity_force_variance)) {
14834 measured_variance_error =
14835 (rho_pred_gradient - oracle_results[0].gradient).norm();
14836 measured_variance_reported = fidelity_force_variance;
14837 measured_variance_calibration =
14838 detail::measuredVarianceCalibration(
14839 measured_variance_error, fidelity_force_variance,
14840 rho_pred_gradient.size(), gp.getSigma2());
14841 const bool measured_on_band =
14842 !oracle_positions_batch.empty() &&
14843 oracle_indices[0] > 0 &&
14844 oracle_indices[0] < path.numImages() &&
14845 detail::positionsCoincide(
14846 oracle_positions_batch[0],
14847 path.image(oracle_indices[0]).positions);
14848 drift_left_posterior = detail::keptDriftOutsidePosterior(
14849 kept_certified_drift, measured_on_band,
14850 measured_variance_error, fidelity_force_variance,
14851 rho_pred_gradient.size(), gp.getSigma2());
14852 }
14853 for (std::size_t k = 0; k < oracle_positions_batch.size();
14854 ++k) {
14855 const int image_idx = oracle_indices[k];
14856 const Eigen::VectorXd& oracle_positions =
14857 oracle_positions_batch[k];
14858 const bool off_path_position =
14859 oracle_off_path_position[k] != 0;
14860 // Geometry-based current-chain test: fixed-point /
14861 // rejected arms still target live band positions
14862 // (measured-chain sweep). The rejected flag alone must
14863 // not mark those rows off-path or skip_off_path_growth
14864 // drops durable training while residual force is high
14865 // (Baker 01: arm=rejected, oracle_calls↑, ntrain frozen).
14866 const bool geometry_is_current_path =
14867 detail::positionsCoincide(
14868 oracle_positions, path.image(image_idx).positions);
14869 if (!off_path_position) {
14870 path.image(image_idx).positions = oracle_positions;
14871 }
14872 const bool updates_current_path = geometry_is_current_path;
14873 if (k == 0) {
14874 oracle_updates_current_path = updates_current_path;
14875 }
14876 // A rewrite that reproduces the image's stored state
14877 // bitwise changes nothing; counting it as an update
14878 // suppresses the fixed-point detector and the loop
14879 // replays verbatim at one wasted oracle call per outer.
14880 bool oracle_state_changes = false;
14881 if (updates_current_path) {
14882 const auto& image_prior = path.image(image_idx);
14883 oracle_state_changes =
14884 !image_prior.evaluated ||
14885 image_prior.energy != oracle_results[k].energy ||
14886 image_prior.gradient.size() !=
14887 oracle_results[k].gradient.size() ||
14888 (image_prior.gradient.size() > 0 &&
14889 !(image_prior.gradient.array() ==
14890 oracle_results[k].gradient.array())
14891 .all());
14892 }
14893 const double e_oracle = oracle_results[k].energy;
14894 const Eigen::VectorXd& g_oracle =
14895 oracle_results[k].gradient;
14896 if (config.oracle_optimization_outcome) {
14897 const auto progress = oracle_force_progress.observe(
14898 image_idx, g_oracle.norm());
14899 if (progress) {
14900 config.oracle_optimization_outcome(*progress);
14901 }
14902 }
14903 if (adjacent_mep_recovery_active &&
14904 adjacent_mep_recovery.hasPendingTrial() &&
14905 image_idx == adjacent_mep_recovery.targetImage() &&
14906 detail::positionsCoincide(
14907 oracle_positions,
14908 adjacent_mep_recovery.pendingTrialPosition())) {
14909 adjacent_mep_trial.measured = true;
14910 adjacent_mep_trial.energy = e_oracle;
14911 adjacent_mep_trial.gradient = g_oracle;
14912 }
14913 const bool is_recovery_growth_row =
14914 oracle_uses_recovery_growth_proposal &&
14915 recovery_model_growth_target &&
14916 image_idx == recovery_model_growth_target.image_index &&
14917 detail::positionsCoincide(
14918 oracle_positions,
14919 recovery_model_growth_target.positions);
14920 if (is_recovery_growth_row) {
14921 recovery_growth_trial.measured = true;
14922 recovery_growth_trial.energy = e_oracle;
14923 recovery_growth_trial.gradient = g_oracle;
14924 recovery_growth_trial.positions = oracle_positions;
14925 }
14926 if (updates_current_path) {
14927 path.image(image_idx).energy = e_oracle;
14928 path.image(image_idx).gradient = g_oracle;
14929 path.image(image_idx).evaluated = true;
14930 if (image_idx == ci_idx) {
14931 current_ci_oracle_updates_path = true;
14932 }
14933 }
14934 // Per-image dual-update: the session overload writes to
14935 // both the global ~training_obs~ and to image
14936 // ~image_idx~'s local set, so the per-image GP at
14937 // ~image_idx~ accumulates evidence of its own
14938 // neighbourhood across outer iters. Without a session
14939 // there is no per-image storage; fall back to a
14940 // global-only append.
14941 //
14942 // Every measurement enters the ledger. The planner selects
14943 // a rejected proposal exactly because the ledger lacks it;
14944 // withholding the row would re-select the same geometry on
14945 // the next outer and spend an oracle call per outer without
14946 // changing the model. Redundant rows leave through the
14947 // influence pruner, not through an admission gate.
14948 const bool force_quality_current_chain =
14949 updates_current_path &&
14950 oracle_context_batch[k].force_quality;
14951 const bool policy_admits =
14952 config.training_policy == nullptr ||
14953 policyAdmitsRow(*config.training_policy,
14954 oracle_positions, e_oracle, g_oracle,
14955 training_obs);
14956 if (policy_admits && session) {
14957 if (is_recovery_growth_row) {
14958 recovery_row_admitted_in_outer = true;
14959 }
14960 if (force_quality_current_chain) {
14961 session->appendCurrentChainObservation(
14962 image_idx, oracle_positions, e_oracle,
14963 g_oracle);
14964 } else {
14965 session->appendObservation(image_idx,
14966 oracle_positions,
14967 e_oracle, g_oracle);
14968 }
14969 } else if (policy_admits) {
14970 appendObservation(training_obs, oracle_positions,
14971 e_oracle, g_oracle);
14972 }
14973 // Oracle progress requires durable evidence across the
14974 // outer-top restore and re-derivation.
14975 any_oracle_path_update =
14976 any_oracle_path_update ||
14977 (oracle_state_changes &&
14978 detail::hasPosition(training_obs, oracle_positions));
14979 }
14980 detail::throwIfOracleSessionRestartRequested(
14981 config.oracle_session_restart_requested);
14982 }
14983 if (config.training_policy != nullptr)
14984 pruned_in_outer = retainTrainingObservation(
14985 *config.training_policy, training_obs, gp, session);
14986 }
14987
14988 // The inner loop already kept this drift. The oracle gradient at
14989 // the point it reached has a squared error larger than the
14990 // posterior's own expected squared error, so the mean that walked
14991 // there is not a force to follow. Keep the row (it is already in
14992 // the training set, and the refit below conditions on it) and put
14993 // the band back on the geometry the outer started from.
14994 if (drift_left_posterior) {
14995 const gpr::Observation& obs =
14996 session ? session->training_obs : training_obs;
14997 for (int i = 0; i < path.numImages(); ++i) {
14998 if (i >= static_cast<int>(outer_start_image_positions.size()))
14999 break;
15000 path.image(i).positions =
15001 outer_start_image_positions[static_cast<std::size_t>(i)];
15002 path.image(i).evaluated = false;
15003 const bool restored =
15004 detail::restoreObservedImageIfPresent(obs, path.image(i));
15005 if (!restored) {
15006 path.image(i).energy =
15007 std::numeric_limits<double>::quiet_NaN();
15008 if (path.image(i).gradient.size() ==
15009 path.image(i).positions.size()) {
15010 path.image(i).gradient.setZero();
15011 }
15012 }
15013 if (i < static_cast<int>(image_observed_current.size())) {
15014 image_observed_current[static_cast<std::size_t>(i)] =
15015 restored ? 1 : 0;
15016 }
15017 if (i < static_cast<int>(image_evaluated.size())) {
15018 image_evaluated[static_cast<std::size_t>(i)] =
15019 path.image(i).evaluated ? 1 : 0;
15020 }
15021 }
15022 path.computeNEBForces();
15023 band_stepper.reset();
15024 oracle_updates_current_path = false;
15025 current_ci_oracle_updates_path = false;
15026 neb_log() << "[gp_oie] outer=" << outer
15027 << " drift outside posterior (error "
15028 << measured_variance_error << " variance "
15029 << measured_variance_reported
15030 << "); restored the pre-drift band\n";
15031 }
15032
15033 if (recovery_growth_trial.measured) {
15034 const auto trial = detail::makeOieRecoveryGrowthTrial(
15035 path, fixed_image, recovery_growth_trial.positions,
15036 recovery_growth_trial.energy, recovery_growth_trial.gradient);
15037 detail::MeasuredResidualStepAssessment assessment;
15038 if (trial) {
15039 assessment = detail::assessMeasuredResidualStep(
15040 trial->source_stencil_positions[1],
15041 trial->source_force_vector, trial->source_force,
15042 trial->positions, trial->trial_force_vector,
15043 trial->trial_force, /*trial_certificate=*/true);
15044 }
15045 const bool accepted =
15046 trial &&
15047 assessment.action ==
15048 detail::MeasuredResidualStepAction::Accept &&
15049 detail::commitOieRecoveryGrowthTrial(path, *trial);
15050 if (accepted) {
15051 recovery_growth_backtrack_target.clear();
15052 if (session) {
15053 pruned_in_outer =
15054 detail::admitRecoveryGrowthObservation(
15055 *session, config.training_policy, fixed_image,
15056 recovery_growth_trial.positions,
15057 recovery_growth_trial.energy,
15058 recovery_growth_trial.gradient,
15059 recovery_row_admitted_in_outer) ||
15060 pruned_in_outer;
15061 }
15062 (void)recovery_stencil_anchor.reanchor(path, fixed_image_lease);
15063 band_stepper.reset();
15064 oracle_updates_current_path = true;
15065 any_oracle_path_update = true;
15066 current_ci_oracle_updates_path =
15067 current_ci_oracle_updates_path || fixed_image == ci_idx;
15068 } else if (trial &&
15069 assessment.action ==
15070 detail::MeasuredResidualStepAction::Backtrack &&
15071 assessment.backtrack_fraction) {
15072 const Eigen::VectorXd source =
15073 trial->source_stencil_positions[1];
15074 Eigen::VectorXd backtracked =
15075 source + *assessment.backtrack_fraction *
15076 (trial->positions - source);
15077 if (backtracked.allFinite() &&
15078 !detail::positionsCoincide(backtracked, source) &&
15079 !detail::hasPosition(training_obs, backtracked)) {
15080 recovery_growth_backtrack_target.image_index = fixed_image;
15081 recovery_growth_backtrack_target.positions =
15082 std::move(backtracked);
15083 } else {
15084 recovery_growth_backtrack_target.clear();
15085 assessment.action =
15086 detail::MeasuredResidualStepAction::Reject;
15087 }
15088 } else {
15089 recovery_growth_backtrack_target.clear();
15090 }
15091 if (config.verbose && log_rank == 0) {
15092 const char* action_name =
15093 accepted ? "accept"
15094 : assessment.action ==
15095 detail::MeasuredResidualStepAction::Backtrack
15096 ? "backtrack"
15097 : "reject";
15098 neb_log() << "[gp_oie] recovery trial outer=" << outer
15099 << " image=" << fixed_image << " source_F="
15100 << (trial ? trial->source_force
15101 : std::numeric_limits<double>::quiet_NaN())
15102 << " trial_F="
15103 << (trial ? trial->trial_force
15104 : std::numeric_limits<double>::quiet_NaN())
15105 << " action=" << action_name;
15106 if (assessment.backtrack_fraction) {
15107 neb_log() << " fraction=" << *assessment.backtrack_fraction;
15108 }
15109 neb_log() << std::endl;
15110 }
15111 }
15112
15113 if (adjacent_mep_trial.measured) {
15114 const detail::AdjacentMepTrialAssessment assessment =
15115 adjacent_mep_recovery.observePendingTrial(
15116 path, adjacent_mep_trial.energy,
15117 adjacent_mep_trial.gradient, config.conv_tol);
15118 auto applied_action = assessment.step.action;
15119 const double backtrack_fraction =
15120 assessment.step.backtrack_fraction.value_or(
15121 std::numeric_limits<double>::quiet_NaN());
15122 if (applied_action == detail::MeasuredResidualStepAction::Accept) {
15123 if (adjacent_mep_recovery.commitPendingTrial(
15124 path, adjacent_mep_trial.energy,
15125 adjacent_mep_trial.gradient)) {
15126 adjacent_mep_recovery.clearPendingTrial();
15127 oracle_updates_current_path = true;
15128 any_oracle_path_update = true;
15129 recordLatestClimbRestartSnapshot(
15130 adjacent_mep_recovery.ciIndex(),
15131 /*from_drift=*/false);
15132 } else {
15133 applied_action = detail::MeasuredResidualStepAction::Reject;
15134 adjacent_mep_recovery.clearPendingTrial();
15135 }
15136 } else if (applied_action ==
15137 detail::MeasuredResidualStepAction::Backtrack) {
15138 if (!std::isfinite(backtrack_fraction) ||
15139 !adjacent_mep_recovery.backtrackPendingTrial(
15140 backtrack_fraction)) {
15141 applied_action = detail::MeasuredResidualStepAction::Reject;
15142 adjacent_mep_recovery.clearPendingTrial();
15143 }
15144 } else {
15145 adjacent_mep_recovery.clearPendingTrial();
15146 }
15147 if (config.verbose && log_rank == 0) {
15148 const char* action_name =
15149 applied_action == detail::MeasuredResidualStepAction::Accept
15150 ? "accept"
15151 : applied_action ==
15152 detail::MeasuredResidualStepAction::Backtrack
15153 ? "backtrack"
15154 : "reject";
15155 neb_log() << "[gp_oie] outer=" << outer << " mep_trial: image="
15156 << adjacent_mep_recovery.targetImage()
15157 << " source_perp_linf="
15158 << adjacent_mep_recovery.sourceResidual()
15159 << " trial_perp_linf=" << assessment.residual
15160 << " saddle_energy_ok="
15161 << assessment.saddle_energy_certificate
15162 << " action=" << action_name;
15163 if (applied_action ==
15164 detail::MeasuredResidualStepAction::Backtrack) {
15165 neb_log() << " fraction=" << backtrack_fraction;
15166 }
15167 neb_log() << std::endl;
15168 }
15169 }
15170
15171 (void)secondary_idx; // canonical OIE admits at most one image/round
15172
15173 // A true force of the climbing image, or of the best evaluated
15174 // saddle candidate, is already under the final tolerance. Stop
15175 // before the refit and before any further oracle call, and return
15176 // that geometry. Sella checks the same way after each true
15177 // evaluation.
15178 auto acceptMeasuredCandidate = [&](int index, bool require_bracket) {
15179 double force = std::numeric_limits<double>::infinity();
15180 if (!detail::measuredForceBelowFinalTolerance(
15181 path, index, config.conv_tol, require_bracket, training_obs,
15182 &force))
15183 return false;
15184 result.returned_true_force = force;
15185 result.converged = true;
15186 result.convergence_status = GPNEBConvergenceStatus::ForceTolerance;
15187 converged_worst_idx = index;
15188 result.max_energy_image = index;
15189 result.outer_iterations = outer + 1;
15190 if (config.record_composition_trace) {
15192 rec.outer_idx = outer;
15193 rec.oracle_target_image = index;
15194 rec.max_oracle_force = path.saddleForce(index);
15195 rec.ci_active = ci_active;
15196 rec.ci_index = ci_active ? index : -1;
15197 rec.barrier_estimate =
15198 detail::forwardBarrierEnergy(path, index);
15199 rec.certificates.force_tolerance = true;
15200 rec.certificates.ci_force_ok = true;
15201 rec.theta.push_back(
15203 rec.theta.push_back(gp.getSigma2());
15204 const auto& length_scales =
15206 for (Eigen::Index k = 0; k < length_scales.size(); ++k)
15207 rec.theta.push_back(*(length_scales.data() + k));
15208 result.composition_trace.push_back(std::move(rec));
15209 }
15210 if (config.verbose && log_rank == 0) {
15211 neb_log() << "[gp_oie] outer=" << outer << " true force "
15212 << force << " at image " << index
15213 << " is below tolerance " << config.conv_tol
15214 << "; returning that geometry" << std::endl;
15215 }
15216 return true;
15217 };
15218 const int measured_candidate =
15219 (ci_active && ci_idx > 0 && ci_idx < path.numImages() - 1)
15220 ? ci_idx
15221 : detail::bestEvaluatedSaddleCandidate(path);
15222 if (acceptMeasuredCandidate(
15223 measured_candidate,
15224 !(ci_active && measured_candidate == ci_idx)))
15225 break;
15226 if (have_best_climb_positions && std::isfinite(best_climb_ci_energy) &&
15227 best_climb_ci_gradient.size() > 0 &&
15228 path.forceMagnitude(best_climb_ci_gradient) < config.conv_tol &&
15229 detail::restoreOieMeasuredClimb(
15230 path, best_climb_positions, best_climb_ci_idx,
15231 best_climb_ci_energy, best_climb_ci_gradient) &&
15232 acceptMeasuredCandidate(best_climb_ci_idx, false)) {
15233 break;
15234 }
15235
15236 // Phase 2 secondary oracle: canonical OIE uses the same
15237 // worst_idx slot for CI refinement.
15238
15239 // Warm-start the hyperparam optimizer after the first
15240 // num_bigiter_initparam outer iters. Re-seeding from data
15241 // every iter blows away the previous fit and lets SCG land
15242 // in a different local minimum, producing wildly different
15243 // GP gradients across iters. AtomicDimer.cpp:1218-1233
15244 // does this for the dimer; without it the gprn NEB chain
15245 // oscillates between unrelated configurations even when
15246 // climbing-image marker reassignment is correct.
15247 const bool reinit_hyperparams =
15248 outer < config.num_bigiter_initparam && !preserve_imported_kernel;
15249 const bool fixed_theta_refresh =
15250 detail::shouldUseFixedThetaRefreshForOracleBatch(
15251 config, config.acquisition, oracle_positions_batch.size(),
15252 selected_imspe_score, imspe_chain_trace, reinit_hyperparams,
15253 frozen_sweep, oracle_uses_rejected_proposal,
15254 oracle_updates_current_path, model_boundary_evidence,
15255 oracle_uses_recovery_growth_proposal);
15256 AccumulateWallTime refit_wall(phase_refit_seconds);
15257 bool conditioned_consistent_rows = false;
15258 if (config.active_posterior_refits) {
15259 gp.clearModeRefitHint();
15260 if (!reinit_hyperparams && !pruned_in_outer &&
15261 refit_oracle_batch.R.rows() > 0) {
15262 const auto force_norm =
15263 path.convergenceForceNorm(refit_oracle_batch.R.cols());
15264 // The kernel parameters are held only when the prediction
15265 // made without the acquired rows resolved them: its error and
15266 // its spread both lie below the convergence tolerance, so the
15267 // rows change no decision of the search. The conditioned
15268 // posterior reproduces its own rows under any kernel and
15269 // cannot supply that evidence; a broad or collapsed kernel
15270 // takes the refit, whose objective stationarity test decides
15271 // whether the parameters move. Coordinate-map changes and
15272 // rows exceeding the active-set ceiling retain their full
15273 // refit path.
15274 gpr::GaussianProcessRegression::RefitTrustReport trust_report;
15275 if (session && !config.attach_manifold_chart &&
15276 !config.use_geodesic_prior)
15277 conditioned_consistent_rows =
15278 session->conditionGPOnConsistentRows(
15279 refit_oracle_batch, force_norm,
15280 config.adaptive_prune_max_observations,
15281 config.conv_tol, &trust_report);
15282 if (!conditioned_consistent_rows)
15284 refit_oracle_batch, config.conv_tol, force_norm,
15285 &trust_report);
15286 }
15287 }
15288 // The posterior and image-row indices must describe the retained set.
15289 // A trusted correction retains the full-fit prefix. Pruning belongs
15290 // to a full refit so it cannot discard data owned by the background.
15291 int ceiling_dropped = 0;
15292 if (session != nullptr && config.adaptive_prune_max_observations > 0 &&
15293 path.numImages() > 0 && !gp.hasPendingActivePosteriorRefit() &&
15295 gpr::Coord ceiling_band(path.numImages(),
15296 path.image(0).positions.size());
15297 for (int i = 0; i < path.numImages(); ++i) {
15298 ceiling_band.row(i) = path.image(i).positions.transpose();
15299 }
15300 ceiling_dropped = session->boundActiveSetToBand(
15301 ceiling_band, config.adaptive_prune_max_observations);
15302 if (ceiling_dropped > 0) {
15303 neb_log() << "[ceiling] outer=" << outer
15304 << " dropped=" << ceiling_dropped
15305 << " ntrain=" << training_obs.R.rows() << "\n";
15306 }
15307 }
15308 if (!oracle_positions_batch.empty() || ceiling_dropped > 0) {
15309 if (wallClockReached()) break;
15310 if (!config.local_tier_classic)
15311 detail::attachClassicGlobalManifoldChart(config, path, session,
15312 gp, training_obs);
15313 if (config.training_policy != nullptr)
15314 noteNebPolicyProgress(session, outer, result,
15315 static_cast<int>(training_obs.R.rows()));
15316 if (conditioned_consistent_rows) {
15317 ++result.fixed_theta_refreshes;
15318 } else if (config.active_posterior_refits) {
15319 const bool refit =
15320 session
15321 ? session->refitGP(reinit_hyperparams)
15322 : optimizeUnlessPolicy(gp, training_obs, atoms_config,
15323 reinit_hyperparams, config,
15324 outer, result, pruned_in_outer);
15325 if (refit)
15326 ++result.hyperparameter_refits;
15327 else
15328 ++result.fixed_theta_refreshes;
15329 } else if (fixed_theta_refresh) {
15330 bool count_as_refit = false;
15331 if (session) {
15332 session->refreshCovarianceCache();
15333 } else if (config.training_policy != nullptr) {
15334 policy::SearchState state;
15335 state.kind = config.training_search_kind;
15336 state.iteration = outer;
15337 state.oracle_calls = liveOracleCalls(result);
15338 state.training_size =
15339 static_cast<int>(training_obs.R.rows());
15340 state.hyperparameter_refits = result.hyperparameter_refits;
15341 state.engine_would_retrain = false;
15342 state.engine_would_rebuild_factor =
15343 !pruned_in_outer &&
15344 !gp.trainingFactorAppendable(training_obs.R.rows());
15345 state.gp = &gp;
15347 *config.training_policy, state)) {
15348 if (training_obs.R.rows() == 0) {
15350 } else {
15352 training_obs, atoms_config, reinit_hyperparams,
15353 reinit_hyperparams, reinit_hyperparams);
15354 gp.optimize(training_obs);
15355 count_as_refit = true;
15356 }
15357 } else {
15358 const bool rebuild =
15360 *config.training_policy, state);
15361 if (training_obs.R.rows() == 0) {
15363 } else if (!(pruned_in_outer &&
15364 !config.attach_manifold_chart &&
15366 if (rebuild) gp.invalidateTrainingFactorCache();
15367 gp.updateModelWithFullData(training_obs);
15368 }
15369 }
15370 } else {
15371 gp.updateModelWithFullData(training_obs);
15372 }
15373 if (count_as_refit)
15374 ++result.hyperparameter_refits;
15375 else
15376 ++result.fixed_theta_refreshes;
15377 } else {
15378 bool count_as_hyperparameter_refit = true;
15379 if (session) {
15380 if (!reinit_hyperparams) {
15381 // Every profile takes the training-revision
15382 // cadence gate in refreshCovarianceCache: a
15383 // full SCG on every append random-walks the
15384 // sloppy magnitude/lengthscale valley, the
15385 // surface breathes with theta, and the band
15386 // re-equilibrates to each new surface (09/17:
15387 // mag2 swings 2-3x between consecutive outers
15388 // with the barrier tracking it). On the
15389 // extended profile the per-append SCG is also
15390 // the outer-iteration wall once ntrain grows:
15391 // O(iters * n^3) per outer, 30-70 s per outer
15392 // at ntrain ~ 100 on the Baker campaign cells
15393 // that never enter the inner loop.
15394 session->refreshCovarianceCache();
15395 } else {
15396 count_as_hyperparameter_refit =
15397 session->refitGP(reinit_hyperparams);
15398 gpr::PhaseTimers::notePeak("after_refit");
15399 // No MAD amplitude clamp; see cold-start refit
15400 // note.
15401 }
15402 } else {
15403 count_as_hyperparameter_refit = optimizeUnlessPolicy(
15404 gp, training_obs, atoms_config, reinit_hyperparams,
15405 config, outer, result, pruned_in_outer);
15406 }
15407 if (count_as_hyperparameter_refit)
15408 ++result.hyperparameter_refits;
15409 else
15410 ++result.fixed_theta_refreshes;
15411 }
15412 apply_secant_consistency();
15413 }
15414 refit_wall.stop();
15415 if (wallClockReached()) break;
15416 // Force gates use the refit posterior for unevaluated images
15417 // while retaining oracle data installed on the accepted band.
15418 const int ci_marker_before_refit =
15419 detail::activeClimbingMarkerIndex(path);
15420 AccumulateWallTime path_wall(phase_path_seconds);
15421 (void)refreshGpPath(/*preserve_evaluated=*/true);
15422 path_wall.stop();
15423 detail::refreshOieClimbingImageAfterRefit(
15424 config, path, ci_active, ci_candidate_idx, ci_marker_before_refit,
15425 protected_oie_ci_idx, per_image_var, uncertainty_threshold,
15426 climb_change);
15427 const bool measured_anchor_improved_after_refit =
15428 updateMeasuredAnchor();
15429 if (detail::shouldProtectMeasuredProposalRestart(
15430 fixed_point_applied_kind != FixedPointProposalKind::None,
15431 measured_anchor_improved_before_refit,
15432 measured_anchor_improved_after_refit)) {
15433 if (ci_active) {
15434 recordLatestClimbRestartSnapshot(
15435 detail::selectOieClimbingImageIndex(ci_active, path),
15436 /*from_drift=*/false);
15437 } else {
15438 latest_equal_positions = snapshotPathPositions();
15439 have_latest_equal_positions = true;
15440 }
15441 measured_reparam_restart_protected = true;
15442 }
15443
15444 // ---- Convergence check (Acq. 2: variance + force) -----------
15445 //
15446 // Two simultaneous gates:
15447 // 1. max chain GP posterior variance < unc_convergence
15448 // (the surrogate is everywhere-confident on the
15449 // relaxed chain),
15450 // 2. max NEB-force across ALL intermediate images
15451 // < conv_tol. Each image's NEB-force uses oracle
15452 // gradient when path.image(i).evaluated, otherwise
15453 // the GP-predicted gradient stored on the image; a
15454 // one-image gate at worst_idx admits false convergence
15455 // whenever the acquisition picks a low-force image
15456 // for information rather than for residual gradient.
15457 const int n_imgs = path.numImages();
15458 auto wholeBandMaxNebForce = [&]() {
15459 path.computeNEBForces();
15460 double max_force = 0.0;
15461 int max_force_idx = -1;
15462 for (int i = 1; i < n_imgs - 1; ++i) {
15463 const double fi = path.nebForceMagnitude(i);
15464 if (std::isfinite(fi) && fi > max_force) {
15465 max_force = fi;
15466 max_force_idx = i;
15467 }
15468 }
15469 return std::make_pair(max_force, max_force_idx);
15470 };
15471 auto [max_oracle_force, max_oracle_force_idx] = wholeBandMaxNebForce();
15472 // The batch can hold stencil or sweep confirmations with no
15473 // planner pick (worst_idx = -1); batch[0]'s path update then
15474 // says nothing about a worst image, and nebForce(-1) is out
15475 // of bounds.
15476 double oracle_target_force =
15477 (oracle_updates_current_path && worst_idx > 0 &&
15478 worst_idx < n_imgs - 1)
15479 ? path.nebForceMagnitude(worst_idx)
15480 : std::numeric_limits<double>::infinity();
15481 if (current_ci_oracle_updates_path && ci_idx > 0 &&
15482 ci_idx < n_imgs - 1) {
15483 current_ci_oracle_force_vector = path.nebForce(ci_idx);
15484 current_ci_oracle_force = current_ci_oracle_force_vector.norm();
15485 current_ci_oracle_position = path.image(ci_idx).positions;
15486 }
15487 for (int i = 0; i < n_imgs; ++i) {
15488 if (path.image(i).evaluated) {
15489 if (i >= static_cast<int>(image_evaluated.size())) {
15490 image_evaluated.resize(n_imgs, 0);
15491 }
15492 image_evaluated[i] = 1;
15493 }
15494 }
15495 const double ci_activation_oracle_force =
15496 detail::oieCurrentTrueForceCertificate(path, image_evaluated,
15497 image_observed_current);
15498 f0_baseline = detail::updateInitialForceBaseline(
15499 f0_baseline, ci_activation_oracle_force, ci_active);
15500 const bool ci_was_active = ci_active;
15501 const bool post_oracle_ci_band_force_gate_ready =
15502 ci_active ||
15503 detail::shouldActivateClimbingImage(
15504 config, /*ci_active=*/false, outer, relaxation_inner,
15505 f0_baseline, ci_candidate_variance);
15506 const auto post_oracle_activation_state =
15507 detail::updateOieClimbingImageActivation(
15508 config, path, ci_active, per_image_var, config.ucb_kappa,
15509 uncertainty_threshold,
15510 protected_oie_ci_idx > 0 ? protected_oie_ci_idx
15511 : transition_focal_handoff
15512 ? config.oracle_transition_focal_image
15513 : -1,
15514 post_oracle_ci_band_force_gate_ready);
15515 ci_active = post_oracle_activation_state.ci_active;
15516 ci_idx = post_oracle_activation_state.ci_idx;
15517 if (!ci_was_active && ci_active) {
15518 const auto refreshed_force = wholeBandMaxNebForce();
15519 max_oracle_force = refreshed_force.first;
15520 max_oracle_force_idx = refreshed_force.second;
15521 oracle_target_force = oracle_updates_current_path
15522 ? path.nebForceMagnitude(worst_idx)
15523 : std::numeric_limits<double>::infinity();
15524 }
15525 current_ci_oracle_updates_path = false;
15526 if (ci_idx > 0 && ci_idx < n_imgs - 1) {
15527 for (std::size_t k = 0; k < oracle_indices.size(); ++k) {
15528 if (oracle_off_path_position[k] == 0 &&
15529 oracle_indices[k] == ci_idx) {
15530 current_ci_oracle_updates_path = true;
15531 current_ci_oracle_force_vector = path.nebForce(ci_idx);
15532 current_ci_oracle_force =
15533 current_ci_oracle_force_vector.norm();
15534 current_ci_oracle_position = path.image(ci_idx).positions;
15535 break;
15536 }
15537 }
15538 }
15539 if (std::isfinite(oracle_target_force) && oracle_target_force > 0.0) {
15540 smallest_oracle_force =
15541 std::min(smallest_oracle_force, oracle_target_force);
15542 }
15543 result.max_force_history.push_back(max_oracle_force);
15544 // Best-path tracking (CatLearn ML-NEB; see best_path_positions
15545 // decl above). Snapshot the band whenever this outer's WHOLE-BAND
15546 // max NEB force (max over every intermediate image, true gradient
15547 // where evaluated else GP) is the lowest seen. The whole-band max
15548 // -- not the picked image's force -- is the merit because the
15549 // divergence that must be rejected is a single non-picked image
15550 // collapsing into a GP-extrapolation region (force spiking to
15551 // 1e3-1e4 eV/A while the picked image stays low); tracking only
15552 // the picked image's force is blind to it. The outer-loop-top
15553 // restore relaxes from this snapshot, so a band with any exploded
15554 // image never becomes the anchor.
15555 if (std::isfinite(max_oracle_force) && max_oracle_force > 0.0 &&
15556 max_oracle_force < best_oracle_force &&
15557 detail::bandBracketsSaddle(path)) {
15558 best_oracle_force = max_oracle_force;
15559 best_path_positions = snapshotPathPositions();
15560 }
15561 if (std::isfinite(max_oracle_force) && max_oracle_force > 0.0) {
15562 last_outer_oracle_force = max_oracle_force;
15563 }
15564 const double current_ci_merit_force = detail::oieClimbMeritForce(
15565 ci_active,
15566 current_ci_oracle_updates_path ? true : oracle_updates_current_path,
15567 current_ci_oracle_updates_path ? ci_idx : worst_idx, ci_idx,
15568 current_ci_oracle_updates_path ? current_ci_oracle_force
15569 : oracle_target_force,
15570 max_oracle_force, max_oracle_force_idx,
15571 detail::shouldUseCiOnlyClimbMerit(
15572 /*mmf_handoff_snapshot=*/false,
15573 config.climbing_image_converged_only));
15574 if (detail::shouldRetainOieBestClimbSnapshot(
15575 ci_active, current_ci_merit_force, best_climb_oracle_force,
15576 detail::hasTruePesSaddleEnergyCertificate(path, ci_idx,
15577 config.conv_tol),
15578 climbRestartBarrier(ci_idx), best_climb_barrier)) {
15579 best_climb_oracle_force = current_ci_merit_force;
15580 recordBestClimbRestartSnapshot(ci_idx);
15581 }
15582 result.outer_iterations = outer + 1;
15583
15584 if (config.record_band_trace) {
15585 auto capture = [&](gpr::GaussianProcessRegression& model) {
15586 result.band_trace.push_back(
15587 captureOieBandTrace(path, model, outer, per_image_var,
15588 config.record_band_trace_geometry,
15589 config.record_band_trace_snapshot,
15590 liveOracleCalls(result)));
15591 };
15592 if (session) {
15593 auto model = session->acquireGlobalModel();
15594 capture(model.gp());
15595 } else {
15596 capture(gp);
15597 }
15598 }
15599
15600 // Canonical OIE convergence + sweep control (Koistinen 2017 /
15601 // 2019 atomic_GP_NEB_OIE.m N_uneval==0 gate). Count the
15602 // intermediate images that still lack TRUE oracle data at
15603 // their current geometry. Posterior certification spares
15604 // oracle calls in the exploring arms, but a convergence
15605 // claim is a statement about the true PES: an image whose
15606 // only evidence is the surrogate's own confidence does not
15607 // count as confirmed, otherwise a smooth seed GP certifies
15608 // the whole band and the N_uneval==0 gate accepts an
15609 // unrelaxed chain with a surrogate barrier.
15610 int n_uneval = 0;
15611 double max_true_force_eval = 0.0;
15612 bool has_true_force_eval = false;
15613 for (int i = 1; i < n_imgs - 1; ++i) {
15614 const bool observed_current_i =
15615 i < static_cast<int>(image_observed_current.size()) &&
15616 image_observed_current[i] != 0;
15617 if (!path.image(i).evaluated && !observed_current_i) {
15618 ++n_uneval;
15619 } else {
15620 const double fi = path.nebForceMagnitude(i);
15621 if (std::isfinite(fi) && fi > max_true_force_eval) {
15622 max_true_force_eval = fi;
15623 }
15624 if (std::isfinite(fi)) {
15625 has_true_force_eval = true;
15626 }
15627 }
15628 }
15629 const int conv_ci_idx =
15630 detail::selectOieClimbingImageIndex(ci_active, path);
15631 if (ci_active && config.climbing_image_converged_only &&
15632 conv_ci_idx > 0 && conv_ci_idx < n_imgs - 1) {
15633 (void)detail::restoreObservedImageIfPresent(
15634 training_obs, path.image(conv_ci_idx));
15635 }
15636 // Saddle convergence uses the oracle force at the climbing image's
15637 // current positions. A gradient left behind by a step that this
15638 // image no longer occupies is not that force.
15639 double ci_force_now = std::numeric_limits<double>::infinity();
15640 if (conv_ci_idx > 0 && conv_ci_idx < n_imgs - 1) {
15641 double measured = std::numeric_limits<double>::infinity();
15642 if (detail::adoptMeasuredOracleRow(path, conv_ci_idx, training_obs,
15643 &measured)) {
15644 ci_force_now = measured;
15645 }
15646 }
15647 continuation_rewards.observe(continuationMerit());
15648 // CI-image GP fixed-point trap: the climbing image's own GP
15649 // NEB force has fallen below inner_conv_tol while its true
15650 // oracle force stays above conv_tol -- the surrogate is
15651 // confidently wrong at the CI. Consumed by the dimer hook.
15652 const bool ci_gp_min_trap =
15653 (current_ci_oracle_updates_path || oracle_updates_current_path) &&
15654 detail::shouldFlagGpMinTrap(
15655 ci_candidate_gp_force,
15656 current_ci_oracle_updates_path ? current_ci_oracle_force
15657 : oracle_target_force,
15658 config.conv_tol, config.inner_conv_tol, inner_exit);
15659 if (detail::shouldInvalidateOieClimbRestartSnapshot(
15660 ci_active,
15661 current_ci_oracle_updates_path ? true
15662 : oracle_updates_current_path,
15663 current_ci_oracle_updates_path ? ci_idx : worst_idx,
15664 ci_candidate_idx, ci_candidate_gp_force,
15665 current_ci_oracle_updates_path ? current_ci_oracle_force
15666 : oracle_target_force,
15667 config.conv_tol, config.inner_conv_tol, inner_exit)) {
15668 clearLatestClimbRestartSnapshot();
15669 }
15670 // CI-only convergence requires a true gradient at this geometry.
15671 // Off-saddle spring residuals do not determine saddle stationarity.
15672 const bool ci_true_saddle_energy_ok =
15673 detail::hasTruePesSaddleEnergyCertificate(path, conv_ci_idx,
15674 config.conv_tol);
15675 const bool same_previous_ci_oracle =
15676 previous_ci_oracle_index &&
15677 *previous_ci_oracle_index == conv_ci_idx;
15678 const double previous_ci_oracle_force_norm =
15679 previous_ci_oracle_force ? previous_ci_oracle_force->norm()
15680 : std::numeric_limits<double>::infinity();
15681 const bool ci_true_force_worsened =
15682 detail::shouldApplyOieTrueForceBbCorrection(
15683 ci_active, current_ci_oracle_updates_path, conv_ci_idx,
15684 previous_ci_oracle_index.value_or(-1), current_ci_oracle_force,
15685 previous_ci_oracle_force_norm, ci_true_saddle_energy_ok);
15686 const double model_noise_tol =
15687 detail::effectiveModelNoiseTolerance(config);
15688 auto refreshAdjacentMepRecovery = [&]() {
15689 if (classic_oie_relaxation &&
15690 config.climbing_image_converged_only) {
15691 adjacent_mep_recovery.clear();
15692 return false;
15693 }
15694 const int target = detail::selectOieAdjacentMepRecoveryTarget(
15695 ci_active, fixed_image > 0, path, conv_ci_idx, config.conv_tol,
15696 model_noise_tol);
15697 if (target > 0) {
15698 return adjacent_mep_recovery.arm(path, conv_ci_idx, target,
15699 model_noise_tol);
15700 }
15701 adjacent_mep_recovery.clear();
15702 return false;
15703 };
15704 (void)refreshAdjacentMepRecovery();
15705 bool lower_barrier_checked = false;
15706 auto lower_barrier_action = detail::OieLowerBarrierAction::KeepCurrent;
15707 bool ci_adjacent_mep_checked = false;
15708 bool ci_adjacent_mep_ok = false;
15709 // Composition-level outer-iter trace (opt-in golden harness).
15710 // Filled once per outer with deterministic decision-state fields;
15711 // pushed on every exit path of this outer (converge breaks + fall
15712 // through). See OuterIterCompositionTrace.h.
15713 bool composition_trace_pushed = false;
15714 OuterIterCompositionTraceRecord composition_rec;
15715 if (config.record_composition_trace) {
15716 composition_rec.outer_idx = outer;
15717 composition_rec.oracle_target_image = worst_idx;
15718 composition_rec.max_oracle_force = max_oracle_force;
15719 composition_rec.n_uneval = n_uneval;
15720 composition_rec.ci_active = ci_active;
15721 composition_rec.ci_index = ci_active ? conv_ci_idx : -1;
15722 {
15723 const int hi_bar =
15724 detail::selectOieClimbingImageIndex(ci_active, path);
15725 composition_rec.barrier_estimate =
15726 detail::forwardBarrierEnergy(path, hi_bar);
15727 }
15728 composition_rec.theta.clear();
15729 composition_rec.theta.push_back(
15731 composition_rec.theta.push_back(gp.getSigma2());
15732 {
15733 const auto& ls =
15735 for (Eigen::Index k = 0; k < ls.size(); ++k)
15736 composition_rec.theta.push_back(*(ls.data() + k));
15737 }
15738 composition_rec.certificates.n_uneval_zero = (n_uneval == 0);
15739 composition_rec.certificates.mep_force_ok =
15740 (max_oracle_force < model_noise_tol);
15741 composition_rec.certificates.ci_force_ok =
15742 (!ci_active || ci_force_now < model_noise_tol);
15743 composition_rec.certificates.true_saddle_energy =
15744 ci_true_saddle_energy_ok;
15745 // ci_adjacent_perp is evaluated only on the CI-only path when
15746 // the force is already below tol; default false until then.
15747 composition_rec.certificates.ci_adjacent_perp = false;
15748 }
15749 auto push_composition_trace = [&]() {
15750 if (!config.record_composition_trace || composition_trace_pushed)
15751 return;
15752 composition_trace_pushed = true;
15753 result.composition_trace.push_back(composition_rec);
15754 };
15755 if (detail::shouldAcceptOieCiOnlyConvergence(
15756 pending_band_action.active(), ci_active,
15757 config.climbing_image_converged_only,
15758 conv_ci_idx > 0 && conv_ci_idx < n_imgs - 1 &&
15759 path.image(conv_ci_idx).evaluated,
15760 ci_true_saddle_energy_ok, belowPathCeiling(conv_ci_idx),
15761 ci_force_now, model_noise_tol)) {
15762 result.converged = true;
15763 result.convergence_status =
15764 detail::convergenceStatusForCurrentTolerance(config);
15765 converged_worst_idx = conv_ci_idx;
15766 if (config.record_composition_trace) {
15767 composition_rec.certificates.certified_ci_only_branch = true;
15768 composition_rec.certificates.ci_force_ok = true;
15769 composition_rec.certificates.ci_adjacent_perp =
15770 detail::ciAdjacentPerpendicularForceConverged(
15771 path, conv_ci_idx, model_noise_tol);
15772 }
15773 push_composition_trace();
15774 break;
15775 }
15776 // Proactive collapse restore: a force-quiet CI on a barrier that
15777 // dropped well below a retained certified climb is a shoulder, not
15778 // a new pass. Restore the best climb even when the collapsed path
15779 // fails the local-max energy certificate (Baker 01 outer~28: bar
15780 // 1.4 with F_ci~0 while best is ~2.16). Without this, the accept
15781 // path never runs and OIE thrashs the shoulder.
15782 //
15783 // A collapse can also present NOT force-quiet: a non-picked image
15784 // detonates into a GP-extrapolation valley, the barrier drops far
15785 // below the retained certified climb, the CI energy certificate
15786 // breaks, and the band posterior variance blows past the ceiling
15787 // (exothermic Diels-Alder: bar 0.09 vs retained ~1.1 with the CI
15788 // still at force ~0.4). The retained CERTIFIED bracket outranks
15789 // an unconfident collapsed state, so the lower-barrier decision
15790 // must also be consulted in that signature; its own logic still
15791 // refuses to restore over a certified or pending true-PES local
15792 // maximum.
15793 const bool ci_force_quiet =
15794 std::isfinite(ci_force_now) && ci_force_now < model_noise_tol;
15795 const bool band_collapse_unconfident =
15796 !ci_true_saddle_energy_ok &&
15797 !detail::posteriorVarianceConverged(max_chain_var,
15798 uncertainty_threshold);
15799 // The surrogate relaxation carried the band above the best measured
15800 // climb by more than the posterior can explain.
15801 const double band_spread =
15802 std::isfinite(max_chain_var) && max_chain_var > 0.0
15803 ? std::sqrt(max_chain_var)
15804 : std::numeric_limits<double>::quiet_NaN();
15805 // That rule is about a barrier the surrogate reports. An evaluated
15806 // climbing image is a measured barrier only when the true-PES
15807 // local-maximum check also holds. Such a barrier above an earlier
15808 // climb is the band climbing, not the surrogate running away: an
15809 // early corner-cutting climb far below the saddle would otherwise
15810 // recall the band after every measured step toward it. An evaluated
15811 // point without that check can still be a surrogate excursion.
15812 const bool climb_measured =
15813 conv_ci_idx > 0 && conv_ci_idx < path.numImages() - 1 &&
15814 path.image(conv_ci_idx).evaluated && ci_true_saddle_energy_ok;
15815 const bool band_excursion =
15816 !climb_measured && have_best_climb_positions &&
15817 std::isfinite(band_spread) && std::isfinite(best_climb_barrier) &&
15818 climbRestartBarrier(conv_ci_idx) - best_climb_barrier >
15819 std::sqrt(2.0) * band_spread;
15820 if (ci_active && config.climbing_image_converged_only &&
15821 have_best_climb_positions &&
15822 (ci_force_quiet || band_collapse_unconfident || band_excursion)) {
15823 const double cur_bar_now = climbRestartBarrier(conv_ci_idx);
15824 detail::OieLowerBarrierEvidence current_evidence;
15825 current_evidence.true_pes_local_max = ci_true_saddle_energy_ok;
15826 lower_barrier_checked = true;
15827 lower_barrier_action = decideRestoreByThompson(
15828 detail::selectOieLowerBarrierAction(
15829 have_best_climb_positions, best_climb_ci_idx,
15830 best_climb_barrier, best_climb_oracle_force, cur_bar_now,
15831 current_evidence,
15832 climb_measured ? std::numeric_limits<double>::quiet_NaN()
15833 : band_spread),
15834 continuationMerit());
15835 if (lower_barrier_action ==
15836 detail::OieLowerBarrierAction::RestoreCertifiedBest &&
15837 detail::restoreOieMeasuredClimb(
15838 path, best_climb_positions, best_climb_ci_idx,
15839 best_climb_ci_energy, best_climb_ci_gradient)) {
15840 // Recovery anchors belong to the geometry they measured.
15841 recovery_stencil_anchor.clear();
15842 recovery_growth_backtrack_target.clear();
15843 adjacent_mep_recovery.clear();
15844 path.computeNEBForces();
15845 band_stepper.reset();
15846 frozen_sweep = false;
15847 // The retained climb supplies its own measurement. Acquire
15848 // missing neighbors once for this retained barrier.
15849 if (best_climb_ci_idx > 0 &&
15850 best_climb_ci_idx < path.numImages() - 1 &&
15851 !(best_climb_barrier == last_restore_stencil_barrier)) {
15852 last_restore_stencil_barrier = best_climb_barrier;
15853 // The accept certificate is band-wide, so refresh
15854 // every interior image of the restored geometry
15855 // with true oracle data before certifying.
15856 std::vector<int> rest_targets;
15857 for (int ti = 1; ti < path.numImages() - 1; ++ti) {
15858 // Climbing-image-only convergence reads the two
15859 // neighbours; the rest of the band is not bought.
15860 if (config.climbing_image_converged_only &&
15861 std::abs(ti - best_climb_ci_idx) > 1) {
15862 continue;
15863 }
15864 if (path.image(ti).evaluated) continue;
15865 // A row already bought at exactly this position
15866 // is the same observation of the same PES: restore
15867 // it from the training set instead of purchasing it
15868 // again.
15869 if (session &&
15870 detail::restoreObservedImageIfPresent(
15871 session->training_obs, path.image(ti))) {
15872 continue;
15873 }
15874 if (oracleGeometryRefused(path.image(ti).positions))
15875 continue;
15876 rest_targets.push_back(ti);
15877 }
15878 if (!rest_targets.empty()) {
15879 std::vector<Eigen::VectorXd> rest_pos;
15880 rest_pos.reserve(rest_targets.size());
15881 std::vector<NEBOracleEvaluationContext> rest_ctx;
15882 rest_ctx.reserve(rest_targets.size());
15883 for (const int ti: rest_targets) {
15884 rest_pos.push_back(path.image(ti).positions);
15885 NEBOracleEvaluationContext ctx;
15886 ctx.image_index = ti;
15887 ctx.force_quality = true;
15888 ctx.current_chain_certificate = true;
15889 ctx.force_stencil = true;
15890 rest_ctx.push_back(ctx);
15891 }
15892 std::vector<char> rest_measured;
15893 const auto rest_res = evaluateBandTargets(
15894 rest_pos, &rest_ctx, rest_measured);
15895 result.oracle_calls +=
15896 static_cast<int>(rest_targets.size());
15897 result.oracle_calls_outer +=
15898 static_cast<int>(rest_targets.size());
15899 for (std::size_t k = 0; k < rest_targets.size(); ++k) {
15900 if (!rest_measured[k]) continue;
15901 const int ti = rest_targets[k];
15902 path.image(ti).energy = rest_res[k].energy;
15903 path.image(ti).gradient = rest_res[k].gradient;
15904 path.image(ti).evaluated = true;
15905 if (session) {
15906 session->appendObservation(
15907 ti, path.image(ti).positions,
15908 rest_res[k].energy, rest_res[k].gradient);
15909 }
15910 }
15911 if (session) session->refreshCovarianceCache();
15912 }
15913 path.computeNEBForces();
15914 const auto f_rest = path.nebForce(best_climb_ci_idx);
15915 const double rest_ci_f =
15916 f_rest.size() > 0
15917 ? path.saddleForce(best_climb_ci_idx)
15918 : std::numeric_limits<double>::infinity();
15919 if (!pending_band_action.active() &&
15920 belowPathCeiling(best_climb_ci_idx) &&
15921 detail::hasTruePesSaddleEnergyCertificate(
15922 path, best_climb_ci_idx, config.conv_tol) &&
15923 (config.climbing_image_converged_only ||
15924 detail::bandPerpendicularForceConverged(
15925 path, model_noise_tol)) &&
15926 std::isfinite(rest_ci_f) &&
15927 rest_ci_f < model_noise_tol) {
15928 result.converged = true;
15929 result.convergence_status =
15930 detail::convergenceStatusForCurrentTolerance(
15931 config);
15932 converged_worst_idx = best_climb_ci_idx;
15933 if (config.record_composition_trace) {
15934 composition_rec.certificates
15935 .certified_ci_only_branch = true;
15936 composition_rec.certificates.true_saddle_energy =
15937 true;
15938 composition_rec.certificates.ci_adjacent_perp =
15939 detail::ciAdjacentPerpendicularForceConverged(
15940 path, best_climb_ci_idx, model_noise_tol);
15941 }
15942 push_composition_trace();
15943 break;
15944 }
15945 }
15946 recordLatestClimbRestartSnapshot(best_climb_ci_idx,
15947 /*from_drift=*/false);
15948 push_composition_trace();
15949 // Force decisions below refer to the displaced band.
15950 continue;
15951 }
15952 }
15953 if (!pending_band_action.active() && ci_active &&
15954 config.climbing_image_converged_only && !ci_true_saddle_energy_ok &&
15955 !oracle_performed && std::isfinite(ci_force_now) &&
15956 ci_force_now < model_noise_tol) {
15957 // A force-quiet climbing image that the true-PES energy
15958 // certificate refutes, with nothing acquired this outer, leaves
15959 // the loop refitting the same model forever (12_ethane: 128
15960 // outers at 0.028 eV/A with arm none, the marker on a 2.98 eV
15961 // shoulder while a measured image sat higher). The marker
15962 // follows the highest measured interior image; the climb
15963 // restarts there on the next outer.
15964 const int marker_before = conv_ci_idx;
15965 detail::refreshOieClimbingImageMarker(ci_active, path);
15966 const int marker_after = detail::activeClimbingMarkerIndex(path);
15967 if (marker_after != marker_before && marker_after > 0) {
15968 clearLatestClimbRestartSnapshot();
15969 if (log_rank == 0)
15970 neb_log()
15971 << "[ci-marker] outer=" << outer
15972 << " energy certificate refuted image " << marker_before
15973 << "; climbing marker moved to image " << marker_after
15974 << std::endl;
15975 }
15976 }
15977 if (!pending_band_action.active() && ci_active &&
15978 config.climbing_image_converged_only && ci_true_saddle_energy_ok &&
15979 std::isfinite(ci_force_now) && ci_force_now < model_noise_tol) {
15980 // CI force under effective model-noise tol (mat26 HCN: CI
15981 // ~0.21, status model-noise floor, bar 2.165). Fill adj stencil
15982 // and require MEP adj-perp. Collapsed lower-barrier shoulders
15983 // are resolved through the typed lower-barrier policy.
15984 std::vector<char> conv_image_evaluated(
15985 static_cast<std::size_t>(path.numImages()), 0);
15986 std::vector<char> conv_image_observed_current(
15987 static_cast<std::size_t>(path.numImages()), 0);
15988 for (int i = 0; i < path.numImages(); ++i) {
15989 const auto& img = path.image(i);
15990 if (img.evaluated && img.gradient.size() > 0) {
15991 conv_image_evaluated[static_cast<std::size_t>(i)] = 1;
15992 conv_image_observed_current[static_cast<std::size_t>(i)] =
15993 1;
15994 }
15995 }
15996 // Neighbour energies establish the measured saddle bracket.
15997 // Their force residuals remain diagnostics in the CI-only phase.
15998 std::vector<int> missing_conv_stencil;
15999 for (int i = conv_ci_idx - 1; i <= conv_ci_idx + 1; i += 2) {
16000 if (i < 1 || i >= path.numImages() - 1) continue;
16001 if (conv_image_evaluated[static_cast<std::size_t>(i)] == 0 &&
16002 !oracleGeometryRefused(path.image(i).positions)) {
16003 missing_conv_stencil.push_back(i);
16004 }
16005 }
16006 if (!missing_conv_stencil.empty()) {
16007 std::vector<Eigen::VectorXd> stencil_positions;
16008 stencil_positions.reserve(missing_conv_stencil.size());
16009 std::vector<NEBOracleEvaluationContext> stencil_contexts;
16010 stencil_contexts.reserve(missing_conv_stencil.size());
16011 for (const int stencil_idx: missing_conv_stencil) {
16012 stencil_positions.push_back(
16013 path.image(stencil_idx).positions);
16014 NEBOracleEvaluationContext ctx;
16015 ctx.image_index = stencil_idx;
16016 ctx.force_quality = true;
16017 ctx.current_chain_certificate = true;
16018 ctx.force_stencil = true;
16019 stencil_contexts.push_back(ctx);
16020 }
16021 std::vector<char> stencil_measured;
16022 const auto stencil_results = evaluateBandTargets(
16023 stencil_positions, &stencil_contexts, stencil_measured);
16024 result.oracle_calls +=
16025 static_cast<int>(missing_conv_stencil.size());
16026 result.oracle_calls_outer +=
16027 static_cast<int>(missing_conv_stencil.size());
16028 int stencil_appended = 0;
16029 for (std::size_t k = 0; k < missing_conv_stencil.size(); ++k) {
16030 if (!stencil_measured[k]) continue;
16031 const int image_idx = missing_conv_stencil[k];
16032 const double e_oracle = stencil_results[k].energy;
16033 const Eigen::VectorXd& g_oracle =
16034 stencil_results[k].gradient;
16035 path.image(image_idx).energy = e_oracle;
16036 path.image(image_idx).gradient = g_oracle;
16037 path.image(image_idx).evaluated = true;
16038 if (session) {
16039 session->appendObservation(
16040 image_idx, path.image(image_idx).positions,
16041 e_oracle, g_oracle);
16042 ++stencil_appended;
16043 }
16044 }
16045 // Session training rows and the shared distributed
16046 // Cholesky factor must remain size-consistent before any
16047 // GP variance probe or relaxation solve.
16048 if (session && stencil_appended > 0) {
16049 session->refreshCovarianceCache();
16050 }
16051 path.computeNEBForces();
16052 if (conv_ci_idx > 0 && conv_ci_idx < path.numImages() - 1) {
16053 ci_force_now = path.saddleForce(conv_ci_idx);
16054 }
16055 }
16056 if (detail::shouldAcceptOieCiOnlyConvergence(
16057 pending_band_action.active(), ci_active,
16058 config.climbing_image_converged_only,
16059 path.image(conv_ci_idx).evaluated,
16060 detail::hasTruePesSaddleEnergyCertificate(path, conv_ci_idx,
16061 config.conv_tol),
16062 belowPathCeiling(conv_ci_idx), ci_force_now,
16063 model_noise_tol)) {
16064 result.converged = true;
16065 result.convergence_status =
16066 detail::convergenceStatusForCurrentTolerance(config);
16067 converged_worst_idx = conv_ci_idx;
16068 if (config.record_composition_trace) {
16069 composition_rec.certificates.certified_ci_only_branch =
16070 true;
16071 composition_rec.certificates.ci_force_ok = true;
16072 composition_rec.certificates.ci_adjacent_perp =
16073 detail::ciAdjacentPerpendicularForceConverged(
16074 path, conv_ci_idx, model_noise_tol);
16075 }
16076 push_composition_trace();
16077 break;
16078 }
16079 const bool adj_perp_ok =
16080 std::isfinite(ci_force_now) && ci_force_now < model_noise_tol &&
16081 detail::ciAdjacentPerpendicularForceConverged(path, conv_ci_idx,
16082 model_noise_tol);
16083 ci_adjacent_mep_checked = true;
16084 ci_adjacent_mep_ok = adj_perp_ok;
16085 (void)refreshAdjacentMepRecovery();
16086 if (config.record_composition_trace) {
16087 composition_rec.certificates.ci_adjacent_perp = adj_perp_ok;
16088 composition_rec.certificates.ci_force_ok =
16089 (ci_force_now < model_noise_tol);
16090 }
16091 const double current_accept_barrier =
16092 climbRestartBarrier(conv_ci_idx);
16093 detail::OieLowerBarrierEvidence current_evidence;
16094 current_evidence.true_pes_local_max = ci_true_saddle_energy_ok;
16095 current_evidence.adjacent_mep_checked = true;
16096 current_evidence.adjacent_mep = adj_perp_ok;
16097 lower_barrier_checked = true;
16098 lower_barrier_action = decideRestoreByThompson(
16099 detail::selectOieLowerBarrierAction(
16100 have_best_climb_positions, best_climb_ci_idx,
16101 best_climb_barrier, best_climb_oracle_force,
16102 current_accept_barrier, current_evidence),
16103 continuationMerit());
16104 if (adj_perp_ok &&
16105 lower_barrier_action ==
16106 detail::OieLowerBarrierAction::RestoreCertifiedBest &&
16107 have_best_climb_positions) {
16108 if (detail::restoreOieMeasuredClimb(
16109 path, best_climb_positions, best_climb_ci_idx,
16110 best_climb_ci_energy, best_climb_ci_gradient)) {
16111 // Recovery anchors belong to the geometry they measured.
16112 recovery_stencil_anchor.clear();
16113 recovery_growth_backtrack_target.clear();
16114 adjacent_mep_recovery.clear();
16115 path.computeNEBForces();
16116 band_stepper.reset();
16117 frozen_sweep = false;
16118 if (best_climb_ci_idx > 0 &&
16119 best_climb_ci_idx < path.numImages() - 1 &&
16120 !(best_climb_barrier == last_restore_stencil_barrier)) {
16121 last_restore_stencil_barrier = best_climb_barrier;
16122 // Band-wide certificate: refresh every interior
16123 // image of the restored geometry.
16124 std::vector<int> rest_targets;
16125 for (int ti = 1; ti < path.numImages() - 1; ++ti) {
16126 if (config.climbing_image_converged_only &&
16127 std::abs(ti - best_climb_ci_idx) > 1) {
16128 continue;
16129 }
16130 if (path.image(ti).evaluated) continue;
16131 // Same reuse rule as the restore path above.
16132 if (session &&
16133 detail::restoreObservedImageIfPresent(
16134 session->training_obs, path.image(ti))) {
16135 continue;
16136 }
16137 if (oracleGeometryRefused(path.image(ti).positions))
16138 continue;
16139 rest_targets.push_back(ti);
16140 }
16141 if (!rest_targets.empty()) {
16142 std::vector<Eigen::VectorXd> rest_pos;
16143 rest_pos.reserve(rest_targets.size());
16144 std::vector<NEBOracleEvaluationContext> rest_ctx;
16145 rest_ctx.reserve(rest_targets.size());
16146 for (const int ti: rest_targets) {
16147 rest_pos.push_back(path.image(ti).positions);
16149 ctx.image_index = ti;
16150 ctx.force_quality = true;
16151 ctx.current_chain_certificate = true;
16152 ctx.force_stencil = true;
16153 rest_ctx.push_back(ctx);
16154 }
16155 std::vector<char> rest_measured;
16156 const auto rest_res = evaluateBandTargets(
16157 rest_pos, &rest_ctx, rest_measured);
16158 result.oracle_calls +=
16159 static_cast<int>(rest_targets.size());
16160 result.oracle_calls_outer +=
16161 static_cast<int>(rest_targets.size());
16162 for (std::size_t k = 0; k < rest_targets.size();
16163 ++k) {
16164 if (!rest_measured[k]) continue;
16165 const int ti = rest_targets[k];
16166 path.image(ti).energy = rest_res[k].energy;
16167 path.image(ti).gradient = rest_res[k].gradient;
16168 path.image(ti).evaluated = true;
16169 if (session) {
16170 session->appendObservation(
16171 ti, path.image(ti).positions,
16172 rest_res[k].energy,
16173 rest_res[k].gradient);
16174 }
16175 }
16176 if (session) session->refreshCovarianceCache();
16177 }
16178 path.computeNEBForces();
16179 const auto f_rest = path.nebForce(best_climb_ci_idx);
16180 const double rest_ci_f =
16181 f_rest.size() > 0
16182 ? path.saddleForce(best_climb_ci_idx)
16183 : std::numeric_limits<double>::infinity();
16184 const bool rest_energy_ok =
16185 detail::hasTruePesSaddleEnergyCertificate(
16186 path, best_climb_ci_idx, config.conv_tol);
16187 const bool rest_adj_ok =
16188 config.climbing_image_converged_only ||
16189 detail::bandPerpendicularForceConverged(
16190 path, model_noise_tol);
16191 if (rest_energy_ok && rest_adj_ok &&
16192 belowPathCeiling(best_climb_ci_idx) &&
16193 std::isfinite(rest_ci_f) &&
16194 rest_ci_f < model_noise_tol) {
16195 result.converged = true;
16196 result.convergence_status =
16197 detail::convergenceStatusForCurrentTolerance(
16198 config);
16199 converged_worst_idx = best_climb_ci_idx;
16200 if (config.record_composition_trace) {
16201 composition_rec.certificates
16202 .certified_ci_only_branch = true;
16203 composition_rec.certificates
16204 .true_saddle_energy = true;
16205 composition_rec.certificates.ci_adjacent_perp =
16206 detail::
16207 ciAdjacentPerpendicularForceConverged(
16208 path, best_climb_ci_idx,
16209 model_noise_tol);
16210 }
16211 push_composition_trace();
16212 break;
16213 }
16214 }
16215 recordLatestClimbRestartSnapshot(best_climb_ci_idx,
16216 /*from_drift=*/false);
16217 push_composition_trace();
16218 // Force decisions below refer to the displaced band.
16219 continue;
16220 }
16221 } else if (adj_perp_ok &&
16222 lower_barrier_action ==
16223 detail::OieLowerBarrierAction::KeepCurrent &&
16224 belowPathCeiling(conv_ci_idx)) {
16225 result.converged = true;
16226 result.convergence_status =
16227 detail::convergenceStatusForCurrentTolerance(config);
16228 converged_worst_idx = conv_ci_idx;
16229 if (config.record_composition_trace) {
16230 composition_rec.certificates.certified_ci_only_branch =
16231 true;
16232 }
16233 push_composition_trace();
16234 break;
16235 }
16236 }
16237 if (pending_band_action.active()) {
16238 frozen_sweep = false;
16239 }
16240 if (!pending_band_action.active() && n_uneval == 0) {
16241 // Every intermediate image carries oracle-grade data at its
16242 // current geometry. Accept when the band force is below the
16243 // effective model-noise tol and (for CI-NEB) the climbing
16244 // image is also quiet with a true-PES energy certificate.
16245 const bool mep_ok = max_oracle_force < model_noise_tol;
16246 const bool ci_ok = !ci_active || ci_force_now < model_noise_tol;
16247 if (mep_ok && ci_ok && belowPathCeiling(conv_ci_idx) &&
16248 (!ci_active || ci_true_saddle_energy_ok)) {
16249 result.converged = true;
16250 result.convergence_status =
16251 detail::convergenceStatusForCurrentTolerance(config);
16252 converged_worst_idx =
16253 (conv_ci_idx > 0 && conv_ci_idx < n_imgs - 1) ? conv_ci_idx
16254 : worst_idx;
16255 if (config.record_composition_trace) {
16256 composition_rec.certificates.mep_force_ok = mep_ok;
16257 composition_rec.certificates.ci_force_ok = ci_ok;
16258 composition_rec.certificates.certified_full_band_branch =
16259 true;
16260 }
16261 push_composition_trace();
16262 break;
16263 }
16264 // Confirmed un-converged on the true PES: leave the sweep
16265 // and relax the band again against the now fully-sampled
16266 // GP.
16267 frozen_sweep = false;
16268 } else if (frozen_sweep) {
16269 // Mid-sweep: keep confirming images one per round as long
16270 // as every image confirmed so far sits below the band
16271 // acceptance tier on the true PES. The band tier is the
16272 // two-tier T_MEP role (Koistinen 2017 Sec. 5): the full-band
16273 // accept above demands max_oracle_force < model_noise_tol,
16274 // and the CI keeps the tight conv_tol via its certificates,
16275 // so a sweep only becomes pointless once a confirmed image
16276 // exceeds BOTH tiers -- the GP-converged band was wrong
16277 // there; bail out and relax again with the new data.
16278 frozen_sweep = (max_true_force_eval <
16279 std::max(config.conv_tol, model_noise_tol));
16280 } else {
16281 // Exploring: enter the full-band sweep once the inner
16282 // relaxation drove the GP band force below conv_tol
16283 // everywhere (MATLAB normF_R < T_MEP), the posterior
16284 // variance is below threshold, and any true-gradient
16285 // current-chain image already observed in this round also
16286 // sits below conv_tol.
16287 // Bayesian acquisition stop: the GP is confident the climbing
16288 // image's force is converged when (a) its GP NEB force is below
16289 // conv_tol and (b) the GP is locally confident there -- the
16290 // climbing image's posterior ENERGY variance is below the same
16291 // scale-relative threshold (unc_convergence * sigma_f^2) the
16292 // global gate uses, applied to the climbing image alone rather
16293 // than the chain max. Using the local variance lets the sweep
16294 // start while far-from-saddle images are still uncertain; the
16295 // force and energy-variance gates are kept separate (no
16296 // dimensional mixing of an eV^2 variance into an eV/A force).
16297 // The full-band sweep confirms selected images on the true PES
16298 // without changing the CI-only convergence exit above.
16299 const double ci_var =
16300 (conv_ci_idx > 0 &&
16301 conv_ci_idx < static_cast<int>(per_image_var.size()))
16302 ? std::max(0.0, per_image_var[conv_ci_idx])
16303 : std::numeric_limits<double>::infinity();
16304 const bool ci_force_confident =
16305 detail::oieCiPosteriorForceCertificate(ci_active, ci_force_now,
16306 ci_var, config.conv_tol,
16307 uncertainty_threshold);
16308 const double terminal_reference_force =
16309 detail::oieTerminalSweepReferenceForce(
16310 relaxed_gp_force, max_oracle_force, has_true_force_eval);
16311 // The sweep-entry force gates are band-tier checks (MATLAB
16312 // normF_R < T_MEP): the GP band force and any already
16313 // observed true force compare against the loosest tier an
16314 // accept path uses, not the tight CI conv_tol. The CI's own
16315 // gate (ci_force_confident above) keeps conv_tol.
16316 frozen_sweep =
16317 !pending_band_action.active() &&
16318 detail::shouldStartTerminalSweep(
16319 terminal_reference_force, max_chain_var,
16320 uncertainty_threshold, has_true_force_eval,
16321 max_true_force_eval,
16322 std::max(config.conv_tol, model_noise_tol),
16323 ci_force_confident,
16324 config.climbing_image_converged_only && ci_active);
16325 }
16326 bool measured_ci_step_applied = false;
16327 // The image is at a measured point above tolerance, whether the
16328 // measurement is this outer's or a restored row's: a band whose
16329 // surrogate reports the climbing image converged relaxes nothing
16330 // and measures chain images while the true force stands
16331 // (09_parentdielsalder: inner=0 every outer after one rejected
16332 // step). The step's own trust radius bounds the retries.
16333 if (!result.converged && !config.outer_iter_hook && session &&
16334 ci_active && config.climbing_image_converged_only &&
16335 ci_true_saddle_energy_ok && conv_ci_idx > 0 &&
16336 conv_ci_idx < n_imgs - 1 && path.image(conv_ci_idx).evaluated) {
16337 int measured_step_calls = 0;
16338 double& step_radius =
16339 measured_step_radius.try_emplace(conv_ci_idx, band_max_step)
16340 .first->second;
16341 bool marginal_step = false;
16342 measured_ci_step_applied =
16343 detail::applyOieMeasuredClimbingImageStep(
16344 path, conv_ci_idx, *session, oracle, measured_step_calls,
16346 config.conv_tol, band_max_step, step_radius,
16347 /*surrogate_measured_non_descent=*/false, outer,
16348 config.verbose && log_rank == 0, config.cell,
16349 acquisition_contact_floor, &marginal_step);
16350 result.oracle_calls += measured_step_calls;
16351 result.oracle_calls_outer += measured_step_calls;
16352 const double marginal_radius = step_radius;
16353 if (measured_ci_step_applied) {
16354 // An accepted step is a measured improvement at a measured
16355 // point and supersedes the climb-restart bookkeeping: the
16356 // best-climb restart otherwise restores the higher-barrier
16357 // geometry the step left and undoes it on the next outer
16358 // (10_tetrazine: the same step accepted four times from
16359 // the same point).
16360 best_climb_oracle_force = path.nebForceMagnitude(conv_ci_idx);
16361 last_outer_oracle_force = best_climb_oracle_force;
16362 recordBestClimbRestartSnapshot(conv_ci_idx);
16363 // The recovery anchors refer to the geometry before the
16364 // step; left active they re-stage that geometry and
16365 // suppress the measurement the step asks for.
16366 adjacent_mep_recovery.clear();
16367 recovery_stencil_anchor.clear();
16368 recovery_growth_backtrack_target.clear();
16369 recordLatestClimbRestartSnapshot(conv_ci_idx,
16370 /*from_drift=*/false);
16371 // A marginal step leaves the stored radius at zero, which
16372 // spends the measured-step radius of this image; the zero
16373 // survives the best-climb snapshot reset above.
16374 if (marginal_step)
16375 measured_step_radius[conv_ci_idx] = marginal_radius;
16376 frozen_sweep = false;
16377 band_stepper.reset();
16378 }
16379 }
16380 // The surrogate walk from the best measured climb was measured as
16381 // non-descent: the climbing image's true force this outer is above
16382 // the best measured at the same image. Left to the next outer, the
16383 // restart restores that geometry and the same surrogate relaxes it
16384 // along the same walk (17_claisen: 0.065 eV/A at the restored point,
16385 // 0.2-2 eV/A after each walk, outers 60-90). A measured non-descent
16386 // is the trust-region evidence: the band returns to the best
16387 // measured climb now and takes the measured step from it, the step
16388 // radius the only walk the model still owns. A rejected step halves
16389 // that radius and the band stands at the measured point either way.
16390 // The measured step decides for itself whether the model at the
16391 // best climb still has a step to offer (its radius); the return
16392 // costs no call when it has none.
16393 // A walk whose endpoint the surrogate itself ranks below the best
16394 // measured climb proposed an improvement; when the oracle refuses
16395 // it, the row is information and the refit makes the next walk a
16396 // different walk (09_dfcp: fourteen returns for nothing). A walk
16397 // whose endpoint the surrogate ranks no better than the best climb
16398 // was cut short by its budget, not proposed: the measured step
16399 // from the best climb is the step the model still owns
16400 // (17_claisen: the surrogate's climbing force at every endpoint
16401 // above the best climb's measured force). The posterior force error
16402 // and uncertainty remain diagnostics in the return log.
16403 const bool walk_not_a_proposal =
16404 std::isfinite(walk_endpoint_gp_force) &&
16405 std::isfinite(best_climb_oracle_force) &&
16406 walk_endpoint_gp_force >= best_climb_oracle_force;
16407 // A walk that ended where the previous walk ended measured a point
16408 // the model already holds: the return would restore the same best
16409 // climb for the same walk (23_hcn_h2: fifteen outers at one drift
16410 // endpoint, the true force creeping 2.70 to 2.89 eV/A, the step
16411 // radius spent). The band keeps that endpoint and the drift
16412 // restart continues from it.
16413 const bool walk_reproduced_endpoint =
16414 current_ci_oracle_updates_path && previous_ci_oracle_position &&
16415 same_previous_ci_oracle &&
16416 current_ci_oracle_position.size() ==
16417 previous_ci_oracle_position->size() &&
16418 detail::positionsCoincide(current_ci_oracle_position,
16419 *previous_ci_oracle_position);
16420 // The return applies the tolerance-edge step, and the tolerance
16421 // edge is the best climb within one tolerance of convergence: its
16422 // residual above the tolerance no larger than the tolerance itself
16423 // (17_claisen: 0.014 eV/A of residual against 0.051). A best climb
16424 // further out (23_hcn_h2 at 1.0 eV/A, 09_dfcp at 0.86, 12_ethane
16425 // at 0.39) is explored by the walk; returning to it restored a
16426 // band the walks had left for good reason. The model's force
16427 // uncertainty at a measured climb is far below either residual and
16428 // does not separate them.
16429 const auto bestClimbAtTheToleranceEdge = [&]() {
16430 if (best_climb_ci_gradient.size() == 0) return false;
16431 const double residual =
16432 path.forceMagnitude(best_climb_ci_gradient) - config.conv_tol;
16433 return residual > 0.0 && residual <= config.conv_tol;
16434 };
16435 const bool surrogate_walk_measured_non_descent =
16436 walk_not_a_proposal && !walk_reproduced_endpoint && ci_active &&
16437 current_ci_oracle_updates_path && have_best_climb_positions &&
16438 best_climb_ci_idx == conv_ci_idx &&
16439 std::isfinite(best_climb_oracle_force) &&
16440 best_climb_oracle_force > config.conv_tol &&
16441 std::isfinite(current_ci_oracle_force) &&
16442 current_ci_oracle_force > best_climb_oracle_force &&
16443 std::isfinite(best_climb_ci_energy) && conv_ci_idx > 0 &&
16444 conv_ci_idx < n_imgs - 1 &&
16445 best_climb_ci_gradient.size() ==
16446 path.image(conv_ci_idx).positions.size() &&
16447 bestClimbAtTheToleranceEdge();
16448 if (!measured_ci_step_applied && !result.converged &&
16449 !config.outer_iter_hook && session &&
16450 config.climbing_image_converged_only &&
16451 surrogate_walk_measured_non_descent) {
16452 restorePathPositions(best_climb_positions);
16453 Image& climb = path.image(conv_ci_idx);
16454 climb.energy = best_climb_ci_energy;
16455 climb.gradient = best_climb_ci_gradient;
16456 climb.evaluated = true;
16457 path.computeNEBForces();
16458 int measured_step_calls = 0;
16459 double& step_radius =
16460 measured_step_radius.try_emplace(conv_ci_idx, band_max_step)
16461 .first->second;
16462 bool marginal_step = false;
16463 measured_ci_step_applied =
16464 detail::applyOieMeasuredClimbingImageStep(
16465 path, conv_ci_idx, *session, oracle, measured_step_calls,
16467 config.conv_tol, band_max_step, step_radius,
16468 /*surrogate_measured_non_descent=*/true, outer,
16469 config.verbose && log_rank == 0, config.cell,
16470 acquisition_contact_floor, &marginal_step);
16471 result.oracle_calls += measured_step_calls;
16472 result.oracle_calls_outer += measured_step_calls;
16473 // Accepted or not, the band stands at a measured climb whose
16474 // force is the best measured at this image; the restart
16475 // bookkeeping records that geometry so the next outer relaxes
16476 // from it rather than from the walk's endpoint.
16477 best_climb_oracle_force = path.nebForceMagnitude(conv_ci_idx);
16478 last_outer_oracle_force = best_climb_oracle_force;
16479 const double retained_radius = step_radius;
16480 recordBestClimbRestartSnapshot(conv_ci_idx);
16481 if (!measured_ci_step_applied || marginal_step)
16482 measured_step_radius[conv_ci_idx] = retained_radius;
16483 adjacent_mep_recovery.clear();
16484 recovery_stencil_anchor.clear();
16485 recovery_growth_backtrack_target.clear();
16486 recordLatestClimbRestartSnapshot(conv_ci_idx,
16487 /*from_drift=*/false);
16488 frozen_sweep = false;
16489 band_stepper.reset();
16490 if (config.verbose && log_rank == 0 && measured_step_calls > 0) {
16491 neb_log() << "[oie-measured-step] outer=" << outer
16492 << " returned to the best measured climb (force "
16493 << best_climb_oracle_force
16494 << ") after the walk "
16495 "measured "
16496 << current_ci_oracle_force << " (surrogate "
16497 << walk_endpoint_gp_force
16498 << " at the endpoint; walk error "
16499 << ci_walk_force_error << ", posterior sd "
16500 << ci_walk_force_sd << ")"
16501 << (measured_ci_step_applied ? "; step accepted"
16502 : "; step rejected")
16503 << std::endl;
16504 }
16505 }
16506 if (!measured_ci_step_applied && !result.converged &&
16507 !config.outer_iter_hook &&
16508 (ci_gp_min_trap || ci_true_force_worsened) &&
16509 current_ci_oracle_updates_path && previous_ci_oracle_position &&
16510 previous_ci_oracle_force && same_previous_ci_oracle &&
16511 conv_ci_idx > 0 && conv_ci_idx < n_imgs - 1) {
16512 if (detail::applyOieBbForceCorrection(
16513 path, conv_ci_idx, *previous_ci_oracle_position,
16514 *previous_ci_oracle_force, current_ci_oracle_force_vector,
16515 config.conv_tol, band_max_step)) {
16516 recordLatestClimbRestartSnapshot(conv_ci_idx,
16517 /*from_drift=*/false);
16518 if (detail::shouldScheduleOiePathMotionReparam(config, true)) {
16519 hook_reparam_pending = true;
16520 hook_reparam_anchor_idx = conv_ci_idx;
16521 hook_reparam_source_signature =
16522 interiorPositionSignature(path);
16523 }
16524 frozen_sweep = false;
16525 band_stepper.reset();
16526 }
16527 }
16528 if (current_ci_oracle_updates_path &&
16529 current_ci_oracle_position.size() > 0 &&
16530 current_ci_oracle_force_vector.size() > 0) {
16531 previous_ci_oracle_position = current_ci_oracle_position;
16532 previous_ci_oracle_force = current_ci_oracle_force_vector;
16533 previous_ci_oracle_index = conv_ci_idx;
16534 }
16535 // The measured climbing step can be the evaluation that crosses
16536 // the final tolerance. Return that geometry before the handoff
16537 // buys another force.
16538 if (!result.converged) {
16539 double stepped_returned = std::numeric_limits<double>::infinity();
16540 if (detail::measuredForceBelowFinalTolerance(
16541 path, conv_ci_idx, config.conv_tol, false, training_obs,
16542 &stepped_returned)) {
16543 result.returned_true_force = stepped_returned;
16544 result.converged = true;
16545 result.convergence_status =
16547 converged_worst_idx = conv_ci_idx;
16548 result.max_energy_image = conv_ci_idx;
16549 result.outer_iterations = outer + 1;
16550 if (config.record_composition_trace) {
16551 composition_rec.certificates.ci_force_ok = true;
16552 composition_rec.certificates.force_tolerance = true;
16553 }
16554 push_composition_trace();
16555 break;
16556 }
16557 }
16558 // Per-outer-iter hook: the OCI-NEB MMF dimer burst. The
16559 // burst target is the current climbing image, which the
16560 // reassignment above keeps on the highest-energy image.
16561 // The controller owns the relative adaptive trigger; the
16562 // GP-NEB layer only provides the climbing-image callback.
16563 const int hook_ci_idx = conv_ci_idx;
16564 const bool hook_ci_evaluated = hook_ci_idx > 0 &&
16565 hook_ci_idx < path.numImages() - 1 &&
16566 path.image(hook_ci_idx).evaluated;
16567 bool hook_ran = false;
16568 bool hook_converged = false;
16569 bool hook_added_training = false;
16570 bool hook_left_chain_moved = false;
16571 const std::vector<Eigen::VectorXd> pre_hook_positions =
16572 snapshotPathPositions();
16573 double hook_max_chain_var = std::numeric_limits<double>::infinity();
16574 if (!per_image_var.empty()) {
16575 hook_max_chain_var = 0.0;
16576 for (int i = 1; i < path.numImages() - 1; ++i) {
16577 if (i >= static_cast<int>(per_image_var.size())) break;
16578 const double v = per_image_var[static_cast<std::size_t>(i)];
16579 if (std::isfinite(v) && v > hook_max_chain_var)
16580 hook_max_chain_var = v;
16581 }
16582 }
16583 if (config.outer_iter_hook && session &&
16584 !pending_band_action.active() &&
16585 detail::shouldRunOciMmfHookOnCurrentTrueCi(
16586 ci_active, hook_ci_idx, worst_idx, oracle_updates_current_path,
16587 path.numImages(), hook_ci_evaluated, max_oracle_force_idx,
16588 ci_force_now, max_oracle_force, config.conv_tol,
16589 hook_max_chain_var, uncertainty_threshold,
16590 config.inner_unc_relative,
16591 (static_cast<bool>(config.current_ci_oracle_priority) &&
16592 saddle_handoff_needs_ci_oracle) ||
16593 fixed_point_requests_mmf,
16594 ci_adjacent_mep_checked && !ci_adjacent_mep_ok)) {
16595 const Eigen::Index pre_hook_training_rows = training_obs.R.rows();
16596 const bool granted_burst = fixed_point_requests_mmf;
16597 {
16599 context.image_index = hook_ci_idx;
16600 context.force_quality = true;
16601 context.minimum_mode_search = true;
16602 const ScopedOracleEvaluationContext context_scope(
16603 config.oracle_evaluation_context, context);
16604 // The fixed-point grant is one MMF burst. The adaptive
16605 // force bar would refuse it while the climb is still
16606 // above the handoff tolerance, and the grant is then
16607 // spent. Mark the session so this burst actually runs.
16608 if (fixed_point_requests_mmf)
16609 session->stagnation_handoff = true;
16610 config.outer_iter_hook(path, hook_ci_idx, outer, *session,
16611 hook_converged, ci_gp_min_trap);
16612 }
16613 if (wallClockReached()) break;
16614 detail::throwIfOracleSessionRestartRequested(
16615 config.oracle_session_restart_requested);
16616 hook_ran = true;
16617 // A fixed-point grant is spent by the burst it authorized.
16618 fixed_point_requests_mmf = false;
16619 hook_added_training =
16620 training_obs.R.rows() > pre_hook_training_rows;
16621 if (granted_burst && !hook_added_training && session &&
16622 hook_ci_idx > 0 && hook_ci_idx < path.numImages() - 1) {
16623 // The stall that granted this burst means the trust-ball
16624 // information is exhausted, and the controller's harvest
16625 // caps can then reject every row the dimer paid for
16626 // (02_hcch: 29 oracle calls, saddle estimate refined from
16627 // a runaway channel to 0.14 eV, zero rows committed, and
16628 // the next fixed point stops "without new information").
16629 // Commit the burst's refined, measured climbing-image row
16630 // so the training set sees what the grant bought.
16631 const Image& refined = path.image(hook_ci_idx);
16632 if (refined.evaluated &&
16633 refined.gradient.size() == refined.positions.size() &&
16634 refined.positions.allFinite() &&
16635 refined.gradient.allFinite() &&
16636 std::isfinite(refined.energy) &&
16637 detail::findRestorableObservationRow(training_obs,
16638 refined) < 0) {
16639 session->appendObservation(
16640 hook_ci_idx, refined.positions, refined.energy,
16641 refined.gradient,
16644 session->refreshCovarianceCache();
16645 hook_added_training =
16646 training_obs.R.rows() > pre_hook_training_rows;
16647 if (config.verbose && log_rank == 0) {
16648 neb_log() << "[gp_oie] outer=" << outer
16649 << " granted burst: committed the "
16650 "refined climbing-image row"
16651 << std::endl;
16652 }
16653 }
16654 }
16655 const std::vector<Eigen::VectorXd> post_hook_positions =
16656 snapshotPathPositions();
16657 auto positions_match = [](const std::vector<Eigen::VectorXd>& lhs,
16658 const std::vector<Eigen::VectorXd>& rhs) {
16659 if (lhs.size() != rhs.size()) return false;
16660 for (std::size_t i = 0; i < lhs.size(); ++i) {
16661 if (lhs[i].size() != rhs[i].size() ||
16662 !lhs[i].isApprox(rhs[i])) {
16663 return false;
16664 }
16665 }
16666 return true;
16667 };
16668 // Reparam (redistribute + reset L-BFGS) only when the hook
16669 // moved the band beyond the trust radius, measured in the same
16670 // earth-mover's metric the drift certifier uses (the paper ties
16671 // the SIDPP arc redistribution and the trust ball to one active
16672 // path geometry). A sub-trust-radius nudge -- e.g. the dimer
16673 // burst refining a near-saddle climbing image -- does not
16674 // change the arc-length distribution enough to justify
16675 // discarding the L-BFGS curvature pairs and the burst's own CI
16676 // progress.
16677 bool hook_moved_chain =
16678 !positions_match(pre_hook_positions, post_hook_positions);
16679 if (hook_moved_chain && trust_threshold > 0.0) {
16680 gpr::TrustRadius hook_metric;
16681 hook_metric.setAtomsConfiguration(atoms_config);
16682 hook_metric.setDistanceMetric(config.trust_metric);
16683 double hook_max_move = 0.0;
16684 for (int i = 1; i < path.numImages() - 1 &&
16685 i < static_cast<int>(pre_hook_positions.size());
16686 ++i) {
16687 EigenMatrix R_anchor(1, pre_hook_positions[i].size());
16688 R_anchor.row(0) = pre_hook_positions[i].transpose();
16689 hook_metric.setTrainingData(R_anchor);
16690 const double d_i =
16691 hook_metric.distanceToTraining(post_hook_positions[i]);
16692 if (std::isfinite(d_i) && d_i > hook_max_move)
16693 hook_max_move = d_i;
16694 }
16695 hook_moved_chain = hook_max_move > trust_threshold;
16696 }
16697 // A dimer/MMF burst is a local second-order saddle
16698 // certificate. Final OCI-NEB convergence also requires the
16699 // band to run through that saddle: the CI-adjacent true-PES
16700 // perpendicular force certificate excludes off-path saddles
16701 // while leaving spring-parallel force out of the MEP test.
16702 // Re-oracle the CI-adjacent stencil after a converged burst so
16703 // the energy local-max and adj-perp certificates see current
16704 // true-PES neighbors rather than pre-burst ridge energies.
16705 std::vector<ActiveLearningSession::IndexedObservation>
16706 hook_stencil_observations;
16707 bool hook_stencil_committed = false;
16708 const auto commitHookStencil = [&]() {
16709 if (!session || hook_stencil_committed ||
16710 hook_stencil_observations.empty()) {
16711 return;
16712 }
16713 session->appendIndexedObservations(hook_stencil_observations);
16714 hook_stencil_committed = true;
16715 };
16716 double hook_returned = std::numeric_limits<double>::infinity();
16717 if (hook_converged && detail::measuredForceBelowFinalTolerance(
16718 path, hook_ci_idx, config.conv_tol, false,
16719 training_obs, &hook_returned)) {
16720 result.returned_true_force = hook_returned;
16721 // The burst already measured a climbing image under the
16722 // final tolerance. Neighbour forces already on the path stay
16723 // there; do not buy another stencil.
16724 result.converged = true;
16725 result.convergence_status =
16727 converged_worst_idx = hook_ci_idx;
16728 result.max_energy_image = hook_ci_idx;
16729 result.outer_iterations = outer + 1;
16730 push_composition_trace();
16731 break;
16732 }
16733 if (hook_converged) {
16734 std::vector<char> hook_image_evaluated(
16735 static_cast<std::size_t>(path.numImages()), 0);
16736 std::vector<char> hook_image_observed_current(
16737 static_cast<std::size_t>(path.numImages()), 0);
16738 for (int i = 0; i < path.numImages(); ++i) {
16739 const auto& img = path.image(i);
16740 if (img.evaluated && img.gradient.size() > 0) {
16741 hook_image_evaluated[static_cast<std::size_t>(i)] = 1;
16742 hook_image_observed_current[static_cast<std::size_t>(
16743 i)] = 1;
16744 }
16745 }
16746 // Force re-evaluation of CI-adjacent interiors: clear the
16747 // observed flags so selectOciHandoffStencilOracleTargets
16748 // returns them even when stale true data exists.
16749 for (int j = hook_ci_idx - 1; j <= hook_ci_idx + 1; j += 2) {
16750 if (j <= 0 || j >= path.numImages() - 1) continue;
16751 hook_image_observed_current[static_cast<std::size_t>(j)] =
16752 0;
16753 hook_image_evaluated[static_cast<std::size_t>(j)] = 0;
16754 }
16755 const auto hook_missing_stencil =
16756 detail::selectOciHandoffStencilOracleTargets(
16757 hook_ci_idx, path.numImages(), hook_image_evaluated,
16758 hook_image_observed_current);
16759 if (!hook_missing_stencil.empty()) {
16760 std::vector<Eigen::VectorXd> stencil_positions;
16761 stencil_positions.reserve(hook_missing_stencil.size());
16762 std::vector<NEBOracleEvaluationContext> stencil_contexts;
16763 stencil_contexts.reserve(hook_missing_stencil.size());
16764 for (const int stencil_idx: hook_missing_stencil) {
16765 stencil_positions.push_back(
16766 path.image(stencil_idx).positions);
16768 ctx.image_index = stencil_idx;
16769 ctx.force_quality = true;
16770 ctx.current_chain_certificate = true;
16771 ctx.force_stencil = true;
16772 stencil_contexts.push_back(ctx);
16773 }
16774 std::vector<char> stencil_measured;
16775 const auto stencil_results = evaluateBandTargets(
16776 stencil_positions, &stencil_contexts, stencil_measured);
16777 result.oracle_calls +=
16778 static_cast<int>(hook_missing_stencil.size());
16779 result.oracle_calls_outer +=
16780 static_cast<int>(hook_missing_stencil.size());
16781 for (std::size_t k = 0; k < hook_missing_stencil.size();
16782 ++k) {
16783 if (!stencil_measured[k]) continue;
16784 const int image_idx = hook_missing_stencil[k];
16785 path.image(image_idx).energy =
16786 stencil_results[k].energy;
16787 path.image(image_idx).gradient =
16788 stencil_results[k].gradient;
16789 path.image(image_idx).evaluated = true;
16790 if (session) {
16791 hook_stencil_observations.push_back(
16792 {image_idx, path.image(image_idx).positions,
16793 stencil_results[k].energy,
16794 stencil_results[k].gradient, true});
16795 }
16796 }
16797 path.computeNEBForces();
16798 }
16799 }
16800 // Chemistry-quiet CI after a second-order MMF help: eOn CI-only
16801 // acceptance. Neighbor spring/perp residuals after a single-
16802 // image burst must not veto (Baker 12: Helped F->0.039 then
16803 // hook_reject via adj-perp, mat26 greened the same help).
16804 const double hook_ci_force_magnitude =
16805 (hook_ci_idx > 0 && hook_ci_idx < path.numImages() - 1 &&
16806 path.nebForce(hook_ci_idx).size() > 0)
16807 ? path.saddleForce(hook_ci_idx)
16808 : std::numeric_limits<double>::infinity();
16809 const bool hook_energy_ok =
16810 detail::hasTruePesSaddleEnergyCertificate(
16811 path, hook_ci_idx, config.conv_tol,
16812 /*force_quiet_adjacent=*/true);
16813 const double hook_effective_force_tol =
16814 detail::effectiveModelNoiseTolerance(config);
16815 const bool hook_chemistry_quiet =
16816 detail::oieHookChemistryQuietAtTolerance(
16817 hook_converged, hook_energy_ok, hook_ci_force_magnitude,
16818 hook_effective_force_tol);
16819 // Dimer returns obey the same explicit energy limit as the band.
16820 const bool hook_below_path_ceiling = belowPathCeiling(hook_ci_idx);
16821 // Neighbour forces constrain path convergence. CI-only
16822 // convergence retains their measured values as diagnostics.
16823 const bool hook_mep_converged =
16824 detail::ciAdjacentPerpendicularForceConverged(
16825 path, hook_ci_idx, hook_effective_force_tol);
16826 const bool hook_would_certify =
16827 (hook_chemistry_quiet &&
16828 (config.climbing_image_converged_only ||
16829 hook_mep_converged)) ||
16830 detail::shouldAcceptOieHookConvergence(
16831 hook_converged, path, hook_ci_idx, config.conv_tol,
16832 hook_effective_force_tol,
16833 config.climbing_image_converged_only);
16834 // Band-wide MEP certificate: a hook accept with interior
16835 // images missing true data (or off the MEP) declines here
16836 // and the terminal accepts below evaluate and decide.
16837 const bool hook_certified =
16838 hook_below_path_ceiling && hook_would_certify &&
16839 (config.climbing_image_converged_only ||
16840 detail::bandPerpendicularForceConverged(
16841 path, hook_effective_force_tol));
16842 // Above-ceiling rejection reroutes rather than refuses:
16843 // the certified-but-too-high saddle proves the search left
16844 // the channel, and the witness band that DEFINES the
16845 // ceiling is a correct-channel restart. Rethread the whole
16846 // band onto the witness (all accumulated rows retained),
16847 // so the climb resumes where a lower crossing is known to
16848 // exist instead of re-deriving the same wrong saddle until
16849 // the wall expires.
16850 bool ceiling_rerouted = false;
16851 if (hook_would_certify && !hook_below_path_ceiling &&
16852 !ceiling_witness_positions.empty()) {
16853 ceiling_rerouted = true;
16854 commitHookStencil();
16855 if (config.verbose) {
16856 neb_log()
16857 << "[gp_oie] outer=" << outer << " ceiling_reject: E="
16858 << path.image(hook_ci_idx).energy
16859 << " ceiling=" << connecting_path_energy_ceiling
16860 << "; rethreading onto witness band" << std::endl;
16861 }
16862 if (detail::restoreOiePathPositions(
16863 path, ceiling_witness_positions,
16864 /*preserve_climbing_marker=*/false)) {
16865 (void)refreshAllGpPath();
16866 path.computeNEBForces();
16867 band_stepper.reset();
16868 frozen_sweep = false;
16869 hook_moved_chain = true;
16870 recordLatestClimbRestartSnapshot(
16871 path.highestEnergyImageIndex(),
16872 /*from_drift=*/false);
16873 }
16874 if (config.outer_iter_hook_reject) {
16875 config.outer_iter_hook_reject(path, hook_ci_idx, outer,
16876 *session);
16877 }
16878 }
16879 if (hook_certified) {
16880 commitHookStencil();
16881 result.converged = true;
16882 result.convergence_status =
16883 detail::convergenceStatusForCurrentTolerance(config);
16884 converged_worst_idx = hook_ci_idx;
16885 if (config.record_composition_trace) {
16886 composition_rec.certificates.certified_hook_branch = true;
16887 composition_rec.ci_index = hook_ci_idx;
16888 composition_rec.max_oracle_force = max_oracle_force;
16889 }
16890 push_composition_trace();
16891 break;
16892 }
16893 if (!ceiling_rerouted &&
16894 detail::shouldRestoreRejectedOieHookConvergence(
16895 hook_converged, hook_certified)) {
16896 int hook_log_rank = 0;
16897#ifdef GPR_HAVE_MPI
16898 int hook_log_mpi_up = 0;
16899 MPI_Initialized(&hook_log_mpi_up);
16900 if (hook_log_mpi_up)
16901 MPI_Comm_rank(MPI_COMM_WORLD, &hook_log_rank);
16902#endif
16903 if (config.verbose && hook_log_rank == 0) {
16904 neb_log()
16905 << "[gp_oie] outer=" << outer << " hook_reject: "
16906 << detail::oieHookConvergenceRejectionDiagnostic(
16907 path, hook_ci_idx, config.conv_tol,
16908 detail::effectiveModelNoiseTolerance(config),
16909 config.climbing_image_converged_only)
16910 << std::endl;
16911 }
16912 if (detail::restoreOiePathPositions(
16913 path, pre_hook_positions,
16914 /*preserve_climbing_marker=*/ci_active)) {
16915 path.computeNEBForces();
16916 hook_moved_chain = false;
16917 }
16918 if (hook_added_training) {
16919 session->rollbackTrainingObservationsRetaining(
16920 pre_hook_training_rows, hook_stencil_observations);
16921 hook_stencil_committed = true;
16922 } else {
16923 commitHookStencil();
16924 }
16925 if (config.outer_iter_hook_reject) {
16926 config.outer_iter_hook_reject(path, hook_ci_idx, outer,
16927 *session);
16928 }
16929 }
16930 if (detail::shouldScheduleOieHookReparam(config,
16931 hook_moved_chain)) {
16932 hook_reparam_pending = true;
16933 hook_reparam_anchor_idx = hook_ci_idx;
16934 hook_reparam_source_signature = interiorPositionSignature(path);
16935 }
16936 const Eigen::VectorXd hook_ci_force_vector =
16937 (hook_ci_idx > 0 && hook_ci_idx < path.numImages() - 1)
16938 ? path.nebForce(hook_ci_idx)
16939 : Eigen::VectorXd();
16940 if (!result.converged && !hook_converged && ci_gp_min_trap &&
16941 previous_ci_oracle_position && previous_ci_oracle_force &&
16942 same_previous_ci_oracle &&
16943 detail::hasTruePesSaddleEnergyCertificate(path, hook_ci_idx,
16944 config.conv_tol)) {
16945 if (detail::applyOieBbForceCorrection(
16946 path, hook_ci_idx, *previous_ci_oracle_position,
16947 *previous_ci_oracle_force, hook_ci_force_vector,
16948 config.conv_tol, band_max_step)) {
16949 recordLatestClimbRestartSnapshot(hook_ci_idx,
16950 /*from_drift=*/false);
16951 if (detail::shouldScheduleOiePathMotionReparam(config,
16952 true)) {
16953 hook_reparam_pending = true;
16954 hook_reparam_anchor_idx = hook_ci_idx;
16955 hook_reparam_source_signature =
16956 interiorPositionSignature(path);
16957 }
16958 frozen_sweep = false;
16959 band_stepper.reset();
16960 }
16961 }
16962 hook_left_chain_moved =
16963 !positions_match(pre_hook_positions, snapshotPathPositions());
16964 if (detail::shouldSkipOieInnerAfterRejectedHookAttempt(
16965 hook_ran, hook_added_training, hook_converged,
16966 hook_certified, hook_left_chain_moved)) {
16967 skip_next_inner_after_rejected_hook = true;
16968 }
16969 }
16970 if (detail::shouldRetainOieHookRestartSnapshot(ci_active, hook_ran,
16971 hook_converged)) {
16972 auto [hook_max_force, hook_max_force_idx] = wholeBandMaxNebForce();
16973 max_oracle_force = hook_max_force;
16974 max_oracle_force_idx = hook_max_force_idx;
16975 if (std::isfinite(max_oracle_force) && max_oracle_force > 0.0 &&
16976 max_oracle_force < best_oracle_force) {
16977 best_oracle_force = max_oracle_force;
16978 best_path_positions = snapshotPathPositions();
16979 }
16980 if (std::isfinite(max_oracle_force) && max_oracle_force > 0.0) {
16981 last_outer_oracle_force = max_oracle_force;
16982 }
16983 recordLatestClimbRestartSnapshot(hook_ci_idx,
16984 /*from_drift=*/false);
16985 const double hook_ci_force =
16986 (hook_ci_idx > 0 && hook_ci_idx < n_imgs - 1)
16987 ? path.nebForceMagnitude(hook_ci_idx)
16988 : std::numeric_limits<double>::infinity();
16989 const double hook_ci_merit_force = detail::oieClimbMeritForce(
16990 ci_active, /*oracle_updates_current_path=*/true, hook_ci_idx,
16991 hook_ci_idx, hook_ci_force, max_oracle_force,
16992 max_oracle_force_idx,
16993 detail::shouldUseCiOnlyClimbMerit(
16994 /*mmf_handoff_snapshot=*/true,
16995 config.climbing_image_converged_only));
16996 const bool promote_hook_restart =
16997 detail::shouldPromoteOieHookRestartSnapshot(
16998 hook_ran, hook_converged, hook_left_chain_moved);
16999 if (promote_hook_restart) {
17000 best_climb_oracle_force = hook_ci_merit_force;
17001 recordBestClimbRestartSnapshot(hook_ci_idx);
17002 } else if (detail::shouldRetainOieBestClimbSnapshot(
17003 ci_active, hook_ci_merit_force,
17004 best_climb_oracle_force,
17005 detail::hasTruePesSaddleEnergyCertificate(
17006 path, hook_ci_idx, config.conv_tol),
17007 climbRestartBarrier(hook_ci_idx),
17008 best_climb_barrier)) {
17009 best_climb_oracle_force = hook_ci_merit_force;
17010 recordBestClimbRestartSnapshot(hook_ci_idx);
17011 }
17012 }
17013
17014 if (hook_ran) {
17015 // A hook handback owns the local geometry. Retaining an
17016 // adjacent-recovery source across it would restore a competing
17017 // path snapshot.
17018 adjacent_mep_recovery.clear();
17019 }
17020
17021 const auto reported_forces = detail::summarizeOieBandForces(path);
17022 if (auto* tracker = gpr::track::activeRun(); tracker && log_rank == 0) {
17023 // One record per outer: the state of the surrogate and of the
17024 // band at the boundary, with the per-image energies and the
17025 // GP's own prediction at the climbing image against its
17026 // measured row, so a post-mortem can locate a surrogate-only
17027 // ridge or a misfit without re-running the search.
17028 const int hi = detail::selectOieClimbingImageIndex(ci_active, path);
17029 const double bar = detail::forwardBarrierEnergy(path, hi);
17030 const auto& cf = gp.getSexpAtCovarianceFunction();
17031 const auto& ls = cf.getLengthScaleRef();
17032 Eigen::VectorXd length_scales(ls.size());
17033 for (Eigen::Index k = 0; k < ls.size(); ++k)
17034 length_scales(k) = *(ls.data() + k);
17035 Eigen::VectorXd image_energy(path.numImages());
17036 Eigen::VectorXd image_force(path.numImages());
17037 Eigen::VectorXd image_variance(path.numImages());
17038 Eigen::VectorXd image_evaluated(path.numImages());
17039 for (int i = 0; i < path.numImages(); ++i) {
17040 image_energy(i) = path.image(i).energy;
17041 image_force(i) = path.nebForceMagnitude(i);
17042 image_variance(i) = path.image(i).posterior_variance;
17043 image_evaluated(i) = path.image(i).evaluated ? 1.0 : 0.0;
17044 }
17045 gpr::track::JsonRecord record;
17046 record.add("outer", outer)
17047 .add("inner", inner)
17048 .add("exit", inner_exit)
17049 .add("arm", detail::oieOracleSelectionArmName(
17050 local_oracle_decision.arm))
17051 .add("ci_active", ci_active)
17052 .add("ci", hi)
17053 .add("ci_oracle", current_ci_oracle_updates_path)
17054 .add("barrier", bar)
17055 .add("max_gp_force", max_inner)
17056 .add("ci_gp_force", ci_candidate_gp_force)
17057 .add("ci_true_force", ci_force_now)
17058 .add("max_band_force", reported_forces.max_neb_force)
17059 .add("max_measured_neb_force",
17060 reported_forces.max_measured_neb_force)
17061 .add("measured_images", reported_forces.measured_images)
17062 .add("interior_images", reported_forces.interior_images)
17063 .add("max_variance", max_chain_var)
17064 .add("measured_variance_calibration",
17065 measured_variance_calibration)
17066 .add("measured_force_error", measured_variance_error)
17067 .add("measured_force_variance", measured_variance_reported)
17068 .add("oracle_calls", static_cast<long>(result.oracle_calls))
17069 .add("oracle_calls_outer",
17070 static_cast<long>(result.oracle_calls_outer))
17071 .add("ntrain", static_cast<long>(training_obs.R.rows()))
17072 .add("nvirtual",
17073 static_cast<long>(session ? session->virtual_obs.R.rows()
17074 : Eigen::Index{0}))
17075 .add("magnitude_sigma2", cf.getMagnSigma2())
17076 .add("noise_sigma2", gp.getSigma2())
17077 .add("length_scales", length_scales)
17078 .add("refit", gp.lastRefitKind())
17080 .add("active_posterior", gp.hasActivePosterior())
17081 .add("accepted_inner_steps",
17082 static_cast<long>(accepted_inner_steps))
17083 .add("band_max_step", band_max_step)
17084 .add("seconds_inner", phase_inner_seconds)
17085 .add("seconds_refit", phase_refit_seconds)
17086 .add("seconds_path", phase_path_seconds)
17087 .add("seconds_predict", phase_predict_seconds)
17088 .add("seconds_certificate", phase_cert_seconds)
17089 .add("seconds_drift", phase_drift_seconds)
17090 .add("seconds_assembly", gpr::PhaseTimers::assembly_seconds)
17091 .add("seconds_factorization",
17093 .add("seconds_objective", gpr::PhaseTimers::objective_seconds)
17094 .add("seconds_residual", gpr::PhaseTimers::residual_seconds)
17095 .add("seconds_correction", gpr::PhaseTimers::correction_seconds)
17096 .add("seconds_subset", gpr::PhaseTimers::subset_seconds)
17097 .add("seconds_condition", gpr::PhaseTimers::condition_seconds)
17098 .add("seconds_cholesky", gpr::PhaseTimers::cholesky_seconds)
17099 .add("seconds_gradient", gpr::PhaseTimers::gradient_seconds)
17100 .add("seconds_gradient_inverse",
17102 .add("seconds_gradient_accumulate",
17104 .add("objective_rows",
17105 static_cast<long>(gpr::PhaseTimers::objective_rows))
17106 .add("objective_channels",
17107 static_cast<long>(gpr::PhaseTimers::objective_channels))
17108 .add("gradient_count",
17109 static_cast<long>(gpr::PhaseTimers::gradient_count))
17110 .add("geometry_builds",
17111 static_cast<long>(gpr::PhaseTimers::geometry_builds))
17112 .add("objective_count",
17113 static_cast<long>(gpr::PhaseTimers::objective_count))
17114 .add("factorization_count",
17115 static_cast<long>(gpr::PhaseTimers::factorization_count))
17116 .add("factorization_rows",
17117 static_cast<long>(gpr::PhaseTimers::factorization_rows))
17118 .add("rss_mb", detail::residentSetMegabytes())
17119 .add("image_energy", image_energy)
17120 .add("image_force", image_force)
17121 .add("image_variance", image_variance)
17122 .add("image_evaluated", image_evaluated);
17123 double accepted_step = 0.0;
17124 for (double travel: cumulative_inner_travel)
17125 if (std::isfinite(travel))
17126 accepted_step = std::max(accepted_step, travel);
17127 record.add("trust_radius", trust_threshold)
17128 .add("step", accepted_step)
17129 .add("step_cap", band_max_step)
17130 .add("curvature", band_stepper.lastCurvatureScale())
17131 .add("gp_variance", max_chain_var)
17132 .add("hook_ran", hook_ran);
17133 double predicted_energy = std::numeric_limits<double>::quiet_NaN();
17134 double actual_energy = std::numeric_limits<double>::quiet_NaN();
17135 if (hi > 0 && hi < path.numImages() - 1) {
17136 const auto& ci_image = path.image(hi);
17137 record.add("ci_positions", ci_image.positions);
17138 if (ci_image.evaluated) {
17139 record.add("ci_oracle_gradient", ci_image.gradient);
17140 if (std::isfinite(ci_image.energy))
17141 actual_energy = ci_image.energy;
17142 }
17143 if (session) {
17144 gpr::Observation probe = makeProbe(hi);
17145 {
17146 auto model = session->acquireGlobalModel();
17147 model.gp().calculatePotentialDispatched(probe);
17148 }
17149 const Eigen::VectorXd gp_gradient =
17150 observationGradient(probe);
17151 record.add("ci_gp_gradient", gp_gradient);
17152 if (probe.E.size() > 0) {
17153 record.add("ci_gp_energy", probe.E(0));
17154 if (std::isfinite(probe.E(0)))
17155 predicted_energy = probe.E(0);
17156 }
17157 if (ci_image.evaluated &&
17158 ci_image.gradient.size() == gp_gradient.size())
17159 record.add("ci_gradient_misfit",
17160 (gp_gradient - ci_image.gradient).norm());
17161 }
17162 }
17163 const auto energy_change = [](double now, double previous) {
17164 if (!std::isfinite(now) || !std::isfinite(previous))
17165 return std::numeric_limits<double>::quiet_NaN();
17166 return now - previous;
17167 };
17168 record.add("predicted_energy", predicted_energy)
17169 .add("actual_energy", actual_energy)
17170 .add("predicted_energy_change",
17171 energy_change(predicted_energy,
17172 logged_prev_predicted_energy))
17173 .add("actual_energy_change",
17174 energy_change(actual_energy, logged_prev_actual_energy));
17175 if (std::isfinite(predicted_energy))
17176 logged_prev_predicted_energy = predicted_energy;
17177 if (std::isfinite(actual_energy))
17178 logged_prev_actual_energy = actual_energy;
17179 tracker->appendRecord("band/outer", record);
17180 const long step = static_cast<long>(outer);
17181 tracker->logMetric("band.ci_true_force", ci_force_now, step);
17182 tracker->logMetric("band.ci_gp_force", ci_candidate_gp_force, step);
17183 tracker->logMetric("band.max_gp_force", max_inner, step);
17184 tracker->logMetric("band.max_force", reported_forces.max_neb_force,
17185 step);
17186 tracker->logMetric("band.max_measured_neb_force",
17187 reported_forces.max_measured_neb_force, step);
17188 tracker->logMetric("band.measured_images",
17189 reported_forces.measured_images, step);
17190 tracker->logMetric("band.max_variance", max_chain_var, step);
17191 tracker->logMetric("band.measured_variance_calibration",
17192 measured_variance_calibration, step);
17193 tracker->logMetric("band.measured_force_error",
17194 measured_variance_error, step);
17195 tracker->logMetric("band.barrier", bar, step);
17196 tracker->logMetric("band.oracle_calls",
17197 static_cast<double>(result.oracle_calls), step);
17198 tracker->logMetric("band.ntrain",
17199 static_cast<double>(training_obs.R.rows()),
17200 step);
17201 tracker->logMetric("band.seconds_refit", phase_refit_seconds, step);
17202 tracker->logMetric("band.seconds_correction",
17204 tracker->logMetric("band.seconds_gradient",
17206 tracker->logMetric("band.seconds_inner", phase_inner_seconds, step);
17207 tracker->logMetric("band.seconds_predict", phase_predict_seconds,
17208 step);
17209 tracker->logMetric(
17210 "band.factorization_count",
17211 static_cast<double>(gpr::PhaseTimers::factorization_count),
17212 step);
17213 tracker->logMetric("band.noise_sigma2", gp.getSigma2(), step);
17214 tracker->logMetric("band.magnitude_sigma2", cf.getMagnSigma2(),
17215 step);
17216 tracker->logMetric("band.rss_mb", detail::residentSetMegabytes(),
17217 step);
17218 tracker->flush();
17219 }
17220 if (config.verbose && log_rank == 0) {
17221 int hi = detail::selectOieClimbingImageIndex(ci_active, path);
17222 const double bar = detail::forwardBarrierEnergy(path, hi);
17223 neb_log()
17224 << "[gp_oie] outer=" << outer << " inner=" << inner
17225 << " max_gp_F=" << max_inner
17226 << " ci_gp_F=" << ci_candidate_gp_force
17227 << " ci_true_Fmax=" << ci_force_now
17228 << " ci_oracle=" << (current_ci_oracle_updates_path ? 1 : 0)
17229 << " ci_energy_cert=" << (ci_true_saddle_energy_ok ? 1 : 0)
17230 << " ci_adj_checked=" << (ci_adjacent_mep_checked ? 1 : 0)
17231 << " ci_adj_perp=" << (ci_adjacent_mep_ok ? 1 : 0)
17232 << " lower_barrier_checked=" << (lower_barrier_checked ? 1 : 0)
17233 << " lower_barrier_action="
17234 << detail::oieLowerBarrierActionName(lower_barrier_action)
17235 << " max_band_F=" << reported_forces.max_neb_force
17236 << " max_measured_neb_F="
17237 << reported_forces.max_measured_neb_force
17238 << " measured_images=" << reported_forces.measured_images
17239 << " interior_images=" << reported_forces.interior_images
17240 << " max_var=" << max_chain_var << " worst=" << worst_idx
17241 << " joint_energy_ratio=" << joint_readiness.max_energy_ratio
17242 << " joint_force_ratio=" << joint_readiness.max_force_ratio
17243 << " reported_force_ratio="
17244 << reported_joint_readiness.max_force_ratio
17245 << " variance_calibration="
17246 << variance_probe.max_reported_variance_calibration
17247 << " measured_calibration=" << measured_variance_calibration
17248 << " measured_error=" << measured_variance_error
17249 << " measured_reported_var=" << measured_variance_reported
17250 << " force_cert_image="
17251 << variance_probe.max_gradient_trace.second
17252 << " force_cert_observed="
17253 << (variance_probe.max_gradient_trace.second >= 0 &&
17254 variance_probe.max_gradient_trace.second <
17255 static_cast<int>(current_band_observed.size())
17256 ? static_cast<int>(
17257 current_band_observed
17258 [variance_probe.max_gradient_trace.second])
17259 : 0)
17260 << " force_cert_gp_row="
17261 << globalGpOwnsCurrentGeometry(
17262 variance_probe.max_gradient_trace.second)
17263 << " global_gp_ntrain=" << globalGpTrainingConfigurationCount()
17264 << " joint_ready=" << joint_readiness.resolved()
17265 << " joint_acquisition_target="
17266 << current_band_acquisition_image << " arm="
17267 << detail::oieOracleSelectionArmName(local_oracle_decision.arm)
17268 << " ci=" << (ci_active ? 1 : 0) << " hi=" << hi
17269 << " hmode=" << gp.hyperparameterOptimizationModeName()
17270 << " refit=" << gp.lastRefitKind()
17271 << " active_posterior=" << gp.hasActivePosterior()
17272 << " shift=" << gp.lastStationarityShift()
17273 << " thr=" << gp.lastStationarityThreshold()
17274 << " smodel=" << gp.lastStationarityModel()
17276 << " bar=" << bar << " ntrain=" << training_obs.R.rows()
17277 << " virt="
17278 << (session ? session->virtual_obs.R.rows() : Eigen::Index{0})
17279 << " oracle_calls=" << result.oracle_calls
17280 << " exit=" << inner_exit << " asteps=" << accepted_inner_steps
17281 << " bms=" << band_max_step
17282 << " kappa=" << band_stepper.lastCurvatureScale();
17283 if (std::strcmp(inner_exit, "drift") == 0) {
17284 neb_log() << " drift_img=" << drift_diagnostic_image
17285 << " drift_d=" << drift_diagnostic_distance
17286 << " drift_radius=" << drift_diagnostic_radius
17287 << " drift_cycle=" << drift_diagnostic_cycle
17288 << " drift_kernel=" << drift_diagnostic_kernel;
17289 }
17290 if (config.rho_trust) {
17291 neb_log() << " rtr=" << rho_trust_radius
17292 << " rho_fid=" << rho_last_fidelity;
17293 }
17294 {
17295 // Band-tear indicator: the largest adjacent-image
17296 // Cartesian separation. A segment far above the mean
17297 // spacing turns the k~10 spring term into the dominant
17298 // force and the inner relaxation spends its budget
17299 // equalizing spacing instead of descending.
17300 double max_seg = 0.0;
17301 for (int i = 0; i + 1 < path.numImages(); ++i) {
17302 const double seg =
17303 (path.image(i + 1).positions - path.image(i).positions)
17304 .norm();
17305 if (std::isfinite(seg)) max_seg = std::max(max_seg, seg);
17306 }
17307 neb_log() << " maxseg=" << max_seg;
17308 }
17309 {
17310 const auto& ls =
17312 double lmin = std::numeric_limits<double>::infinity();
17313 double lmax = 0.;
17314 for (Eigen::Index k = 0; k < ls.size(); ++k) {
17315 const double v = *(ls.data() + k);
17316 lmin = std::min(lmin, v);
17317 lmax = std::max(lmax, v);
17318 }
17319 neb_log() << " mag2="
17321 << " s2n=" << gp.getSigma2() << " lmin=" << lmin
17322 << " lmax=" << lmax;
17323 }
17324 const double* energy_noise_rms =
17325 detail::oracleEnergyNoiseRmsPtr(config);
17326 const double force_noise_rms =
17327 config.oracle_force_noise_rms &&
17328 std::isfinite(*config.oracle_force_noise_rms) &&
17329 *config.oracle_force_noise_rms > 0.0
17330 ? *config.oracle_force_noise_rms
17331 : 0.0;
17332 const double energy_noise =
17333 energy_noise_rms && std::isfinite(*energy_noise_rms) &&
17334 *energy_noise_rms > 0.0
17335 ? *energy_noise_rms
17336 : 0.0;
17337 neb_log() << " force_noise=" << force_noise_rms
17338 << " energy_noise=" << energy_noise << " effective_tol="
17339 << detail::effectiveModelNoiseTolerance(config);
17340 // Direct solve-health observable: the GP's force misfit at
17341 // the climbing image's own stored training row. A healthy
17342 // fit interpolates its data to the likelihood noise; a
17343 // misfit orders of magnitude above sigma_n at a training
17344 // point indicts the solve (conditioning floor smoothing,
17345 // stale factor, dropped rows), not the data.
17346 if (session) {
17347 const int misfit_idx =
17348 detail::selectOieClimbingImageIndex(ci_active, path);
17349 if (misfit_idx > 0 && misfit_idx < path.numImages() - 1) {
17350 const int row = detail::findRestorableObservationRow(
17351 training_obs, path.image(misfit_idx));
17352 if (row >= 0) {
17353 gpr::Observation misfit_probe = makeProbe(misfit_idx);
17354 {
17355 auto model = session->acquireGlobalModel();
17357 misfit_probe);
17358 }
17359 const Eigen::VectorXd pred_grad =
17360 observationGradient(misfit_probe);
17361 if (pred_grad.size() ==
17362 training_obs.G.row(row).size()) {
17363 const double misfit =
17364 (pred_grad -
17365 training_obs.G.row(row).transpose())
17366 .norm();
17367 neb_log() << " ci_row_misfit=" << misfit;
17368 }
17369 }
17370 }
17371 }
17372 neb_log() << " pt_inner=" << phase_inner_seconds
17373 << " pt_refit=" << phase_refit_seconds
17374 << " pt_path=" << phase_path_seconds
17375 << " pt_pred=" << phase_predict_seconds
17376 << " pt_cert=" << phase_cert_seconds
17377 << " pt_drift=" << phase_drift_seconds
17378 << " npred=" << phase_predict_count
17379 << " pt_var=" << gpr::PhaseTimers::variance_seconds
17381 << " pt_asm=" << gpr::PhaseTimers::assembly_seconds
17385 << " pt_grad=" << gpr::PhaseTimers::gradient_seconds
17387 << " fac_rows=" << gpr::PhaseTimers::factorization_rows
17388 << " pt_resid=" << gpr::PhaseTimers::residual_seconds
17389 << " pt_corr=" << gpr::PhaseTimers::correction_seconds
17390 << " pt_subset=" << gpr::PhaseTimers::subset_seconds
17391 << " pt_cond=" << gpr::PhaseTimers::condition_seconds
17392 << " pt_chol=" << gpr::PhaseTimers::cholesky_seconds
17393 << " pt_ginv="
17395 << " pt_gacc="
17397 << " obj_rows=" << gpr::PhaseTimers::objective_rows
17399 << " ngrad=" << gpr::PhaseTimers::gradient_count
17400 << " ngeom=" << gpr::PhaseTimers::geometry_builds
17401 << " rss_mb=" << detail::residentSetMegabytes()
17402 << " rss_peak_mb=" << gpr::PhaseTimers::rss_peak_mb
17403 << " rss_peak_phase=" << gpr::PhaseTimers::rss_peak_phase;
17405 // Return freed heap to the system at the outer boundary: the
17406 // dense temporaries of a refit (n x n kernel, factors, per-
17407 // direction derivative matrices) are released here, and glibc
17408 // otherwise keeps their arenas mapped, so the resident size of
17409 // a long run reads fragmentation rather than live data.
17410#if defined(__GLIBC__)
17411 malloc_trim(0);
17412#endif
17413 neb_log() << " dt="
17414 << std::chrono::duration<double>(
17415 std::chrono::steady_clock::now() - outer_wall_t0)
17416 .count();
17417 neb_log() << std::endl;
17418 if (ci_adjacent_mep_checked && !ci_adjacent_mep_ok) {
17419 neb_log() << "[gp_oie] outer=" << outer
17420 << (config.climbing_image_converged_only
17421 ? " ci_path_diagnostic: "
17422 : " ci_certificate_reject: ")
17423 << detail::oieHookConvergenceRejectionDiagnostic(
17424 path, conv_ci_idx, config.conv_tol,
17425 model_noise_tol,
17426 config.climbing_image_converged_only)
17427 << std::endl;
17428 }
17429 }
17430 // Non-converged outers still contribute one composition snapshot.
17431 push_composition_trace();
17432 // A refused purchase supplies no evidence. Release actions waiting on
17433 // that purchase and let fixed-point recovery select admissible data
17434 // or report non-convergence when it has no remaining action.
17435 const bool acquisition_blocked =
17436 acquisition_refused &&
17437 static_cast<long>(result.oracle_calls) == outer_start_oracle_calls;
17438 if (acquisition_blocked) {
17439 pending_fixed_point.clear();
17440 pending_band_action.clear();
17441 pending_band_action_acquisition.clear();
17442 frozen_sweep = false;
17443 }
17444 // An outer whose acquisition the oracle refused is a rejected
17445 // trial: the refused geometries stay unavailable and the next outer
17446 // chooses another acquisition. It is not a fixed point, since the
17447 // admissible set changed; the consecutive-failure bound ends a run
17448 // in which the oracle refuses every acquisition.
17449 const bool oracle_rejected_trial =
17450 acquisition_blocked && outer_oracle_refusal;
17451 if (oracle_rejected_trial)
17452 oracle_failures.failed("acquisition", outer_oracle_refusal_text);
17453 // A band without new observations or motion at the training-set
17454 // coordinate resolution needs measured-force recovery. Smaller
17455 // changes cannot produce a distinct oracle row and therefore do
17456 // not establish progress of the outer map.
17457 // Acquisition and hook bypasses do not evaluate the GP relaxation
17458 // map. A resolved measured proposal must return to that map before
17459 // unchanged coordinates can establish another fixed point.
17460 const bool outer_without_new_information =
17461 !result.converged && !frozen_sweep && !oracle_rejected_trial &&
17462 (acquisition_blocked ||
17463 (!skip_inner_for_pending_acquisition && !skip_inner_for_handoff &&
17464 !skip_inner_after_rejected_hook)) &&
17465 (worst_idx < 0 || !any_oracle_path_update) &&
17466 training_obs.R.rows() == outer_start_ntrain &&
17467 // A measurement this outer is new information even when
17468 // pruning kept the row count level (irc 11_trans_butadiene
17469 // ocineb: off-band acquisition at image 1, one row pruned,
17470 // fixed point declared at outer 84).
17471 static_cast<long>(result.oracle_calls) == outer_start_oracle_calls;
17472 if (!outer_without_new_information) {
17473 outer_cycle_anchor.resize(0);
17474 outer_cycle_epoch.clear();
17475 outer_cycle_power = 1;
17476 outer_cycle_steps = 0;
17477 }
17478 if (outer_without_new_information) {
17479 const Eigen::VectorXd current_signature =
17480 interiorPositionSignature(path);
17481 std::vector<std::uint64_t> current_epoch{
17482 static_cast<std::uint64_t>(result.oracle_calls),
17483 static_cast<std::uint64_t>(training_obs.R.rows()),
17484 session ? session->trainingRevision() : 0,
17485 gp.factorEpoch(),
17486 session ? session->globalModelSurrogateRevision() : 0,
17487 static_cast<std::uint64_t>(
17488 detail::activeClimbingMarkerIndex(path) + 1),
17489 static_cast<std::uint64_t>(fixed_image + 1),
17490 static_cast<std::uint64_t>(ci_active),
17491 static_cast<std::uint64_t>(band_stepper.iteration())};
17492 if (session) {
17493 for (int i = 0;
17494 i < static_cast<int>(session->image_models.size()); ++i) {
17495 current_epoch.push_back(
17496 session->imageModelSurrogateRevision(i));
17497 }
17498 }
17499 const Eigen::Vector3d current_parameters{
17500 trust_threshold, band_max_step, measured_variance_calibration};
17501 bool band_recurrent = false;
17502 if (outer_cycle_anchor.size() != current_signature.size() ||
17503 outer_cycle_anchor.size() == 0 ||
17504 outer_cycle_epoch != current_epoch ||
17505 outer_cycle_parameters != current_parameters) {
17506 outer_cycle_anchor = current_signature;
17507 outer_cycle_epoch = std::move(current_epoch);
17508 outer_cycle_parameters = current_parameters;
17509 outer_cycle_power = 1;
17510 outer_cycle_steps = 0;
17511 } else {
17512 ++outer_cycle_steps;
17513 const Eigen::Index dof = path.image(1).positions.size();
17514 band_recurrent = dof > 0;
17515 for (Eigen::Index offset = 0;
17516 offset < current_signature.size() && band_recurrent;
17517 offset += dof) {
17518 band_recurrent = detail::positionsCoincide(
17519 current_signature.segment(offset, dof),
17520 outer_cycle_anchor.segment(offset, dof));
17521 }
17522 if (!band_recurrent && outer_cycle_steps == outer_cycle_power) {
17523 outer_cycle_anchor = current_signature;
17524 outer_cycle_steps = 0;
17525 const auto largest =
17526 std::numeric_limits<std::size_t>::max();
17527 outer_cycle_power = outer_cycle_power <= largest / 2
17528 ? 2 * outer_cycle_power
17529 : largest;
17530 }
17531 }
17532 bool state_unchanged = true;
17533 for (int i = 1; i < path.numImages() - 1 && state_unchanged; ++i) {
17534 const Eigen::VectorXd& now = path.image(i).positions;
17535 const Eigen::VectorXd& then_pos =
17536 outer_start_image_positions[i];
17537 state_unchanged = detail::positionsCoincide(now, then_pos);
17538 }
17539 if (state_unchanged || band_recurrent) {
17540 if (band_recurrent && config.verbose && log_rank == 0) {
17541 neb_log() << "[gp_oie] outer=" << outer
17542 << " fixed-point: recurrent band period="
17543 << outer_cycle_steps << std::endl;
17544 }
17545 // Prefer CI-certified accept before reparam burn when the
17546 // climbing image and its adjacent MEP certificate both
17547 // support the same true-PES saddle.
17548 const int fp_ci =
17549 detail::selectOieClimbingImageIndex(ci_active, path);
17550 // Recover the measurements this geometry already paid
17551 // for. The saddle energy certificate reads
17552 // Image::evaluated, and setPositions clears that flag on
17553 // every active interior image on every accepted inner
17554 // step -- tens of them in an outer. A band that returns
17555 // to a geometry it has already oracled therefore arrives
17556 // here holding no evidence, and the certificate refuses
17557 // a saddle the run has in fact measured. Observed on the
17558 // Baker board with the climbing image at a true force of
17559 // 0.0104 and a predicted force of 0.0203, both inside a
17560 // 0.0514 tolerance, rejected for want of a flag.
17561 //
17562 // This buys nothing and fabricates nothing: the restore
17563 // matches a training row against the image's exact
17564 // positions, so the certificate still rests on a real
17565 // oracle evaluation of the geometry being certified.
17566 for (int fp_i = (fp_ci > 0 ? fp_ci - 1 : -1);
17567 fp_ci > 0 && fp_i <= fp_ci + 1; ++fp_i) {
17568 if (fp_i <= 0 || fp_i >= path.numImages() - 1) continue;
17569 if (path.image(fp_i).evaluated) continue;
17570 (void)detail::restoreObservedImageIfPresent(
17571 training_obs, path.image(fp_i));
17572 }
17573 const double fp_ci_force =
17574 (ci_active && fp_ci > 0 && fp_ci < path.numImages() - 1 &&
17575 path.nebForce(fp_ci).size() > 0)
17576 ? path.saddleForce(fp_ci)
17577 : std::numeric_limits<double>::infinity();
17578 const double fp_noise_tol =
17579 detail::effectiveModelNoiseTolerance(config);
17580 const bool fp_energy_ok =
17581 detail::hasTruePesSaddleEnergyCertificate(path, fp_ci,
17582 config.conv_tol);
17583 const bool fp_ci_ok =
17584 ci_active && fp_energy_ok && std::isfinite(fp_ci_force) &&
17585 fp_ci_force < fp_noise_tol &&
17586 (config.climbing_image_converged_only ||
17587 detail::ciAdjacentPerpendicularForceConverged(
17588 path, fp_ci, fp_noise_tol));
17589 if (fp_ci_ok) {
17590 result.converged = true;
17591 result.convergence_status =
17592 detail::convergenceStatusForCurrentTolerance(config);
17593 converged_worst_idx = fp_ci;
17594 if (config.verbose && log_rank == 0) {
17595 neb_log() << "[gp_oie] outer=" << outer
17596 << " fixed-point: accepting CI-certified "
17597 "saddle (ci_force="
17598 << fp_ci_force << " < tol=" << fp_noise_tol
17599 << ")\n";
17600 }
17601 break;
17602 }
17603 const Eigen::VectorXd signature =
17604 interiorPositionSignature(path);
17605 fixed_point_history.observeTraining(
17606 training_obs.R.rows(),
17607 session ? session->trainingRevision()
17608 : static_cast<std::uint64_t>(result.oracle_calls));
17609 // Only await when an acquisition target is still open.
17610 // Empty reselect (all current geometries already in the
17611 // training set) must fall through to re-schedule or clear;
17612 // otherwise the campaign spins forever with no oracle.
17613 if (pending_fixed_point.acquisition &&
17614 pending_fixed_point.active() &&
17615 detail::positionsCoincide(
17616 signature, pending_fixed_point.source_signature)) {
17617 if (config.verbose && log_rank == 0) {
17618 const char* proposal_name =
17619 pending_fixed_point.kind ==
17620 FixedPointProposalKind::MeasuredNebStep
17621 ? "measured NEB step"
17622 : pending_fixed_point.kind ==
17623 FixedPointProposalKind::MeasuredChainSweep
17624 ? "measured chain"
17625 : "reparameterization";
17626 neb_log() << "[gp_oie] outer=" << outer
17627 << " fixed-point: awaiting " << proposal_name
17628 << " acquisition at image "
17629 << pending_fixed_point.acquisition.image_index
17630 << std::endl;
17631 }
17632 continue;
17633 }
17634 if (!acquisition_blocked &&
17635 detail::shouldDeferOieFixedPointRecovery(
17636 local_recovery_suppresses_replaceable_work,
17637 oracle_performed)) {
17638 if (config.verbose && log_rank == 0) {
17639 neb_log() << "[gp_oie] outer=" << outer
17640 << " fixed-point: local recovery owns image "
17641 << local_recovery_image << std::endl;
17642 }
17643 continue;
17644 }
17645 bool recurring = false;
17646 for (const Eigen::VectorXd& seen: fixed_point_signatures) {
17647 if (seen.size() == signature.size() &&
17648 (seen.array() == signature.array()).all()) {
17649 recurring = true;
17650 break;
17651 }
17652 }
17653 if (!recurring) {
17654 bool recovery_scheduled = false;
17655 if (config.oie_fixed_point_measured_step) {
17656 const int recovery_ci =
17657 ci_active && config.climbing_image_converged_only
17658 ? fp_ci
17659 : -1;
17660 const int uncertainty_preferred_image =
17661 recovery_ci > 0 ? recovery_ci
17662 : fixedPointTpePreferredImage();
17663 if (!detail::allInteriorImagesObserved(
17664 path, training_obs, recovery_ci)) {
17665 std::vector<Eigen::VectorXd> current_positions =
17666 snapshotPathPositions();
17667 detail::ProposalAcquisitionTarget target =
17668 selectFixedPointProposalTarget(
17669 current_positions,
17670 uncertainty_preferred_image, recovery_ci);
17671 if (target) {
17672 pending_fixed_point.acquisition =
17673 std::move(target);
17674 pending_fixed_point.source_signature =
17675 signature;
17676 pending_fixed_point.candidate_positions =
17677 std::move(current_positions);
17678 pending_fixed_point.kind =
17679 FixedPointProposalKind::MeasuredChainSweep;
17680 pending_fixed_point.climbing_image =
17681 recovery_ci;
17682 recovery_scheduled = true;
17683 if (config.verbose && log_rank == 0) {
17684 neb_log() << "[gp_oie] outer=" << outer
17685 << " fixed-point: acquiring true "
17686 "force for current image "
17687 << pending_fixed_point.acquisition
17688 .image_index
17689 << std::endl;
17690 }
17691 }
17692 } else {
17693 const int force_preferred_image =
17694 recovery_ci > 0
17695 ? recovery_ci
17696 : detail::selectMeasuredBandForceTarget(
17697 path);
17698 GPNEBConfig measured_recovery_config = config;
17699 measured_recovery_config.lbfgs_inverse_curvature =
17700 measured_band_recovery.inverseCurvature(
17701 force_preferred_image,
17702 config.lbfgs_inverse_curvature);
17703 std::vector<Eigen::VectorXd> proposed_positions =
17704 recovery_ci > 0
17705 ? detail::proposeCertifiedMeasuredNebStep(
17706 path, training_obs,
17707 measured_recovery_config, recovery_ci)
17708 : detail::proposeMeasuredNebStep(
17709 path, measured_recovery_config);
17710 const Eigen::Index image_dof =
17711 band_objective.imageDof();
17712 const Eigen::Index expected_size =
17713 static_cast<Eigen::Index>(path.numImages() -
17714 2) *
17715 image_dof;
17716 if (image_dof > 0 && proposed_positions.size() ==
17717 static_cast<std::size_t>(
17718 path.numImages())) {
17719 Eigen::VectorXd flat_proposal(expected_size);
17720 bool valid_proposal = expected_size > 0;
17721 for (int i = 1;
17722 i < path.numImages() - 1 && valid_proposal;
17723 ++i) {
17724 const Eigen::VectorXd& image_positions =
17725 proposed_positions
17726 [static_cast<std::size_t>(i)];
17727 valid_proposal =
17728 image_positions.size() == image_dof;
17729 if (valid_proposal) {
17730 flat_proposal.segment(
17731 static_cast<Eigen::Index>(i - 1) *
17732 image_dof,
17733 image_dof) = image_positions;
17734 }
17735 }
17736 if (valid_proposal) {
17737 (void)projectProposalToOuterTrust(
17738 flat_proposal);
17739 for (int i = 1; i < path.numImages() - 1;
17740 ++i) {
17741 proposed_positions
17742 [static_cast<std::size_t>(i)] =
17743 flat_proposal.segment(
17744 static_cast<Eigen::Index>(
17745 i - 1) *
17746 image_dof,
17747 image_dof);
17748 }
17749 detail::ProposalAcquisitionTarget target =
17750 selectFixedPointProposalTarget(
17751 proposed_positions,
17752 force_preferred_image, recovery_ci);
17753 if (target) {
17754 std::vector<Eigen::VectorXd> candidate =
17755 detail::isolateBandProposalImage(
17756 path, proposed_positions,
17757 target.image_index);
17758 if (!candidate.empty()) {
17759 pending_fixed_point.acquisition =
17760 std::move(target);
17761 pending_fixed_point
17762 .source_signature = signature;
17763 pending_fixed_point
17764 .candidate_positions =
17765 std::move(candidate);
17766 pending_fixed_point.kind =
17767 FixedPointProposalKind::
17768 MeasuredNebStep;
17769 pending_fixed_point.climbing_image =
17770 recovery_ci;
17771 recovery_scheduled = true;
17772 if (config.verbose &&
17773 log_rank == 0) {
17774 neb_log()
17775 << "[gp_oie] outer="
17776 << outer
17777 << " fixed-point: "
17778 "acquiring "
17779 "measured NEB step "
17780 "at image "
17781 << pending_fixed_point
17782 .acquisition
17783 .image_index
17784 << std::endl;
17785 }
17786 }
17787 } else {
17788 bool proposal_moves_band = false;
17789 for (int i = 1;
17790 i < path.numImages() - 1; ++i) {
17791 proposal_moves_band =
17792 proposal_moves_band ||
17793 !detail::positionsCoincide(
17794 proposed_positions
17795 [static_cast<
17796 std::size_t>(i)],
17797 path.image(i).positions);
17798 }
17799 if (proposal_moves_band) {
17800 pending_fixed_point
17801 .source_signature = signature;
17802 pending_fixed_point
17803 .candidate_positions =
17804 std::move(proposed_positions);
17805 pending_fixed_point.kind =
17806 FixedPointProposalKind::
17807 MeasuredNebStep;
17808 pending_fixed_point.climbing_image =
17809 recovery_ci;
17810 recovery_scheduled = true;
17811 if (config.verbose &&
17812 log_rank == 0) {
17813 neb_log()
17814 << "[gp_oie] outer="
17815 << outer
17816 << " fixed-point: "
17817 "applying "
17818 "observed measured "
17819 "NEB step"
17820 << std::endl;
17821 }
17822 }
17823 }
17824 }
17825 }
17826 }
17827 }
17828 if (recovery_scheduled) {
17829 fixed_point_signatures.push_back(signature);
17830 band_stepper.reset();
17831 continue;
17832 }
17833 if (measured_reparam_restart_protected) {
17834 if (config.verbose && log_rank == 0) {
17835 neb_log()
17836 << "[gp_oie] outer=" << outer
17837 << " fixed-point: measured recovery anchor "
17838 "remains unconverged"
17839 << std::endl;
17840 }
17841 break;
17842 }
17843 if (!config.oie_fixed_point_reparam) {
17844 if (config.verbose && log_rank == 0) {
17845 neb_log() << "[gp_oie] outer=" << outer
17846 << " fixed-point: recovery exhausted and "
17847 "reparameterization disabled"
17848 << std::endl;
17849 }
17850 break;
17851 }
17852 // Redistribution addresses only a measured tangential
17853 // spring defect. The complete proposal must remain in
17854 // the current image-local trust and posterior support;
17855 // missing exact rows are acquired while the live band
17856 // stays unchanged, and the measured force profile
17857 // authorizes the eventual mutation.
17858 const int reparam_anchor = ci_active ? fp_ci : -1;
17859 std::vector<Eigen::VectorXd> proposed_positions =
17860 detail::proposeReparametrizedBand(path, config,
17861 reparam_anchor);
17862 const auto reparam_support = fixedPointProposalSupport();
17863 const bool launch_reparam =
17864 detail::shouldLaunchFixedPointReparametrization(
17865 path, proposed_positions, reparam_support,
17866 reparam_anchor);
17867 fixed_point_signatures.push_back(signature);
17868 band_stepper.reset();
17869 if (!launch_reparam) {
17870 bool grant_mmf =
17871 static_cast<bool>(config.outer_iter_hook) &&
17872 session && ci_active;
17873 for (const Eigen::VectorXd& spent:
17874 fixed_point_mmf_grants) {
17875 if (grant_mmf && spent.size() == signature.size() &&
17876 (spent.array() == signature.array()).all()) {
17877 grant_mmf = false;
17878 }
17879 }
17880 if (grant_mmf) {
17881 fixed_point_mmf_grants.push_back(signature);
17882 fixed_point_requests_mmf = true;
17883 if (config.verbose && log_rank == 0) {
17884 neb_log() << "[gp_oie] outer=" << outer
17885 << " fixed-point: no redistribution "
17886 "recourse; granting one MMF burst"
17887 << std::endl;
17888 }
17889 continue;
17890 }
17891 if (config.verbose && log_rank == 0) {
17892 neb_log()
17893 << "[gp_oie] outer=" << outer
17894 << " fixed-point: redistribution lacks "
17895 "measured tangential need or GP support"
17896 << std::endl;
17897 }
17898 break;
17899 }
17900 detail::ProposalAcquisitionTarget unobserved_target =
17901 detail::selectUnobservedBandProposalTarget(
17902 proposed_positions, fixedPointTpePreferredImage(),
17903 reparam_support,
17904 [&](int, const Eigen::VectorXd& positions) {
17905 return detail::hasPosition(training_obs,
17906 positions);
17907 });
17908 if (unobserved_target) {
17909 pending_fixed_point.acquisition =
17910 std::move(unobserved_target);
17911 pending_fixed_point.source_signature = signature;
17912 pending_fixed_point.candidate_positions =
17913 proposed_positions;
17914 pending_fixed_point.kind =
17915 FixedPointProposalKind::Reparameterization;
17916 if (config.verbose && log_rank == 0) {
17917 neb_log()
17918 << "[gp_oie] outer=" << outer
17919 << " fixed-point: acquiring unobserved "
17920 "reparametrization image "
17921 << pending_fixed_point.acquisition.image_index
17922 << std::endl;
17923 }
17924 } else {
17925 pending_fixed_point.source_signature = signature;
17926 pending_fixed_point.candidate_positions =
17927 std::move(proposed_positions);
17928 pending_fixed_point.kind =
17929 FixedPointProposalKind::Reparameterization;
17930 if (config.verbose && log_rank == 0) {
17931 neb_log() << "[gp_oie] outer=" << outer
17932 << " fixed-point: applying observed "
17933 "reparametrization (anchor="
17934 << reparam_anchor << ")" << std::endl;
17935 }
17936 }
17937 } else {
17938 // A completed resolution attempt left the outer map
17939 // unchanged without a CI certificate.
17940 bool grant_mmf =
17941 static_cast<bool>(config.outer_iter_hook) && session &&
17942 ci_active;
17943 for (const Eigen::VectorXd& spent: fixed_point_mmf_grants) {
17944 if (grant_mmf && spent.size() == signature.size() &&
17945 (spent.array() == signature.array()).all()) {
17946 grant_mmf = false;
17947 }
17948 }
17949 if (grant_mmf) {
17950 fixed_point_mmf_grants.push_back(signature);
17951 fixed_point_requests_mmf = true;
17952 if (config.verbose && log_rank == 0) {
17953 neb_log() << "[gp_oie] outer=" << outer
17954 << " fixed-point recurred; granting "
17955 "one MMF burst before stopping"
17956 << std::endl;
17957 }
17958 continue;
17959 }
17960 if (config.verbose && log_rank == 0) {
17961 neb_log() << "[gp_oie] outer=" << outer
17962 << " fixed-point resolution recurred without "
17963 "new information; stopping unconverged"
17964 << std::endl;
17965 }
17966 break;
17967 }
17968 }
17969 }
17970 }
17971
17972 // Barrier from the convergence-gate's stored oracle data,
17973 // plus a single saddle-image oracle when needed.
17974 //
17975 // The convergence gate evaluates worst_idx through the
17976 // distributed oracle every outer iter and stores true E + G
17977 // into path.image(worst_idx). In Phase 2 worst_idx is the
17978 // latched climbing image = the highest-energy image, so the
17979 // converged worst_idx already carries the saddle's true-PES
17980 // energy and the barrier needs no recompute.
17981 //
17982 // In a Phase-1 convergence (the chain force fell everywhere
17983 // below tol before the climbing image ever activated),
17984 // worst_idx is the IMSPE / max-variance acquisition pick --
17985 // NOT the highest-energy image. Reading the barrier off that
17986 // image gives a value unrelated to the saddle (observed
17987 // baker_04_ch3o: 0.006 eV vs the true ~2 eV). So when the
17988 // GP-predicted highest-energy image differs from the oracled
17989 // worst_idx, evaluate that one image on the true PES -- a
17990 // single oracle call, not a full n_im chain validation pass.
17991 //
17992 // Non-converged runs (hit max_outer_iter) have no oracled
17993 // saddle; fall back to the GP-predicted highest-energy image
17994 // for a best-effort advisory barrier.
17995 path.computeNEBForces();
17996 (void)wallClockReached();
17997 if (result.converged) {
17998 const int gp_max_idx =
17999 detail::selectOieClimbingImageIndex(ci_active, path);
18000 if (converged_worst_idx >= 0 && gp_max_idx == converged_worst_idx) {
18001 // Saddle already carries true-PES energy from the gate.
18002 result.max_energy_image = converged_worst_idx;
18003 } else if (gp_max_idx > 0 && gp_max_idx < path.numImages() - 1) {
18004 // Phase-1 case: oracle the highest-energy image once so
18005 // the reported barrier is true-PES.
18006 const Eigen::VectorXd saddle_pos = path.image(gp_max_idx).positions;
18007 std::vector<char> saddle_measured;
18008 std::string saddle_failure;
18009 const auto saddle_result =
18010 evaluateTrialPoints({saddle_pos}, oracle, nullptr, {},
18011 config.oracle_session_restart_requested,
18012 &config.batch_oracle,
18013 config.oracle_batch_chunk, saddle_measured,
18014 saddle_failure)
18015 .front();
18016 result.oracle_calls++;
18017 result.oracle_calls_validation++;
18018 if (!saddle_measured.front()) {
18019 // Without a true-PES energy at the band maximum the
18020 // barrier is the surrogate's; the result does not claim
18021 // convergence.
18022 if (config.verbose)
18023 neb_log() << "[oracle-refused] saddle validation what="
18024 << saddle_failure << std::endl;
18025 result.converged = false;
18026 result.convergence_status =
18028 }
18029 const double e_saddle = saddle_result.energy;
18030 const Eigen::VectorXd g_saddle = saddle_result.gradient;
18031 if (!saddle_measured.front()) {
18032 result.max_energy_image = gp_max_idx;
18033 } else {
18034 path.image(gp_max_idx).energy = e_saddle;
18035 path.image(gp_max_idx).gradient = g_saddle;
18036 path.image(gp_max_idx).evaluated = true;
18037 if (session)
18038 session->appendObservation(gp_max_idx, saddle_pos, e_saddle,
18039 g_saddle);
18040 result.max_energy_image = gp_max_idx;
18041 }
18042 } else {
18043 result.max_energy_image =
18044 (converged_worst_idx >= 0) ? converged_worst_idx : gp_max_idx;
18045 }
18046 } else {
18047 result.max_energy_image = path.highestEnergyImageIndex();
18048 }
18049 // The stop is the oracle force at the geometry that is returned. A
18050 // stored gradient from a step that this image no longer occupies does
18051 // not pass, and neither does a different image chosen after the stop.
18052 if (result.converged) {
18053 double force = std::numeric_limits<double>::infinity();
18054 const int returned = result.max_energy_image;
18055 const double returned_tol =
18056 result.convergence_status == GPNEBConvergenceStatus::ModelNoiseFloor
18057 ? detail::effectiveModelNoiseTolerance(config)
18058 : config.conv_tol;
18059 const bool returned_ok = detail::measuredForceBelowFinalTolerance(
18060 path, returned, returned_tol, false, training_obs, &force);
18061 const double returned_force = force;
18062 if (returned_ok) {
18063 result.returned_true_force = force;
18064 } else if (converged_worst_idx > 0 && converged_worst_idx != returned &&
18065 detail::measuredForceBelowFinalTolerance(
18066 path, converged_worst_idx, returned_tol, false,
18067 training_obs, &force)) {
18068 result.max_energy_image = converged_worst_idx;
18069 result.returned_true_force = force;
18070 neb_log() << "[gp_oie] true force " << force << " at image "
18071 << converged_worst_idx
18072 << " is the returned geometry; image " << returned
18073 << " is above tolerance " << returned_tol << std::endl;
18074 } else {
18075 neb_log() << "[gp_oie] true force " << returned_force
18076 << " at the returned image " << returned
18077 << " is above tolerance " << returned_tol
18078 << "; not converged" << std::endl;
18079 result.returned_true_force = returned_force;
18080 result.converged = false;
18081 result.convergence_status = GPNEBConvergenceStatus::NotConverged;
18082 }
18083 }
18084 // Non-converged exits report from the ANCHOR band -- the best
18085 // state the run has MEASURED on the true PES -- never from
18086 // whatever mid-excursion band the wall kill happened to catch
18087 // (fast01 Baker 05 reported a 16.2 eV phantom while holding a
18088 // measured witness band at the correct scale).
18089 if (!result.converged && !anchor_positions.empty() &&
18090 static_cast<int>(anchor_positions.size()) == path.numImages()) {
18091 if (detail::restoreOiePathPositions(
18092 path, anchor_positions,
18093 /*preserve_climbing_marker=*/false)) {
18094 for (int i = 1; i < path.numImages() - 1; ++i) {
18095 (void)detail::restoreObservedImageIfPresent(training_obs,
18096 path.image(i));
18097 }
18098 path.computeNEBForces();
18099 result.max_energy_image = path.highestEnergyImageIndex();
18100 }
18101 }
18102 if (!result.converged) {
18103 double force = std::numeric_limits<double>::infinity();
18104 if (!detail::adoptMeasuredOracleRow(path, result.max_energy_image,
18105 training_obs, &force))
18106 force = std::numeric_limits<double>::infinity();
18107 result.returned_true_force = force;
18108 }
18109 // Forward barrier: E_saddle - E_reactant. The earlier
18110 // min(reactant, product) variant gave the reverse barrier for
18111 // exothermic reactions; on Baker24 it printed gpr_bar = 2.25
18112 // eV for 02_hcch vs eOn 0.27, even though both saddles were
18113 // the same -22.12 eV first-order TS (1 imag mode at -1.2 kcm
18114 // under PET-MAD-s, validated via scripts/validate_saddle.py).
18115 result.barrier_energy =
18116 detail::forwardBarrierEnergy(path, result.max_energy_image);
18117 result.reverse_barrier_energy =
18118 detail::reverseBarrierEnergy(path, result.max_energy_image);
18119 (void)wallClockReached();
18120 if (config.channel_survey && result.converged &&
18121 !channel_survey_initial_band.empty()) {
18122 runChannelSurvey(gp, channel_survey_initial_band, path,
18123 path.image(0).energy);
18124 }
18125 (void)wallClockReached();
18126 if (result.converged) {
18127 result.stop_reason = GPNEBStopReason::Converged;
18128 const int image = result.max_energy_image;
18129 double variance = std::numeric_limits<double>::quiet_NaN();
18130 if (image >= 0 && image < path.numImages())
18131 variance = path.image(image).posterior_variance;
18132 const double threshold = indexGateVarianceThreshold(gp.getSigma2());
18133 const Eigen::VectorXd gradient = image >= 0 && image < path.numImages()
18134 ? path.image(image).gradient
18135 : Eigen::VectorXd();
18136 const Eigen::VectorXd positions = image >= 0 && image < path.numImages()
18137 ? path.image(image).positions
18138 : Eigen::VectorXd();
18139 const int n_images = path.numImages();
18140 const int budget = vibrationalIndexOuterBudget(config, n_images);
18141 const bool force_already_under_tolerance =
18142 image > 0 && image < n_images - 1 && path.image(image).evaluated &&
18143 std::isfinite(path.saddleForce(image)) &&
18144 path.saddleForce(image) < config.conv_tol;
18145 result.path = std::move(path_ptr);
18146 // A force already under tolerance is certified by gpNEB, once,
18147 // for every mode. This gate is the stop that has not reached it.
18148 // Both belong to the requested certificate.
18149 if (config.force_stop_certificate && !force_already_under_tolerance) {
18150 const auto decision = decideVibrationalIndex(
18151 positions, gradient, &atoms_config, &gp, variance, threshold,
18152 config.lbfgs_max_move > 0.0 ? config.lbfgs_max_move
18153 : config.ci_stencil_step,
18154 gpr::optim::stencilStepOrDefault(config.ci_stencil_step),
18155 &oracle, &config.batch_oracle, config.oracle_batch_chunk,
18156 config.vibrational_stencil);
18157 applyVibrationalIndexDecision(result, decision, budget);
18158 }
18159 } else {
18160 if (result.stop_reason == GPNEBStopReason::Unspecified)
18161 result.stop_reason = GPNEBStopReason::IterationBudget;
18162 result.path = std::move(path_ptr);
18163 }
18165 if (auto* tracker = gpr::track::activeRun(); tracker) {
18166 int terminal_rank = 0;
18167#ifdef GPR_HAVE_MPI
18168 int terminal_mpi_up = 0;
18169 MPI_Initialized(&terminal_mpi_up);
18170 if (terminal_mpi_up) MPI_Comm_rank(MPI_COMM_WORLD, &terminal_rank);
18171#endif
18172 if (terminal_rank == 0) {
18173 gpr::track::JsonRecord terminal;
18174 terminal.add("terminal", true)
18175 .add("converged", result.converged)
18176 .add("oracle_calls", static_cast<long>(result.oracle_calls))
18177 .add("oracle_calls_to_convergence",
18178 static_cast<long>(result.oracle_calls_to_convergence()))
18179 .add("hyperparameter_refits",
18180 static_cast<long>(result.hyperparameter_refits));
18181 tracker->appendRecord("band/terminal", terminal);
18182 tracker->flush();
18183 }
18184 }
18185 return std::move(result);
18186}
18187
18188} // namespace
18189
18190namespace {
18191
18205GPNEBResult runGpLocalOie(NEBOracle& oracle, const GPNEBConfig& config,
18206 std::unique_ptr<NEBPath>& path_ptr, NEBPath& path,
18207 GPNEBResult& result, bool ci_active,
18208 ActiveLearningSession* session)
18209{
18210 const auto wallClockReached = [&]() {
18211 if (!gpr::collectiveWallClockLimitReached(config.wall_clock_limit))
18212 return false;
18213 result.converged = false;
18214 result.convergence_status = GPNEBConvergenceStatus::NotConverged;
18215 result.stop_reason = GPNEBStopReason::WallClockLimit;
18216 return true;
18217 };
18218 std::function<bool()> fit_stop_requested;
18219 if (config.wall_clock_limit) {
18220 fit_stop_requested = [limit = config.wall_clock_limit] {
18221 return limit->reached();
18222 };
18223 }
18224 const int n_images = path.numImages();
18225 const int n_int = n_images - 2;
18226 const Eigen::Index band_dof =
18227 n_images > 0 ? path.image(0).positions.size() : Eigen::Index(0);
18228 std::vector<Eigen::Index> local_dofs = detail::selectLocalPolishDofs(
18229 path.image(0).positions, path.image(n_images - 1).positions,
18230 config.gp_local_fraction, config.gp_local_radius);
18231 std::vector<char> is_local(static_cast<std::size_t>(band_dof), 0);
18232 std::vector<Eigen::Index> far_dofs;
18233 Eigen::Index d = 0, df = 0;
18234 const bool atomic = band_dof % 3 == 0 && band_dof > 0;
18235 const Eigen::Index per = atomic ? 3 : 1;
18236 const Eigen::Index n_atoms = band_dof / per;
18237 std::vector<char> local_atoms(static_cast<std::size_t>(n_atoms), 0);
18238 auto split_dofs = [&]() {
18239 std::fill(is_local.begin(), is_local.end(), 0);
18240 for (const auto k: local_dofs)
18241 is_local[static_cast<std::size_t>(k)] = 1;
18242 far_dofs.clear();
18243 for (Eigen::Index k = 0; k < band_dof; ++k)
18244 if (!is_local[static_cast<std::size_t>(k)]) far_dofs.push_back(k);
18245 d = static_cast<Eigen::Index>(local_dofs.size());
18246 df = static_cast<Eigen::Index>(far_dofs.size());
18247 std::fill(local_atoms.begin(), local_atoms.end(), 0);
18248 for (const auto k: local_dofs)
18249 local_atoms[static_cast<std::size_t>(k / per)] = 1;
18250 // The springs space the images by the local coordinates and act on
18251 // them alone. The substrate holds modes far softer than a spring
18252 // (free layers sliding over fixed ones); it follows the true force
18253 // and carries no spring. Rest lengths are measured on the whole
18254 // chord, so a band that holds them keeps the whole chord.
18255 if (d > 0 && df > 0 && path.springRestLengths().empty())
18256 path.setSpringCoordinates(local_dofs);
18257 else
18258 path.setSpringCoordinates({});
18259 };
18260 // The phase set moves in the local phase of a round: the local atoms
18261 // and their neighbours within the grow radius. Its shell atoms keep a
18262 // block-Jacobi scale from the substrate Hessian; everything outside it
18263 // stands still in that phase.
18264 std::vector<char> phase_atoms(static_cast<std::size_t>(n_atoms), 0);
18265 std::vector<char> is_phase(static_cast<std::size_t>(band_dof), 0);
18266 std::vector<Eigen::Index> phase_dofs, outside_dofs;
18267 std::vector<Eigen::Index> shell_atoms;
18268 std::vector<Eigen::Index> far_pos(static_cast<std::size_t>(band_dof), -1);
18269 // Shell radius of the phase set; stalled rounds widen it.
18270 double phase_radius = config.gp_local_grow_radius;
18271 auto build_phase_set = [&]() {
18272 phase_dofs = local_dofs;
18273 if (atomic && phase_radius > 0.0) {
18274 const auto grown = detail::selectLocalPolishDofs(
18275 path.image(0).positions, path.image(n_images - 1).positions,
18276 config.gp_local_fraction,
18277 std::max(config.gp_local_radius, phase_radius));
18278 phase_dofs.insert(phase_dofs.end(), grown.begin(), grown.end());
18279 std::sort(phase_dofs.begin(), phase_dofs.end());
18280 phase_dofs.erase(std::unique(phase_dofs.begin(), phase_dofs.end()),
18281 phase_dofs.end());
18282 }
18283 std::fill(is_phase.begin(), is_phase.end(), 0);
18284 std::fill(phase_atoms.begin(), phase_atoms.end(), 0);
18285 for (const auto k: phase_dofs) {
18286 is_phase[static_cast<std::size_t>(k)] = 1;
18287 phase_atoms[static_cast<std::size_t>(k / per)] = 1;
18288 }
18289 outside_dofs.clear();
18290 for (Eigen::Index k = 0; k < band_dof; ++k)
18291 if (!is_phase[static_cast<std::size_t>(k)])
18292 outside_dofs.push_back(k);
18293 shell_atoms.clear();
18294 for (Eigen::Index atom = 0; atom < n_atoms; ++atom)
18295 if (phase_atoms[static_cast<std::size_t>(atom)] &&
18296 !local_atoms[static_cast<std::size_t>(atom)])
18297 shell_atoms.push_back(atom);
18298 std::fill(far_pos.begin(), far_pos.end(), -1);
18299 for (std::size_t p = 0; p < far_dofs.size(); ++p)
18300 far_pos[static_cast<std::size_t>(far_dofs[p])] =
18301 static_cast<Eigen::Index>(p);
18302 };
18303 split_dofs();
18304 build_phase_set();
18305 auto gather = [](const Eigen::VectorXd& v,
18306 const std::vector<Eigen::Index>& idx) {
18307 Eigen::VectorXd out(static_cast<Eigen::Index>(idx.size()));
18308 for (std::size_t k = 0; k < idx.size(); ++k)
18309 out(static_cast<Eigen::Index>(k)) = v(idx[k]);
18310 return out;
18311 };
18312 auto scatter = [](const Eigen::VectorXd& part,
18313 const std::vector<Eigen::Index>& idx,
18314 Eigen::VectorXd& full) {
18315 for (std::size_t k = 0; k < idx.size(); ++k)
18316 full(idx[k]) = part(static_cast<Eigen::Index>(k));
18317 };
18318 auto clip_per_atom = [&](Eigen::VectorXd& step, double max_move) {
18319 double largest = 0.0;
18320 for (Eigen::Index g = 0; g + per <= step.size(); g += per)
18321 largest = std::max(largest, step.segment(g, per).norm());
18322 if (largest > max_move && largest > 0.0) step *= max_move / largest;
18323 };
18324
18325 // Pair-additive baseline over every atom, available for Cartesian bands.
18326 std::unique_ptr<PairSplineModel> pair;
18327 // A cubic spline's force error scales as the fourth power of its knot
18328 // spacing; the spacing follows the force tolerance from 0.05 A at 0.01.
18329 const double pair_spacing =
18330 config.gp_local_pair_spacing > 0.0
18331 ? config.gp_local_pair_spacing
18332 : std::clamp(
18333 0.05 * std::pow(std::max(config.conv_tol, 1e-6) / 0.01, 0.25),
18334 0.01, 0.25);
18335 if (atomic && config.gp_local_pair_cutoff > 0.0) {
18336 PairSplineModel probe(n_atoms, config.frozen_positions, config.cell,
18337 0.5, config.gp_local_pair_cutoff, pair_spacing);
18338 double closest = std::numeric_limits<double>::infinity();
18339 for (int i = 0; i < n_images; ++i)
18340 closest = std::min(
18341 closest, probe.minimumSeparation(path.image(i).positions));
18342 const double r_min = std::isfinite(closest) ? 0.8 * closest : 0.5;
18343 pair = std::make_unique<PairSplineModel>(
18344 n_atoms, config.frozen_positions, config.cell, r_min,
18345 config.gp_local_pair_cutoff, pair_spacing);
18346 pair->setNoise(config.gp_local_noise, config.gp_local_noise);
18347 if (config.gp_local_pair_split > 0.0)
18348 pair->setTailSplit(config.gp_local_pair_split,
18349 config.gp_local_pair_tail_refresh);
18350 }
18351 // Substrate Hessian of each image at its own geometry, refreshed when
18352 // the image moves past gp_local_far_refresh or the baseline is refitted.
18353 // One Cholesky factor of the reactant's substrate Hessian seeds the
18354 // quasi-Newton inverse on the far block of every image; the band
18355 // L-BFGS pairs supply the rest. The factor is shifted when indefinite
18356 // and refreshed with the baseline. It stays in double: a float Cholesky
18357 // rounds each entry onto a boundary a last-bit change in the pair
18358 // Hessian can cross, and the climb then leaves the basin.
18359 Eigen::LLT<Eigen::MatrixXd> far_llt;
18360 bool far_hessian_ready = false;
18361 double far_hessian_shift = 0.0;
18362 int far_factorisations = 0;
18363 // Images whose substrate response the reactant factor misrepresents
18364 // get their own factor at their own geometry, refreshed once they move
18365 // past gp_local_far_refresh.
18366 std::vector<char> own_far_factor(static_cast<std::size_t>(n_images), 0);
18367 std::vector<Eigen::LLT<Eigen::MatrixXd>> image_far_llt(
18368 static_cast<std::size_t>(n_images));
18369 std::vector<Eigen::VectorXd> image_far_at(
18370 static_cast<std::size_t>(n_images));
18371 std::vector<char> image_far_ok(static_cast<std::size_t>(n_images), 0);
18372 // The Hessians behind the factors, kept so that a round can refactor
18373 // them with the stiffness its tangents add (NEBPath::tangentStiffness).
18374 Eigen::MatrixXd far_hessian;
18375 std::vector<Eigen::MatrixXd> image_far_hessian(
18376 static_cast<std::size_t>(n_images));
18377 auto shifted_llt = [&](Eigen::MatrixXd H,
18378 Eigen::LLT<Eigen::MatrixXd>& llt) {
18379 double shift = 0.0;
18380 for (int attempt = 0; attempt < 10; ++attempt) {
18381 if (shift > 0.0) H.diagonal().array() += shift;
18382 llt = factorSubstrate(H);
18383 ++far_factorisations;
18384 if (llt.info() == Eigen::Success) return true;
18385 shift = shift > 0.0 ? shift : 0.5;
18386 }
18387 return false;
18388 };
18389 auto image_far_ready = [&](int i) -> bool {
18390 if (!pair || !pair->ready() || df <= 0) return false;
18391 auto& at = image_far_at[static_cast<std::size_t>(i)];
18392 const Eigen::VectorXd& x = path.image(i).positions;
18393 bool stale = at.size() != x.size();
18394 if (!stale) {
18395 double moved = 0.0;
18396 for (Eigen::Index g = 0; g + per <= x.size(); g += per)
18397 moved = std::max(
18398 moved, (x.segment(g, per) - at.segment(g, per)).norm());
18399 stale = moved > config.gp_local_far_refresh;
18400 }
18401 if (stale) {
18402 auto& H = image_far_hessian[static_cast<std::size_t>(i)];
18403 H = pair->hessian(x, far_dofs, i);
18404 image_far_ok[static_cast<std::size_t>(i)] =
18405 shifted_llt(H, image_far_llt[static_cast<std::size_t>(i)]) ? 1
18406 : 0;
18407 at = x;
18408 }
18409 return image_far_ok[static_cast<std::size_t>(i)] != 0;
18410 };
18411 std::vector<Eigen::Matrix3d> shell_block_inv(
18412 static_cast<std::size_t>(n_atoms), Eigen::Matrix3d::Identity());
18413 // The shared substrate factor plus one tangent stiffness. A later round
18414 // with the same Hessian and the same stiffness reuses the factor.
18415 int far_hessian_epoch = 0;
18416 int cached_stiff_epoch = -1;
18417 double cached_stiffness = std::numeric_limits<double>::quiet_NaN();
18418 Eigen::LLT<Eigen::MatrixXd> cached_stiffened_llt;
18419 auto factor_far_hessian = [&]() {
18420 far_hessian_ready = false;
18421 if (!pair || !pair->ready() || df <= 0) return;
18422 Eigen::MatrixXd H = pair->hessian(path.image(0).positions, far_dofs, 0);
18423 // Diagonal blocks of the shell atoms for the local phase.
18424 for (const auto atom: shell_atoms) {
18425 const Eigen::Index p = far_pos[static_cast<std::size_t>(3 * atom)];
18426 if (p < 0 || p + 2 >= df) continue;
18427 const Eigen::Matrix3d block = H.block<3, 3>(p, p);
18428 Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es(block);
18429 Eigen::Vector3d inv = es.eigenvalues();
18430 const double floor =
18431 std::max(1e-2 * inv.cwiseAbs().maxCoeff(), 1e-3);
18432 for (int c = 0; c < 3; ++c)
18433 inv(c) = 1.0 / std::max(inv(c), floor);
18434 shell_block_inv[static_cast<std::size_t>(atom)] =
18435 es.eigenvectors() * inv.asDiagonal() *
18436 es.eigenvectors().transpose();
18437 }
18438 double shift = 0.0;
18439 for (int attempt = 0; attempt < 10; ++attempt) {
18440 if (shift > 0.0) H.diagonal().array() += shift;
18441 far_llt = factorSubstrate(H);
18442 ++far_factorisations;
18443 if (far_llt.info() == Eigen::Success) {
18444 far_hessian_ready = true;
18445 far_hessian_shift = shift;
18446 far_hessian = std::move(H);
18447 ++far_hessian_epoch;
18448 return;
18449 }
18450 shift = shift > 0.0 ? shift : 0.5;
18451 }
18452 };
18453 // Trust-region Newton step on the substrate Hessian by Steihaug-Toint
18454 // conjugate gradients: the step stops at the trust boundary or at the
18455 // first direction of nonpositive curvature, so a soft or indefinite
18456 // mode cannot dominate the move of every other atom.
18457 auto far_trust_step = [&](const Eigen::MatrixXd& far_hessian,
18458 const Eigen::VectorXd& g, double radius) {
18459 Eigen::VectorXd z = Eigen::VectorXd::Zero(g.size());
18460 Eigen::VectorXd r = g; // residual of H z = -g
18461 Eigen::VectorXd dvec = -r;
18462 const double g_norm = g.norm();
18463 if (!(g_norm > 0.0)) return z;
18464 const double tol = std::min(0.1, std::sqrt(g_norm)) * g_norm;
18465 const int max_iter =
18466 static_cast<int>(std::min<Eigen::Index>(g.size(), 200));
18467 for (int it = 0; it < max_iter; ++it) {
18468 const Eigen::VectorXd Hd = far_hessian * dvec;
18469 const double curvature = dvec.dot(Hd);
18470 if (!(curvature > 1e-12)) {
18471 // Follow the direction to the boundary.
18472 const double zd = z.dot(dvec), dd = dvec.squaredNorm();
18473 const double zz = z.squaredNorm();
18474 const double tau =
18475 (-zd + std::sqrt(std::max(
18476 zd * zd - dd * (zz - radius * radius), 0.0))) /
18477 std::max(dd, 1e-300);
18478 return Eigen::VectorXd(z + tau * dvec);
18479 }
18480 const double alpha = r.squaredNorm() / curvature;
18481 const Eigen::VectorXd z_next = z + alpha * dvec;
18482 if (z_next.norm() >= radius) {
18483 const double zd = z.dot(dvec), dd = dvec.squaredNorm();
18484 const double zz = z.squaredNorm();
18485 const double tau =
18486 (-zd + std::sqrt(std::max(
18487 zd * zd - dd * (zz - radius * radius), 0.0))) /
18488 std::max(dd, 1e-300);
18489 return Eigen::VectorXd(z + tau * dvec);
18490 }
18491 const Eigen::VectorXd r_next = r + alpha * Hd;
18492 z = z_next;
18493 if (r_next.norm() < tol) return z;
18494 const double beta = r_next.squaredNorm() / r.squaredNorm();
18495 r = r_next;
18496 dvec = -r + beta * dvec;
18497 }
18498 return z;
18499 };
18500
18501 double observe_seconds = 0.0, gp_seconds = 0.0, restore_seconds = 0.0;
18502 // Residual model on the local subspace with the full geometry as input.
18503 LocalCartesianGP gp(band_dof, local_dofs);
18504 gp.setWindow(config.gp_local_window);
18505 gp.setNoise(config.gp_local_noise, config.gp_local_noise);
18506 gp.setLengthScaleBounds(0.05, 50.0);
18507 gp.setHyperparameters(1.0, 1.0);
18508 struct Raw {
18509 Eigen::VectorXd x;
18510 double energy;
18511 Eigen::VectorXd gradient;
18512 int slot; // band image the geometry belongs to, for its pair list
18513 };
18514 std::deque<Raw> raw;
18515 // A fit has happened. This is not an imported kernel.
18516 bool gp_seeded = false;
18517 // Set only by the seed hook. An ordinary rebuild must not latch it.
18518 bool kernel_imported = false;
18519 auto residual_targets = [&](const Raw& r, double& energy,
18520 Eigen::VectorXd& local_gradient) {
18521 energy = r.energy;
18522 local_gradient = gather(r.gradient, local_dofs);
18523 if (pair && pair->ready()) {
18524 Eigen::VectorXd g;
18525 energy -= pair->energy(r.x, &g, r.slot);
18526 local_gradient -= gather(g, local_dofs);
18527 }
18528 };
18529 double seeded_sf2 = 1.0, seeded_ell = 1.0;
18530 if (session && session->localKernelSeed().present) {
18531 seeded_sf2 = session->localKernelSeed().signal_variance;
18532 seeded_ell = session->localKernelSeed().length_scale;
18533 kernel_imported = true;
18534 }
18535 auto rebuild_gp = [&]() {
18536 gp = LocalCartesianGP(band_dof, local_dofs);
18537 gp.setWindow(config.gp_local_window);
18538 gp.setNoise(config.gp_local_noise, config.gp_local_noise);
18539 gp.setLengthScaleBounds(0.05, 50.0);
18540 gp.setHyperparameters(seeded_sf2, seeded_ell);
18541 for (const auto& r: raw) {
18542 double e;
18543 Eigen::VectorXd g;
18544 residual_targets(r, e, g);
18545 gp.add(r.x, e, g);
18546 }
18547 if (gp.size() < 2) {
18548 gp.condition();
18549 return;
18550 }
18551 // With a pair baseline the residual is small and the data-spacing
18552 // seed suffices; without one the model carries the whole surface
18553 // and fits its hyperparameters on every rebuild.
18554 // An imported kernel is the warm start. Data spacing must not
18555 // replace it, and a default refit count of zero leaves it in place.
18556 // A fit that already happened is not that kernel.
18557 const bool imported = kernel_imported;
18558 const int fit_iterations =
18559 imported ? config.gp_local_refit_iters
18560 : (pair ? config.gp_local_refit_iters
18561 : std::max(config.gp_local_refit_iters, 20));
18562 const bool refit = !pair || (!imported && !gp_seeded);
18563 if (refit) {
18564 if (!imported) gp.setHyperparametersFromData(3.0);
18565 if (fit_iterations > 0) {
18566 (void)gp.fit(fit_iterations, fit_stop_requested);
18567 ++result.hyperparameter_refits;
18568 } else {
18569 gp.condition();
18570 }
18571 if (!imported || fit_iterations > 0) {
18572 seeded_sf2 = gp.signalVariance();
18573 seeded_ell = gp.lengthScale();
18574 }
18575 gp_seeded = true;
18576 } else {
18577 gp.condition();
18578 }
18579 };
18580 auto append_session_seed = [&]() {
18581 if (!session) return;
18582 const auto& obs = session->training_obs;
18583 if (obs.R.rows() == 0) return;
18584 if (obs.R.cols() != band_dof)
18585 throw std::runtime_error(
18586 "gp-state.npz coordinates do not match this search (" +
18587 std::to_string(obs.R.cols()) + " columns, this search has " +
18588 std::to_string(band_dof) + ")");
18589 for (Eigen::Index row = 0; row < obs.R.rows(); ++row) {
18590 if (obs.E.rows() <= row || obs.E.cols() < 1 ||
18591 obs.G.rows() <= row || obs.G.cols() != obs.R.cols())
18592 continue;
18593 const Eigen::VectorXd x = obs.R.row(row).transpose();
18594 bool seen = false;
18595 for (const auto& have: raw) {
18596 if (have.x.size() == x.size() && (have.x - x).norm() <= 1e-7) {
18597 seen = true;
18598 break;
18599 }
18600 }
18601 if (seen) continue;
18602 raw.push_back({x, obs.E(row, 0), obs.G.row(row).transpose(), 0});
18603 }
18604 while (static_cast<int>(raw.size()) > config.gp_local_window &&
18605 !raw.empty())
18606 raw.pop_front();
18607 };
18608 // A measurement joins the baseline fit while the baseline still misses
18609 // its forces by more than a fifth of the tolerance anywhere; once the
18610 // pair function is pinned down, new points only feed the residual.
18611 bool pair_dirty = true;
18612 int pair_skipped = 0;
18613 auto record = [&](const Eigen::VectorXd& x, double energy,
18614 const Eigen::VectorXd& gradient, int slot) {
18615 raw.push_back({x, energy, gradient, slot});
18616 while (static_cast<int>(raw.size()) > config.gp_local_window)
18617 raw.pop_front();
18618 const auto t0 = std::chrono::steady_clock::now();
18619 if (pair) {
18620 bool needed = true;
18621 if (pair->ready() && pair->observations() >= 4) {
18622 Eigen::VectorXd g;
18623 (void)pair->energy(x, &g, slot);
18624 const double miss = (gradient - g).lpNorm<Eigen::Infinity>();
18625 needed = !(miss < 0.2 * config.conv_tol);
18626 }
18627 if (needed) {
18628 pair->observe(x, energy, gradient, slot);
18629 pair_dirty = true;
18630 } else {
18631 ++pair_skipped;
18632 }
18633 }
18634 observe_seconds +=
18635 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0)
18636 .count();
18637 double e;
18638 Eigen::VectorXd g;
18639 residual_targets(raw.back(), e, g);
18640 gp.add(x, e, g);
18641 };
18642 // Fit the baseline when it has new data, refresh the substrate Hessian
18643 // and rebuild the residual model on the new baseline. Returns whether
18644 // the baseline changed.
18645 auto refit_models = [&]() {
18646 bool changed = false;
18647 if (pair && pair_dirty && pair->fit()) {
18648 factor_far_hessian();
18649 pair_dirty = false;
18650 changed = true;
18651 }
18652 const auto t0 = std::chrono::steady_clock::now();
18653 rebuild_gp();
18654 gp_seconds +=
18655 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0)
18656 .count();
18657 return changed;
18658 };
18659
18660 struct Measurement {
18661 bool have = false;
18662 Eigen::VectorXd positions;
18663 double energy = 0.0;
18664 Eigen::VectorXd gradient;
18665 double trust = 0.0;
18666 int count = 0;
18667 };
18668 std::vector<Measurement> meas(static_cast<std::size_t>(n_images));
18669 for (int i = 0; i < n_images; ++i) {
18670 const Image& image = path.image(i);
18671 auto& m = meas[static_cast<std::size_t>(i)];
18672 m.trust = config.gp_local_trust;
18673 if (!image.evaluated || image.gradient.size() != band_dof) continue;
18674 m.have = true;
18675 m.positions = image.positions;
18676 m.energy = image.energy;
18677 m.gradient = image.gradient;
18678 m.count = 1;
18679 raw.push_back({image.positions, image.energy, image.gradient, i});
18680 if (pair)
18681 pair->observe(image.positions, image.energy, image.gradient, i);
18682 }
18683 append_session_seed();
18684 refit_models();
18685 // Only the retry after a stalled local band carries these springs.
18686 // A search that converges on the atoms that move between the endpoints
18687 // never reaches here, so its calls stay the ones that search made.
18688 // A substrate atom the local move pushes against its own endpoint
18689 // displacement, by more than the tolerance, then carries the fraction
18690 // of the configured spring equal to that push over the displacement,
18691 // and never more than the whole spring. An atom the endpoints agree
18692 // on has nothing to oppose, and one loaded below the tolerance stays
18693 // free, so a relaxed substrate is not pinned to the chord.
18694 if (config.gp_local_carry_springs && pair && pair->ready() && atomic &&
18695 !path.springCoordinates().empty() && path.springRestLengths().empty() &&
18696 config.spring_constant > 0.0 && config.conv_tol > 0.0) {
18697 const Eigen::VectorXd& reactant = path.image(0).positions;
18698 const Eigen::VectorXd& product = path.image(n_images - 1).positions;
18699 Eigen::VectorXd moved = reactant;
18700 for (const auto k: local_dofs)
18701 moved(k) = product(k);
18702 Eigen::VectorXd g_reactant, g_moved;
18703 const int spare = n_images;
18704 (void)pair->energy(reactant, &g_reactant, spare);
18705 (void)pair->energy(moved, &g_moved, spare);
18706 if (g_reactant.size() == band_dof && g_moved.size() == band_dof &&
18707 g_reactant.allFinite() && g_moved.allFinite()) {
18708 const Eigen::VectorXd induced = g_moved - g_reactant;
18709 std::vector<Eigen::Index> coords = path.springCoordinates();
18710 std::vector<double> weights(coords.size(), 1.0);
18711 for (Eigen::Index atom = 0; atom < n_atoms; ++atom) {
18712 if (local_atoms[static_cast<std::size_t>(atom)]) continue;
18713 const Eigen::Vector3d displacement =
18714 (product - reactant).segment(3 * atom, 3);
18715 const double length = displacement.norm();
18716 if (!(length > 0.0)) continue;
18717 const double opposing =
18718 -induced.segment(3 * atom, 3).dot(displacement) / length;
18719 if (!(opposing > config.conv_tol)) continue;
18720 const double weight =
18721 std::min(1.0, opposing / (config.spring_constant * length));
18722 if (!(weight > 0.0)) continue;
18723 for (int axis = 0; axis < 3; ++axis) {
18724 coords.push_back(3 * atom + axis);
18725 weights.push_back(weight);
18726 }
18727 }
18728 if (coords.size() != path.springCoordinates().size())
18729 path.setSpringCoordinates(std::move(coords),
18730 std::move(weights));
18731 }
18732 }
18733 const double max_move =
18734 config.lbfgs_max_move > 0.0 ? config.lbfgs_max_move : 0.2;
18735
18736 auto measured_current = [&](int i) {
18737 const auto& m = meas[static_cast<std::size_t>(i)];
18738 return m.have && m.positions.size() == band_dof &&
18739 (path.image(i).positions - m.positions)
18740 .lpNorm<Eigen::Infinity>() < 1e-12;
18741 };
18742 // Local phase of a round: the far atoms stand still, so the baseline
18743 // pairs among them are constant and only the pairs touching a local
18744 // atom are summed; the far gradient keeps the value of the full
18745 // evaluation the phase started from.
18746 bool local_phase = false;
18747 std::vector<Eigen::VectorXd> phase_gradient(
18748 static_cast<std::size_t>(n_images));
18749 std::vector<double> phase_energy(static_cast<std::size_t>(n_images), 0.0);
18750 std::vector<Eigen::VectorXd> pair_cache_x(
18751 static_cast<std::size_t>(n_images));
18752 std::vector<Eigen::VectorXd> pair_cache_g(
18753 static_cast<std::size_t>(n_images));
18754 std::vector<double> pair_cache_e(static_cast<std::size_t>(n_images), 0.0);
18755 // Surrogate energy and gradient of an image: baseline plus residual.
18756 auto surrogate = [&](const Eigen::VectorXd& x, Eigen::VectorXd& gradient,
18757 int slot = 0) {
18758 double energy = 0.0;
18759 gradient.setZero(band_dof);
18760 if (pair && pair->ready()) {
18761 auto& pg = phase_gradient[static_cast<std::size_t>(slot)];
18762 if (local_phase && pg.size() == band_dof) {
18763 gradient = pg;
18764 Eigen::VectorXd g_part;
18765 const double e_part =
18766 pair->maskedEnergy(x, phase_atoms, &g_part, slot);
18767 for (const auto k: phase_dofs)
18768 gradient(k) = g_part(k);
18769 energy = phase_energy[static_cast<std::size_t>(slot)] + e_part;
18770 } else {
18771 energy = pair->energy(x, &gradient, slot);
18772 pair_cache_x[static_cast<std::size_t>(slot)] = x;
18773 pair_cache_g[static_cast<std::size_t>(slot)] = gradient;
18774 pair_cache_e[static_cast<std::size_t>(slot)] = energy;
18775 }
18776 }
18777 if (config.gp_local_residual) {
18778 double e_res = 0.0;
18779 Eigen::VectorXd g_res;
18780 gp.predict(x, e_res, g_res);
18781 energy += e_res;
18782 for (std::size_t k = 0; k < local_dofs.size(); ++k)
18783 gradient(local_dofs[k]) += g_res(static_cast<Eigen::Index>(k));
18784 }
18785 return energy;
18786 };
18787 // Surrogate values of each image at the geometry they were computed
18788 // for, so repeated refreshes at an unchanged geometry cost nothing.
18789 struct SurrogateCache {
18790 Eigen::VectorXd x;
18791 double energy = 0.0;
18792 Eigen::VectorXd gradient;
18793 int model_epoch = -1;
18794 };
18795 std::vector<SurrogateCache> cache(static_cast<std::size_t>(n_images));
18796 int model_epoch = 0;
18797 auto cached_surrogate = [&](int i, Image& image) {
18798 auto& c = cache[static_cast<std::size_t>(i)];
18799 if (c.model_epoch == model_epoch && c.x.size() == band_dof &&
18800 (c.x - image.positions).lpNorm<Eigen::Infinity>() == 0.0) {
18801 image.energy = c.energy;
18802 image.gradient = c.gradient;
18803 return;
18804 }
18805 image.energy = surrogate(image.positions, image.gradient, i);
18806 c.x = image.positions;
18807 c.energy = image.energy;
18808 c.gradient = image.gradient;
18809 c.model_epoch = model_epoch;
18810 };
18811 // Measured images carry their oracle energy and gradient; moved images
18812 // carry the surrogate.
18813 auto restore = [&]() {
18814 const auto t0 = std::chrono::steady_clock::now();
18815 for (int i = 1; i < n_images - 1; ++i) {
18816 Image& image = path.image(i);
18817 const auto& m = meas[static_cast<std::size_t>(i)];
18818 if (measured_current(i)) {
18819 image.energy = m.energy;
18820 image.gradient = m.gradient;
18821 image.evaluated = true;
18822 continue;
18823 }
18824 cached_surrogate(i, image);
18825 image.evaluated = false;
18826 }
18827 path.computeNEBForces();
18828 restore_seconds +=
18829 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0)
18830 .count();
18831 };
18832 auto image_converged = [&](int i) {
18833 return measured_current(i) &&
18834 path.nebForceMagnitude(i) < config.conv_tol;
18835 };
18836
18837 // Band quasi-Newton memory kept across outer iterations; the surrogate
18838 // changes slowly once the baseline has settled.
18839 std::deque<Eigen::VectorXd> band_s_hist, band_y_hist;
18840 std::deque<double> band_rho_hist;
18841 Eigen::Index band_history_dof = -1;
18842 double h0_local = 0.05;
18843 int stall_rounds = 0;
18844 int grows = 0;
18845 double initial_max_force = 0.0;
18846 double local_fit_seconds = 0.0, local_polish_seconds = 0.0;
18847 double measure_seconds = 0.0;
18848 int polish_steps_total = 0;
18849 const int outer_budget = config.max_outer_iter;
18850 if (config.verbose) {
18851 neb_log() << "[gp_local] subspace dofs=" << d << " far=" << df << " of "
18852 << band_dof << " fraction=" << config.gp_local_fraction
18853 << " radius=" << config.gp_local_radius
18854 << " window=" << config.gp_local_window
18855 << " trust=" << config.gp_local_trust
18856 << " pair_basis=" << (pair ? pair->nBasis() : 0)
18857 << " pair_cutoff=" << (pair ? pair->cutoff() : 0.0)
18858 << " far_hessian=" << (far_hessian_ready ? 1 : 0)
18859 << " shift=" << far_hessian_shift
18860 << " pair_rms=" << (pair ? pair->gradientResidual() : 0.0)
18861 << "\n";
18862 }
18863 double last_far_step = 0.0;
18864 double last_far_force = 0.0;
18865 (void)far_trust_step;
18866 BandForceStall band_stall;
18867 const int stall_window = bandStallWindow(n_images, static_cast<int>(d));
18868 for (int outer = 0; outer < outer_budget; ++outer) {
18869 if (wallClockReached()) break;
18870 // 1. Models: baseline refit every outer, residual model rebuilt on
18871 // the schedule and otherwise appended.
18872 const auto t0 = std::chrono::steady_clock::now();
18873 if (outer > 0) {
18874 const bool scheduled = config.gp_local_refit_every > 0 &&
18875 outer % config.gp_local_refit_every == 0;
18876 if (scheduled) {
18877 if (refit_models()) {
18878 // The surrogate changed; the band memory is stale.
18879 band_s_hist.clear();
18880 band_y_hist.clear();
18881 band_rho_hist.clear();
18882 }
18883 } else {
18884 gp.condition();
18885 ++result.fixed_theta_refreshes;
18886 }
18887 ++model_epoch;
18888 }
18889 const auto t1 = std::chrono::steady_clock::now();
18890 local_fit_seconds += std::chrono::duration<double>(t1 - t0).count();
18891
18892 restore();
18893 if (!ci_active) {
18894 double band_force = 0.0;
18895 for (int i = 1; i < n_images - 1; ++i)
18896 band_force = std::max(band_force, path.nebForceMagnitude(i));
18897 if (initial_max_force <= 0.0 && std::isfinite(band_force))
18898 initial_max_force = band_force;
18899 if (detail::ciActivationForceGateReady(
18900 config, ci_active, outer, band_force, initial_max_force))
18901 ci_active = true;
18902 }
18903 if (config.climbing_image && ci_active) path.enableClimbingImage();
18904
18905 std::vector<char> frozen(static_cast<std::size_t>(n_images), 0);
18906 for (int i = 1; i < n_images - 1; ++i)
18907 frozen[static_cast<std::size_t>(i)] = image_converged(i) ? 1 : 0;
18908 std::vector<Eigen::VectorXd> anchor(static_cast<std::size_t>(n_images));
18909 for (int i = 1; i < n_images - 1; ++i) {
18910 const auto& m = meas[static_cast<std::size_t>(i)];
18911 anchor[static_cast<std::size_t>(i)] =
18912 m.have ? gather(m.positions, local_dofs)
18913 : gather(path.image(i).positions, local_dofs);
18914 }
18915 const auto t2 = std::chrono::steady_clock::now();
18916 int steps = 0;
18917 // 2. Relax every unconverged image on the surrogate with one band
18918 // quasi-Newton over all coordinates. The substrate block of the
18919 // initial inverse Hessian is the baseline Hessian of each image,
18920 // the local block a scalar scale, so the springs, the tangent
18921 // projection and the climbing image act on every atom at once.
18922 if (band_dof > 0 && (gp.ready() || (pair && pair->ready()))) {
18923 std::vector<int> active;
18924 for (int i = 1; i < n_images - 1; ++i)
18925 if (!frozen[static_cast<std::size_t>(i)]) active.push_back(i);
18926 const Eigen::Index n_active =
18927 static_cast<Eigen::Index>(active.size());
18928 auto refresh = [&]() {
18929 for (int i = 1; i < n_images - 1; ++i) {
18930 Image& image = path.image(i);
18931 if (measured_current(i)) {
18932 const auto& m = meas[static_cast<std::size_t>(i)];
18933 image.energy = m.energy;
18934 image.gradient = m.gradient;
18935 image.evaluated = true;
18936 continue;
18937 }
18938 cached_surrogate(i, image);
18939 image.evaluated = false;
18940 }
18941 path.computeNEBForces();
18942 };
18943 auto band_force = [&]() {
18944 Eigen::VectorXd f(n_active * band_dof);
18945 for (Eigen::Index a = 0; a < n_active; ++a)
18946 f.segment(a * band_dof, band_dof) =
18947 path.nebForce(active[static_cast<std::size_t>(a)]);
18948 return f;
18949 };
18950 auto band_positions = [&]() {
18951 Eigen::VectorXd z(n_active * band_dof);
18952 for (Eigen::Index a = 0; a < n_active; ++a)
18953 z.segment(a * band_dof, band_dof) =
18954 path.image(active[static_cast<std::size_t>(a)])
18955 .positions;
18956 return z;
18957 };
18958 // Per-coordinate scale of the local block from the diagonal of
18959 // the baseline Hessian at each active image: a positive metric
18960 // that cannot mix the climbing direction into the step.
18961 std::vector<Eigen::VectorXd> local_scale(
18962 static_cast<std::size_t>(n_active));
18963 if (config.gp_local_jacobi && pair && pair->ready() && d > 0) {
18964 for (Eigen::Index a = 0; a < n_active; ++a) {
18965 const int i = active[static_cast<std::size_t>(a)];
18966 const Eigen::VectorXd diag =
18967 pair->hessian(path.image(i).positions, local_dofs, i)
18968 .diagonal()
18969 .cwiseAbs();
18970 const double floor = std::max(0.1 * diag.mean(), 1e-3);
18971 Eigen::VectorXd inv(d);
18972 for (Eigen::Index k = 0; k < d; ++k)
18973 inv(k) = 1.0 / std::max(diag(k), floor);
18974 local_scale[static_cast<std::size_t>(a)] = inv;
18975 }
18976 }
18977 std::vector<char> own(static_cast<std::size_t>(n_active), 0);
18978 for (Eigen::Index a = 0; a < n_active; ++a) {
18979 const int i = active[static_cast<std::size_t>(a)];
18980 if (own_far_factor[static_cast<std::size_t>(i)] &&
18981 image_far_ready(i))
18982 own[static_cast<std::size_t>(a)] = 1;
18983 }
18984 // The factors of this round: the substrate Hessian plus the
18985 // stiffness the tangents add, set before the first band step.
18986 const Eigen::LLT<Eigen::MatrixXd>* round_far_llt = &far_llt;
18987 std::vector<Eigen::LLT<Eigen::MatrixXd>> stiffened_image_far_llt(
18988 static_cast<std::size_t>(n_images));
18989 std::vector<char> image_stiffened(
18990 static_cast<std::size_t>(n_images), 0);
18991 auto round_image_far_llt =
18992 [&](int i) -> const Eigen::LLT<Eigen::MatrixXd>& {
18993 const auto s = static_cast<std::size_t>(i);
18994 return image_stiffened[s] ? stiffened_image_far_llt[s]
18995 : image_far_llt[s];
18996 };
18997 auto apply_h0 = [&](const Eigen::VectorXd& q) {
18998 Eigen::VectorXd out = h0_local * q;
18999 for (Eigen::Index a = 0; a < n_active; ++a) {
19000 const auto& inv = local_scale[static_cast<std::size_t>(a)];
19001 if (inv.size() != d) continue;
19002 for (std::size_t k = 0; k < local_dofs.size(); ++k)
19003 out(a * band_dof + local_dofs[k]) =
19004 inv(static_cast<Eigen::Index>(k)) *
19005 q(a * band_dof + local_dofs[k]);
19006 }
19007 // Outside the phase set the force is zero while those atoms
19008 // stand still, so the local phase skips the substrate solve
19009 // and scales the shell atoms by their own Hessian blocks.
19010 if (local_phase) {
19011 if (far_hessian_ready)
19012 for (Eigen::Index a = 0; a < n_active; ++a)
19013 for (const auto atom: shell_atoms)
19014 out.segment<3>(a * band_dof + 3 * atom) =
19015 shell_block_inv[static_cast<std::size_t>(
19016 atom)] *
19017 q.segment<3>(a * band_dof + 3 * atom);
19018 return out;
19019 }
19020 if (!far_hessian_ready) return out;
19021 // One triangular solve for the far blocks of every image on
19022 // the shared factor; images with their own factor solve alone.
19023 Eigen::MatrixXd q_far(df, n_active);
19024 for (Eigen::Index a = 0; a < n_active; ++a)
19025 for (std::size_t k = 0; k < far_dofs.size(); ++k)
19026 q_far(static_cast<Eigen::Index>(k), a) =
19027 q(a * band_dof + far_dofs[k]);
19028 Eigen::MatrixXd sol = round_far_llt->solve(q_far);
19029 for (Eigen::Index a = 0; a < n_active; ++a) {
19030 if (own[static_cast<std::size_t>(a)]) {
19031 const int i = active[static_cast<std::size_t>(a)];
19032 sol.col(a) = round_image_far_llt(i).solve(q_far.col(a));
19033 }
19034 for (std::size_t k = 0; k < far_dofs.size(); ++k)
19035 out(a * band_dof + far_dofs[k]) =
19036 sol(static_cast<Eigen::Index>(k), a);
19037 }
19038 return out;
19039 };
19040 const double inner_tol =
19041 config.gp_local_inner_tol_factor * config.conv_tol;
19042 if (band_history_dof != n_active * band_dof ||
19043 !config.gp_local_keep_memory) {
19044 band_s_hist.clear();
19045 band_y_hist.clear();
19046 band_rho_hist.clear();
19047 band_history_dof = n_active * band_dof;
19048 }
19049 auto& s_hist = band_s_hist;
19050 auto& y_hist = band_y_hist;
19051 auto& rho_hist = band_rho_hist;
19052 Eigen::VectorXd z_prev, f_prev;
19053 int inner = 0;
19054 double round_first_worst = -1.0, round_last_worst = -1.0;
19055 int round_worst_image = -1;
19056 const int ci_at_round_start = path.highestEnergyImageIndex();
19057 // The baseline tail is summed afresh for every image at the
19058 // start of the round and held fixed through its band steps.
19059 if (pair && pair->ready()) {
19060 for (int i = 0; i < n_images; ++i)
19061 pair->staleTail(i);
19062 ++model_epoch;
19063 }
19064 // Once the substrate force is under the round tolerance the far
19065 // atoms stand still and the local atoms finish against them on
19066 // the pairs that touch them alone; the full band is checked
19067 // again before the round ends.
19068 local_phase = false;
19069 bool phase_changed = false;
19070 const bool phase_allowed = config.gp_local_phase && atomic &&
19071 df > 0 && d > 0 && pair && pair->ready();
19072 auto zero_far = [&](Eigen::VectorXd& v) {
19073 for (Eigen::Index a = 0; a < n_active; ++a)
19074 for (const auto k: outside_dofs)
19075 v(a * band_dof + k) = 0.0;
19076 };
19077 auto far_worst_of = [&](const Eigen::VectorXd& v) {
19078 double worst = 0.0;
19079 for (Eigen::Index a = 0; a < n_active; ++a)
19080 worst = std::max(
19081 worst,
19082 gather(v.segment(a * band_dof, band_dof), outside_dofs)
19083 .norm());
19084 return worst;
19085 };
19086 auto worst_of = [&](const Eigen::VectorXd& v) {
19087 double worst = 0.0;
19088 for (Eigen::Index a = 0; a < n_active; ++a) {
19089 const double fa = v.segment(a * band_dof, band_dof).norm();
19090 if (fa > worst) {
19091 worst = fa;
19092 round_worst_image = active[static_cast<std::size_t>(a)];
19093 }
19094 }
19095 return worst;
19096 };
19097 int local_steps = 0, phase_entries = 0, full_steps_since_leave = 0;
19098 std::deque<Eigen::VectorXd> full_s_hist, full_y_hist;
19099 std::deque<double> full_rho_hist;
19100 auto enter_local_phase = [&]() {
19101 for (Eigen::Index a = 0; a < n_active; ++a) {
19102 const int i = active[static_cast<std::size_t>(a)];
19103 const auto s = static_cast<std::size_t>(i);
19104 const Eigen::VectorXd& x = path.image(i).positions;
19105 if (pair_cache_x[s].size() != band_dof ||
19106 (pair_cache_x[s] - x).lpNorm<Eigen::Infinity>() !=
19107 0.0) {
19108 pair_cache_e[s] = pair->energy(x, &pair_cache_g[s], i);
19109 pair_cache_x[s] = x;
19110 }
19111 phase_gradient[s] = pair_cache_g[s];
19112 phase_energy[s] =
19113 pair_cache_e[s] -
19114 pair->maskedEnergy(x, phase_atoms, nullptr, i);
19115 }
19116 local_phase = true;
19117 phase_changed = true;
19118 ++phase_entries;
19119 ++model_epoch;
19120 // The full band's memory waits out the phase: the full
19121 // surrogate is unchanged, so its secant pairs stay valid.
19122 std::swap(full_s_hist, s_hist);
19123 std::swap(full_y_hist, y_hist);
19124 std::swap(full_rho_hist, rho_hist);
19125 s_hist.clear();
19126 y_hist.clear();
19127 rho_hist.clear();
19128 };
19129 auto leave_local_phase = [&]() {
19130 local_phase = false;
19131 full_steps_since_leave = 0;
19132 phase_changed = true;
19133 ++model_epoch;
19134 std::swap(full_s_hist, s_hist);
19135 std::swap(full_y_hist, y_hist);
19136 std::swap(full_rho_hist, rho_hist);
19137 full_s_hist.clear();
19138 full_y_hist.clear();
19139 full_rho_hist.clear();
19140 };
19141 // The band force of an image depends on its own position
19142 // through the tangent as well as the gradient: across the path
19143 // it is held by the parallel gradient over the chord length on
19144 // top of the curvature of the surface. A substrate mode softer
19145 // than that (free layers sliding over fixed ones) would take
19146 // the Newton step of the bare Hessian several times too far,
19147 // so the factors of this round carry the tangent stiffness:
19148 // the largest over the images on the shared factor, each
19149 // image's own on its own factor.
19150 if (far_hessian_ready && n_active > 0 && far_hessian.rows() == df) {
19151 refresh();
19152 double shared_stiffness = 0.0;
19153 for (Eigen::Index a = 0; a < n_active; ++a) {
19154 const int i = active[static_cast<std::size_t>(a)];
19155 const double stiffness = path.tangentStiffness(i);
19156 if (!(stiffness > 0.0) || !std::isfinite(stiffness))
19157 continue;
19158 if (!own[static_cast<std::size_t>(a)]) {
19159 shared_stiffness =
19160 std::max(shared_stiffness, stiffness);
19161 continue;
19162 }
19163 const auto s = static_cast<std::size_t>(i);
19164 if (image_far_hessian[s].rows() != df) continue;
19165 Eigen::MatrixXd H = image_far_hessian[s];
19166 H.diagonal().array() += stiffness;
19167 if (shifted_llt(std::move(H), stiffened_image_far_llt[s]))
19168 image_stiffened[s] = 1;
19169 }
19170 if (shared_stiffness > 0.0) {
19171 if (cached_stiff_epoch == far_hessian_epoch &&
19172 cached_stiffness == shared_stiffness &&
19173 cached_stiffened_llt.info() == Eigen::Success) {
19174 round_far_llt = &cached_stiffened_llt;
19175 } else {
19176 Eigen::MatrixXd H = far_hessian;
19177 H.diagonal().array() += shared_stiffness;
19178 if (shifted_llt(std::move(H), cached_stiffened_llt)) {
19179 cached_stiff_epoch = far_hessian_epoch;
19180 cached_stiffness = shared_stiffness;
19181 round_far_llt = &cached_stiffened_llt;
19182 }
19183 }
19184 }
19185 }
19186 // The local phase runs while the substrate force is the smaller
19187 // part and the local force keeps falling by three per cent a
19188 // step; the full band takes over otherwise.
19189 double worst_prev = -1.0;
19190 for (; inner < config.gp_local_inner_max && n_active > 0; ++inner) {
19191 if (wallClockReached()) break;
19192 refresh();
19193 Eigen::VectorXd f = band_force();
19194 if (local_phase) zero_far(f);
19195 double worst = worst_of(f);
19196 if (local_phase)
19197 ++local_steps;
19198 else
19199 ++full_steps_since_leave;
19200 const bool local_stalled = local_phase && worst_prev > 0.0 &&
19201 worst > 0.97 * worst_prev;
19202 if (local_phase &&
19203 (!(worst > inner_tol) || !f.allFinite() || local_stalled)) {
19204 leave_local_phase();
19205 refresh();
19206 f = band_force();
19207 worst = worst_of(f);
19208 } else if (!local_phase && phase_allowed && phase_entries < 5 &&
19209 (phase_entries == 0 ||
19210 full_steps_since_leave >= 2) &&
19211 worst > inner_tol && f.allFinite() &&
19212 far_worst_of(f) <=
19213 std::max(inner_tol, 0.5 * worst)) {
19214 enter_local_phase();
19215 zero_far(f);
19216 worst = worst_of(f);
19217 }
19218 if (round_first_worst < 0.0) round_first_worst = worst;
19219 round_last_worst = worst;
19220 if (!(worst > inner_tol) || !f.allFinite()) break;
19221 const Eigen::VectorXd z = band_positions();
19222 if (inner > 0 && !phase_changed) {
19223 const Eigen::VectorXd sv = z - z_prev;
19224 const Eigen::VectorXd yv = f_prev - f;
19225 const double sy = sv.dot(yv);
19226 if (sy > 1e-14 && std::isfinite(sy)) {
19227 s_hist.push_back(sv);
19228 y_hist.push_back(yv);
19229 rho_hist.push_back(1.0 / sy);
19230 while (static_cast<int>(s_hist.size()) >
19231 config.lbfgs_memory) {
19232 s_hist.pop_front();
19233 y_hist.pop_front();
19234 rho_hist.pop_front();
19235 }
19236 // Scale the local block from its own secant pair.
19237 double sl = 0.0, yl = 0.0;
19238 for (Eigen::Index a = 0; a < n_active; ++a)
19239 for (std::size_t k = 0; k < local_dofs.size();
19240 ++k) {
19241 const Eigen::Index idx =
19242 a * band_dof + local_dofs[k];
19243 sl += sv(idx) * yv(idx);
19244 yl += yv(idx) * yv(idx);
19245 }
19246 if (sl > 0.0 && yl > 0.0)
19247 h0_local = std::clamp(sl / yl, 1e-3, 1.0);
19248 } else {
19249 s_hist.clear();
19250 y_hist.clear();
19251 rho_hist.clear();
19252 }
19253 }
19254 Eigen::VectorXd step = -gpr::optim::twoLoopRecursion(
19255 s_hist, y_hist, rho_hist, f, apply_h0);
19256 if (!(step.dot(f) > 0.0) || !step.allFinite()) {
19257 s_hist.clear();
19258 y_hist.clear();
19259 rho_hist.clear();
19260 step = apply_h0(f);
19261 }
19262 clip_per_atom(step, max_move);
19263 if (local_phase) zero_far(step);
19264 // Trust spheres about the measurement bound the move: the
19265 // local subspace by the adapted radius, the substrate by
19266 // its own.
19267 auto apply_step = [&](const Eigen::VectorXd& delta) {
19268 for (Eigen::Index a = 0; a < n_active; ++a) {
19269 const int i = active[static_cast<std::size_t>(a)];
19270 Image& image = path.image(i);
19271 Eigen::VectorXd target =
19272 z.segment(a * band_dof, band_dof) +
19273 delta.segment(a * band_dof, band_dof);
19274 const auto& anc = anchor[static_cast<std::size_t>(i)];
19275 const double trust =
19276 meas[static_cast<std::size_t>(i)].trust;
19277 Eigen::VectorXd disp = gather(target, local_dofs) - anc;
19278 const double dn = disp.norm();
19279 if (dn > trust && dn > 0.0)
19280 scatter(anc + disp * (trust / dn), local_dofs,
19281 target);
19282 const auto& m = meas[static_cast<std::size_t>(i)];
19283 if (df > 0 && m.have &&
19284 config.gp_local_far_trust > 0.0) {
19285 const Eigen::VectorXd far_anchor =
19286 gather(m.positions, far_dofs);
19287 Eigen::VectorXd far_disp =
19288 gather(target, far_dofs) - far_anchor;
19289 const double fn = far_disp.norm();
19290 if (fn > config.gp_local_far_trust)
19291 scatter(
19292 far_anchor +
19293 far_disp *
19294 (config.gp_local_far_trust / fn),
19295 far_dofs, target);
19296 }
19297 image.positions = target;
19298 path.pinFixedAtoms(image.positions);
19299 }
19300 };
19301 if (config.gp_local_safeguard) {
19302 // A step that raises the largest surrogate band force by
19303 // more than half is halved; one that still does after
19304 // three halvings drops the quasi-Newton memory and takes
19305 // a short descent. The accepted trial's surrogate values
19306 // stay cached for the next iteration.
19307 bool accepted = false;
19308 for (int halving = 0; halving < 3; ++halving) {
19309 apply_step(step);
19310 refresh();
19311 Eigen::VectorXd f_trial = band_force();
19312 if (local_phase) zero_far(f_trial);
19313 double trial_worst = 0.0;
19314 for (Eigen::Index a = 0; a < n_active; ++a)
19315 trial_worst = std::max(
19316 trial_worst,
19317 f_trial.segment(a * band_dof, band_dof).norm());
19318 if (!std::isfinite(trial_worst)) break;
19319 if (trial_worst <= 1.5 * worst) {
19320 accepted = true;
19321 break;
19322 }
19323 step *= 0.5;
19324 }
19325 if (!accepted) {
19326 s_hist.clear();
19327 y_hist.clear();
19328 rho_hist.clear();
19329 step = apply_h0(f);
19330 clip_per_atom(step, 0.25 * max_move);
19331 apply_step(step);
19332 }
19333 } else {
19334 apply_step(step);
19335 }
19336 z_prev = z;
19337 f_prev = f;
19338 phase_changed = false;
19339 worst_prev = worst;
19340 }
19341 if (local_phase) {
19342 leave_local_phase();
19343 refresh();
19344 }
19345 steps = inner;
19346 // A round that fails to lower the worst image's force by a tenth
19347 // moves that image onto its own substrate factor; a second such
19348 // round in a row grows the local set by the neighbours of the
19349 // atoms it holds, so atoms that respond anharmonically leave the
19350 // quadratic substrate model.
19351 const bool stalled = round_worst_image > 0 &&
19352 round_first_worst > 0.0 &&
19353 round_last_worst > 0.9 * round_first_worst &&
19354 round_last_worst > 10.0 * config.conv_tol;
19355 if (stalled && df > 0)
19356 own_far_factor[static_cast<std::size_t>(round_worst_image)] = 1;
19357 stall_rounds = stalled ? stall_rounds + 1 : 0;
19358 if (stalled && stall_rounds >= 3 && grows < 2 && atomic &&
19359 config.gp_local_grow_radius > 0.0) {
19360 // Atoms that respond anharmonically leave the quadratic
19361 // substrate model by joining the phase set, whose shell
19362 // widens by one grow radius; the residual model keeps its
19363 // dofs, so the substrate factor keeps its shape.
19364 phase_radius += config.gp_local_grow_radius;
19365 build_phase_set();
19366 ++grows;
19367 stall_rounds = 0;
19368 if (far_hessian_ready) factor_far_hessian();
19369 ++model_epoch;
19370 if (config.verbose)
19371 neb_log() << "[gp_local] grow outer=" << outer
19372 << " phase_radius=" << phase_radius
19373 << " phase_dofs=" << phase_dofs.size() << "\n";
19374 }
19375 if (config.verbose && n_active > 0) {
19376 double worst_local = 0.0, worst_far = 0.0;
19377 if (round_worst_image > 0) {
19378 const Eigen::VectorXd fw = path.nebForce(round_worst_image);
19379 worst_local = gather(fw, local_dofs).norm();
19380 worst_far = df > 0 ? gather(fw, far_dofs).norm() : 0.0;
19381 }
19382 neb_log() << "[gp_local] round outer=" << outer
19383 << " steps=" << inner
19384 << " worst_image=" << round_worst_image
19385 << " F_first=" << round_first_worst
19386 << " F_last=" << round_last_worst
19387 << " F_local=" << worst_local
19388 << " F_far=" << worst_far
19389 << " ci_start=" << ci_at_round_start
19390 << " ci_end=" << path.highestEnergyImageIndex()
19391 << " active=" << n_active
19392 << " local_steps=" << local_steps
19393 << " phase_entries=" << phase_entries << "\n";
19394 }
19395 }
19396 polish_steps_total += steps;
19397 local_polish_seconds +=
19398 std::chrono::duration<double>(std::chrono::steady_clock::now() - t2)
19399 .count();
19400
19401 // 4. Convergence on measured forces only.
19402 restore();
19403 double max_force = 0.0;
19404 double max_true_force = 0.0;
19405 bool all_measured = true;
19406 for (int i = 1; i < n_images - 1; ++i) {
19407 const double f = path.nebForceMagnitude(i);
19408 max_force = std::max(max_force, f);
19409 if (measured_current(i))
19410 max_true_force = std::max(max_true_force, f);
19411 else
19412 all_measured = false;
19413 }
19414 result.max_force_history.push_back(max_force);
19415 result.outer_iterations = outer + 1;
19416 const auto saddle_candidate = [&]() {
19417 // The stop names the bead that is climbing. The energy
19418 // maximum can be a different bead after the surrogate step.
19419 if (ci_active && config.climbing_image_converged_only)
19420 return detail::activeClimbingMarkerIndex(path);
19421 return ci_active ? path.highestEnergyImageIndex()
19422 : detail::bestEvaluatedSaddleCandidate(path);
19423 };
19424 // The band returns once its candidate is measured under the final
19425 // tolerance. A returned band carries an oracle result at every
19426 // interior image, so the images that moved since their
19427 // measurement are measured where they stand first; the candidate
19428 // is already measured and does not move. The measured neighbours
19429 // can change the tangent at the candidate, so its force is read
19430 // again.
19431 const auto returns_on_candidate = [&]() {
19432 if (wallClockReached()) return false;
19433 if (!detail::evaluatedTrueForceBelowFinalTolerance(
19434 path, saddle_candidate(), config.conv_tol, !ci_active))
19435 return false;
19436 std::vector<int> stale;
19437 for (int i = 1; i < n_images - 1; ++i)
19438 if (!measured_current(i)) stale.push_back(i);
19439 if (stale.empty()) return true;
19440 std::vector<Eigen::VectorXd> points;
19441 for (const int i: stale)
19442 points.push_back(path.image(i).positions);
19443 const auto t_measure = std::chrono::steady_clock::now();
19444 if (wallClockReached()) return false;
19445 std::vector<char> measured;
19446 std::string failure;
19447 auto res = evaluateTrialPoints(
19448 points, oracle, nullptr, {},
19449 config.oracle_session_restart_requested, &config.batch_oracle,
19450 config.oracle_batch_chunk, measured, failure);
19451 result.oracle_calls += static_cast<int>(points.size());
19452 result.oracle_calls_outer += static_cast<int>(points.size());
19453 measure_seconds += std::chrono::duration<double>(
19454 std::chrono::steady_clock::now() - t_measure)
19455 .count();
19456 bool complete = true;
19457 for (std::size_t k = 0; k < stale.size(); ++k) {
19458 const int i = stale[k];
19459 auto& mk = meas[static_cast<std::size_t>(i)];
19460 if (measured.size() <= k || !measured[k]) {
19461 // A refused geometry returns the image to its
19462 // measurement; an image never measured leaves the
19463 // band incomplete and the search goes on.
19464 if (mk.have)
19465 path.image(i).positions = mk.positions;
19466 else
19467 complete = false;
19468 continue;
19469 }
19470 Image& img = path.image(i);
19471 mk.have = true;
19472 mk.positions = img.positions;
19473 mk.energy = res[k].energy;
19474 mk.gradient = res[k].gradient;
19475 ++mk.count;
19476 img.energy = res[k].energy;
19477 img.gradient = res[k].gradient;
19478 img.evaluated = true;
19479 record(img.positions, img.energy, img.gradient, i);
19480 }
19481 restore();
19482 return complete &&
19483 detail::evaluatedTrueForceBelowFinalTolerance(
19484 path, saddle_candidate(), config.conv_tol, !ci_active);
19485 };
19486 if (returns_on_candidate()) {
19487 const int measured_candidate = saddle_candidate();
19488 result.converged = true;
19489 result.convergence_status = GPNEBConvergenceStatus::ForceTolerance;
19490 if (config.verbose)
19491 neb_log() << "[gp_local] outer=" << outer << " true force "
19492 << path.saddleForce(measured_candidate)
19493 << " at image " << measured_candidate
19494 << " is below tolerance; returning that geometry\n";
19495 break;
19496 }
19497 if (wallClockReached()) break;
19498 double stop_force = max_force;
19499 if (ci_active && config.climbing_image_converged_only) {
19500 const int climbing = saddle_candidate();
19501 stop_force = (climbing > 0 && climbing < n_images - 1)
19502 ? path.saddleForce(climbing)
19503 : std::numeric_limits<double>::infinity();
19504 }
19505 if (all_measured && detail::outerConvergenceCertifiedByTolerance(
19506 config, path, ci_active, stop_force)) {
19507 result.converged = true;
19508 result.convergence_status =
19509 detail::convergenceStatusForCurrentTolerance(config);
19510 if (config.verbose)
19511 neb_log() << "[gp_local] outer=" << outer
19512 << " converged max_F=" << max_force
19513 << " noracle=" << result.oracle_calls << "\n";
19514 break;
19515 }
19516
19517 // 5. Measure the worst images whose geometry has no oracle data, up
19518 // to gp_local_batch per round. An image measured at its current
19519 // geometry above tolerance needs another relaxation round, not a
19520 // repeated call.
19521 std::vector<std::pair<double, int>> candidates;
19522 bool pending_relaxation = false;
19523 for (int i = 1; i < n_images - 1; ++i) {
19524 if (image_converged(i)) continue;
19525 if (measured_current(i)) {
19526 pending_relaxation = true;
19527 continue;
19528 }
19529 candidates.emplace_back(path.nebForceMagnitude(i), i);
19530 }
19531 if (candidates.empty()) {
19532 if (pending_relaxation && steps > 0) continue;
19533 break;
19534 }
19535 std::sort(
19536 candidates.begin(), candidates.end(),
19537 [](const auto& a, const auto& b) { return a.first > b.first; });
19538 // Early rounds measure one image; a band that keeps needing rounds
19539 // measures more per round, up to gp_local_batch_max.
19540 int batch = std::max(1, config.gp_local_batch);
19541 // A short band measures every interior image each round: its
19542 // relaxation costs as much as a long band's and a sweep halves the
19543 // rounds for a few extra calls.
19544 if (n_int <= config.gp_local_sweep_images)
19545 batch = std::max(batch, n_int);
19546 if (config.gp_local_batch_growth > 0)
19547 batch = std::max(batch, 1 + outer / config.gp_local_batch_growth);
19548 batch = std::min(batch, std::max(1, config.gp_local_batch_max));
19549 if (static_cast<int>(candidates.size()) > batch)
19550 candidates.resize(static_cast<std::size_t>(batch));
19551 const int target = candidates.front().second;
19552 const double worst = candidates.front().first;
19553 std::vector<Eigen::VectorXd> points;
19554 std::vector<double> predicted;
19555 for (const auto& c: candidates) {
19556 points.push_back(path.image(c.second).positions);
19557 predicted.push_back(path.image(c.second).energy);
19558 }
19559 const auto t_measure = std::chrono::steady_clock::now();
19560 if (wallClockReached()) break;
19561 std::vector<char> measured;
19562 std::string failure;
19563 auto res = evaluateTrialPoints(
19564 points, oracle, nullptr, {},
19565 config.oracle_session_restart_requested, &config.batch_oracle,
19566 config.oracle_batch_chunk, measured, failure);
19567 result.oracle_calls += static_cast<int>(points.size());
19568 result.oracle_calls_outer += static_cast<int>(points.size());
19569 measure_seconds += std::chrono::duration<double>(
19570 std::chrono::steady_clock::now() - t_measure)
19571 .count();
19572 double surprise = 0.0;
19573 for (std::size_t k = 0; k < candidates.size(); ++k) {
19574 const int i = candidates[k].second;
19575 auto& mk = meas[static_cast<std::size_t>(i)];
19576 if (measured.size() <= k || !measured[k]) {
19577 // A refused geometry returns the image to its measurement.
19578 if (mk.have) path.image(i).positions = mk.positions;
19579 mk.trust = std::max(0.5 * mk.trust, 0.02);
19580 if (config.verbose)
19581 neb_log() << "[gp_local] outer=" << outer << " image=" << i
19582 << " refused what=" << failure << "\n";
19583 continue;
19584 }
19585 Image& img = path.image(i);
19586 const double s_k = std::isfinite(predicted[k])
19587 ? std::abs(res[k].energy - predicted[k])
19588 : 0.0;
19589 surprise = std::max(surprise, s_k);
19590 // An energy surprise of a hundred force tolerances over an Angstrom
19591 // halves the trust sphere; ten widen it.
19592 if (s_k > 100.0 * config.conv_tol)
19593 mk.trust = std::max(0.5 * mk.trust, 0.02);
19594 else if (s_k < 10.0 * config.conv_tol)
19595 mk.trust = std::min(1.5 * mk.trust,
19596 std::max(1.0, config.gp_local_trust));
19597 mk.have = true;
19598 mk.positions = img.positions;
19599 mk.energy = res[k].energy;
19600 mk.gradient = res[k].gradient;
19601 ++mk.count;
19602 img.energy = res[k].energy;
19603 img.gradient = res[k].gradient;
19604 img.evaluated = true;
19605 record(img.positions, img.energy, img.gradient, i);
19606 }
19607 auto& m = meas[static_cast<std::size_t>(target)];
19608 Image& image = path.image(target);
19609 if (!m.have ||
19610 (image.positions - m.positions).lpNorm<Eigen::Infinity>() > 0.0) {
19611 continue;
19612 }
19613 const double far_moved_last = 0.0;
19614 (void)far_moved_last;
19615 restore();
19616 // The baseline evaluation refreshes the reactant slot's neighbour
19617 // list and pair cache. It used to run only while logging, so
19618 // --quiet kept that list stale and the band took another path.
19619 Eigen::VectorXd g_model;
19620 double far_model_error = 0.0, local_model_error = 0.0;
19621 (void)surrogate(image.positions, g_model);
19622 if (df > 0)
19623 far_model_error =
19624 (gather(g_model, far_dofs) - gather(image.gradient, far_dofs))
19625 .norm();
19626 if (d > 0)
19627 local_model_error = (gather(g_model, local_dofs) -
19628 gather(image.gradient, local_dofs))
19629 .norm();
19630 if (config.verbose) {
19631 // Largest per-atom true force of the measured image and whether
19632 // that atom belongs to the local subspace.
19633 Eigen::Index worst_atom = -1;
19634 double worst_atom_force = 0.0;
19635 for (Eigen::Index g = 0; g + per <= band_dof; g += per) {
19636 const double f = image.gradient.segment(g, per).norm();
19637 if (f > worst_atom_force) {
19638 worst_atom_force = f;
19639 worst_atom = g / per;
19640 }
19641 }
19642 neb_log()
19643 << "[gp_local] outer=" << outer << " image=" << target
19644 << " far_moved=" << far_moved_last
19645 << " far_model_err=" << far_model_error
19646 << " local_model_err=" << local_model_error << " worst_pos="
19647 << Eigen::VectorXd(worst_atom >= 0 ? image.positions.segment(
19648 worst_atom * per, per)
19649 : Eigen::VectorXd())
19650 .transpose()
19651 << " worst_F="
19652 << Eigen::VectorXd(worst_atom >= 0 ? image.gradient.segment(
19653 worst_atom * per, per)
19654 : Eigen::VectorXd())
19655 .transpose()
19656 << " worst_atom=" << worst_atom
19657 << " worst_atom_F=" << worst_atom_force << " worst_local="
19658 << (worst_atom >= 0 &&
19659 local_atoms[static_cast<std::size_t>(worst_atom)]
19660 ? 1
19661 : 0)
19662 << " neb_F=" << path.nebForceMagnitude(target)
19663 << " raw_F=" << image.gradient.norm() << " E=" << image.energy
19664 << "\n";
19665 neb_log() << "[gp_local] outer=" << outer << " image=" << target
19666 << " est_F=" << worst
19667 << " true_F=" << path.nebForceMagnitude(target)
19668 << " max_true_F=" << max_true_force
19669 << " surprise=" << surprise << " trust=" << m.trust
19670 << " ci=" << (ci_active ? 1 : 0)
19671 << " hi=" << path.highestEnergyImageIndex()
19672 << " polish=" << steps << " n_obs=" << gp.size()
19673 << " ell=" << gp.lengthScale()
19674 << " pair_rms=" << (pair ? pair->gradientResidual() : 0.0)
19675 << " far_F=" << last_far_force
19676 << " far_step=" << last_far_step
19677 << " far_H=" << (far_hessian_ready ? 1 : 0)
19678 << " noracle=" << result.oracle_calls << "\n";
19679 }
19680 if (returns_on_candidate()) {
19681 result.converged = true;
19682 result.convergence_status = GPNEBConvergenceStatus::ForceTolerance;
19683 result.outer_iterations = outer + 1;
19684 result.max_energy_image = saddle_candidate();
19685 break;
19686 }
19687 if (config.band_stall) {
19688 noteLowestCertifiedClimb(band_stall, path,
19689 path.highestEnergyImageIndex());
19690 double measured_max = 0.0;
19691 for (int i = 1; i < n_images - 1; ++i)
19692 measured_max =
19693 std::max(measured_max, path.nebForceMagnitude(i));
19694 const BandStallAction action = observeMaxBandForce(
19695 band_stall, measured_max, config.conv_tol, stall_window);
19696 if (action != BandStallAction::Continue) {
19697 restoreCertifiedClimb(path, band_stall);
19698 for (int i = 0; i < n_images; ++i) {
19699 const Image& img = path.image(i);
19700 auto& mk = meas[static_cast<std::size_t>(i)];
19701 if (!img.evaluated) {
19702 mk.have = false;
19703 continue;
19704 }
19705 mk.have = true;
19706 mk.positions = img.positions;
19707 mk.energy = img.energy;
19708 mk.gradient = img.gradient;
19709 }
19710 band_s_hist.clear();
19711 band_y_hist.clear();
19712 band_rho_hist.clear();
19713 raw.clear();
19714 for (int i = 0; i < n_images; ++i) {
19715 const Image& img = path.image(i);
19716 if (!img.evaluated) continue;
19717 raw.push_back({img.positions, img.energy, img.gradient, i});
19718 }
19719 append_session_seed();
19720 rebuild_gp();
19721 double restored_max = 0.0;
19722 for (int i = 1; i < n_images - 1; ++i)
19723 restored_max =
19724 std::max(restored_max, path.nebForceMagnitude(i));
19725 band_stall.best_force = restored_max;
19726 if (config.verbose)
19727 neb_log()
19728 << "[band] stall outer=" << outer << " action="
19729 << (action == BandStallAction::Stop ? "stop"
19730 : "restore")
19731 << " image=" << band_stall.image
19732 << " E=" << band_stall.energy << " F=" << restored_max
19733 << " window=" << stall_window << "\n";
19734 if (action == BandStallAction::Stop) {
19735 result.outer_iterations = outer + 1;
19736 if (detail::evaluatedTrueForceBelowFinalTolerance(
19737 path, band_stall.image, config.conv_tol,
19738 !ci_active)) {
19739 result.converged = true;
19740 result.convergence_status =
19742 } else if (session && config.outer_iter_hook && ci_active) {
19743 session->stagnation_handoff = true;
19744 const int handoff_ci =
19745 detail::activeClimbingMarkerIndex(path);
19746 if (handoff_ci > 0 &&
19747 handoff_ci < path.numImages() - 1) {
19748 bool handoff_converged = false;
19749 config.outer_iter_hook(path, handoff_ci, outer,
19750 *session, handoff_converged,
19751 /*trap_detected=*/false);
19752 if (handoff_converged) {
19753 result.converged = true;
19754 result.convergence_status = detail::
19755 convergenceStatusForCurrentTolerance(
19756 config);
19757 }
19758 }
19759 }
19760 break;
19761 }
19762 }
19763 }
19764 }
19765 restore();
19766 if (config.verbose) {
19767 neb_log() << "[gp_local] summary dofs=" << d
19768 << " polish_steps=" << polish_steps_total
19769 << " pair_skipped=" << pair_skipped
19770 << " fit_seconds=" << local_fit_seconds
19771 << " polish_seconds=" << local_polish_seconds
19772 << " measure_seconds=" << measure_seconds
19773 << " observe_seconds=" << observe_seconds
19774 << " gp_seconds=" << gp_seconds
19775 << " restore_seconds=" << restore_seconds
19776 << " list_builds=" << (pair ? pair->listBuilds() : 0)
19777 << " list_seconds=" << (pair ? pair->listSeconds() : 0.0)
19778 << " far_factorisations=" << far_factorisations
19779 << " pair_spacing=" << pair_spacing << "\n";
19780 }
19781 if (ci_active && config.climbing_image_converged_only) {
19782 const int climbing = detail::activeClimbingMarkerIndex(path);
19783 result.max_energy_image =
19784 climbing > 0 ? climbing : path.highestEnergyImageIndex();
19785 } else {
19786 result.max_energy_image = path.highestEnergyImageIndex();
19787 }
19788 result.returned_true_force =
19789 detail::evaluatedTrueForce(path, result.max_energy_image);
19790 result.barrier_energy =
19791 detail::forwardBarrierEnergy(path, result.max_energy_image);
19792 result.reverse_barrier_energy =
19793 detail::reverseBarrierEnergy(path, result.max_energy_image);
19794 result.path = std::move(path_ptr);
19795 if (result.stop_reason == GPNEBStopReason::Unspecified)
19796 result.stop_reason = result.converged
19799 return std::move(result);
19800}
19801
19802} // namespace
19803
19804namespace {
19805
19809EndpointSymmetry bandEndpointSymmetry(const GPNEBConfig& config,
19810 const NEBPath& path,
19811 const ActiveLearningSession* session)
19812{
19813 if (session == nullptr || !isGpOieMode(config.mode))
19814 throw std::invalid_argument(
19815 "GPNEBConfig: symmetry_permutation trains the session GP and "
19816 "needs a session and mode GP_OIE or GP_AIE");
19817 if (config.frozen_positions.size() > 0 ||
19818 std::any_of(config.cell.begin(), config.cell.end(),
19819 [](double v) { return v != 0.0; }) ||
19820 std::any_of(config.moving_atoms.begin(), config.moving_atoms.end(),
19821 [](char moving) { return moving == 0; }))
19822 throw std::invalid_argument(
19823 "GPNEBConfig: symmetry_permutation needs an isolated molecule "
19824 "with every atom moving; fixed atoms or a periodic cell break "
19825 "the rigid-motion invariance it relies on");
19826 return requireEndpointSymmetry(config.symmetry_permutation,
19827 path.image(0).positions,
19828 path.image(path.numImages() - 1).positions,
19829 config.atomic_numbers, config.trust_radius);
19830}
19831
19832} // namespace
19833
19834GPNEBResult gpNEBUngated(NEBOracle oracle, const Eigen::VectorXd& initial,
19835 const Eigen::VectorXd& final_state, int n_images,
19836 const GPNEBConfig& config,
19837 ActiveLearningSession* session)
19838{
19839 const NebVerboseGuard verbose_guard(config.verbose);
19840 GPNEBResult result;
19841 const auto wallClockReached = [&]() {
19843 return false;
19844 result.converged = false;
19847 return true;
19848 };
19849
19850 // The GP modes train their surrogate through gp_setup. Without it the
19851 // run would fall through to the oracle-only branches and report a GP
19852 // search that never built a GP, so refuse it.
19853 if (isGpOieMode(config.mode) && !config.gp_setup) {
19854 throw std::invalid_argument(
19855 std::string("GPNEBConfig: mode ") +
19856 (config.mode == NEBMode::GP_OIE ? "GP_OIE" : "GP_AIE") +
19857 " needs gp_setup to build its Gaussian process; set gp_setup, "
19858 "or choose NEBMode::OIE, AIE or Standard to run without one");
19859 }
19860
19861 // Initialize path
19862 std::unique_ptr<NEBPath> path_ptr;
19863 if (config.has_initial_path) {
19864 path_ptr = std::make_unique<NEBPath>(config.initial_path,
19865 config.spring_constant);
19866 path_ptr->setSpringBounds(config.spring_constant,
19867 config.spring_constant_min);
19868 // A warm-started band holds the spacing it was given (a local
19869 // refinement at the ridge) for the whole attempt; the rest lengths
19870 // are a fixed target, never refreshed under the relaxation.
19871 if (config.hold_refined_spacing &&
19872 static_cast<int>(config.initial_rest_lengths.size()) ==
19873 path_ptr->numImages() - 1) {
19874 path_ptr->setSpringRestLengths(config.initial_rest_lengths);
19875 }
19876 } else {
19877 path_ptr = std::make_unique<NEBPath>(initial, final_state, n_images,
19878 config.spring_constant);
19879 path_ptr->setSpringBounds(config.spring_constant,
19880 config.spring_constant_min);
19881 }
19882 NEBPath& path = *path_ptr;
19884 path.setPeriodicCell(config.cell);
19885 if (!config.moving_atoms.empty()) path.setMovingAtoms(config.moving_atoms);
19886 path.setExternalFixedAtoms(config.frozen_positions.size() > 0);
19888 config.n_atoms >= 2 &&
19889 config.frozen_positions.size() == 0);
19890 path.alignMolecularFrames();
19891 if (!config.has_initial_path) path.interpolateFromEndpoints();
19892 if (!config.rgsaddle_library.empty())
19894 if (!config.has_initial_path && config.use_idpp && config.n_atoms > 0) {
19895 std::cout << "[startup] path_seed engine=rgsaddle\n";
19896 if (config.use_sidpp) {
19897 if (config.sidpp_geodesic) {
19899 config.n_atoms, config.moving_atoms, config.sidpp_alpha);
19900 } else {
19901 path.initializeSIDPP(config.n_atoms, config.moving_atoms,
19902 config.sidpp_alpha);
19903 }
19904 } else {
19905 path.initializeIDPP(config.n_atoms, config.moving_atoms, false);
19906 }
19907 }
19909 // The surrogate bands relax with a predicted interior and are certified
19910 // on measured rows at the same geometry; one spring law serves both.
19912 config.mode != NEBMode::GP_OIE &&
19913 config.mode != NEBMode::OIE);
19914 path.alignMolecularFrames();
19915 (void)detail::publishOracleSessionPathCheckpoint(config, path);
19916 EndpointSymmetry endpoint_symmetry;
19917 if (!config.symmetry_permutation.empty())
19918 endpoint_symmetry = bandEndpointSymmetry(config, path, session);
19919
19920 result.oracle_calls = 0;
19921 std::mt19937 rng(config.seed);
19922 bool ci_active = false;
19923 const bool had_preexisting_session_rows =
19924 session != nullptr && session->training_obs.R.rows() > 0;
19925
19926 try {
19927 // Evaluate endpoints (always needed) - parallelized to avoid
19928 // replication. Wall-budget restarts restore the session's endpoint
19929 // rows instead of re-purchasing them.
19930 {
19931 const bool endpoints_restored =
19932 session &&
19933 detail::restoreObservedImageIfPresent(session->training_obs,
19934 path.image(0)) &&
19935 detail::restoreObservedImageIfPresent(
19936 session->training_obs, path.image(path.numImages() - 1));
19937 if (!endpoints_restored) {
19938 // Sample the band endpoints. A warm start can carry a
19939 // geometry other than the initial/final arguments; writing
19940 // that sample onto the other geometry poisons the endpoint
19941 // rows. A matching warm start has the same positions.
19942 std::vector<Eigen::VectorXd> endpoints = {
19943 path.image(0).positions,
19944 path.image(path.numImages() - 1).positions};
19945 // The endpoints are the given minima the band hangs from; a
19946 // band has no accepted state without them, so a failure there
19947 // ends the run.
19948 std::vector<EvalResult> res;
19949 try {
19950 res = parallelEvaluate(
19951 endpoints, oracle, nullptr, {},
19953 &config.batch_oracle, config.oracle_batch_chunk);
19954 } catch (const OracleSessionRestartRequested&) {
19955 throw;
19956 } catch (const gpr::WallClockLimitReached&) {
19957 throw;
19958 } catch (const std::exception& error) {
19959 throw std::runtime_error(
19960 std::string("the oracle failed at a band endpoint (the "
19961 "given reactant or product): ") +
19962 error.what());
19963 }
19964
19965 path.image(0).energy = res[0].energy;
19966 path.image(0).gradient = res[0].gradient;
19967 path.image(0).evaluated = true;
19968
19969 path.image(path.numImages() - 1).energy = res[1].energy;
19970 path.image(path.numImages() - 1).gradient = res[1].gradient;
19971 path.image(path.numImages() - 1).evaluated = true;
19972 if (session) {
19973 session->appendObservation(0, path.image(0).positions,
19974 res[0].energy, res[0].gradient);
19975 session->appendObservation(
19976 path.numImages() - 1,
19977 path.image(path.numImages() - 1).positions,
19978 res[1].energy, res[1].gradient);
19979 }
19980
19981 // Oracle calls are distributed; we increment by the number of
19982 // points evaluated across all ranks.
19983 result.oracle_calls += 2;
19984 result.oracle_calls_endpoints += 2;
19985 }
19986 }
19987 if (!endpoint_symmetry.empty())
19988 session->setEndpointSymmetry(std::move(endpoint_symmetry));
19989
19990 const bool uses_one_image_eval =
19991 config.mode == NEBMode::OIE || config.mode == NEBMode::GP_OIE;
19992
19993 // Initial-design: oracle every intermediate image once before the
19994 // outer loop. Standard / AIE modes always do this. GP-OIE does it
19995 // when config.seed_full_chain is true (ChemGP's gp_neb_oie default,
19996 // neb_oie.rs:648-664). Without it the GP starts knowing only the 2
19997 // endpoints and any chain-relaxation step is on a path-blind
19998 // surrogate; the chain settles into a wrong basin.
19999 const bool do_initial_design =
20000 config.mode == NEBMode::GP_LOCAL
20001 ? config.gp_local_initial_sweep
20002 : (!uses_one_image_eval ||
20003 (isGpOieMode(config.mode) && config.seed_full_chain));
20004
20005 if (do_initial_design) {
20006 // Bayesian continuation across wall-budget restarts: rows the
20007 // session already holds at these exact positions are restored,
20008 // not re-purchased -- the deterministic band reset makes every
20009 // restart's initial design identical, and re-oracling it would
20010 // pay the full design again on each attempt.
20011 std::vector<Eigen::VectorXd> intermediates;
20012 std::vector<int> pending_idx;
20013 for (int i = 1; i < path.numImages() - 1; ++i) {
20014 if (session && detail::restoreObservedImageIfPresent(
20015 session->training_obs, path.image(i))) {
20016 continue;
20017 }
20018 intermediates.push_back(path.image(i).positions);
20019 pending_idx.push_back(i);
20020 }
20021 if (!intermediates.empty()) {
20022 // A GP band can start without a failed image's row; a band
20023 // relaxed on the true forces cannot move an image it has no
20024 // force for, so there a failure ends the run.
20025 std::vector<char> measured;
20026 std::string failure;
20027 auto res = evaluateTrialPoints(
20028 intermediates, oracle, nullptr, {},
20030 &config.batch_oracle, config.oracle_batch_chunk, measured,
20031 failure);
20032 for (int k = 0; k < static_cast<int>(pending_idx.size()); ++k) {
20033 const int i = pending_idx[k];
20034 if (!measured[static_cast<std::size_t>(k)]) {
20035 if (!isGpOieMode(config.mode))
20036 throw std::runtime_error(
20037 "the oracle failed at image " +
20038 std::to_string(i) +
20039 " of the initial band: " + failure);
20040 if (config.verbose)
20041 neb_log() << "[oracle-refused] initial image=" << i
20042 << " what=" << failure << std::endl;
20043 continue;
20044 }
20045 path.image(i).energy = res[k].energy;
20046 path.image(i).gradient = res[k].gradient;
20047 path.image(i).evaluated = true;
20048 if (session)
20049 session->appendObservation(i, path.image(i).positions,
20050 res[k].energy,
20051 res[k].gradient);
20052 }
20053 result.oracle_calls += static_cast<int>(intermediates.size());
20054 result.oracle_calls_initial +=
20055 static_cast<int>(intermediates.size());
20056 }
20057 }
20058
20059 // Sampled energies do not bound the maximum between images. Only an
20060 // externally supplied energy limit can constrain the accepted saddle.
20061 const double connecting_path_energy_ceiling =
20062 session ? session->path_energy_ceiling
20063 : std::numeric_limits<double>::infinity();
20064 // Retain the initial geometry as a restart target for an explicit
20065 // limit.
20066 std::vector<Eigen::VectorXd> ceiling_witness_positions;
20067 if (std::isfinite(connecting_path_energy_ceiling)) {
20068 ceiling_witness_positions.reserve(path.numImages());
20069 for (int i = 0; i < path.numImages(); ++i) {
20070 ceiling_witness_positions.push_back(path.image(i).positions);
20071 }
20072 }
20073 // Fully measured fallback anchor: initially the seeded band and
20074 // replaced only by a lower-force band whose interior gradients all come
20075 // from the oracle. The restart selector prefers retained trust-bounded
20076 // path/climb snapshots and uses this anchor when none exists; an
20077 // unconverged result also restores it so a surrogate-only excursion is
20078 // never returned as the physical band.
20079 std::vector<Eigen::VectorXd> anchor_positions =
20080 ceiling_witness_positions;
20081 if (anchor_positions.empty()) {
20082 anchor_positions.reserve(path.numImages());
20083 for (int i = 0; i < path.numImages(); ++i) {
20084 anchor_positions.push_back(path.image(i).positions);
20085 }
20086 }
20087 // Descending true-force residuals refine the usual max-force merit:
20088 // equal maxima compare the next-largest residual. The anchor moves only
20089 // to a lexicographically better, fully measured band.
20090 std::vector<double> anchor_true_force_profile =
20091 detail::measuredBandForceProfile(path);
20092 double anchor_true_max_force =
20093 anchor_true_force_profile.empty()
20094 ? std::numeric_limits<double>::infinity()
20095 : anchor_true_force_profile.front();
20096
20097 // Compute initial NEB forces
20098 path.computeNEBForces();
20099 OracleForceProgressTracker oracle_force_progress(path.numImages());
20100 for (int i = 0; i < path.numImages(); ++i) {
20101 const Image& image = path.image(i);
20102 if (image.evaluated && image.gradient.size() > 0 &&
20103 image.gradient.allFinite()) {
20104 (void)oracle_force_progress.observe(i, image.gradient.norm());
20105 }
20106 }
20107
20108 // ------------------------------------------------------------------
20109 // GP-OIE branch: GP inner relaxation with one oracle acquisition.
20110 //
20111 // Outer iter:
20112 // 1. Build a GP with no across-iteration cache state; apply
20113 // layered-chain knobs;
20114 // train on accumulated obs.
20115 // 2. Inner GP-relaxation loop: predict (E, G) at each
20116 // intermediate image's current position from the GP, recompute
20117 // NEB forces, take a clipped global L-BFGS step. Break on
20118 // a condition certificate or an explicit positive inner budget.
20119 // 3. Pick the worst image (max variance with non-MAP modes, max
20120 // GP force otherwise), oracle-eval it, append to the training
20121 // set, then check the oracle-force convergence condition.
20122 //
20123 // Callers without gp_setup use the acquisition branch below.
20124 // ------------------------------------------------------------------
20125 if (config.mode == NEBMode::GP_LOCAL && !config.gp_local_sweep) {
20126 result = runGpLocalOie(oracle, config, path_ptr, path, result,
20127 ci_active, session);
20128 if (result.converged ||
20130 return result;
20131 // A zero outer budget asks for the initial band only; the retries
20132 // below would relax it, so hand it back as built.
20133 if (config.max_outer_iter == 0) return result;
20134 // The surrogate stopped above the force tolerance. Its springs
20135 // followed only the atoms that move between the endpoints, so a
20136 // substrate atom the pair model says is loaded by that motion was
20137 // left free. Search the same chord once more with those atoms
20138 // sprung. A search that already carried them, and still stopped,
20139 // finishes on the plain band.
20140 if (!config.gp_local_carry_springs) {
20141 GPNEBConfig carried = config;
20142 carried.gp_local_carry_springs = true;
20143 carried.has_initial_path = false;
20144 GPNEBResult second = gpNEBUngated(oracle, initial, final_state,
20145 n_images, carried, session);
20148 second.oracle_calls_outer += result.oracle_calls_outer;
20149 second.oracle_calls_validation +=
20151 second.oracle_calls = second.oracle_calls_endpoints +
20152 second.oracle_calls_initial +
20153 second.oracle_calls_outer +
20155 return second;
20156 }
20157 // The plain band on the same chord springs every atom. Finish
20158 // there and keep the surrogate's calls.
20159 GPNEBConfig plain = config;
20160 plain.mode = NEBMode::Standard;
20161 plain.has_initial_path = false;
20162 GPNEBResult finished = gpNEBUngated(oracle, initial, final_state,
20163 n_images, plain, session);
20165 finished.oracle_calls_initial += result.oracle_calls_initial;
20166 finished.oracle_calls_outer += result.oracle_calls_outer;
20168 finished.oracle_calls = finished.oracle_calls_endpoints +
20169 finished.oracle_calls_initial +
20170 finished.oracle_calls_outer +
20171 finished.oracle_calls_validation;
20172 return finished;
20173 }
20174 if (isGpOieMode(config.mode) && config.gp_setup) {
20175 return runGpOieNeb(oracle, config, session, path_ptr, path, result,
20176 oracle_force_progress, anchor_positions,
20177 anchor_true_force_profile, anchor_true_max_force,
20178 ceiling_witness_positions, ci_active,
20179 connecting_path_energy_ceiling,
20180 had_preexisting_session_rows);
20181 }
20182 // ------------------------------------------------------------------
20183 // Standard / AIE / OIE branches.
20184 // Allocate a band-L-BFGS chain optimizer once for these branches.
20185 // refresh() does NOT touch the GP -- the chain image gradients
20186 // come from the oracle (in AIE/Standard via re-evaluate after each
20187 // step; in OIE via the worst-image oracle). NEB forces are
20188 // recomputed from the stored gradients each refresh.
20189 detail::GlobalLBFGSOptions ndl_band_options;
20190 ndl_band_options.memory = config.lbfgs_memory;
20191 ndl_band_options.inverse_curvature = config.lbfgs_inverse_curvature;
20192 ndl_band_options.finite_difference = config.lbfgs_finite_difference;
20193 ndl_band_options.auto_scale = config.lbfgs_auto_scale;
20194 ndl_band_options.angle_reset = config.lbfgs_angle_reset;
20195 ndl_band_options.distance_reset = config.lbfgs_distance_reset;
20196 ndl_band_options.newton_agreement = config.lbfgs_newton_agreement;
20197 ndl_band_options.sketch_history = config.lbfgs_sketch_history;
20198 ndl_band_options.sketch_seed = config.lbfgs_sketch_seed;
20199 ndl_band_options.sketch_h0_rank = config.lbfgs_sketch_h0_rank;
20200 // GP_LOCAL never buys an oracle sweep inside a band step, so the
20201 // finite-difference curvature probe, which would read stale gradients
20202 // at the probed geometry, stays off and H0 comes from the scalar seed.
20203 if (config.mode == NEBMode::GP_LOCAL)
20204 ndl_band_options.finite_difference = 0.0;
20205 detail::GlobalLBFGSOptimizer ndl_band_optimizer(ndl_band_options);
20206 // Consecutive refused band evaluations; past the bound the run stops.
20207 OracleFailureBudget oracle_failures;
20208 auto ndl_refresh = [&]() {
20209 if (wallClockReached()) return false;
20210 // Standard / AIE relax the band on the TRUE potential. The L-BFGS
20211 // chain optimizer probes the objective at perturbed band geometries
20212 // (finite-difference curvature + trial steps); without a GP to
20213 // supply forces there, the image gradients must be re-evaluated on
20214 // the oracle at the current positions, else computeNEBForces() runs
20215 // on stale gradients, the curvature model degenerates, and the band
20216 // freezes (max NEB force constant across outer iters). The
20217 // post-step re-eval (the mode switch below) still runs; the extra
20218 // evals here are what make the chain L-BFGS see a consistent
20219 // true-force surface.
20220 if (config.mode == NEBMode::Standard ||
20221 config.mode == NEBMode::AIE) {
20222 std::vector<Eigen::VectorXd> pts;
20223 for (int i = 1; i < path.numImages() - 1; ++i) {
20224 pts.push_back(path.image(i).positions);
20225 }
20226 if (!pts.empty()) {
20227 // A refused image keeps its last measured state, and the
20228 // refresh reports failure so the optimizer rejects the
20229 // probe that led there.
20230 std::vector<char> measured;
20231 std::string failure;
20232 auto res = evaluateTrialPoints(
20233 pts, oracle, nullptr, {},
20235 &config.batch_oracle, config.oracle_batch_chunk,
20236 measured, failure);
20237 bool all_measured = true;
20238 for (int i = 0; i < static_cast<int>(pts.size()); ++i) {
20239 if (!measured[static_cast<std::size_t>(i)]) {
20240 all_measured = false;
20241 continue;
20242 }
20243 path.image(i + 1).energy = res[i].energy;
20244 path.image(i + 1).gradient = res[i].gradient;
20245 noteMeasuredSecant(session, config, i + 1,
20246 path.image(i + 1).positions,
20247 res[i].energy, res[i].gradient);
20248 }
20249 result.oracle_calls += static_cast<int>(pts.size());
20250 result.oracle_calls_outer += static_cast<int>(pts.size());
20251 if (!all_measured) {
20252 oracle_failures.failed("band", failure);
20253 if (config.verbose)
20254 neb_log() << "[oracle-refused] band refresh what="
20255 << failure << std::endl;
20256 detail::installSecantClimbingDirection(path, session,
20257 config);
20258 path.computeNEBForces();
20259 return false;
20260 }
20261 oracle_failures.measured();
20262 }
20263 }
20264 detail::installSecantClimbingDirection(path, session, config);
20265 path.computeNEBForces();
20266 return true;
20267 };
20268 detail::NEBBandObjective ndl_band_objective(path, ndl_refresh);
20269 // Halved after a band step whose geometry the oracle refused.
20270 double ndl_band_max_step = config.lbfgs_max_move;
20271 // Running maximum of the initial NEB force across the band. eOn's
20272 // relative CI activation rule fires once the current max NEB
20273 // force drops below ci_activation_factor * initial_max_force,
20274 // capped from below by ci_activation_tol.
20275 double initial_max_force = 0.0;
20276 // ------------------------------------------------------------------
20277
20278 // Main outer loop
20279 // Outer budget, optionally per image. The acquisition oracles about
20280 // one image per outer iteration, so a band of n images needs n outers
20281 // to be covered once; read absolutely, the same number gives a longer
20282 // band less chance per image, and a setting tuned at one image count
20283 // is silently wrong at another.
20284 const int outer_budget =
20285 (config.outer_budget_per_image && path.numImages() > 0)
20286 ? static_cast<int>(
20287 std::min<long>(static_cast<long>(config.max_outer_iter) *
20288 path.numImages(),
20289 std::numeric_limits<int>::max()))
20290 : config.max_outer_iter;
20291 // This loop is the model-free driver for OIE and for GP-OIE with
20292 // no gp_setup. Unevaluated interiors still hold energy 0.
20293 const bool model_free_one_image =
20294 config.mode == NEBMode::OIE || config.mode == NEBMode::GP_OIE;
20295 // ------------------------------------------------------------------
20296 // GP_LOCAL: the atoms that carry the endpoint motion form a Cartesian
20297 // subspace; a gradient GP over that subspace polishes every interior
20298 // image after each true-force band step, with the other coordinates
20299 // held at the stepped geometry. The oracle then measures the polished
20300 // band once, so each outer costs one sweep, and the band L-BFGS keeps
20301 // every measured secant pair, including the polish displacement.
20302 // ------------------------------------------------------------------
20303 const bool local_polish = config.mode == NEBMode::GP_LOCAL;
20304 std::vector<Eigen::Index> local_dofs;
20305 std::unique_ptr<LocalCartesianGP> local_gp;
20306 double local_trust = config.gp_local_trust;
20307 std::vector<double> local_predicted_energy;
20308 double local_fit_seconds = 0.0;
20309 double local_polish_seconds = 0.0;
20310 int local_polish_steps = 0;
20311 const Eigen::Index band_dof = path.numImages() > 0
20312 ? path.image(0).positions.size()
20313 : Eigen::Index(0);
20314 if (local_polish && band_dof > 0) {
20315 local_dofs = detail::selectLocalPolishDofs(
20316 path.image(0).positions,
20317 path.image(path.numImages() - 1).positions,
20318 config.gp_local_fraction, config.gp_local_radius);
20319 if (!local_dofs.empty()) {
20320 local_gp =
20321 std::make_unique<LocalCartesianGP>(band_dof, local_dofs);
20322 local_gp->setWindow(config.gp_local_window);
20323 local_gp->setNoise(config.gp_local_noise,
20324 config.gp_local_noise);
20325 local_gp->setLengthScaleBounds(0.05, 50.0);
20326 local_gp->setHyperparameters(1.0, 1.0);
20327 }
20328 if (config.verbose) {
20329 neb_log() << "[gp_local] subspace dofs=" << local_dofs.size()
20330 << " of " << band_dof
20331 << " fraction=" << config.gp_local_fraction
20332 << " radius=" << config.gp_local_radius
20333 << " window=" << config.gp_local_window
20334 << " trust=" << local_trust << "\n";
20335 }
20336 }
20337 auto local_gather = [&](const Eigen::VectorXd& v) {
20338 Eigen::VectorXd out(static_cast<Eigen::Index>(local_dofs.size()));
20339 for (std::size_t k = 0; k < local_dofs.size(); ++k)
20340 out(static_cast<Eigen::Index>(k)) = v(local_dofs[k]);
20341 return out;
20342 };
20343 // Every measured image feeds the local model; a repeated geometry
20344 // replaces its earlier row.
20345 auto local_observe = [&](const Image& image) {
20346 if (!local_gp || !image.evaluated) return;
20347 if (image.gradient.size() != band_dof ||
20348 !std::isfinite(image.energy))
20349 return;
20350 local_gp->add(image.positions, image.energy,
20351 local_gather(image.gradient));
20352 };
20353 if (local_gp) {
20354 for (int i = 0; i < path.numImages(); ++i)
20355 local_observe(path.image(i));
20356 }
20357 // Relax the local subspace of every interior image on the GP mean
20358 // under the band projection, the other coordinates fixed. Returns the
20359 // number of inner iterations taken.
20360 auto local_polish_band = [&](int outer) -> int {
20361 if (!local_gp || wallClockReached()) return 0;
20362 const auto t_fit = std::chrono::steady_clock::now();
20363 if (local_gp->size() >= 2 && !local_gp->ready() &&
20364 result.hyperparameter_refits == 0) {
20365 local_gp->setHyperparametersFromData(3.0);
20366 (void)local_gp->fit(config.gp_local_refit_iters);
20367 ++result.hyperparameter_refits;
20368 } else if (config.gp_local_refit_every > 0 &&
20369 outer % config.gp_local_refit_every == 0) {
20370 (void)local_gp->fit(config.gp_local_refit_iters);
20371 ++result.hyperparameter_refits;
20372 } else {
20373 local_gp->condition();
20374 ++result.fixed_theta_refreshes;
20375 }
20376 const auto t_polish = std::chrono::steady_clock::now();
20377 local_fit_seconds +=
20378 std::chrono::duration<double>(t_polish - t_fit).count();
20379 if (!local_gp->ready()) return 0;
20380 const int n_int = path.numImages() - 2;
20381 const Eigen::Index d = static_cast<Eigen::Index>(local_dofs.size());
20382 const Eigen::Index per = (band_dof % 3 == 0) ? 3 : 1;
20383 if (n_int <= 0 || d <= 0) return 0;
20384 std::vector<Eigen::VectorXd> start(static_cast<std::size_t>(n_int));
20385 std::vector<Image> before(static_cast<std::size_t>(n_int));
20386 for (int i = 0; i < n_int; ++i) {
20387 before[static_cast<std::size_t>(i)] = path.image(i + 1);
20388 start[static_cast<std::size_t>(i)] =
20389 local_gather(path.image(i + 1).positions);
20390 }
20391 auto refresh = [&]() {
20392 for (int i = 1; i < path.numImages() - 1; ++i) {
20393 Image& image = path.image(i);
20394 double energy = 0.0;
20395 Eigen::VectorXd grad;
20396 local_gp->predict(image.positions, energy, grad);
20397 gpr::numerics::perturbPosterior(energy, grad);
20398 image.energy = energy;
20399 image.gradient.setZero(band_dof);
20400 for (std::size_t k = 0; k < local_dofs.size(); ++k)
20401 image.gradient(local_dofs[k]) =
20402 grad(static_cast<Eigen::Index>(k));
20403 image.evaluated = false;
20404 }
20405 path.computeNEBForces();
20406 };
20407 auto band_force = [&]() {
20408 Eigen::VectorXd f(static_cast<Eigen::Index>(n_int) * d);
20409 for (int i = 0; i < n_int; ++i)
20410 f.segment(static_cast<Eigen::Index>(i) * d, d) =
20411 local_gather(path.nebForce(i + 1));
20412 return f;
20413 };
20414 auto band_positions = [&]() {
20415 Eigen::VectorXd z(static_cast<Eigen::Index>(n_int) * d);
20416 for (int i = 0; i < n_int; ++i)
20417 z.segment(static_cast<Eigen::Index>(i) * d, d) =
20418 local_gather(path.image(i + 1).positions);
20419 return z;
20420 };
20421 const double inner_tol =
20422 config.gp_local_inner_tol_factor * config.conv_tol;
20423 const double max_move =
20424 config.lbfgs_max_move > 0.0 ? config.lbfgs_max_move : 0.2;
20425 std::deque<Eigen::VectorXd> s_hist, y_hist;
20426 std::deque<double> rho_hist;
20427 Eigen::VectorXd z_prev, f_prev;
20428 double H0 = 0.05;
20429 int steps = 0;
20430 for (; steps < config.gp_local_inner_max; ++steps) {
20431 if (wallClockReached()) break;
20432 refresh();
20433 const Eigen::VectorXd f = band_force();
20434 double worst = 0.0;
20435 for (int i = 0; i < n_int; ++i)
20436 worst = std::max(
20437 worst,
20438 f.segment(static_cast<Eigen::Index>(i) * d, d).norm());
20439 if (!(worst > inner_tol) || !f.allFinite()) break;
20440 const Eigen::VectorXd z = band_positions();
20441 if (steps > 0) {
20442 const Eigen::VectorXd sv = z - z_prev;
20443 const Eigen::VectorXd yv = f_prev - f;
20444 const double sy = sv.dot(yv);
20445 if (sy > 1e-14 && std::isfinite(sy)) {
20446 s_hist.push_back(sv);
20447 y_hist.push_back(yv);
20448 rho_hist.push_back(1.0 / sy);
20449 while (static_cast<int>(s_hist.size()) > 20) {
20450 s_hist.pop_front();
20451 y_hist.pop_front();
20452 rho_hist.pop_front();
20453 }
20454 H0 =
20456 } else {
20457 s_hist.clear();
20458 y_hist.clear();
20459 rho_hist.clear();
20460 }
20461 }
20462 Eigen::VectorXd step = -gpr::optim::twoLoopRecursion(
20463 s_hist, y_hist, rho_hist, f, H0);
20464 if (step.dot(f) <= 0.0) {
20465 s_hist.clear();
20466 y_hist.clear();
20467 rho_hist.clear();
20468 step = H0 * f;
20469 }
20470 // Per-atom move bound, then the per-image trust sphere about
20471 // the stepped geometry.
20472 double largest = 0.0;
20473 for (Eigen::Index g = 0; g + per <= step.size(); g += per)
20474 largest = std::max(largest, step.segment(g, per).norm());
20475 if (largest > max_move) step *= max_move / largest;
20476 for (int i = 0; i < n_int; ++i) {
20477 const Eigen::Index off = static_cast<Eigen::Index>(i) * d;
20478 Eigen::VectorXd target =
20479 z.segment(off, d) + step.segment(off, d);
20480 Eigen::VectorXd disp =
20481 target - start[static_cast<std::size_t>(i)];
20482 const double dn = disp.norm();
20483 if (dn > local_trust && dn > 0.0) {
20484 target = start[static_cast<std::size_t>(i)] +
20485 disp * (local_trust / dn);
20486 }
20487 Image& image = path.image(i + 1);
20488 for (std::size_t k = 0; k < local_dofs.size(); ++k)
20489 image.positions(local_dofs[k]) =
20490 target(static_cast<Eigen::Index>(k));
20491 path.pinFixedAtoms(image.positions);
20492 }
20493 z_prev = z;
20494 f_prev = f;
20495 }
20496 refresh();
20497 local_predicted_energy.assign(static_cast<std::size_t>(n_int), 0.0);
20498 for (int i = 0; i < n_int; ++i)
20499 local_predicted_energy[static_cast<std::size_t>(i)] =
20500 path.image(i + 1).energy;
20501 local_polish_steps += steps;
20502 local_polish_seconds +=
20503 std::chrono::duration<double>(std::chrono::steady_clock::now() -
20504 t_polish)
20505 .count();
20506 if (config.verbose) {
20507 double moved = 0.0;
20508 for (int i = 0; i < n_int; ++i)
20509 moved = std::max(
20510 moved, (local_gather(path.image(i + 1).positions) -
20511 start[static_cast<std::size_t>(i)])
20512 .norm());
20513 neb_log() << "[gp_local] outer=" << outer
20514 << " polish_steps=" << steps << " moved=" << moved
20515 << " trust=" << local_trust
20516 << " n_obs=" << local_gp->size()
20517 << " ell=" << local_gp->lengthScale()
20518 << " sf=" << std::sqrt(local_gp->signalVariance())
20519 << "\n";
20520 }
20521 return steps;
20522 };
20523 BandForceStall band_stall;
20524 const int stall_window = bandStallWindow(
20525 path.numImages(), static_cast<int>(local_dofs.size()));
20526 for (int outer = 0; outer < outer_budget; ++outer) {
20527 if (wallClockReached()) break;
20528 if (local_gp) {
20529 for (int i = 1; i < path.numImages() - 1; ++i)
20530 local_observe(path.image(i));
20531 }
20532 if (session) {
20533 session->ci_active_at_outer_start = ci_active;
20534 if (ci_active)
20535 ++session->ci_stable_outer_count;
20536 else
20537 session->ci_stable_outer_count = 0;
20538 }
20539 // Check convergence
20540 double max_force = 0.0;
20541 for (int i = 1; i < path.numImages() - 1; ++i) {
20542 double f = path.nebForceMagnitude(i);
20543 max_force = std::max(max_force, f);
20544 }
20545 // CI-converged-only semantics. eOn (neb_loose default) checks
20546 // only the climbing image's NEB-force norm once CI is active;
20547 // the off-saddle band can remain slack since the saddle is the
20548 // physically meaningful target. Mirrors
20549 // NudgedElasticBand::convergenceForce() in eOn:399-422. Without
20550 // this gate the Standard/AIE branch needs ~2x more outer iters
20551 // (gpr AIE 03_h2co: 626 calls vs eOn 298 at conv_tol=0.5).
20552 double convergence_force = max_force;
20553 const bool climb_only =
20554 config.climbing_image_converged_only && ci_active;
20555 // The installed marker, not the current energy maximum. The
20556 // maximum can move onto a quieter neighbour while the bead that
20557 // is climbing is still above --converged-force.
20558 const int climbing_image =
20559 climb_only ? detail::activeClimbingMarkerIndex(path) : -1;
20560 const int measured_candidate =
20561 climb_only
20562 ? climbing_image
20563 : (ci_active ? path.highestEnergyImageIndex()
20564 : detail::bestEvaluatedSaddleCandidate(path));
20565 if (detail::evaluatedTrueForceBelowFinalTolerance(
20566 path, measured_candidate, config.conv_tol, !ci_active)) {
20567 // The climbing bead's true force is already the final
20568 // tolerance. Do not spend another outer on the rest of the
20569 // band.
20570 result.converged = true;
20571 result.convergence_status =
20573 convergence_force = path.saddleForce(measured_candidate);
20574 }
20575 if (climb_only) {
20576 if (climbing_image > 0 &&
20577 climbing_image < path.numImages() - 1) {
20578 convergence_force = path.saddleForce(climbing_image);
20579 } else {
20580 convergence_force = std::numeric_limits<double>::infinity();
20581 }
20582 }
20583 result.max_force_history.push_back(convergence_force);
20584
20585 if (detail::outerConvergenceCertifiedByTolerance(
20586 config, path, ci_active, convergence_force)) {
20587 result.converged = true;
20588 result.convergence_status =
20589 detail::convergenceStatusForCurrentTolerance(config);
20590 // Fall through to the composition-trace write below, then
20591 // break.
20592 }
20593
20594 // Climbing image activation. eOn (neb_loose) uses
20595 // activate when max_force <= max(ci_after,
20596 // ci_after_rel *
20597 // initial_max_force)
20598 // with ci_after = 0.5 eV/A and ci_after_rel = 0.8. The relative
20599 // trigger fires much earlier than the absolute one for runs
20600 // starting with max_force >> 1 eV/A; the absolute floor caps
20601 // it so converged_force=0.5 runs still activate CI before
20602 // reaching the band-wide convergence threshold (otherwise
20603 // ci_converged_only never kicks in and the convergence
20604 // criterion is max-over-band, which costs ~2x more outer
20605 // iterations than eOn).
20606 if (result.converged) {
20607 // Count the accepting outer (parity with the GP-OIE branch,
20608 // which sets outer_iterations before its convergence gate).
20609 result.outer_iterations = outer + 1;
20610 // Still emit one composition snapshot for the accepting outer
20611 // before leaving the loop (no further band step / re-eval).
20612 if (config.record_composition_trace) {
20614 rec.outer_idx = outer;
20615 rec.oracle_target_image = -1;
20616 rec.max_oracle_force = max_force;
20617 rec.n_uneval = 0;
20618 rec.ci_active = ci_active;
20619 rec.ci_index = ci_active
20620 ? (climbing_image > 0
20621 ? climbing_image
20622 : path.highestEnergyImageIndex())
20623 : -1;
20624 {
20625 const int hi = path.highestEnergyImageIndex();
20626 rec.barrier_estimate =
20627 detail::forwardBarrierEnergy(path, hi);
20628 }
20629 rec.certificates.force_tolerance = true;
20631 (max_force <
20632 detail::effectiveModelNoiseTolerance(config));
20634 (!ci_active ||
20635 convergence_force <
20636 detail::effectiveModelNoiseTolerance(config));
20637 rec.certificates.n_uneval_zero = true;
20639 result.composition_trace.push_back(std::move(rec));
20640 }
20641 break;
20642 }
20643 if (initial_max_force <= 0.0 && std::isfinite(max_force)) {
20644 initial_max_force = max_force;
20645 }
20646 const double ci_relative_trigger =
20647 (initial_max_force > 0.0 && config.ci_activation_factor > 0.0)
20648 ? config.ci_activation_factor * initial_max_force
20649 : 0.0;
20650 const double ci_activation_threshold =
20651 std::max(config.ci_activation_tol, ci_relative_trigger);
20652 if (config.climbing_image && !ci_active &&
20653 max_force < ci_activation_threshold) {
20654 ci_active = true;
20655 }
20656 if (config.climbing_image && ci_active) {
20657 if (model_free_one_image &&
20658 detail::hasUnevaluatedInterior(path)) {
20659 detail::assignClimbingImageFromEvaluatedEnergies(path);
20660 } else {
20661 path.enableClimbingImage();
20662 }
20663 }
20664
20665 // Band L-BFGS step. Same chain optimizer the GP-OIE branch uses
20666 // (gpr::neb::detail::GlobalLBFGSOptimizer with Nocedal two-loop
20667 // recursion and per-atom maxMove clip), matching eOn/ChemGP
20668 // NEB chain optimization. Per-image steepest descent
20669 // (step = inner_step_size * nebForce, clipped to 0.1 A) can
20670 // park the barrier near the saddle while leaving max force
20671 // above conv_tol; L-BFGS is the force-reducing step.
20672 detail::installSecantClimbingDirection(path, session, config);
20673 path.computeNEBForces();
20674 // The measured band before the step, restored when the oracle
20675 // refuses a geometry the step moved an image to.
20676 std::vector<Image> band_before_step;
20677 band_before_step.reserve(
20678 static_cast<std::size_t>(path.numImages()));
20679 for (int i = 0; i < path.numImages(); ++i)
20680 band_before_step.push_back(path.image(i));
20681 const int prev_hist = ndl_band_optimizer.historySize();
20682 const std::optional<double> secant_inverse_curvature =
20683 secantBandInverseCurvature(session, config);
20684 (void)ndl_band_optimizer.step(ndl_band_objective, ndl_band_max_step,
20685 secant_inverse_curvature);
20686 if (wallClockReached()) {
20687 for (int i = 0; i < path.numImages(); ++i)
20688 path.image(i) =
20689 band_before_step[static_cast<std::size_t>(i)];
20690 path.computeNEBForces();
20691 break;
20692 }
20693 const int post_hist = ndl_band_optimizer.historySize();
20694 const bool hist_reset = post_hist <= prev_hist && prev_hist > 0;
20695 // Per-outer AIE trace (one line per outer iter). Mirrors the
20696 // [gp_oie] line emitted by the GP-OIE branch so smokes can
20697 // diff iteration-by-iteration against eOn / OIE for the same
20698 // cell. Includes the chain L-BFGS history size and a
20699 // history-reset flag so angle_reset cascades
20700 // are visible without recompiling for verbose mode.
20701 if (config.verbose) {
20702 const int hi_now = path.highestEnergyImageIndex();
20703 const double bar_now =
20704 detail::forwardBarrierEnergy(path, hi_now);
20705 neb_log() << "[aie] outer=" << outer << " max_F=" << max_force
20706 << " conv_F=" << convergence_force
20707 << " ci=" << (ci_active ? 1 : 0) << " hi=" << hi_now
20708 << " bar=" << bar_now << " hist=" << post_hist
20709 << (hist_reset ? " (LBFGS_RESET)" : "")
20710 << " noracle=" << result.oracle_calls << "\n";
20711 }
20712
20713 // Re-evaluate based on mode
20714 switch (config.mode) {
20715 case NEBMode::Standard:
20716 case NEBMode::AIE:
20717 case NEBMode::GP_LOCAL: {
20718 if (local_polish) (void)local_polish_band(outer);
20719 std::vector<Eigen::VectorXd> pts;
20720 for (int i = 1; i < path.numImages() - 1; ++i) {
20721 pts.push_back(path.image(i).positions);
20722 }
20723 std::vector<char> measured;
20724 std::string failure;
20725 auto res = evaluateTrialPoints(
20726 pts, oracle, nullptr, {},
20728 &config.batch_oracle, config.oracle_batch_chunk,
20729 measured, failure);
20730 result.oracle_calls += static_cast<int>(pts.size());
20731 result.oracle_calls_outer += static_cast<int>(pts.size());
20732 if (std::find(measured.begin(), measured.end(), 0) !=
20733 measured.end()) {
20734 // A rejected band step: the measured band comes back,
20735 // the step bound halves, and the curvature pairs that
20736 // aimed at the refused geometry are dropped.
20737 oracle_failures.failed("band", failure);
20738 for (int i = 0; i < path.numImages(); ++i)
20739 path.image(i) =
20740 band_before_step[static_cast<std::size_t>(i)];
20741 path.computeNEBForces();
20742 ndl_band_max_step *= 0.5;
20743 ndl_band_optimizer.reset();
20744 if (config.verbose)
20745 neb_log() << "[oracle-refused] band step rejected, "
20746 "max move "
20747 << ndl_band_max_step
20748 << " what=" << failure << std::endl;
20749 break;
20750 }
20751 oracle_failures.measured();
20752 for (int i = 0; i < static_cast<int>(pts.size()); ++i) {
20753 path.image(i + 1).energy = res[i].energy;
20754 path.image(i + 1).gradient = res[i].gradient;
20755 path.image(i + 1).evaluated = true;
20756 noteMeasuredSecant(session, config, i + 1,
20757 path.image(i + 1).positions,
20758 res[i].energy, res[i].gradient);
20759 }
20760 if (local_polish && local_gp &&
20761 local_predicted_energy.size() == pts.size()) {
20762 // The measured energies grade the polish: a surprise
20763 // halves the trust sphere, agreement widens it.
20764 double surprise = 0.0;
20765 for (std::size_t i = 0; i < pts.size(); ++i)
20766 surprise = std::max(
20767 surprise, std::abs(res[i].energy -
20768 local_predicted_energy[i]));
20769 if (surprise > 0.1) {
20770 local_trust = std::max(0.5 * local_trust, 0.02);
20771 } else if (surprise < 0.01) {
20772 local_trust =
20773 std::min(1.5 * local_trust,
20774 std::max(1.0, config.gp_local_trust));
20775 }
20776 if (config.verbose)
20777 neb_log() << "[gp_local] outer=" << outer
20778 << " surprise=" << surprise
20779 << " trust=" << local_trust << "\n";
20780 }
20781 // OCINEB MMF on the climbing image, true-potential dimer.
20782 // Standard/AIE relax the band but otherwise never run the
20783 // minimum-mode-following step, so they were plain CI-NEB
20784 // and climbed a higher saddle than the eOn OCINEB
20785 // reference. Drive the SAME outer_iter_hook the GP-OIE
20786 // branch uses (the OCINEB controller): it gates triggering
20787 // via stability + adaptive threshold and writes the
20788 // dimer-refined saddle back to the CI.
20789 if (config.outer_iter_hook && session && ci_active) {
20790 const int hook_ci_idx =
20791 detail::activeClimbingMarkerIndex(path);
20792 if (hook_ci_idx > 0 &&
20793 hook_ci_idx < path.numImages() - 1) {
20794 path.computeNEBForces();
20795 bool hook_converged = false;
20796 config.outer_iter_hook(path, hook_ci_idx, outer,
20797 *session, hook_converged,
20798 /*trap_detected=*/false);
20799 if (hook_converged) {
20800 result.converged = true;
20801 result.convergence_status = detail::
20802 convergenceStatusForCurrentTolerance(
20803 config);
20804 }
20805 }
20806 }
20807 break;
20808 }
20809
20810 case NEBMode::GP_AIE:
20811 case NEBMode::GP_OIE:
20812 case NEBMode::OIE: {
20813 // Select image(s) to evaluate via acquisition strategy.
20814 int n_int = path.numIntermediate();
20815 std::vector<Eigen::VectorXd> forces(n_int);
20816 std::vector<ObservationVariance> variances(n_int);
20817 const bool have_variance_estimator = static_cast<bool>(
20819 std::vector<Eigen::VectorXd> tangents(n_int);
20820 std::vector<bool> evaluated(n_int, false);
20821
20822 for (int i = 0; i < n_int; ++i) {
20823 forces[i] = path.nebForce(i + 1);
20824 // Tangent at image i+1
20825 Eigen::VectorXd tau = path.image(i + 2).positions -
20826 path.image(i).positions;
20827 double tn = tau.norm();
20828 if (tn > 1e-10) tau /= tn;
20829 tangents[i] = tau;
20830
20831 if (have_variance_estimator) {
20832 variances[i] =
20834 path.image(i + 1).positions);
20835 } else {
20836 variances[i].gradient = Eigen::VectorXd::Zero(
20837 path.image(i + 1).positions.size());
20838 }
20839 }
20840
20841 // Select images to evaluate
20842 std::vector<int> to_eval;
20843 for (int ev = 0; ev < config.evals_per_iter; ++ev) {
20844 int sel = selectNextImage(forces, variances, tangents,
20845 evaluated, config.acquisition,
20846 config.ucb_kappa, &rng);
20847 if (sel >= 0) {
20848 if (config.use_triplet) {
20849 auto triplet =
20850 expandToTriplet(sel + 1, path.numImages());
20851 for (int idx: triplet) {
20852 if (idx > 0 && idx < path.numImages() - 1) {
20853 to_eval.push_back(idx);
20854 evaluated[idx - 1] = true;
20855 }
20856 }
20857 } else {
20858 to_eval.push_back(sel + 1);
20859 evaluated[sel] = true;
20860 }
20861 }
20862 }
20863
20864 // Evaluate selected images
20865 std::vector<Eigen::VectorXd> pts_to_eval;
20866 for (int idx: to_eval) {
20867 pts_to_eval.push_back(path.image(idx).positions);
20868 }
20869 std::vector<char> measured;
20870 std::string failure;
20871 auto res = evaluateTrialPoints(
20872 pts_to_eval, oracle, nullptr, {},
20874 &config.batch_oracle, config.oracle_batch_chunk,
20875 measured, failure);
20876 if (std::find(measured.begin(), measured.end(), 0) !=
20877 measured.end()) {
20878 // As for the full-band modes: the step that moved the
20879 // image onto the refused geometry is rejected.
20880 result.oracle_calls += static_cast<int>(to_eval.size());
20881 result.oracle_calls_outer +=
20882 static_cast<int>(to_eval.size());
20883 oracle_failures.failed("band", failure);
20884 for (int i = 0; i < path.numImages(); ++i)
20885 path.image(i) =
20886 band_before_step[static_cast<std::size_t>(i)];
20887 path.computeNEBForces();
20888 ndl_band_max_step *= 0.5;
20889 ndl_band_optimizer.reset();
20890 if (config.verbose)
20891 neb_log() << "[oracle-refused] band step rejected, "
20892 "max move "
20893 << ndl_band_max_step
20894 << " what=" << failure << std::endl;
20895 break;
20896 }
20897 oracle_failures.measured();
20898 for (int i = 0; i < static_cast<int>(to_eval.size()); ++i) {
20899 int idx = to_eval[i];
20900 path.image(idx).energy = res[i].energy;
20901 path.image(idx).gradient = res[i].gradient;
20902 path.image(idx).evaluated = true;
20903 }
20904 if (model_free_one_image && config.climbing_image &&
20905 ci_active && detail::hasUnevaluatedInterior(path)) {
20906 detail::assignClimbingImageFromEvaluatedEnergies(path);
20907 }
20908 result.oracle_calls += static_cast<int>(to_eval.size());
20909 result.oracle_calls_outer +=
20910 static_cast<int>(to_eval.size());
20911 break;
20912 }
20913 }
20914
20915 if (wallClockReached()) break;
20916 // Recompute NEB forces with updated energies/gradients
20917 path.computeNEBForces();
20918 result.outer_iterations = outer + 1;
20919 if (config.band_stall) {
20920 noteLowestCertifiedClimb(band_stall, path,
20922 double measured_max = 0.0;
20923 for (int i = 1; i < path.numImages() - 1; ++i)
20924 measured_max =
20925 std::max(measured_max, path.nebForceMagnitude(i));
20926 const BandStallAction action = observeMaxBandForce(
20927 band_stall, measured_max, config.conv_tol, stall_window);
20928 if (action != BandStallAction::Continue) {
20929 restoreCertifiedClimb(path, band_stall);
20930 ndl_band_optimizer.reset();
20931 double restored_max = 0.0;
20932 for (int i = 1; i < path.numImages() - 1; ++i)
20933 restored_max =
20934 std::max(restored_max, path.nebForceMagnitude(i));
20935 band_stall.best_force = restored_max;
20936 if (config.verbose)
20937 neb_log()
20938 << "[band] stall outer=" << outer << " action="
20939 << (action == BandStallAction::Stop ? "stop"
20940 : "restore")
20941 << " image=" << band_stall.image
20942 << " E=" << band_stall.energy
20943 << " F=" << restored_max
20944 << " window=" << stall_window << "\n";
20945 if (action == BandStallAction::Stop) {
20946 if (detail::evaluatedTrueForceBelowFinalTolerance(
20947 path, band_stall.image, config.conv_tol,
20948 !ci_active)) {
20949 result.converged = true;
20950 result.convergence_status =
20952 } else if (session && config.outer_iter_hook &&
20953 ci_active) {
20954 session->stagnation_handoff = true;
20955 const int handoff_ci =
20956 detail::activeClimbingMarkerIndex(path);
20957 if (handoff_ci > 0 &&
20958 handoff_ci < path.numImages() - 1) {
20959 bool handoff_converged = false;
20960 config.outer_iter_hook(path, handoff_ci, outer,
20961 *session,
20962 handoff_converged,
20963 /*trap_detected=*/false);
20964 if (handoff_converged) {
20965 result.converged = true;
20966 result.convergence_status = detail::
20967 convergenceStatusForCurrentTolerance(
20968 config);
20969 }
20970 }
20971 }
20972 break;
20973 }
20974 }
20975 }
20976
20977 // Composition-level snapshot for Standard / AIE / model-free OIE.
20978 // Captures post-step decision state for this outer. (The accepting
20979 // outer is recorded on the early-exit path above.)
20980 if (config.record_composition_trace) {
20981 double post_max_force = 0.0;
20982 for (int i = 1; i < path.numImages() - 1; ++i) {
20983 const double f = path.nebForceMagnitude(i);
20984 post_max_force = std::max(post_max_force, f);
20985 }
20987 rec.outer_idx = outer;
20988 // Standard/AIE re-eval the full band; OIE uses acquisition.
20989 // This composition branch does not retain the primary target,
20990 // so -1 means "band-wide / acquisition-driven".
20991 rec.oracle_target_image = -1;
20992 rec.max_oracle_force = post_max_force;
20993 rec.n_uneval = 0;
20994 rec.ci_active = ci_active;
20995 const int trace_ci =
20996 ci_active ? detail::activeClimbingMarkerIndex(path) : -1;
20997 rec.ci_index = trace_ci;
20998 {
20999 const int hi = path.highestEnergyImageIndex();
21000 rec.barrier_estimate =
21001 detail::forwardBarrierEnergy(path, hi);
21002 }
21003 const double model_tol =
21004 detail::effectiveModelNoiseTolerance(config);
21005 rec.certificates.n_uneval_zero = true;
21006 rec.certificates.mep_force_ok = (post_max_force < model_tol);
21008 (!ci_active ||
21009 (trace_ci > 0 && path.saddleForce(trace_ci) < model_tol));
21010 const double trace_stop_force =
21011 (config.climbing_image_converged_only && ci_active)
21012 ? (trace_ci > 0
21013 ? path.saddleForce(trace_ci)
21014 : std::numeric_limits<double>::infinity())
21015 : post_max_force;
21017 detail::outerConvergenceCertifiedByTolerance(
21018 config, path, ci_active, trace_stop_force);
21019 result.composition_trace.push_back(std::move(rec));
21020 }
21021 }
21022
21023 if (local_polish && config.verbose) {
21024 neb_log() << "[gp_local] summary dofs=" << local_dofs.size()
21025 << " polish_steps=" << local_polish_steps
21026 << " fit_seconds=" << local_fit_seconds
21027 << " polish_seconds=" << local_polish_seconds << "\n";
21028 }
21029 // Find barrier (forward convention: E_saddle - E_reactant, matching
21030 // the eOn results.dat extremum convention consumed downstream).
21031 // Energy 0 on an image the oracle has not touched is not a saddle.
21032 if (model_free_one_image && detail::hasUnevaluatedInterior(path)) {
21033 const int evaluated_hi =
21034 detail::highestEvaluatedInteriorImageIndex(path);
21035 result.max_energy_image = evaluated_hi > 0
21036 ? evaluated_hi
21037 : path.highestEnergyImageIndex();
21038 } else if (config.climbing_image_converged_only && ci_active) {
21039 const int climbing = detail::activeClimbingMarkerIndex(path);
21040 result.max_energy_image =
21041 climbing > 0 ? climbing : path.highestEnergyImageIndex();
21042 } else {
21044 }
21045 result.returned_true_force =
21046 detail::evaluatedTrueForce(path, result.max_energy_image);
21047 result.barrier_energy =
21048 detail::forwardBarrierEnergy(path, result.max_energy_image);
21049 result.reverse_barrier_energy =
21050 detail::reverseBarrierEnergy(path, result.max_energy_image);
21051 result.path = std::move(path_ptr);
21053 result.stop_reason = result.converged
21056
21057 return result;
21058 } catch (const gpr::WallClockLimitReached&) {
21059 result.converged = false;
21062 if (session) {
21063 for (int image = 0; image < path.numImages(); ++image)
21064 (void)detail::restoreObservedImageIfPresent(
21065 session->training_obs, path.image(image));
21066 }
21067 result.max_energy_image =
21068 detail::highestEvaluatedInteriorImageIndex(path);
21069 const bool measured_saddle = result.max_energy_image > 0;
21070 if (result.max_energy_image <= 0)
21072 result.returned_true_force =
21073 detail::evaluatedTrueForce(path, result.max_energy_image);
21074 if (measured_saddle && path.image(0).evaluated &&
21075 path.image(path.numImages() - 1).evaluated) {
21076 result.barrier_energy =
21077 detail::forwardBarrierEnergy(path, result.max_energy_image);
21078 result.reverse_barrier_energy =
21079 path.image(result.max_energy_image).energy -
21080 path.image(path.numImages() - 1).energy;
21081 } else {
21082 result.barrier_energy = std::numeric_limits<double>::quiet_NaN();
21083 result.reverse_barrier_energy =
21084 std::numeric_limits<double>::quiet_NaN();
21085 }
21086 result.path = std::move(path_ptr);
21087 return result;
21088 }
21089}
21090
21091namespace {
21092
21093void resumeFromSteppedPath(GPNEBConfig& cfg, const GPNEBConfig& original,
21094 const GPNEBResult& result, long cap, long spent)
21095{
21096 const NEBPath& path = *result.path;
21097 cfg = original;
21098 cfg.has_initial_path = true;
21099 cfg.initial_path.resize(path.numImages(), path.image(0).positions.size());
21100 for (int i = 0; i < path.numImages(); ++i)
21101 cfg.initial_path.row(i) = path.image(i).positions.transpose();
21102 cfg.initial_rest_lengths.clear();
21103 cfg.outer_budget_per_image = false;
21104 cfg.band_refinement_max = 0;
21105 cfg.max_outer_iter = static_cast<int>(std::max<long>(cap - spent, 1));
21106}
21107
21108} // namespace
21109
21110GPNEBResult gpNEB(NEBOracle oracle, const Eigen::VectorXd& initial,
21111 const Eigen::VectorXd& final_state, int n_images,
21112 const GPNEBConfig& config, ActiveLearningSession* session)
21113{
21114 GPNEBConfig cfg = config;
21115 // A band the force-stop certificate resumes continues the search that
21116 // measured it. Without a session each pass builds an empty model: the
21117 // resumed band re-measures its endpoints and fits three rows, the tied
21118 // endpoint minima and the stepped image, so the prior alone sets its
21119 // hyperparameters. One session carries every row across the passes.
21120 std::optional<ActiveLearningSession> resumable;
21121 if (session == nullptr && config.force_stop_certificate &&
21122 isGpOieMode(config.mode) && config.gp_setup) {
21123 resumable.emplace();
21124 resumable->gp_setup = config.gp_setup;
21125 session = &*resumable;
21126 }
21127 if (n_images > 1 && cfg.secant_hessian.quadratic_prior_mean) {
21128 // Band observations and MMF leases cross image histories. A single
21129 // quadratic extrapolated through those displacements is not a local
21130 // curvature model, so keep the independently safe consistency and
21131 // seed features but gate the quadratic for the whole band driver.
21133 std::cout << "[secant-quadratic] mean disabled across band images; "
21134 "consistency and curvature seeds remain enabled\n";
21135 }
21136 if (session != nullptr) session->setSecantHessianConfig(cfg.secant_hessian);
21137 if (cfg.wall_clock_limit) {
21138 auto unguarded_oracle = std::move(oracle);
21139 const auto limit = cfg.wall_clock_limit;
21140 oracle = [unguarded = std::move(unguarded_oracle),
21141 limit](const Eigen::VectorXd& positions) mutable {
21142 gpr::requireWallClock(limit);
21143 return unguarded(positions);
21144 };
21145 if (cfg.batch_oracle) {
21146 auto unguarded_batch = std::move(cfg.batch_oracle);
21147 cfg.batch_oracle =
21148 [unguarded = std::move(unguarded_batch),
21149 limit](const std::vector<Eigen::VectorXd>& points) mutable {
21150 gpr::requireWallClock(limit);
21151 return unguarded(points);
21152 };
21153 }
21154 }
21155 long spent = 0;
21156 long cap = -1;
21157 int carried_oracle = 0;
21158 int carried_true = 0;
21159 int carried_validation = 0;
21160 int carried_certificate = 0;
21161 Eigen::VectorXd refused_at;
21162 GPNEBResult result;
21163 const auto finish = [&](GPNEBResult done) {
21164 if (session) done.prior_observations = session->priorObservations();
21165 return done;
21166 };
21167 for (int guard = 0; guard < gpr::optim::forceStopMinModeEscapes();
21168 ++guard) {
21169 result =
21170 gpNEBUngated(oracle, initial, final_state, n_images, cfg, session);
21171 result.oracle_calls += carried_oracle;
21172 // Certificate calls of an earlier pass stay validation calls.
21173 result.oracle_calls_outer += carried_oracle - carried_validation;
21174 result.oracle_calls_validation += carried_validation;
21175 result.force_stop_certificate_calls += carried_certificate;
21176 result.index_gate_true_calls += carried_true;
21177 spent += result.outer_iterations;
21178 if (config.force_stop_certificate && result.converged &&
21179 !result.index_checked && result.path) {
21180 const int image = result.max_energy_image;
21181 NEBPath& path = *result.path;
21182 const bool force_under = image > 0 &&
21183 image < path.numImages() - 1 &&
21184 path.image(image).evaluated &&
21185 std::isfinite(path.saddleForce(image)) &&
21186 path.saddleForce(image) < config.conv_tol;
21187 if (force_under) {
21189 result, oracle, cfg,
21190 session != nullptr ? &session->atoms_config : nullptr);
21191 } else if (image > 0 && image < path.numImages() - 1) {
21192 const double move = config.lbfgs_max_move > 0.0
21193 ? config.lbfgs_max_move
21194 : config.ci_stencil_step;
21195 const int images = path.numImages();
21196 const int budget = vibrationalIndexOuterBudget(config, images);
21197 const double threshold =
21198 session != nullptr
21200 : std::numeric_limits<double>::infinity();
21201 const auto decision = decideVibrationalIndex(
21202 path.image(image).positions, path.image(image).gradient,
21203 session != nullptr ? &session->atoms_config : nullptr,
21204 session != nullptr ? &session->gp : nullptr,
21205 path.image(image).posterior_variance, threshold, move,
21207 &oracle, &cfg.batch_oracle, config.oracle_batch_chunk,
21208 config.vibrational_stencil);
21209 applyVibrationalIndexDecision(result, decision, budget);
21210 }
21211 }
21212 if (!result.index_continue || !result.path)
21213 return finish(std::move(result));
21214 if (cap < 0)
21215 cap = vibrationalIndexOuterBudget(config, result.path->numImages());
21216 const int image = result.max_energy_image;
21217 const Eigen::VectorXd& claimed = result.path->image(image).positions;
21218 const bool repeated =
21219 refused_at.size() == claimed.size() &&
21220 (claimed - refused_at).norm() <= 1e-8 * (1.0 + refused_at.norm());
21221 if (spent >= cap || repeated) {
21222 result.converged = false;
21224 result.index_refused = true;
21225 result.index_continue = false;
21226 return finish(std::move(result));
21227 }
21228 refused_at = claimed;
21229 carried_oracle = result.oracle_calls;
21230 carried_true = result.index_gate_true_calls;
21231 carried_validation = result.oracle_calls_validation;
21232 carried_certificate = result.force_stop_certificate_calls;
21233 resumeFromSteppedPath(cfg, config, result, cap, spent);
21234 }
21235 result.converged = false;
21237 result.index_refused = true;
21238 result.index_continue = false;
21239 return finish(std::move(result));
21240}
21241
21242} // namespace neb
21243} // namespace gpr
TPE-style OIE acquisition over the discrete interior-image axis.
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
ConvergenceNormType
Definition Enums.h:48
Scalar expected improvement, shared by path acquisition and parameter search.
GP-accelerated NEB: AIE and OIE variants.
GP-OCINEB controller – faithful port of the eOn ~NEBOcinebController~ pattern (eOn/client/ NEBOcinebC...
One step's oracle points shared out over the ranks of a communicator, with a layout-independent owner...
Dimensionless, self-tuning trust region for GP-accelerated NEB.
Trust radius for GP surrogate validity.
void dist_at(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, gpr::FieldMatrixd &dist, bool take_sqrt=true)
Give the distance between two atomic configurations as defined in the special GPstuff covariance func...
Definition Distance.cpp:620
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.
bool activateFrozenAtoms(const gpr::Coord &R, const double activation_distance, gpr::AtomsConfiguration &atoms_config)
Update the active frozen-atom set for one or more configurations.
void setObjectiveStationaritySkipAuto(bool use) noexcept
void setOptimizationSubsetHistory(int rows) noexcept
void setOutputScaleFloor(bool enabled) noexcept
bool tryGateEnergyVariance(const Observation &query, Eigen::RowVectorXd &energy_variance)
Definition Variance.cpp:604
void setHssvdDualRandomizedSketch(int sketch_size) noexcept
void setHyperparameterObjectiveMode(HyperparameterObjectiveMode mode) noexcept
void setUncertaintyMode(UncertaintyMode mode)
void setFitStepStop(bool use) noexcept
Whether the auto stationarity mode also ends each fit at its scale.
HyperparameterOptimizationMode getHyperparameterOptimizationMode() const noexcept
void setInternalCoordinateChart(std::shared_ptr< const geometry::InternalCoordinateChart > chart, double length_scale)
void setHssvdLocalPosteriorActiveSetSize(int size) noexcept
void setUsePsisDeterministicGrid(bool use) noexcept
void calculateVarianceDispatched(Observation &image1)
void setHutchinsonProbes(int num_probes) noexcept
bool hasPendingResidualModelRefit() const noexcept
void setSubsetFailureEscalation(bool enabled) noexcept
void setHssvdDualChopTolerance(double tol) noexcept
void setAtomicEnvironmentModel(bool enabled)
bool hasPendingActivePosteriorRefit() const noexcept
void setKappaMax(double kappa_max) noexcept
void optimize(const Observation &observation)
Optimize paramaters of a Gaussian process.
Definition Optimize.cpp:550
bool configureMinimumModeRefit(const Observation &oracle, double force_tolerance, ConvergenceNormType force_norm=ConvergenceNormType::L2_NORM, const RefitTrustReport *trust_report=nullptr)
double reportedVarianceCalibrationFactor() const noexcept
void setScalapackBlockSize(int block_size) noexcept
double lastStationarityThreshold() const noexcept
double getPhysicalTotalDiagonalRegularization() const noexcept
double fitGeodesicHeatPrior(const Coord &reference_path, const Observation &training_data)
void setWallClockLimit(std::shared_ptr< const WallClockLimit > limit)
void setVarianceConvention(VarianceConvention convention) noexcept
std::size_t fullCholeskyFactorizationsForTesting() const noexcept
void setDisableOutputNormalization(bool d) noexcept
void setRigidNullDeflation(bool enabled)
Opt-in rigid-motion nullspace deflation for free systems.
void setChemFactorizedHyperparameters(bool enabled) noexcept
void setPriorMeanStatistic(PriorMeanStatistic statistic) noexcept
void setPhysicsCollocationPath(const Coord &path_points)
Physics collocation set for hyperparameter selection: the live band (discrete IRC)....
void setVarianceSubsetConfigurations(int configurations) noexcept
void setModelProfile(GPModelProfile profile)
void setRgminInitialLogMove(double distance) noexcept
void setHyperparameterOptimizationMode(HyperparameterOptimizationMode mode) noexcept
void initialize(const InputParameters &parameters, const AtomsConfiguration &conf_info)
Initialize GPR class.
void setPopulationPrior(priors::PopulationPrior prior)
void setRgminMethod(rgmin_method_t m) noexcept
double lastStationarityShift() const noexcept
void setPairLocalDirectionalTiles(bool enabled) noexcept
void setUseLogNormalMagnPrior(bool use) noexcept
std::uint64_t factorEpoch() const noexcept
void setHssvdBackend(bool enabled) noexcept
void calculatePotentialDispatched(Observation &image1)
Definition Predict.cpp:982
std::size_t hssvdFullFactorizationsForTesting() const noexcept
void updateModelWithFullData(const Observation &full_observation)
void calculateObservationPosteriorCovariance(const EigenMatrix &positions, EigenMatrix &K_post, bool allow_hssvd_local=true)
void setHssvdDualLapackRrr(bool enabled) noexcept
void setHssvdObjectiveContractions(bool enabled) noexcept
void enableRFFFeatureSelection(double force_tol_fraction=0.0)
bool trainingFactorAppendable(Eigen::Index observations) const
void setLengthScaleSeedChemicalFloor(bool enabled) noexcept
void setActivePosteriorRefits(bool enabled) noexcept
void updateConfiguration(const AtomsConfiguration &conf_info)
Update the internal atoms configuration. Use this when the set of active/frozen atoms changes dynamic...
std::optional< double > inferInternalCoordinateLengthScale(const geometry::InternalCoordinateChart &chart) const
void setRgminInitialLogMoveWholeSession(bool whole_session) noexcept
void setEnvironmentResiduals(bool enabled)
void setAdditivePairResiduals(bool enabled) noexcept
void setSkipUnchangedSubsetFit(bool enabled) noexcept
void setHyperparameters(const Observation &all_obs, const AtomsConfiguration &conf_info, const bool update_sexpat_cf_param=true, const bool update_const_cf_param=true, const bool update_sqrt_prior_param=true)
Set up hyperparameters for GPR.
const EigenMatrix & getRMatrix() const noexcept
MeasuredRowVerdict measuredRowsAgreeWithPosterior(const Observation &rows, ConvergenceNormType force_norm, double *max_force_error=nullptr, double *max_force_sd=nullptr, double *evidence_nats=nullptr, double variance_calibration=1.0, RefitTrustReport *trust_report=nullptr)
void setHssvdLocalActiveSetSize(int size) noexcept
void setObjectiveStationaritySkipThreshold(double threshold) noexcept
const AtomsConfiguration & getAtomsConfig() const
void setAnnealStage(bool enabled, std::size_t budget, std::size_t replicas, std::size_t every, std::uint64_t seed)
HyperparameterObjectiveMode getHyperparameterObjectiveMode() const noexcept
const char * hyperparameterOptimizationModeName() const noexcept
Name of the hyperparameter fit in force, for the run report.
void setOptimizeSigma2(bool optimize) noexcept
Definition LikGaussian.h:82
double getSigma2() const noexcept
Get sigma2 value (the per-row noise variance added to the energy diagonal of the training kernel by e...
Definition LikGaussian.h:74
Self-tuning scale-free trust region (state = the current radius).
bool usesManifoldChart() const noexcept
Definition SexpatCF.h:616
double getMagnSigma2()
Definition SexpatCF.inl:53
FieldMatrixd & getLengthScaleRef()
Definition SexpatCF.inl:58
bool usesGeodesicHeatKernel() const noexcept
Definition SexpatCF.h:664
static std::size_t factorizationCount() noexcept
Trust radius enforcement for GP surrogate models.
Definition TrustRadius.h:36
double distanceToTraining(const Eigen::VectorXd &x_new) const
Minimum Euclidean distance from x_new to any training point.
std::vector< int > kNearestIndices(const Eigen::VectorXd &x_new, int k) const
Indices of the k training points nearest to x_new.
void setDistanceMetric(DistanceMetricType metric)
Select the atomic distance metric for trust checks.
double certifiedLineStep(const Eigen::VectorXd &x_from, const Eigen::VectorXd &x_to, double radius) const
Largest certified fraction of the segment x_from -> x_to that stays within the trust radius,...
bool projectLineToTrustBoundary(const Eigen::VectorXd &x_current, const Eigen::VectorXd &x_trial, double radius, Eigen::VectorXd &x_projected) const
Project a trial point along a line segment to the trust boundary.
void setTrainingData(const EigenMatrix &R_train)
Store training positions for distance queries.
void setAtomsConfiguration(const AtomsConfiguration &atoms_config)
Store atomic metadata for permutation-aware distance metrics.
const std::vector< PrimitiveInternal > & primitives() const
Eigen::VectorXd values(const Eigen::VectorXd &positions) const
Squared-exponential Gaussian process with partial gradients.
Definition LocalGP.h:28
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
void setExternalFixedAtoms(bool present)
Definition NEBPath.cpp:436
void setMolecularRigidMotion(bool enabled)
Definition NEBPath.cpp:491
int numImages() const
Definition NEBPath.h:338
void initializeIDPP(int n_atoms, bool collective=false)
Initialize from IDPP (image dependent pair potential) interpolation.
Definition NEBPath.cpp:697
void setEnergyWeightedSprings(bool on)
Allow the energy-weighted spring taper.
Definition NEBPath.h:414
void alignMolecularFrames()
Normalize seed frames before evaluation, invalidating changed images.
Definition NEBPath.cpp:538
void enableClimbingImage()
Enable climbing image on the highest-energy intermediate image.
Definition NEBPath.cpp:1121
void initializeSIDPP(int n_atoms, double alpha=0.33)
Initialize via Sequential IDPP (SIDPP). rgsaddle_sidpp_alternating_path. The spring on that call is t...
Definition NEBPath.cpp:712
void interpolateFromEndpoints()
Rebuild interior images on the chord between the current endpoints.
Definition NEBPath.cpp:610
void setMovingAtoms(std::vector< char > moving_atoms)
Definition NEBPath.cpp:424
void initializeSIDPPGeodesic(int n_atoms, double alpha=0.33)
Initialize via inverse-distance S-IDPP. rgsaddle_sidpp_alternating_inverse_distance_path....
Definition NEBPath.cpp:732
void pinFixedAtoms(Eigen::Ref< Eigen::VectorXd > positions) const
Copy reactant coordinates onto fixed atoms.
Definition NEBPath.cpp:552
double nebForceMagnitude(int i) const
Definition NEBPath.h:287
int numIntermediate() const
Definition NEBPath.h:342
void setPeriodicCell(const std::array< double, 9 > &cell)
Definition NEBPath.cpp:414
const Eigen::VectorXd & nebForce(int i) const
Get the NEB force for image i.
Definition NEBPath.h:257
void setGeometricSpring(bool on)
Toggle the geometric (cubic-potential) spring on the intermediate-image NEB force....
Definition NEBPath.h:390
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 setConvergenceForceNorm(std::optional< ConvergenceNormType > norm)
Definition NEBPath.h:268
std::optional< NEBOracleOptimizationOutcome > observe(int image_index, double force_norm)
Definition GPNEB.cpp:175
Pair-additive energy with a cubic B-spline radial function.
PosteriorFactorizationScope(PosteriorFactorizationCounts &counts)
Definition GPNEB.cpp:8815
OIE acquisition over the currently informative band images.
bool read(std::istream &input)
JsonRecord & add(std::string_view key, double value)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
eon_relax_band_t * band
Eigen::MatrixXd rigid_motion_basis(const gpr::Coord &R, bool rotations)
Build an orthonormal basis for rigid-body translations and rotations.
Definition Dimer.cpp:30
double expectedImprovementScore(double mu, double mu_best, double sigma)
Jones expected improvement for a maximizer.
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
bool isfinite(DoubleDouble a)
double uniqueImageRadius(const double cell[9]) noexcept
Definition MinImage.h:112
bool cellIsMicLattice(const double cell[9]) noexcept
Nonzero ASE 3x3 that is not the 25 A vacuum convention.
Definition MinImage.h:56
std::vector< PrimitiveInternal > primitiveTopologyFromBondGraph(int n_atoms, const std::vector< std::pair< int, int > > &bonds)
bool copyMicLattice(double dest[9], const double src[9]) noexcept
Copy src onto dest only when src is a MIC lattice.
Definition MinImage.h:68
std::array< double, 9 > micLattice(const double cell[9]) noexcept
Definition MinImage.h:76
double minimumPairDistance(const Eigen::VectorXd &positions, const std::array< double, 9 > &cell, Eigen::Index moving_count=-1)
std::vector< std::pair< int, int > > unionBondGraph(int n_atoms, const std::vector< Eigen::VectorXd > &geometries, const std::vector< char > &moving_atoms, BondGraphKind kind, const std::array< double, 9 > &cell)
std::vector< PrimitiveInternal > resolveCollinearAngles(const std::vector< PrimitiveInternal > &primitives, const Eigen::VectorXd &positions, const std::array< double, 9 > &cell)
Half surrogate(GaussianProcessRegression &gp, const Eigen::VectorXd &x, Kind kind, const Options &options)
Half measured(const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &options)
Full central difference of the oracle gradient: 2 d calls.
Half refined(GaussianProcessRegression &gp, const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &raw_options)
Kokkos::IndexType< std::size_t > Index
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40
void configureStablePosteriorVariance(bool enabled) noexcept
Turn stable posterior variance reductions on or off for the process.
Definition ExactSchur.h:34
DistributedFactorization distributedFactorization() noexcept
Process-wide selection; Reproducible unless configured otherwise.
void configureDistributedFactorization(DistributedFactorization mode)
const char * tpeObjectiveLogName(bool evaluated, TpeObjective objective) noexcept
TpeObjective tpeObjectiveForSaddleState(bool ci_active, bool candidate_confident, bool chain_certificate_met) noexcept
The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition,...
std::function< std::vector< std::pair< double, Eigen::VectorXd > >( const std::vector< Eigen::VectorXd > &positions)> NEBBatchOracle
Definition GPNEB.h:89
int selectNextImage(const std::vector< Eigen::VectorXd > &neb_forces, const std::vector< ObservationVariance > &variances, const std::vector< Eigen::VectorXd > &tangents, const std::vector< bool > &evaluated, AcquisitionType strategy, double kappa, std::mt19937 *rng)
Select the next unevaluated intermediate image by a per-image score.
int vibrationalIndexOuterBudget(const GPNEBConfig &config, int n_images)
Outer-iteration cap, including the per-image reading.
EndpointSymmetry requireEndpointSymmetry(const std::vector< int > &permutation, const Eigen::VectorXd &reactant, const Eigen::VectorXd &product, const std::vector< int > &atomic_numbers, double radius)
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
void restoreCertifiedClimb(NEBPath &path, const BandForceStall &stall)
Put the certified climb back and make it the climbing image.
Definition BandStall.h:100
@ IterationBudget
The configured outer-iteration budget was exhausted.
Definition GPNEB.h:3676
@ WallClockLimit
The shared monotonic wall-clock deadline was reached.
Definition GPNEB.h:3678
@ Unspecified
No terminal condition has been assigned.
Definition GPNEB.h:3672
@ Converged
The requested force and certificate conditions were satisfied.
Definition GPNEB.h:3674
BandStallAction observeMaxBandForce(BandForceStall &stall, double max_force, double force_tolerance, int window)
Definition BandStall.h:80
GPNEBResult gpNEBUngated(NEBOracle oracle, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, int n_images, const GPNEBConfig &config, ActiveLearningSession *session)
Definition GPNEB.cpp:19834
BandStallAction
What to do when the max band force stops falling.
Definition BandStall.h:17
GPNEBConvergenceStatus
Definition GPNEB.h:228
void noteLowestCertifiedClimb(BandForceStall &stall, const NEBPath &path, int image)
Definition BandStall.h:50
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
OieBandTraceRecord captureOieBandTrace(const NEBPath &path, GaussianProcessRegression &gp, int outer, const std::vector< double > &acquisition_variance, bool con_geometry, bool global_snapshot, int oracle_calls)
Definition BandTrace.cpp:13
std::vector< int > expandToTriplet(int center, int n_total)
Expand a single image index to a triplet {i-1, i, i+1}.
double indexGateVarianceThreshold(double noise_variance) noexcept
Eigen::LLT< Eigen::MatrixXd > factorSubstrate(const Eigen::MatrixXd &hessian)
void applyConfigToGP(const GPNEBConfig &config, gpr::GaussianProcessRegression &gp)
Definition GPNEB.cpp:8296
static double bandPairCutoff(const GPNEBConfig &config)
Definition GPNEB.cpp:8289
AcquisitionType
Available acquisition strategies for image selection.
void applyVibrationalIndexDecision(GPNEBResult &result, const VibrationalIndexDecision &decision, int outer_budget)
void certifyForceStoppedNeb(GPNEBResult &result, NEBOracle &oracle, const GPNEBConfig &config, const gpr::AtomsConfiguration *atoms)
int bandStallWindow(int n_images, int polished_dofs) noexcept
Definition BandStall.h:39
bool exceedsThreshold(double value, double threshold) noexcept
void perturbPosterior(double &energy, Eigen::VectorXd &gradient)
bool clearlyGreater(double candidate, double incumbent) noexcept
bool withinThreshold(double value, double threshold) noexcept
SpectralTrustRegionStep spectralTrustRegionStep(const Eigen::VectorXd &curvatures, const Eigen::MatrixXd &modes, Eigen::Index mode_index, const Eigen::VectorXd &force, double radius, const std::vector< std::pair< Eigen::VectorXd, double > > &measured_negative)
std::optional< double > secantPositiveInverseScale(const SecantHessian &secant)
constexpr double stencilStepOrDefault(double requested) noexcept
The requested stencil step, or the default when none was requested.
double barzilaiBorweinInverseScale(const Eigen::VectorXd &s, const Eigen::VectorXd &y, double fallback)
Scalar BB2 inverse-curvature seed for L-BFGS H0.
Definition LBFGS.cpp:39
void excludeNonPositiveCurvatureBlock(Eigen::VectorXd &s, Eigen::VectorXd &y, Eigen::Index offset, Eigen::Index length)
Definition LBFGS.cpp:25
Eigen::VectorXd twoLoopRecursion(const std::deque< Eigen::VectorXd > &s_hist, const std::deque< Eigen::VectorXd > &y_hist, const std::deque< double > &rho_hist, const Eigen::VectorXd &force, double H0)
Nocedal two-loop recursion (the LBFGS kernel).
Definition LBFGS.cpp:51
SecantSeed secantSeedDirection(const SecantHessian &secant, const Eigen::VectorXd &current_direction)
void setBofillRgsaddleLibrary(const char *path)
constexpr int forceStopMinModeEscapes() noexcept
Min-mode escapes after a higher-order certificate, for every search.
bool consensusShouldRebuildFactor(const TrainingPolicy &policy, const SearchState &state)
bool consensusShouldRetrainHyperparameters(const TrainingPolicy &policy, const SearchState &state)
double variance(const Weights &w, const Matrix &covariance)
MlflowRun * activeRun() noexcept
VecchiaResult evaluate(const Eigen::MatrixXd &points, const Eigen::VectorXd &y, double lengthscale, double noise, int max_neighbours)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
FieldMatrixd Coord
Definition Macros.h:35
void requireWallClock(const std::shared_ptr< const WallClockLimit > &limit)
Definition PhaseTimers.h:73
bool usesClassicJointEnergyForcePrior(GPModelProfile profile) noexcept
Definition Structures.h:206
bool collectiveWallClockLimitReached(const std::shared_ptr< const WallClockLimit > &limit, const linalg::MpiContext &context)
Definition PhaseTimers.h:81
double forceNorm(const Eigen::MatrixBase< Derived > &force, ConvergenceNormType norm)
Definition ForceNorm.h:45
constexpr bool iterationAllowedByLimit(Index_t iteration, Index_t configured_limit) noexcept
Definition Structures.h:90
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
std::optional< JointObservationVarianceReduction > jointObservationForceVarianceReduction(const Eigen::MatrixXd &posterior_covariance, const Eigen::Index query_count, const Eigen::Index dimensions, const Eigen::Index candidate_query, const std::vector< Eigen::Index > &target_queries, const double noise_variance)
Integrated force-variance reduction from one joint energy-force query.
void allreduceOwnedOracleMask(std::vector< char > &accepted, const OracleBatchLayout &layout)
OracleBatchStatus
What one rank reports about its groups before the value collectives.
Definition OracleBatch.h:78
@ Restart
The oracle asked for a session restart; takes precedence.
Definition OracleBatch.h:83
@ WallClockLimit
The enclosing search deadline expired; no further point may start.
Definition OracleBatch.h:85
@ Failed
A geometry was refused or a value was not finite; message set.
Definition OracleBatch.h:81
OracleBatchOutcome agreeOracleBatchStatus(OracleBatchStatus local_status, const std::string &local_message, const OracleBatchLayout &layout)
std::vector< std::vector< Eigen::Index > > ownedOracleGroups(Eigen::Index count, const OracleBatchLayout &layout)
The groups this rank evaluates, each one batch call, in point order.
void allreduceOwnedOracleValues(std::vector< double > &energies, Eigen::MatrixXd &gradients, const OracleBatchLayout &layout, double *communication_seconds)
bool resolved(Dual value, Dual error, const BridgeResidualOptions &options)
FieldMatrixi atomicNrs
Atomic Number of each atom.
Definition Structures.h:836
AtomsPositionAndType atoms_froz_inactive
Info on inactive frozen atoms.
Definition Structures.h:843
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841
KeyValuePair< double > actdist_fro
Definition Structures.h:379
Observation data: energy, gradient and positions.
FieldMatrixd E
static double band_predict_seconds
static double gradient_inverse_seconds
static int geometry_builds
static void reset() noexcept
static double cholesky_seconds
static double band_refit_seconds
static const char * rss_peak_phase
static long factorization_rows
static double band_inner_seconds
static long objective_channels
static double condition_seconds
static void notePeak(const char *phase) noexcept
static double band_certificate_seconds
static int factorization_count
static double subset_seconds
static double objective_seconds
static double factorization_seconds
static double band_drift_seconds
static long band_predict_count
static double assembly_seconds
static double gradient_seconds
static double correction_seconds
static double rss_peak_mb
static double band_path_seconds
static int gradient_count
static double residual_seconds
Residual-kernel candidate fits of the active correction.
static int variance_count
static long objective_rows
static double variance_seconds
static double communication_seconds
static double gradient_accumulate_seconds
static int objective_count
Dimensionless knobs. All O(1) and metric-independent by construction.
double tau
radius = tau * median spread (dimensionless)
void setSecantHessianConfig(const optim::SecantHessianConfig &config)
Definition Session.h:253
int priorObservations() const noexcept
Rows loaded from a seed file. Not an oracle-call count.
Definition Session.h:1288
void setEndpointSymmetry(EndpointSymmetry symmetry)
Definition Session.h:1601
gpr::Observation training_obs
Definition Session.h:246
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
bool empty() const noexcept
Configuration for GP-NEB.
Definition GPNEB.h:246
bool remove_molecular_rigid_motion
Definition GPNEB.h:379
std::vector< char > moving_atoms
Definition GPNEB.h:422
double theta_shift_skip_tol
Definition GPNEB.h:790
gpr::optim::SecantHessianConfig secant_hessian
Definition GPNEB.h:536
gpr::HyperparameterOptimizationMode hyperparameter_mode
Definition GPNEB.h:800
double lbfgs_max_move
Definition GPNEB.h:960
gpr::linalg::DistributedFactorization linalg_mode
Definition GPNEB.h:782
double gp_local_inner_tol_factor
Definition GPNEB.h:900
double gp_local_radius
Definition GPNEB.h:889
OuterIterHook outer_iter_hook
Definition GPNEB.h:1225
std::vector< int > symmetry_permutation
Definition GPNEB.h:670
gpr::GaussianProcessRegression::VarianceConvention variance_convention
Definition GPNEB.h:562
Eigen::Index oracle_batch_chunk
Definition GPNEB.h:259
bool outer_budget_per_image
Definition GPNEB.h:300
std::optional< ConvergenceNormType > convergence_force_norm
Definition GPNEB.h:263
gpr::UncertaintyMode uncertainty_mode
Definition GPNEB.h:559
bool disable_output_normalization
Definition GPNEB.h:569
bool hssvd_dual_lapack_rrr
Definition GPNEB.h:766
bool active_posterior_refits
Definition GPNEB.h:690
bool ls_seed_chemical_floor
Definition GPNEB.h:726
OieFixedImageLeaseProvider oie_fixed_image_lease
Definition GPNEB.h:1265
double rgmin_initial_log_move
Definition GPNEB.h:736
double lbfgs_inverse_curvature
Definition GPNEB.h:1010
unsigned int seed
Definition GPNEB.h:505
std::vector< double > initial_rest_lengths
Definition GPNEB.h:542
NEBBatchOracle batch_oracle
Definition GPNEB.h:253
double lbfgs_finite_difference
Definition GPNEB.h:1011
bool force_stop_certificate
Definition GPNEB.h:847
bool hyperparameter_objective_explicit
Definition GPNEB.h:808
int hssvd_local_active_set_size
Definition GPNEB.h:767
ObservationVarianceEstimator observation_variance_estimator
Definition GPNEB.h:1209
double ci_activation_tol
Definition GPNEB.h:354
bool environment_residuals
Definition GPNEB.h:691
AcquisitionType acquisition
Definition GPNEB.h:445
Eigen::VectorXd frozen_positions
Definition GPNEB.h:387
bool gp_local_initial_sweep
Definition GPNEB.h:921
gpr::optim::VibrationalStencil vibrational_stencil
Definition GPNEB.h:852
double rff_force_tol_fraction
Definition GPNEB.h:754
uint64_t lbfgs_sketch_seed
Definition GPNEB.h:1088
double pair_cutoff_width
Definition GPNEB.h:428
double lbfgs_newton_agreement
Definition GPNEB.h:1020
bool gp_local_carry_springs
Definition GPNEB.h:959
std::string rgsaddle_library
Definition GPNEB.h:711
bool subset_failure_escalation
Definition GPNEB.h:733
bool additive_pair_residuals
Definition GPNEB.h:695
bool use_psis_deterministic
Definition GPNEB.h:565
GPModelProfile model_profile
Definition GPNEB.h:689
double gp_local_trust
Definition GPNEB.h:894
int hssvd_local_posterior_active_set_size
Definition GPNEB.h:768
OieFixedImage oie_fixed_image
Definition GPNEB.h:1259
bool skip_unchanged_subset_fit
Definition GPNEB.h:746
std::array< double, 9 > cell
Definition GPNEB.h:426
bool hold_refined_spacing
Definition GPNEB.h:873
bool record_composition_trace
Definition GPNEB.h:525
bool theta_shift_skip_auto
Definition GPNEB.h:793
gpr::HyperparameterObjectiveMode hyperparameter_objective
Definition GPNEB.h:802
std::shared_ptr< const gpr::WallClockLimit > wall_clock_limit
Definition GPNEB.h:485
bool learn_likelihood_noise
Definition GPNEB.h:582
bool use_geometric_spring
Definition GPNEB.h:434
bool stable_posterior_variance
Definition GPNEB.h:786
double ci_activation_factor
Definition GPNEB.h:355
std::function< void(gpr::InputParameters &, gpr::AtomsConfiguration &)> gp_setup
Definition GPNEB.h:1204
bool rgmin_initial_log_move_whole_session
Definition GPNEB.h:739
double ci_stencil_step
Definition GPNEB.h:856
bool climbing_image_converged_only
Definition GPNEB.h:328
double gp_local_fraction
Definition GPNEB.h:886
double gp_local_noise
Definition GPNEB.h:909
double spring_constant
Definition GPNEB.h:313
EigenMatrix initial_path
Definition GPNEB.h:538
bool use_rigid_null_deflation
Definition GPNEB.h:730
std::string gp_population_prior
Population prior table (gpr/prior/PopulationPrior.h); empty is none.
Definition GPNEB.h:722
int hssvd_dual_randomized_sketch
Definition GPNEB.h:765
PriorMeanStatistic prior_mean_statistic
Definition GPNEB.h:697
double spring_constant_min
Definition GPNEB.h:315
bool use_chem_factorized_hyper
Definition GPNEB.h:684
bool use_hssvd_objective_contractions
Definition GPNEB.h:760
bool use_lognormal_magn_prior
Definition GPNEB.h:720
double hssvd_dual_chop_tol
Definition GPNEB.h:764
std::function< bool()> oracle_session_restart_requested
Definition GPNEB.h:279
std::vector< OuterIterCompositionTraceRecord > composition_trace
Definition GPNEB.h:3756
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
double returned_true_force
Definition GPNEB.h:3730
GPNEBConvergenceStatus convergence_status
Definition GPNEB.h:3685
double reverse_barrier_energy
Definition GPNEB.h:3739
bool index_continue
The gate stepped the climbing image; the caller resumes the search.
Definition GPNEB.h:3692
std::vector< double > max_force_history
Definition GPNEB.h:3748
int force_stop_certificate_calls
Definition GPNEB.h:3759
std::unique_ptr< NEBPath > path
Definition GPNEB.h:3682
A single image on the NEB path.
Definition NEBPath.h:39
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
Predictive variance of one joint energy-and-gradient observation.
bool force_tolerance
AIE/Standard path: outerConvergenceCertifiedByTolerance.
bool certified_full_band_branch
Composite: accepted via full-band N_uneval==0 branch.
bool ci_force_ok
Climbing-image force below tol, or CI inactive (vacuous pass).
bool mep_force_ok
Whole-band max oracle/NEB force below effective model-noise tolerance.
One outer-iteration composition snapshot.
double barrier_estimate
Forward barrier estimate E_max - E_reactant at this outer.
double max_oracle_force
Max intermediate NEB force (oracle-grade where available).
int n_uneval
Count of intermediate images still lacking current oracle data.
int ci_index
Climbing-image index when active; -1 when inactive.
Result of a TPE acquisition pick over the interior band.
Eigen::Index flat
Transverse modes with nonpositive curvature the step left out.
How a step's oracle points are shared out.
Definition OracleBatch.h:46
static OracleBatchLayout world(Eigen::Index chunk=0, int owner_offset=0)
The layout of the running communicator (rank 0 of 1 without MPI).