Loading...
Searching...
No Matches
AtomicDimer.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/*
6 * AtomicDimer.cpp
7 *
8 * Created on: 23 Oct 2020
9 * Author: Maxim Masterov
10 * Company: SURFSara
11 */
12
13#include "AtomicDimer.h"
14
15#ifndef USE_READCON_DB
16namespace readcon_db {
17class Corpus { };
18} // namespace readcon_db
19#endif
20
21#include <Eigen/Eigenvalues>
22#include <algorithm>
23#include <cmath>
24#include <optional>
25
27#include "neb/OracleStencil.h"
29#if defined(GPR_LINALG_SCALAPACK) || defined(GPR_HAVE_MPI)
30#include <mpi.h>
31#endif
32#include <unistd.h>
33
34#include <cstddef>
35#include <cstdio>
36#include <filesystem>
37#include <fstream>
38#include <iostream>
39#include <iterator>
40#include <limits>
41#include <memory>
42#include <numeric>
43#include <ostream>
44#include <sstream>
45#include <vector>
46
48#include "auxiliary/Distance.h"
50#include "auxiliary/ForceNorm.h"
52#include "auxiliary/MinImage.h"
55#include "dimer/Dimer.h"
56#include "gpr/Enums.h"
57#include "linalg/RayleighRitz.h"
62#include "ml/PhaseTimers.h"
63#include "ml/TrustRadius.h"
79#include "readcon-core.h"
81#ifdef USE_READCON_DB
82#include <rgpot/elements.hpp>
83
85#include "readcon-db.h"
86#endif
87
88#ifdef WITH_HDF5
89
90#define H5_USE_EIGEN
92
93#ifdef H5_USE_EIGEN
94#include <Eigen/Eigen>
95#endif
96
97#endif
98
99namespace atmd {
100
101namespace {
102
103double finiteAbsOrInf(const double value)
104{
105 if (!std::isfinite(value)) return std::numeric_limits<double>::infinity();
106 return std::abs(value);
107}
108
109double maxPredictiveForceVariance(const gpr::Coord& gradient_variance,
110 const ConvergenceNormType norm_type)
111{
112 if (gradient_variance.size() == 0)
113 return std::numeric_limits<double>::infinity();
114
115 double max_variance = 0.0;
116 switch (norm_type) {
118 for (Eigen::Index i = 0; i < gradient_variance.size(); ++i) {
119 max_variance =
120 std::max(max_variance,
121 finiteAbsOrInf(*(gradient_variance.data() + i)));
122 }
123 return max_variance;
125 if (gradient_variance.cols() % 3 != 0)
126 return std::numeric_limits<double>::infinity();
127 const Eigen::Index num_atoms = gradient_variance.cols() / 3;
128 for (Eigen::Index row = 0; row < gradient_variance.rows(); ++row) {
129 for (Eigen::Index atom = 0; atom < num_atoms; ++atom) {
130 double atom_trace = 0.0;
131 for (Eigen::Index axis = 0; axis < 3; ++axis) {
132 atom_trace += finiteAbsOrInf(
133 gradient_variance(row, 3 * atom + axis));
134 }
135 max_variance = std::max(max_variance, atom_trace);
136 }
137 }
138 return max_variance;
139 }
141 default:
142 for (Eigen::Index row = 0; row < gradient_variance.rows(); ++row) {
143 double trace = 0.0;
144 for (Eigen::Index col = 0; col < gradient_variance.cols();
145 ++col) {
146 trace += finiteAbsOrInf(gradient_variance(row, col));
147 }
148 max_variance = std::max(max_variance, trace);
149 }
150 return max_variance;
151 }
152}
153
154bool mpiWorld(int& rank, int& nprocs)
155{
156 rank = 0;
157 nprocs = 1;
158#if defined(GPR_LINALG_SCALAPACK) || defined(GPR_HAVE_MPI)
159 int mpi_up = 0;
160 MPI_Initialized(&mpi_up);
161 if (!mpi_up) return false;
162 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
163 MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
164 return nprocs > 1;
165#else
166 return false;
167#endif
168}
169
170template <typename Matrix>
171void broadcastDenseMatrix(Matrix& matrix, int root_rank = 0)
172{
173 int rank = 0;
174 int nprocs = 1;
175 if (!mpiWorld(rank, nprocs)) return;
176
177#if defined(GPR_LINALG_SCALAPACK) || defined(GPR_HAVE_MPI)
178 int shape[2] = {0, 0};
179 if (rank == root_rank) {
180 shape[0] = static_cast<int>(matrix.rows());
181 shape[1] = static_cast<int>(matrix.cols());
182 }
183 MPI_Bcast(shape, 2, MPI_INT, root_rank, MPI_COMM_WORLD);
184 if (rank != root_rank) {
185 matrix.resize(shape[0], shape[1]);
186 }
187 const int count = shape[0] * shape[1];
188 if (count > 0) {
189 MPI_Bcast(matrix.data(), count, MPI_DOUBLE, root_rank, MPI_COMM_WORLD);
190 }
191#endif
192}
193
194void broadcastObservation(gpr::Observation& obs, int root_rank = 0)
195{
196 broadcastDenseMatrix(obs.R, root_rank);
197 broadcastDenseMatrix(obs.E, root_rank);
198 broadcastDenseMatrix(obs.G, root_rank);
199}
200
201bool broadcastBool(bool value, int root_rank = 0)
202{
203 int rank = 0;
204 int nprocs = 1;
205 if (!mpiWorld(rank, nprocs)) return value;
206
207#if defined(GPR_LINALG_SCALAPACK) || defined(GPR_HAVE_MPI)
208 int flag = value ? 1 : 0;
209 MPI_Bcast(&flag, 1, MPI_INT, root_rank, MPI_COMM_WORLD);
210 return flag != 0;
211#else
212 return value;
213#endif
214}
215
216double broadcastDouble(double value, int root_rank = 0)
217{
218 int rank = 0;
219 int nprocs = 1;
220 if (!mpiWorld(rank, nprocs)) return value;
221
222#if defined(GPR_LINALG_SCALAPACK) || defined(GPR_HAVE_MPI)
223 MPI_Bcast(&value, 1, MPI_DOUBLE, root_rank, MPI_COMM_WORLD);
224#endif
225 return value;
226}
227
228void broadcastIndex(gpr::Index_t& value, int root_rank = 0)
229{
230 int rank = 0;
231 int nprocs = 1;
232 if (!mpiWorld(rank, nprocs)) return;
233
234#if defined(GPR_LINALG_SCALAPACK) || defined(GPR_HAVE_MPI)
235 long long wire = static_cast<long long>(value);
236 MPI_Bcast(&wire, 1, MPI_LONG_LONG, root_rank, MPI_COMM_WORLD);
237 value = static_cast<gpr::Index_t>(wire);
238#endif
239}
240
241Eigen::MatrixXd projectedCartesianBasis(const gpr::Coord& R, Eigen::Index dof,
242 const gpr::AtomsConfiguration& config)
243{
244 std::vector<Eigen::VectorXd> basis;
245 basis.reserve(static_cast<std::size_t>(dof));
246 const double threshold =
247 std::sqrt(std::numeric_limits<double>::epsilon()) *
248 std::sqrt(static_cast<double>(std::max<Eigen::Index>(dof, 1)));
249
250 Eigen::MatrixXd excluded(dof, 0);
251 const bool anchored = config.atoms_froz_active.positions.size() > 0 ||
252 config.atoms_froz_inactive.positions.size() > 0;
253 if (!anchored && R.size() > 0 && R.rows() == 1 && R.cols() == dof &&
254 dof % 3 == 0)
255 excluded = dimer::rigid_motion_basis(
257 for (Eigen::Index c = 0; c < dof; ++c) {
258 Eigen::VectorXd v = Eigen::VectorXd::Zero(dof);
259 v(c) = 1.0;
260 v -= excluded * (excluded.transpose() * v);
261 for (const Eigen::VectorXd& q: basis)
262 v -= q.dot(v) * q;
263 const double norm = v.norm();
264 if (norm > threshold) basis.push_back(v / norm);
265 }
266
267 Eigen::MatrixXd Q(dof, static_cast<Eigen::Index>(basis.size()));
268 for (Eigen::Index c = 0; c < Q.cols(); ++c)
269 Q.col(c) = basis[static_cast<std::size_t>(c)];
270 return Q;
271}
272
273bool directionsSpanTwoNegativeCurvatures(
275 const gpr::Coord& positions, const Eigen::VectorXd& first,
276 const Eigen::VectorXd& second, const gpr::AtomsConfiguration& config)
277{
278 if (first.size() != positions.cols() || second.size() != first.size() ||
279 !first.allFinite() || !second.allFinite())
280 return false;
281 const Eigen::MatrixXd physical =
282 projectedCartesianBasis(positions, first.size(), config);
283 if (physical.cols() < 2) return false;
284 Eigen::VectorXd axis = physical * (physical.transpose() * first);
285 const double axis_norm = axis.norm();
286 if (!(axis_norm > 0.0) || !std::isfinite(axis_norm)) return false;
287 axis /= axis_norm;
288 Eigen::VectorXd transverse = physical * (physical.transpose() * second);
289 transverse -= axis * axis.dot(transverse);
290 const double transverse_norm = transverse.norm();
291 const double eps = std::numeric_limits<double>::epsilon();
292 if (!std::isfinite(transverse_norm) ||
293 transverse_norm <= std::sqrt(eps) * second.norm())
294 return false;
295 transverse /= transverse_norm;
296 Eigen::VectorXd axis_action, transverse_action;
297 if (!hessian(axis, axis_action) ||
298 !hessian(transverse, transverse_action) ||
299 axis_action.size() != first.size() ||
300 transverse_action.size() != first.size() || !axis_action.allFinite() ||
301 !transverse_action.allFinite())
302 return false;
303 Eigen::Matrix2d projected;
304 projected(0, 0) = axis.dot(axis_action);
305 projected(1, 1) = transverse.dot(transverse_action);
306 projected(0, 1) = projected(1, 0) =
307 0.5 * (axis.dot(transverse_action) + transverse.dot(axis_action));
308 const Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> spectrum(projected);
309 // The negative subspace must resolve the Cartesian dot-product and
310 // projection roundoff. Two negative Ritz values imply at least two
311 // unstable directions without assembling the complete Hessian.
312 const double roundoff =
313 8.0 * eps * static_cast<double>(first.size()) *
314 std::max(axis_action.norm(), transverse_action.norm());
315 return spectrum.info() == Eigen::Success &&
316 spectrum.eigenvalues()(1) < -roundoff;
317}
318
319gpr::Coord rowModeFromVector(const Eigen::VectorXd& mode)
320{
321 if (mode.size() == 0 || mode.norm() == 0.0) return {};
322 Eigen::VectorXd normalized = mode / mode.norm();
323 Eigen::Index pivot = 0;
324 normalized.cwiseAbs().maxCoeff(&pivot);
325 if (normalized(pivot) < 0.0) normalized *= -1.0;
326 gpr::Coord out(1, normalized.size());
327 out.row(0) = normalized.transpose();
328 return out;
329}
330
331} // namespace
332
333bool shouldLogDimerFinalState(const gpr::Index_t debug_level) noexcept
334{
335 return debug_level == DEBUG_L1 || debug_level == DEBUG_L2 ||
336 debug_level == DEBUG_L3;
337}
338
339void writeDimerCampaignSummary(std::ostream& os, double energy, bool converged,
340 double energy_zero)
341{
342 os << "Saddle energy (eV): " << energy << "\n";
343 os << "Saddle energy zero-level (eV): " << energy_zero << "\n";
344 os << "Converged: " << (converged ? "yes" : "no") << "\n";
345}
346
347Eigen::Index selectHssvdModeIndex(const Eigen::VectorXd& eigenvalues,
348 const Eigen::MatrixXd& eigenvectors,
349 const Eigen::VectorXd& reference,
350 HssvdModeSelectionPolicy policy) noexcept
351{
352 if (eigenvalues.size() == 0) return 0;
353
354 Eigen::Index lowest_index = 0;
355 eigenvalues.minCoeff(&lowest_index);
356 double scale = 0.0;
357 for (Eigen::Index i = 0; i < eigenvalues.size(); ++i) {
358 if (std::isfinite(eigenvalues(i)))
359 scale = std::max(scale, std::abs(eigenvalues(i)));
360 }
362 eigenvectors.cols() != eigenvalues.size() ||
363 eigenvectors.rows() != reference.size() || !reference.allFinite() ||
364 reference.norm() == 0.0) {
365 return lowest_index;
366 }
367
368 // A dot product inside the square root of epsilon is the eigensolver's
369 // residual, not a connection. OpenBLAS, the reference LAPACK and Eigen
370 // leave different residuals, so the larger of two 1e-13 overlaps is not
371 // a direction. Treating it as one makes a saddle search take a different
372 // mode, and a different number of oracle calls, after a basis change.
373 const double resolved_overlap =
374 std::sqrt(std::numeric_limits<double>::epsilon()) * reference.norm();
375 Eigen::Index selected_index = -1;
376 double selected_overlap = -1.0;
377 bool saw_negative = false;
378 for (Eigen::Index i = 0; i < eigenvalues.size(); ++i) {
379 // A curvature inside the eigensolver's backward error is not a
380 // negative mode. OpenBLAS and the reference LAPACK flip that sign.
381 if (!gpr::linalg::curvatureIsNegative(eigenvalues(i), scale,
382 eigenvalues.size()) ||
383 !eigenvectors.col(i).allFinite()) {
384 continue;
385 }
386 saw_negative = true;
387 const double overlap = std::abs(eigenvectors.col(i).dot(reference));
388 if (!(overlap > resolved_overlap)) continue;
389 if (selected_index < 0 || overlap > selected_overlap ||
390 (overlap == selected_overlap &&
391 eigenvalues(i) < eigenvalues(selected_index))) {
392 selected_index = i;
393 selected_overlap = overlap;
394 }
395 }
396 if (selected_index >= 0) return selected_index;
397 // The reference does not meet a negative mode. Residual dots still
398 // differ across eigensolvers, so the canonical signed vector, the same
399 // order canonicalizeEigenpairs uses for an unresolved cluster, picks
400 // the mode instead.
401 if (saw_negative) {
402 Eigen::Index canonical = -1;
403 for (Eigen::Index i = 0; i < eigenvalues.size(); ++i) {
404 if (!gpr::linalg::curvatureIsNegative(eigenvalues(i), scale,
405 eigenvalues.size()) ||
406 !eigenvectors.col(i).allFinite())
407 continue;
408 if (canonical < 0 ||
409 gpr::linalg::signedEigenvectorLess(eigenvectors.col(i),
410 eigenvectors.col(canonical)))
411 canonical = i;
412 }
413 if (canonical >= 0) return canonical;
414 }
415 return lowest_index;
416}
417
419 const gpr::Coord& initial_reference, const gpr::Coord& current_orientation,
420 HssvdModeSelectionPolicy policy, bool preserve_initial_reference) noexcept
421{
423 preserve_initial_reference) {
424 return initial_reference;
425 }
426 return current_orientation;
427}
428
429#ifdef USE_READCON_DB
430namespace {
431const char* dimerTraceElementSymbol(int atomic_number)
432{
433 constexpr int last_trace_element = 103;
434 if (atomic_number < 1 || atomic_number > last_trace_element) return "X";
435 return rgpot::elements::symbols[static_cast<std::size_t>(atomic_number - 1)]
436 .data();
437}
438
439uint64_t dimerTraceTrajId(const std::string& phase)
440{
441 if (phase.find("initial_rotations") != std::string::npos) return 3;
442 if (phase.find("inner_loop") != std::string::npos) return 2;
443 if (phase.find("outer_loop") != std::string::npos) return 1;
444 return 0;
445}
446
447// Returns an owned RKRConFrame*; the caller frees it with
448// free_rkr_frame. Previously this serialised the frame to a temporary
449// file and read it back as text, which cost a filesystem round trip per
450// observation before the ingest did a second one.
451readcon::RKRConFrame* buildDimerTraceFrame(
452 const gpr::Observation& obs, const std::string& phase, size_t idx,
453 const gpr::AtomsConfiguration& atoms_config,
454 const gpr::vector3_reg (&cell_dimensions)[3])
455{
456 if (obs.R.rows() < 1 || obs.R.cols() < 3) return nullptr;
457 const Eigen::Index natoms = obs.R.cols() / 3;
458 if (natoms <= 0) return nullptr;
459
460 double cell[3] = {cell_dimensions[0](0), cell_dimensions[1](1),
461 cell_dimensions[2](2)};
462 if (!(cell[0] > 0.0)) cell[0] = 25.0;
463 if (!(cell[1] > 0.0)) cell[1] = 25.0;
464 if (!(cell[2] > 0.0)) cell[2] = 25.0;
465 const double angles[3] = {90.0, 90.0, 90.0};
466 const double energy =
467 (obs.E.rows() > 0 && obs.E.cols() > 0) ? obs.E(0, 0) : 0.0;
468 char meta[256];
469 std::snprintf(
470 meta, sizeof meta,
471 "{\"energy\": %.17g, \"frame_index\": %zu, \"phase\": \"%s\"}", energy,
472 idx, phase.c_str());
473
475 readcon::RKRConFrameBuilder* builder =
476 readcon::rkr_frame_new(cell, angles, "Generated by gprd", meta, "", "");
477 if (!builder) return nullptr;
478 // wrap d6e2084 ignores prebox1; metadata is set on the builder.
479 (void)readcon::rkr_frame_builder_set_metadata_json(builder, meta);
480 (void)readcon::rkr_frame_builder_set_energy(builder, energy);
481 (void)readcon::rkr_frame_builder_set_frame_index(
482 builder, static_cast<uint64_t>(idx));
483 (void)readcon::rkr_frame_builder_set_string_metadata(builder, "role",
484 phase.c_str());
485 const bool have_forces = obs.G.rows() > 0 && obs.G.cols() >= 3 * natoms &&
486 obs.G.row(0).allFinite();
487 if (have_forces) {
488 std::vector<double> flat(static_cast<std::size_t>(3 * natoms));
489 for (Eigen::Index k = 0; k < 3 * natoms; ++k)
490 flat[static_cast<std::size_t>(k)] = obs.G(0, k);
491 const double fmax = gpr::io::maxAtomicForce(
492 flat.data(), static_cast<std::size_t>(natoms));
493 if (std::isfinite(fmax))
494 (void)readcon::rkr_frame_builder_set_scalar_metadata(builder,
495 "fmax", fmax);
496 }
497
498 bool ok = true;
499 for (Eigen::Index a = 0; a < natoms && ok; ++a) {
500 int z = 1;
501 if (atoms_config.atomicNrs.size() > a) {
502 z = static_cast<int>(atoms_config.atomicNrs(0, a));
503 }
504 bool frozen = false;
505 if (atoms_config.is_frozen.size() > a) {
506 frozen = atoms_config.is_frozen(0, a) != MOVING_ATOM;
507 }
508 uint64_t atom_id = static_cast<uint64_t>(a);
509 if (atoms_config.id.size() > a) {
510 atom_id = static_cast<uint64_t>(atoms_config.id(0, a));
511 }
512 double force_buf[3];
513 const double* force = nullptr;
514 if (have_forces) {
515 // obs.G is the energy gradient; the CON section holds forces.
516 force_buf[0] = -obs.G(0, 3 * a);
517 force_buf[1] = -obs.G(0, 3 * a + 1);
518 force_buf[2] = -obs.G(0, 3 * a + 2);
519 force = force_buf;
520 }
522 builder, dimerTraceElementSymbol(z), obs.R(0, 3 * a),
523 obs.R(0, 3 * a + 1), obs.R(0, 3 * a + 2), frozen, atom_id, 1.0,
524 force) != 0) {
525 ok = false;
526 }
527 }
528 if (!ok) {
529 readcon::free_rkr_frame_builder(builder);
530 return nullptr;
531 }
532 readcon::RKRConFrame* frame = readcon::rkr_frame_builder_build(builder);
533 if (!frame) return nullptr;
534
535 return frame;
536}
537} // namespace
538#endif
539
541 bool path_leashed_recovery, bool oracle_certified, double best_oracle_force,
542 double trial_oracle_force) noexcept
543{
544 if (!path_leashed_recovery || !oracle_certified ||
545 !std::isfinite(best_oracle_force)) {
547 }
548 return std::isfinite(trial_oracle_force) &&
549 trial_oracle_force < best_oracle_force
552}
553
554bool is_subsystem(const gpr::AtomsConfiguration& atoms_config)
555{
556 return atoms_config.atoms_froz_active.positions.size() > 0 ||
557 atoms_config.atoms_froz_inactive.positions.size() > 0;
558}
559
561{
562 clear();
563
564 // Planted CuH2 fixture cell: orthorhombic 15.35 x 21.70 x 100.
565 cell_dimensions[0] = {15.3455999999999992, 0., 0.};
566 cell_dimensions[1] = {0., 21.7020000000000017, 0.};
567 cell_dimensions[2] = {0., 0., 100.0000000000000000};
568
569 // Self-owned path. ~attachExternalGP~ repoints ~gpr_model~ at a
570 // caller-owned GP and releases this allocation. Eager allocation
571 // keeps default construction usable without a separate attach step.
572 owned_gpr_model_ = std::make_unique<gpr::GaussianProcessRegression>();
573 gpr_model = owned_gpr_model_.get();
574 uses_external_gp_ = false;
575 preserve_seed_kernel_ = false;
576
577 num_of_gen_potential_calls = 0;
578 profile_phase_timing_ = false;
579 early_params._threshold = 0.4;
580 early_params._use_adaptive_threshold = false;
581 early_params._adaptive_A = 1.3;
582 early_params._adaptive_floor = 0.25;
583 early_params._adaptive_t_min = 0.15;
584 early_params._adaptive_delta_explore = 0.35;
585 early_params._adaptive_half_life = 50;
586 early_params._dist_metric = DistanceMetricType::EMD;
587 rgmin_trans_ = std::make_unique<gpr::optim::RgminStep>();
588}
589
591{
592 // ~clear~ drops the borrowed pointer; the unique_ptr destructor
593 // releases the owned GP (if any). External GPs are not touched.
594 clear();
595}
596
598 gpr::GaussianProcessRegression* external_gp) noexcept
599{
600 if (external_gp != nullptr) {
601 // Borrow: release any self-owned GP and point the access alias at
602 // the caller's instance. ~initialize~ uses the borrowed GP when
603 // ~owned_gpr_model_~ is empty.
604 owned_gpr_model_.reset();
605 gpr_model = external_gp;
606 uses_external_gp_ = true;
607 } else {
608 // Self-owned path. ~initialize~ allocates and configures the GP.
609 owned_gpr_model_ = std::make_unique<gpr::GaussianProcessRegression>();
610 gpr_model = owned_gpr_model_.get();
611 uses_external_gp_ = false;
612 }
613 if (wall_clock_limit_) gpr_model->setWallClockLimit(wall_clock_limit_);
614}
615
616void AtomicDimer::clear()
617{
618 if (rgmin_trans_) rgmin_trans_->forget();
619 surrogate_spectrum_ = SurrogateSpectrum{};
620 higher_order_restart_ = false;
621 measured_negative_directions_.clear();
622 measured_negative_reference_.resize(0, 0);
623 index_search_directions_.resize(0, 0);
624 last_certificate_hessian_.resize(0, 0);
625 last_certificate_positions_.resize(0, 0);
626 pending_flat_direction_.resize(0);
627 pending_flat_curvature_ = std::numeric_limits<double>::quiet_NaN();
628 last_step_descends_measured_negative_ = false;
630 cell_dimensions[0].setZero();
631 cell_dimensions[1].setZero();
632 cell_dimensions[2].setZero();
633 orient_init.resize(0, 0);
634
635 middle_point_init.clear();
636 image1.clear();
637 all_obs.clear();
638 refit_oracle_batch_.clear();
639 curvature_requires_full_refit_ = false;
640 N_obs_init = 0;
641
642 E_zero_level.resize(0, 0);
643 phase_history_.clear();
644 first_surrogate_action_ = {};
645 relaxation_termination_reason_ =
647 stop_citeria_dimer.clear();
648 stop_citeria_gpr.clear();
649
650 dimer_sep = 0.;
651
652 max_iter_init_rot.setZero();
653 max_iter_new_pairs.setZero();
654 max_iter_relax_rot.setZero();
655
656 evaluate_image1_each_phase_ = false;
657 ratio_at_limit = 0;
658 actdist_fro = 0.;
659 num_bigiter_initparam = 0;
660 num_bigiter_initloc = 0;
661
662 configured_force_criterion_ = std::numeric_limits<double>::quiet_NaN();
663 last_certificate_force_target_ = std::numeric_limits<double>::infinity();
664 curvature_final = 0.;
665 latest_mode_curvature_ = 0.;
666 final_converged_ = false;
667 totalIterations = 0;
668
669 // Release the owned GP, if any; drop the borrowed pointer either way.
670 // Construction and ~attachExternalGP~ establish the alias used by
671 // ~initialize~.
672 owned_gpr_model_.reset();
673 gpr_model = nullptr;
674 uses_external_gp_ = false;
675 preserve_seed_kernel_ = false;
676 accurate_potential_seconds_ = 0.0;
677 gp_optimize_seconds_ = 0.0;
678 gp_predict_seconds_ = 0.0;
679 gp_predict_mean_seconds_ = 0.0;
680 gp_predict_variance_seconds_ = 0.0;
681 gp_mode_seconds_ = 0.0;
682 gp_mode_calls_ = 0;
683 gp_fixed_theta_refresh_seconds_ = 0.0;
684 use_hssvd_analytic_curvature_ = false;
685 inexact_curvature_logged_ = false;
686 accurate_potential_calls_ = 0;
687 gp_optimize_calls_ = 0;
688 gp_predict_calls_ = 0;
689 gp_predict_mean_calls_ = 0;
690 gp_predict_variance_calls_ = 0;
691 dedup_rejected_observations_ = 0;
692 consecutive_degenerate_probes_ = 0;
693 consecutive_uninformative_rotations_ = 0;
694 fixed_theta_refresh_calls_ = 0;
695 imspe_admitted_near_duplicate_observations_ = 0;
696 all_obs_revision_ = 0;
697 optimized_all_obs_revision_ = kUnoptimizedObservationRevision;
698}
699
700void AtomicDimer::applyLikelihoodNoiseFloorAfterRefit()
701{
702 if (!std::isfinite(likelihood_noise_floor_sigma2_) ||
703 !(likelihood_noise_floor_sigma2_ > 0.0)) {
704 return;
705 }
706 (void)gpr_model->applyLikelihoodNoiseVarianceFloor(
707 likelihood_noise_floor_sigma2_, all_obs);
708}
709
710bool AtomicDimer::keepsAbsoluteEnergies() const noexcept
711{
712 return uses_external_gp_ || preserve_seed_kernel_ ||
713 (gpr_model != nullptr && (gpr_model->getUseZBLPriorMean() ||
714 gpr_model->getUseFFPriorMean()));
715}
716
717void AtomicDimer::reseedAttachedModelIfWarmStartInfeasible()
718{
719 // The attached model's fitted theta can sit outside the MAP amplitude
720 // barrier of the dimer's own rows (the ceiling follows the rows'
721 // signal-variance anchor); the optimizer then cannot move from it. A
722 // seed derived from these rows is consistent by construction.
723 if (!uses_external_gp_ || gpr_model == nullptr ||
724 !gpr_model->lastWarmStartInfeasible())
725 return;
726 log_man << "Warm refit of the attached model started outside its MAP "
727 "barrier (the fitted theta is infeasible for these rows); "
728 "re-seeding the hyperparameters.\n";
729 gpr_model->setHyperparameters(all_obs, atoms_config, true, true, true);
730 optimizeGPRModel();
731 applyLikelihoodNoiseFloorAfterRefit();
732}
733
734std::vector<bool> AtomicDimer::hyperparameterRowPool()
735{
736 // A handed-over archive spans a whole path; the farthest-point subset
737 // the optimizer fits on then holds the path's ends and nothing near the
738 // search. The rows that inform the hyperparameters of a local search
739 // are the rows within its own footprint: every row this search
740 // measured, and every seed row no farther (in the pair-distance metric
741 // the admission rules use) from the last measured center than the
742 // farthest of the search's own rows. The posterior itself is
743 // conditioned on every row. Without a measured center or without own
744 // rows the pool is empty and the optimizer selects as published.
745 std::vector<bool> pool;
746 if (!(preserve_seed_kernel_ || uses_external_gp_) ||
747 hyperparameter_pool_reference_.rows() != 1 || N_obs_init <= 0 ||
748 all_obs.R.rows() <= N_obs_init ||
749 hyperparameter_pool_reference_.cols() != all_obs.R.cols())
750 return pool;
751 aux::Distance distance;
753 distance.dist_emd(hyperparameter_pool_reference_, all_obs.R, atoms_config,
754 dist);
755 const Eigen::Index rows = all_obs.R.rows();
756 if (dist.size() != rows || !dist.allFinite()) return pool;
757 double radius = 0.0;
758 for (Eigen::Index i = N_obs_init; i < rows; ++i)
759 radius = std::max(radius, dist.data()[i]);
760 pool.assign(static_cast<std::size_t>(rows), false);
761 std::size_t members = 0;
762 for (Eigen::Index i = 0; i < rows; ++i) {
763 const bool member = i >= N_obs_init || dist.data()[i] <= radius;
764 pool[static_cast<std::size_t>(i)] = member;
765 if (member) ++members;
766 }
767 log_man << "Hyperparameter subset pool: " << members << " of " << rows
768 << " rows within the search footprint (pair-distance radius "
769 << radius << ").\n";
770 return pool;
771}
772
773void AtomicDimer::synchronizeObservedData()
774{
775 broadcastObservation(all_obs);
776#ifdef GPR_LINALG_SCALAPACK
777 int rank = 0;
778 int nprocs = 1;
779 if (mpiWorld(rank, nprocs)) {
780 // A broadcast preserves the root's evidence and fitted state. Only
781 // a training-data mutation invalidates the posterior it supports.
782 std::uint64_t revisions[] = {all_obs_revision_,
783 optimized_all_obs_revision_,
784 policy_retained_all_obs_revision_};
785 MPI_Bcast(revisions, 3, MPI_UINT64_T, 0, MPI_COMM_WORLD);
786 all_obs_revision_ = revisions[0];
787 optimized_all_obs_revision_ = revisions[1];
788 policy_retained_all_obs_revision_ = revisions[2];
789 }
790#endif
791}
792
793void AtomicDimer::updateVarianceSubsetFootprint(const std::vector<bool>& pool,
794 bool preserve_support)
795{
796 if (!gpr_model->varianceSubsetFootprint()) return;
797 std::vector<int> ids;
798 if (preserve_support && !pool.empty()) {
799 ids = gpr_model->varianceSubsetConfigurationIds();
800 // Fixed-parameter conditioning retains the information represented
801 // by its covariance. Empty identifiers select every training row.
802 if (ids.empty()) return;
803 }
804 for (std::size_t i = 0; i < pool.size(); ++i)
805 if (pool[i]) ids.push_back(static_cast<int>(i));
806 gpr_model->setVarianceSubsetConfigurationIds(std::move(ids));
807}
808
811{
812 // BFGS only accepts positive-curvature pairs. Replacing a saddle model
813 // with that positive-only range can erase its measured negative mode.
814 if (config.seed_curvature &&
816 throw std::invalid_argument(
817 "saddle secant curvature seed does not support the BFGS method");
818 secant_config_ = config;
819 secant_hessian_ = gpr::optim::SecantHessian(config.method);
820 secant_force_samples_.clear();
821 secant_counts_ = {};
822 secant_pairs_checked_ = 0;
823 if (gpr_model != nullptr && !config.quadratic_prior_mean)
824 gpr_model->clearSecantQuadraticPrior();
825 if (!config.enabled()) return;
826 for (Eigen::Index row = 0; row < all_obs.R.rows(); ++row) {
827 if (row >= all_obs.E.rows() || all_obs.E.cols() < 1 ||
828 row >= all_obs.G.rows() || all_obs.G.cols() != all_obs.R.cols())
829 throw std::logic_error(
830 "secant replay is missing a retained true force");
832 secant_hessian_, all_obs.R.row(row).transpose(),
833 all_obs.G.row(row).transpose(), all_obs.E(row, 0), secant_counts_);
834 rememberSecantForceSample(all_obs.R.row(row).transpose(),
835 all_obs.G.row(row).transpose(),
836 all_obs.E(row, 0));
837 }
838}
839
841{
842 gpr::optim::SecantCurvatureCounts counts = secant_counts_;
843 if (gpr_model != nullptr)
844 counts.quadratic_mean_uses += gpr_model->secantQuadraticPriorUses();
845 return counts;
846}
847
848void AtomicDimer::syncSecantQuadraticPrior()
849{
850 if (!secant_config_.quadratic_prior_mean || gpr_model == nullptr) return;
851 if (!secant_hessian_.available() || !secant_hessian_.hasReferenceEnergy()) {
852 gpr_model->clearSecantQuadraticPrior();
853 return;
854 }
855 if (gpr_model->physicalPriorMeanActive()) {
856 if (secant_force_samples_.empty())
857 throw std::logic_error(
858 "secant quadratic mean has no true-force stream to "
859 "residualize");
860 const gpr::optim::SecantHessian residual =
862 secant_config_.method, secant_force_samples_,
863 [&](const Eigen::VectorXd& position, double& energy,
864 Eigen::VectorXd& gradient) {
865 if (!gpr_model->samplePhysicalPriorMean(position, energy,
866 gradient))
867 throw std::logic_error(
868 "secant quadratic mean lost its physical prior");
869 });
870 if (!residual.available() || !residual.hasReferenceEnergy()) {
871 gpr_model->clearSecantQuadraticPrior();
872 return;
873 }
874 gpr_model->setSecantQuadraticPrior(
875 residual.referencePosition(), residual.referenceGradient(),
876 residual.hessian(), residual.referenceEnergy());
877 return;
878 }
879 gpr_model->setSecantQuadraticPrior(secant_hessian_.referencePosition(),
880 secant_hessian_.referenceGradient(),
881 secant_hessian_.hessian(),
882 secant_hessian_.referenceEnergy());
883}
884
885void AtomicDimer::rememberSecantForceSample(const Eigen::VectorXd& position,
886 const Eigen::VectorXd& gradient,
887 double energy)
888{
889 if (!secant_config_.quadratic_prior_mean) return;
890 gpr::optim::SecantForceSample sample;
891 sample.position = position;
892 sample.gradient = gradient;
893 sample.energy = energy;
894 secant_force_samples_.push_back(std::move(sample));
895}
896
897Eigen::VectorXd AtomicDimer::secantQuadraticHessianAction(
898 const Eigen::VectorXd& direction) const
899{
900 if (gpr_model == nullptr || !gpr_model->secantQuadraticPriorActive())
901 return Eigen::VectorXd::Zero(direction.size());
902 return gpr_model->secantQuadraticHessian() * direction;
903}
904
905void AtomicDimer::recordTrueForceSecant(const gpr::Observation& observation,
907{
908 if (!secant_config_.enabled()) return;
909 for (Eigen::Index row = 0; row < observation.R.rows(); ++row) {
910 if (row >= observation.E.rows() || observation.E.cols() < 1 ||
911 row >= observation.G.rows() ||
912 observation.G.cols() != observation.R.cols())
913 throw std::logic_error(
914 "secant observation is missing a true force");
916 secant_hessian_, observation.R.row(row).transpose(),
917 observation.G.row(row).transpose(), observation.E(row, 0),
918 secant_counts_, accounting);
919 rememberSecantForceSample(observation.R.row(row).transpose(),
920 observation.G.row(row).transpose(),
921 observation.E(row, 0));
922 }
923}
924
925void AtomicDimer::purchaseSecantConsistency(pot::PotentialWrapper& potential)
926{
927 if (!secant_config_.consistency_check || secant_probe_in_progress_) return;
928 if (!secant_hessian_.available() ||
929 secant_hessian_.pairs() <= secant_pairs_checked_ ||
930 gpr_model == nullptr)
931 return;
932 const double length = secant_hessian_.lastDirection().norm();
933 if (!(length > 0.0) || !std::isfinite(length))
934 throw std::runtime_error(
935 "secant consistency requested but the latest step is degenerate");
936 const Eigen::VectorXd direction = secant_hessian_.lastDirection() / length;
937 gpr::Coord at_reference(1, direction.size());
938 at_reference.row(0) = secant_hessian_.referencePosition().transpose();
939 Eigen::VectorXd posterior_action;
940 if (!gpr_model->isDecomposedSuccessfully() &&
941 !gpr_model->hasActivePosterior())
942 return;
943 if (!gpr_model->calculateMeanHessianVectorDispatched(
944 at_reference, direction, posterior_action))
945 throw std::runtime_error(
946 "secant consistency requested but GP Hessian action is "
947 "unavailable");
948 const gpr::optim::SecantConsistency consistency =
949 secant_hessian_.consistency(
950 posterior_action, secant_config_.consistency_relative_tolerance);
951 if (!consistency.available)
952 throw std::runtime_error(
953 "secant consistency requested but comparison is invalid");
954 secant_pairs_checked_ = secant_hessian_.pairs();
955 if (consistency.trusted) return;
956 ++secant_counts_.consistency_rejections;
957 if (secant_counts_.hvp_calls != 0) return;
958 if (!(secant_config_.finite_difference_step > 0.0) ||
959 !std::isfinite(secant_config_.finite_difference_step))
960 throw std::invalid_argument(
961 "secant finite-difference step must be positive");
962 if (oracleBudgetSpent()) return;
963 gpr::Observation probe;
964 probe.R.resize(1, direction.size());
965 probe.R.row(0) =
966 (secant_hessian_.referencePosition() +
967 secant_config_.finite_difference_step * consistency.direction)
968 .transpose();
969 secant_probe_in_progress_ = true;
970 AccurateObservationResult measured{false, false};
971 try {
972 // This displacement is an explicitly purchased directional probe.
973 // EMD deduplication is for archive rows and must not erase the HVP.
974 measured = evaluateAccurateObservation(probe, potential,
975 /*apply_emd_dedup=*/false);
976 } catch (...) {
977 secant_probe_in_progress_ = false;
978 throw;
979 }
980 secant_probe_in_progress_ = false;
981 if (!measured.measured || !probe.E.allFinite() || !probe.G.allFinite())
982 return;
983 ++secant_counts_.hvp_calls;
984 if (!measured.appended) return;
985 optimizeGPRModel();
986}
987
988void AtomicDimer::seedOrientationFromSecant(gpr::Coord& orient) const
989{
990 if (!secant_orientation_seed_) return;
991 const bool has_orientation = orient.rows() >= 1 && orient.cols() > 0;
992 const Eigen::VectorXd current =
993 has_orientation ? Eigen::VectorXd(orient.row(0).transpose())
994 : Eigen::VectorXd();
995 const gpr::optim::SecantSeed seed =
996 gpr::optim::secantSeedDirection(secant_hessian_, current);
998 std::cout << "[secant-seed] orientation keeps its direction: "
1000 return;
1001 }
1002 orient.row(0) = (seed.direction * current.norm()).transpose();
1003}
1004
1005void AtomicDimer::optimizeGPRModel()
1006{
1007 syncSecantQuadraticPrior();
1008 // The previous fit's curvature pairs are the opening Hessian when the
1009 // new rows stay inside the trust. Measured contradictions drop the
1010 // record inside the posterior check; this only asks for it.
1011 gpr_model->setRgminWarmStart(true);
1012 if (gpr_model->getSexpAtCovarianceFunction().usesManifoldChart()) {
1013 refreshGPRModelFixedTheta();
1014 markGPRModelOptimizedForObservedData();
1015 return;
1016 }
1017 const auto start = std::chrono::steady_clock::now();
1018 const std::vector<bool> pool = hyperparameterRowPool();
1019 updateVarianceSubsetFootprint(pool);
1020 gpr_model->setOptimizationRowPool(pool);
1021 // The fit must see the measurements that requested it and the accepted
1022 // center. Geometric coverage alone can omit a short curvature stencil
1023 // or the center retained across several rejected trials.
1024 gpr::Coord required = refit_oracle_batch_.R;
1025 if (measured_trial_anchor_.rows() == 1 &&
1026 measured_trial_anchor_.cols() == all_obs.R.cols()) {
1027 const Eigen::Index rows = required.rows();
1028 required.conservativeResize(rows + 1, all_obs.R.cols());
1029 required.row(rows) = measured_trial_anchor_.row(0);
1030 }
1031 gpr_model->setOptimizationRequiredRows(std::move(required));
1032 struct FitRowsLease {
1033 gpr::GaussianProcessRegression& model;
1034 ~FitRowsLease()
1035 {
1038 }
1039 } fit_rows_lease{*gpr_model};
1040 gpr_model->optimize(all_obs);
1041 markGPRModelOptimizedForObservedData();
1042 if (!profile_phase_timing_) return;
1043
1044 gp_optimize_seconds_ +=
1045 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
1046 .count();
1047 ++gp_optimize_calls_;
1048}
1049
1051{
1052 training_policy_owner_.reset();
1053 training_policy_ = policy;
1054}
1055
1057 std::shared_ptr<const gpr::policy::TrainingPolicy> policy)
1058{
1059 training_policy_owner_ = std::move(policy);
1060 training_policy_ = training_policy_owner_.get();
1061}
1062
1063bool AtomicDimer::policySuppressesAccurateCall(const gpr::Observation& obs,
1064 DimerOracleProbeRole role)
1065{
1066 if (training_policy_ == nullptr || gpr_model == nullptr ||
1067 gpr_model->failedOptim() || obs.R.rows() == 0 || obs.R.cols() == 0)
1068 return false;
1069 variance_probe_scratch_.R = obs.R;
1070 calculateApproximateVariance(variance_probe_scratch_);
1071 double energy_variance = std::numeric_limits<double>::quiet_NaN();
1072 double force_variance = std::numeric_limits<double>::quiet_NaN();
1073 if (variance_probe_scratch_.E.size() > 0 &&
1074 variance_probe_scratch_.E.allFinite()) {
1075 energy_variance = variance_probe_scratch_.E.cwiseAbs().maxCoeff();
1076 }
1077 if (variance_probe_scratch_.G.size() > 0) {
1078 force_variance = maxPredictiveForceVariance(variance_probe_scratch_.G,
1079 convergence_force_norm);
1080 }
1081 const Eigen::VectorXd positions = obs.R.row(0).transpose();
1082 gpr::policy::SearchState state;
1084 state.role = role == DimerOracleProbeRole::Midpoint
1087 state.oracle_calls = static_cast<int>(getNumEvaluations());
1088 state.training_size = static_cast<int>(all_obs.R.rows());
1089 state.hyperparameter_refits = static_cast<int>(gp_optimize_calls_);
1090 state.posterior_variance = energy_variance;
1091 state.force_variance = force_variance;
1092 state.engine_would_call_oracle = true;
1093 state.positions = positions.data();
1094 state.n_coords = static_cast<int>(positions.size());
1095 state.gp = gpr_model;
1096 return !gpr::policy::consensusShouldCallOracle(*training_policy_, state);
1097}
1098
1099bool AtomicDimer::policyRetainObservations()
1100{
1101 if (training_policy_ == nullptr || all_obs.R.rows() == 0) return false;
1102 if (policy_retained_owner_ == training_policy_ &&
1103 policy_retained_all_obs_revision_ == all_obs_revision_) {
1104 return false;
1105 }
1106 const int n = static_cast<int>(all_obs.R.rows());
1107 std::vector<Eigen::VectorXd> rows;
1108 rows.reserve(static_cast<std::size_t>(n));
1109 for (Eigen::Index row = 0; row < all_obs.R.rows(); ++row)
1110 rows.emplace_back(all_obs.R.row(row).transpose());
1111 const std::vector<int> keep =
1112 gpr::policy::consensusRetainTrainingRows(*training_policy_, rows);
1113 const std::vector<int> accepted =
1115 if (gpr::policy::indexListIsIdentity(accepted, n)) {
1116 policy_retained_owner_ = training_policy_;
1117 policy_retained_all_obs_revision_ = all_obs_revision_;
1118 return false;
1119 }
1120 gpr::Observation next;
1121 const Eigen::Index kept = static_cast<Eigen::Index>(accepted.size());
1122 const Eigen::Index dof = all_obs.R.cols();
1123 next.R.resize(kept, dof);
1124 next.E.resize(kept, all_obs.E.cols() > 0 ? all_obs.E.cols() : 1);
1125 next.G.resize(kept, all_obs.G.cols() > 0 ? all_obs.G.cols() : dof);
1126 for (Eigen::Index out = 0; out < kept; ++out) {
1127 const Eigen::Index row = accepted[static_cast<std::size_t>(out)];
1128 next.R.row(out) = all_obs.R.row(row);
1129 if (all_obs.E.rows() > row) next.E.row(out) = all_obs.E.row(row);
1130 if (all_obs.G.rows() > row) next.G.row(out) = all_obs.G.row(row);
1131 }
1132 // Harvest reads a prefix of length N_obs_init. That prefix is the
1133 // kept initial rows only when they still lead the new order.
1134 gpr::Index_t new_init = 0;
1135 bool seen_later = false;
1136 bool contiguous = true;
1137 for (const int index: accepted) {
1138 const bool initial = index < static_cast<int>(N_obs_init);
1139 if (initial && seen_later) {
1140 contiguous = false;
1141 break;
1142 }
1143 if (initial)
1144 ++new_init;
1145 else
1146 seen_later = true;
1147 }
1148 N_obs_init = contiguous ? new_init : 0;
1149 all_obs = std::move(next);
1150 markObservedDataChanged();
1151 policy_retained_owner_ = training_policy_;
1152 policy_retained_all_obs_revision_ = all_obs_revision_;
1153 return true;
1154}
1155
1156void AtomicDimer::refitGPRModel(bool reinitialize,
1157 const gpr::Observation& witness,
1158 const gpr::Coord& mode,
1159 bool measured_trial_rejected)
1160{
1161 syncSecantQuadraticPrior();
1162 const bool pruned =
1163 training_policy_ != nullptr && policyRetainObservations();
1164 // A prune drops rows the current factor still describes. Rebuild at
1165 // the current theta before any early return, and keep the pending
1166 // measurement batch: it is not an index into all_obs.
1167 if (pruned && gpr_model != nullptr && all_obs.R.rows() > 0 &&
1168 gpr_model->hasBeenOptimized()) {
1169 gpr_model->invalidateTrainingFactorCache();
1170 gpr_model->updateModelWithFullData(all_obs);
1171 optimized_all_obs_revision_ = all_obs_revision_;
1172 }
1173 gpr_model->clearModeRefitHint();
1174 if (witness.R.rows() == 1 && witness.R.allFinite())
1175 hyperparameter_pool_reference_ = witness.R;
1176 // A handed-over kernel was fit on every row it came with. Test the
1177 // acquired forces against that posterior before choosing a correction
1178 // objective: agreement requires conditioning, not a parameter fit.
1179 // Measured curvature contradictions still require a full refit.
1180 const bool fitted_on_full_evidence =
1181 preserve_seed_kernel_ || uses_external_gp_;
1182 // A changed row set must not keep the pre-prune posterior and skip
1183 // the retrain decision the engine still wants.
1184 if (!pruned && !reinitialize && !curvature_requires_full_refit_ &&
1185 !measured_trial_rejected && fitted_on_full_evidence &&
1186 retainFittedKernelForConsistentRows()) {
1187 applyLikelihoodNoiseFloorAfterRefit();
1188 return;
1189 }
1190 bool restricted_refit = false;
1191 if (!reinitialize && !curvature_requires_full_refit_) {
1192 restricted_refit =
1193 gpr_model->activePosteriorRefitsEnabled()
1194 ? gpr_model->configureMinimumModeRefit(refit_oracle_batch_,
1195 stop_citeria_dimer.force,
1196 convergence_force_norm)
1197 : gpr_model->configureModeRefit(witness, mode,
1198 stop_citeria_dimer.force,
1199 convergence_force_norm);
1200 }
1201 log_man << "Dimer GP refit: measured rows " << refit_oracle_batch_.R.rows()
1202 << ", active correction "
1203 << gpr_model->hasPendingActivePosteriorRefit()
1204 << ", residual expansion "
1205 << gpr_model->hasPendingResidualModelRefit() << ", reinitialize "
1206 << reinitialize << ", curvature contradiction "
1207 << curvature_requires_full_refit_ << ", rejected force trial "
1208 << measured_trial_rejected << "\n";
1209 const Eigen::VectorXd theta_before = gpr_model->fittedKernelParameters();
1210 const double noise_before = gpr_model->likelihoodNoiseVariance();
1211 // Null path: reseed, then the stationarity refresh, then optimize.
1212 // A policy consults should_retrain_hyperparameters before reseeding so a
1213 // freeze keeps the existing theta and output transform intact and can
1214 // either extend or rebuild the factor according to should_rebuild_factor.
1215 if (training_policy_ == nullptr) {
1216 gpr_model->setHyperparameters(all_obs, atoms_config, reinitialize,
1217 reinitialize, reinitialize);
1218 const bool engine_optimizes =
1219 measured_trial_rejected ||
1220 gpr_model->hasPendingActivePosteriorRefit() ||
1221 gpr_model->hasPendingResidualModelRefit() || !restricted_refit ||
1222 !refreshGPRModelFixedThetaIfObjectiveStationary();
1223 if (engine_optimizes) optimizeGPRModel();
1224 } else {
1225 const bool unseeded = !gpr_model->isDecomposedSuccessfully() &&
1226 !gpr_model->hasBeenOptimized();
1227 if (unseeded && all_obs.R.rows() > 0) {
1228 gpr_model->setHyperparameters(all_obs, atoms_config, reinitialize,
1229 reinitialize, reinitialize);
1230 }
1231 gpr::policy::SearchState state;
1233 state.oracle_calls = static_cast<int>(getNumEvaluations());
1234 state.training_size = static_cast<int>(all_obs.R.rows());
1235 state.hyperparameter_refits = static_cast<int>(gp_optimize_calls_);
1236 state.engine_would_retrain = true;
1237 state.engine_would_rebuild_factor = true;
1238 state.gp = gpr_model;
1240 *training_policy_, state)) {
1241 if (!unseeded) {
1242 gpr_model->setHyperparameters(all_obs, atoms_config,
1243 reinitialize, reinitialize,
1244 reinitialize);
1245 }
1246 const bool engine_optimizes =
1247 measured_trial_rejected ||
1248 gpr_model->hasPendingActivePosteriorRefit() ||
1249 gpr_model->hasPendingResidualModelRefit() ||
1250 !restricted_refit ||
1251 !refreshGPRModelFixedThetaIfObjectiveStationary();
1252 if (engine_optimizes) optimizeGPRModel();
1253 } else {
1254 const bool rebuild = gpr::policy::consensusShouldRebuildFactor(
1255 *training_policy_, state);
1256 gpr_model->clearModeRefitHint();
1257 if (all_obs.R.rows() == 0) {
1258 gpr_model->invalidateTrainingFactorCache();
1259 } else {
1260 const bool own_model = !uses_external_gp_;
1261 if (!rebuild && own_model && !gpr_model->hasActivePosterior() &&
1262 gpr_model->trainingFactorAppendable(all_obs.R.rows())) {
1263 gpr_model->updateModelWithFullData(all_obs);
1264 ++fixed_theta_refresh_calls_;
1265 } else if (!pruned || !gpr_model->isDecomposedSuccessfully()) {
1266 if (rebuild) gpr_model->invalidateTrainingFactorCache();
1267 gpr_model->updateModelWithFullData(all_obs);
1268 }
1269 markGPRModelOptimizedForObservedData();
1270 }
1271 }
1272 }
1273 gpr_model->clearModeRefitHint();
1274 applyLikelihoodNoiseFloorAfterRefit();
1275 reseedAttachedModelIfWarmStartInfeasible();
1276 recordContradictionRefitOutcome(theta_before, noise_before);
1277 curvature_requires_full_refit_ = false;
1278}
1279
1280bool AtomicDimer::retainFittedKernelForConsistentRows()
1281{
1282 // The fitted kernel stays in force until a measured row contradicts the
1283 // posterior it was drawn against. The rows of the pending batch are the
1284 // measurements taken since that posterior was conditioned, so the test
1285 // runs before they enter it. A hyperparameter fit on the optimization
1286 // subset is the alternative; it discards the rows that anchor the
1287 // midpoint and, on a band archive, moved the amplitude by an order of
1288 // magnitude and planted negative transverse curvature at the seed. The
1289 // posterior itself is conditioned on every row either way.
1290 if (gpr_model == nullptr || all_obs.R.rows() == 0 ||
1291 !gpr_model->hasBeenOptimized())
1292 return false;
1293 // A repeated observation can leave the fitted evidence unchanged.
1294 // With no pending rows, the conditioned model needs no further fit.
1295 if (refit_oracle_batch_.R.rows() == 0 &&
1296 hasOptimizedCurrentObservedData() &&
1297 gpr_model->isDecomposedSuccessfully())
1298 return true;
1300 // The rows are judged against the variance the last measured trial
1301 // calibrated, the same calibration the next walk stops on.
1302 double force_error = 0.0, force_sd = 0.0, evidence_nats = 0.0;
1303 const Verdict verdict = gpr_model->measuredRowsAgreeWithPosterior(
1304 refit_oracle_batch_, convergence_force_norm, &force_error, &force_sd,
1305 &evidence_nats, trial_variance_calibration_);
1306 if (verdict == Verdict::Unmeasurable) {
1307 if (gpr_model->isDecomposedSuccessfully()) return false;
1308 // A fitted kernel without a conditioned posterior: the archive
1309 // handoff. Its evidence fit is the model for these rows.
1310 refreshGPRModelFixedTheta();
1311 if (!gpr_model->isDecomposedSuccessfully()) return false;
1312 markGPRModelOptimizedForObservedData();
1313 log_man << "Fixed-theta refresh: conditioned the fitted kernel on "
1314 << all_obs.R.rows() << " rows.\n";
1315 return true;
1316 }
1317 log_man << "Fixed-theta refresh: measured rows "
1318 << refit_oracle_batch_.R.rows() << ", force error " << force_error
1319 << (verdict == Verdict::Consistent ? " within" : " exceeds")
1320 << " posterior force uncertainty " << force_sd
1321 << " (variance calibration " << trial_variance_calibration_
1322 << ", evidence " << evidence_nats << " nats)"
1323 << (verdict == Verdict::Consistent
1324 ? "; retaining the fitted kernel.\n"
1325 : "; refitting hyperparameters.\n");
1326 if (verdict != Verdict::Consistent) {
1327 if (contradictionRefitWouldBeFutile(evidence_nats)) {
1328 log_man << "Fixed-theta refresh: the last refit of a contradiction "
1329 "of "
1330 << futile_refit_evidence_nats_
1331 << " nats returned the same hyperparameters; a "
1332 "contradiction of "
1333 << evidence_nats
1334 << " nats conditions the fitted kernel instead.\n";
1335 refreshGPRModelFixedTheta();
1336 if (!gpr_model->isDecomposedSuccessfully()) return false;
1337 markGPRModelOptimizedForObservedData();
1338 return true;
1339 }
1340 pending_contradiction_evidence_nats_ = evidence_nats;
1341 return false;
1342 }
1343 refreshGPRModelFixedTheta();
1344 if (!gpr_model->isDecomposedSuccessfully()) return false;
1345 markGPRModelOptimizedForObservedData();
1346 return true;
1347}
1348
1349bool AtomicDimer::contradictionRefitWouldBeFutile(double evidence_nats) const
1350{
1351 // The guard holds while a contradiction is no stronger than twice the
1352 // one whose refit changed nothing: the kernel the fit returns is the
1353 // kernel already conditioned, so the fit buys a full rebuild of the
1354 // same posterior. A contradiction beyond that margin is new evidence
1355 // and refits.
1356 return std::isfinite(futile_refit_evidence_nats_) && gpr_model != nullptr &&
1357 gpr_model->likelihoodNoiseVariance() ==
1358 futile_refit_noise_variance_ &&
1359 std::isfinite(evidence_nats) &&
1360 evidence_nats <= 2.0 * futile_refit_evidence_nats_;
1361}
1362
1363void AtomicDimer::recordContradictionRefitOutcome(
1364 const Eigen::VectorXd& theta_before, double noise_before)
1365{
1366 const double evidence = pending_contradiction_evidence_nats_;
1367 pending_contradiction_evidence_nats_ =
1368 std::numeric_limits<double>::quiet_NaN();
1369 const Eigen::VectorXd theta_after = gpr_model->fittedKernelParameters();
1370 const double noise_after = gpr_model->likelihoodNoiseVariance();
1371 // A changed likelihood variance changes the posterior even when the
1372 // kernel parameters stay fixed. This includes noise-floor adjustments.
1373 if (theta_after.size() == 0 || theta_after.size() != theta_before.size() ||
1374 !theta_after.allFinite() || !theta_before.allFinite() ||
1375 !std::isfinite(noise_after) || noise_after < 0.0 ||
1376 noise_after != noise_before) {
1377 futile_refit_evidence_nats_ = std::numeric_limits<double>::quiet_NaN();
1378 return;
1379 }
1380 // A shift the optimizer's own step tolerance calls no move.
1381 const double step_tolerance = gpr_model->fitStepTolerance();
1382 const double unchanged_shift =
1383 std::isfinite(step_tolerance) && step_tolerance > 0.0 ? step_tolerance
1384 : 1e-3;
1385 const double shift = (theta_after - theta_before).cwiseAbs().maxCoeff();
1386 if (shift > unchanged_shift) {
1387 futile_refit_evidence_nats_ = std::numeric_limits<double>::quiet_NaN();
1388 return;
1389 }
1390 // A fit for another reason that left the hyperparameters where they
1391 // were leaves the guard as it stands.
1392 if (!std::isfinite(evidence)) return;
1393 futile_refit_evidence_nats_ = evidence;
1394 futile_refit_noise_variance_ = noise_after;
1395 log_man << "Dimer GP refit: a contradiction of " << evidence
1396 << " nats refit the hyperparameters to within " << shift
1397 << " of their previous values; the next contradiction of that "
1398 "size conditions the fitted kernel instead.\n";
1399}
1400
1401void AtomicDimer::refreshGPRModelFixedTheta()
1402{
1403 if (gpr_model == nullptr || all_obs.R.rows() == 0) return;
1404 const auto start = std::chrono::steady_clock::now();
1405 // The uncertainty subset follows measured geometry even when the kernel
1406 // parameters stay fixed. Conditional factors must use that same subset.
1407 if (gpr_model->varianceSubsetFootprint())
1408 updateVarianceSubsetFootprint(hyperparameterRowPool(), true);
1409 // Rows appended to a fitted, factorized posterior condition it in the
1410 // cost of their own count; the dense factorization is rebuilt only when
1411 // the fitted prefix no longer matches (rows coalesced or replaced). A
1412 // rebuild on every phase was the O(n^3) term that grew with every
1413 // measurement.
1414 // A session model attached by a band burst keeps the band's own
1415 // factorization contract: the burst may not leave an active posterior
1416 // on it that the band's refits and Hessian shortcuts then have to
1417 // honour. The dimer's own model conditions incrementally.
1418 const bool own_model = !uses_external_gp_;
1419 // A live distributed factor that the new rows extend is appended to at
1420 // O(n^2 k); the active correction is then empty and its next fit
1421 // starts from the rows of one outer, which keeps the correction's
1422 // objective from growing with the outer count.
1423 if (own_model && !gpr_model->hasActivePosterior() &&
1424 gpr_model->trainingFactorAppendable(all_obs.R.rows())) {
1425 gpr_model->updateModelWithFullData(all_obs);
1426 } else if (!gpr_model->refreshActivePosterior(all_obs) &&
1427 !(own_model &&
1428 gpr_model->conditionActivePosterior(all_obs, nullptr)))
1429 gpr_model->updateModelWithFullData(all_obs);
1430 ++fixed_theta_refresh_calls_;
1431 if (!profile_phase_timing_) return;
1432
1433 gp_fixed_theta_refresh_seconds_ +=
1434 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
1435 .count();
1436}
1437
1438bool AtomicDimer::refreshGPRModelFixedThetaIfObjectiveStationary()
1439{
1440 if (gpr_model == nullptr || all_obs.R.rows() == 0) return false;
1441 if (!gpr_model->objectiveStationaritySkipMayBeActive()) return false;
1442 if (!gpr_model->usesFullObservationForHyperparameterOptimization(all_obs))
1443 return false;
1444
1445 const auto start = std::chrono::steady_clock::now();
1446 double shift_norm = std::numeric_limits<double>::infinity();
1447 const bool refreshed =
1448 gpr_model->refreshFullDataPosteriorIfObjectiveStationary(all_obs,
1449 &shift_norm);
1450 if (!refreshed) return false;
1451 if (gpr_model->varianceSubsetFootprint())
1452 updateVarianceSubsetFootprint(hyperparameterRowPool(), true);
1453
1454 markGPRModelOptimizedForObservedData();
1455 ++fixed_theta_refresh_calls_;
1456 if (!profile_phase_timing_) return true;
1457
1458 gp_fixed_theta_refresh_seconds_ +=
1459 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
1460 .count();
1461 return true;
1462}
1463
1464void AtomicDimer::calculateApproximatePotential(gpr::Observation& obs)
1465{
1466 const auto start = std::chrono::steady_clock::now();
1467 {
1468 gpr::ScopedPredictTimer predict_timer;
1469 gpr_model->calculatePotentialDispatched(obs);
1470 if (local_potential_reference_ != nullptr) {
1471 auto& reference = *local_potential_reference_;
1472 const auto& measured = *reference.measured;
1473 if (reference.factor_epoch != gpr_model->factorEpoch()) {
1474 reference.prediction.R = measured.R;
1476 gpr_model->calculatePotentialDispatched(reference.prediction);
1477 reference.factor_epoch = gpr_model->factorEpoch();
1478 }
1479 const auto& predicted = reference.prediction;
1480 const Eigen::RowVectorXd gradient_shift =
1481 measured.G.row(0) - predicted.G.row(0);
1482 const double reference_energy =
1483 measured.E.size() == 1 ? measured.E(0, 0) : predicted.E(0, 0);
1484 for (Eigen::Index row = 0; row < obs.R.rows(); ++row) {
1485 const double energy_change = obs.E(0, row) - predicted.E(0, 0);
1486 obs.E(0, row) =
1487 reference_energy + energy_change +
1488 (obs.R.row(row) - measured.R.row(0)).dot(gradient_shift);
1490 measured.G.row(0), predicted.G.row(0), obs.G.row(row));
1491 }
1492 }
1493 }
1494 const double seconds =
1495 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
1496 .count();
1497 gp_predict_seconds_ += seconds;
1498 gp_predict_mean_seconds_ += seconds;
1499 ++gp_predict_calls_;
1500 ++gp_predict_mean_calls_;
1501}
1502
1503void AtomicDimer::calculateApproximateVariance(gpr::Observation& obs)
1504{
1505 const auto start = std::chrono::steady_clock::now();
1506 {
1507 gpr::ScopedPredictTimer predict_timer;
1508 gpr_model->calculateVarianceDispatched(obs);
1509 }
1510 const double seconds =
1511 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
1512 .count();
1513 gp_predict_seconds_ += seconds;
1514 gp_predict_variance_seconds_ += seconds;
1515 ++gp_predict_calls_;
1516 ++gp_predict_variance_calls_;
1517}
1518
1519void AtomicDimer::logPhaseTimingSummary(double elapsed_seconds)
1520{
1521 if (!profile_phase_timing_) return;
1522
1523 const double search_control_seconds =
1524 elapsed_seconds - accurate_potential_seconds_ - gp_optimize_seconds_ -
1525 gp_fixed_theta_refresh_seconds_ - gp_predict_seconds_ -
1526 gp_mode_seconds_;
1527
1528 log_man << "Phase timing summary:\n";
1529 log_man << " Accurate potential: " << accurate_potential_seconds_ << "s"
1530 << " across " << accurate_potential_calls_ << " calls\n";
1531 log_man << " GP optimize: " << gp_optimize_seconds_ << "s"
1532 << " across " << gp_optimize_calls_ << " calls\n";
1533 log_man << " GP fixed-theta refresh: " << gp_fixed_theta_refresh_seconds_
1534 << "s across " << fixed_theta_refresh_calls_ << " calls\n";
1535 log_man << " GP predict: " << gp_predict_seconds_ << "s"
1536 << " across " << gp_predict_calls_ << " calls\n";
1537 log_man << " GP mode: " << gp_mode_seconds_ << "s across " << gp_mode_calls_
1538 << " calls\n";
1539 log_man << " mean: " << gp_predict_mean_seconds_ << "s across "
1540 << gp_predict_mean_calls_ << " calls\n";
1541 log_man << " variance: " << gp_predict_variance_seconds_ << "s across "
1542 << gp_predict_variance_calls_ << " calls\n";
1543 if (gpr_model != nullptr) gpr_model->logProfileSplitSummary();
1544 log_man << " Variance-gated skips: " << variance_skipped_accurate_calls_
1545 << "\n";
1546 log_man << " IMSPE soft skips: " << imspe_soft_skipped_calls_ << "\n";
1547 log_man << " IMSPE EMD-gray admissions: "
1548 << imspe_admitted_near_duplicate_observations_ << "\n";
1549 log_man << " Active-frozen-set changes: " << active_set_change_count_
1550 << " (final active frozen atoms: " << active_frozen_count_ << ")\n";
1551 log_man << " Search control / geometry: " << search_control_seconds
1552 << "s\n";
1553}
1554
1555bool AtomicDimer::isAtomsConfigurationCorrect()
1556{
1557 bool res = true;
1558
1559 if (atoms_config.atoms_froz_active.type.size() == 0) {
1560 res = false;
1561 }
1562 if (atoms_config.atoms_mov.positions.size() ==
1563 atoms_config.positions.size()) {
1564 res = true;
1565 }
1566
1567 return res;
1568}
1569
1570void AtomicDimer::updateLocation(const gpr::Coord orient,
1571 const gpr::Coord& middle_point,
1572 gpr::Coord& new_point)
1573{
1574 new_point = middle_point + orient * dimer_sep;
1575}
1576
1578 const gpr::Observation& middle_point, const double stop_criteria)
1579{
1580 const double max_value = forceNormForConvergence(middle_point);
1581
1582 if (max_value < stop_criteria) return true;
1583 log_man << "Current Max is " << max_value;
1584 if (project_rigid_modes_for_convergence_ && middle_point.G.rows() > 0) {
1585 const double raw_value = forceNormForConvergence(middle_point.G.row(0));
1586 if (std::isfinite(raw_value) && raw_value != max_value) {
1587 log_man << " (raw including rigid gauge modes " << raw_value << ")";
1588 }
1589 }
1590 log_man << "\n";
1591
1592 return false;
1593}
1594
1595bool AtomicDimer::recordMeasuredModeCertificate(
1596 const gpr::Observation& midpoint, const gpr::Coord& orientation,
1597 const gpr::Observation& endpoint)
1598{
1599 latest_mode_curvature_ = std::numeric_limits<double>::quiet_NaN();
1600 latest_mode_curvature_resolution_ = 0.0;
1601 final_rotation_omega_ = std::numeric_limits<double>::infinity();
1602 final_rotation_residual_ = std::numeric_limits<double>::infinity();
1603 measured_rotation_stationary_ = false;
1604 if (orientation.rows() != 1 || orientation.cols() == 0 ||
1605 midpoint.G.rows() != 1 || endpoint.G.rows() != 1 ||
1606 midpoint.G.cols() != orientation.cols() ||
1607 endpoint.G.cols() != orientation.cols() || !orientation.allFinite() ||
1608 !midpoint.G.allFinite() || !endpoint.G.allFinite())
1609 return false;
1610
1611 dimer::Dimer measured(dimer_sep, is_subsystem(atoms_config));
1612 Eigen::MatrixXd physical;
1613 if (std::isfinite(transition_param.rotrem_thresh)) {
1615 midpoint.R, atoms_config, project_measured_rotations_,
1617 measured.setRotationBasis(physical);
1618 }
1619 gpr::Coord gradients = midpoint.G;
1620 gpr::field::appendRows(gradients, endpoint.G);
1621 latest_mode_curvature_ =
1622 measured.calculateCurvature(gradients, orientation);
1623 gpr::Coord rotational_force;
1624 measured.rotateForce(gradients, orientation, rotational_force);
1625 const double angle = measured.estimateRotationalAngle(
1626 orientation, gradients, rotational_force);
1627 if (std::isfinite(angle)) final_rotation_omega_ = angle;
1628 // The measured eigen-residual of the mode in force units: the gradient
1629 // difference across the dimer with its axial part removed, |(g1 - g0)
1630 // - v (v . (g1 - g0))| = |H v - c v| h at separation h. The rotation
1631 // angle divides this residual by the curvature; the residual sequence
1632 // over measured rotations at one midpoint tells whether rotating still
1633 // resolves the mode or has reached what the measurements resolve.
1634 final_rotation_residual_ = std::numeric_limits<double>::infinity();
1635 {
1636 const Eigen::RowVectorXd axis =
1637 orientation.row(0) / std::max(orientation.row(0).norm(),
1638 std::numeric_limits<double>::min());
1639 Eigen::RowVectorXd difference = endpoint.G.row(0) - midpoint.G.row(0);
1640 difference -= axis * axis.dot(difference);
1641 if (physical.rows() > 0)
1642 difference =
1643 (physical * (physical.transpose() * difference.transpose()))
1644 .transpose()
1645 .eval();
1646 const double residual = forceNormForConvergence(difference);
1647 if (std::isfinite(residual)) final_rotation_residual_ = residual;
1648 }
1649 return measuredModeIsCertified();
1650}
1651
1653{
1654 const double angle_tolerance = stop_citeria_dimer.angle_rotation;
1655 // A negative curvature within its own truncation estimate is not a
1656 // certified negative (17_claisen: -0.007 at the escape dimer's end,
1657 // the validation stencil found no negative mode).
1658 if (!std::isfinite(latest_mode_curvature_) ||
1659 !(latest_mode_curvature_ < -latest_mode_curvature_resolution_))
1660 return false;
1661 const bool angle_certified =
1662 std::isfinite(angle_tolerance) &&
1663 (angle_tolerance <= 0.0 || (std::isfinite(final_rotation_omega_) &&
1664 final_rotation_omega_ <= angle_tolerance));
1665 // The force residual is h * (H v - c v). It can fall below the
1666 // translational force tolerance solely by reducing the separation h,
1667 // with no improvement in orientation. Resolution-limited acceptance
1668 // requires the measured rotation sequence to stop improving.
1669 return angle_certified || measured_rotation_stationary_;
1670}
1671
1673{
1674 return measuredModeIsCertified() ||
1675 (external_terminal_certificate_ &&
1676 std::isfinite(latest_mode_curvature_) &&
1677 latest_mode_curvature_ < -latest_mode_curvature_resolution_);
1678}
1679
1681 const gpr::Coord& orientation,
1682 pot::PotentialWrapper& potential,
1683 double surrogate_curvature)
1684{
1685 latest_mode_curvature_resolution_ = 0.0;
1686 if (gpr::optim::curvatureResolvedBySurrogate(latest_mode_curvature_,
1687 surrogate_curvature))
1688 return;
1689 if (orientation.rows() != 1 || midpoint.G.rows() != 1 ||
1690 midpoint.G.cols() != orientation.cols() ||
1691 !(std::isfinite(dimer_sep) && dimer_sep > 0.0))
1692 return;
1693 const Eigen::RowVectorXd axis =
1694 orientation.row(0) /
1695 std::max(orientation.row(0).norm(), std::numeric_limits<double>::min());
1696 gpr::Observation far_image;
1697 far_image.R = midpoint.R + 2.0 * dimer_sep * axis;
1698 evaluateAccurateEnergyAndForce(far_image, potential,
1699 /*apply_emd_dedup=*/false);
1700 broadcastObservation(far_image);
1701 synchronizeObservedData();
1702 if (!far_image.G.allFinite() || far_image.G.cols() != orientation.cols())
1703 return;
1704 const double at_2h =
1705 axis.dot(far_image.G.row(0) - midpoint.G.row(0)) / (2.0 * dimer_sep);
1706 const double at_h = latest_mode_curvature_;
1707 latest_mode_curvature_ =
1709 latest_mode_curvature_resolution_ =
1710 std::abs(gpr::optim::richardsonForwardTruncation(at_h, at_2h));
1711 log_man << "Measured mode curvature refined: " << at_h
1712 << " at the dimer separation, " << at_2h << " at twice it, "
1713 << latest_mode_curvature_
1714 << " extrapolated with truncation "
1715 "estimate "
1716 << latest_mode_curvature_resolution_ << " (surrogate "
1717 << surrogate_curvature << ").\n";
1718}
1719
1720bool AtomicDimer::refineMeasuredMode(const gpr::Observation& midpoint,
1721 gpr::Coord& orientation,
1722 pot::PotentialWrapper& potential)
1723{
1724 const Eigen::Index dimension = midpoint.R.cols();
1725 if (midpoint.R.rows() != 1 || midpoint.G.rows() != 1 ||
1726 midpoint.G.cols() != dimension || orientation.rows() != 1 ||
1727 orientation.cols() != dimension || !midpoint.R.allFinite() ||
1728 !midpoint.G.allFinite() || !orientation.allFinite() ||
1729 !(std::isfinite(dimer_sep) && dimer_sep > 0.0))
1730 throw std::runtime_error("invalid measured terminal rotation");
1731 Eigen::MatrixXd physical = Eigen::MatrixXd::Identity(dimension, dimension);
1732 if (std::isfinite(transition_param.rotrem_thresh))
1734 midpoint.R, atoms_config, project_measured_rotations_,
1736 if (physical.cols() == 0) return false;
1737 const auto same = [](const auto& first, const auto& second) {
1738 return first.rows() == second.rows() && first.cols() == second.cols() &&
1739 (first.array() == second.array()).all();
1740 };
1741 const bool reset = measured_rotation_basis_.cols() == 0 ||
1742 !same(midpoint.R, measured_rotation_reference_.R) ||
1743 !same(midpoint.G, measured_rotation_reference_.G) ||
1744 dimer_sep != measured_rotation_separation_ ||
1745 !same(physical, measured_rotation_physical_);
1746 if (reset) {
1747 measured_rotation_reference_ = midpoint;
1748 measured_rotation_separation_ = dimer_sep;
1749 measured_rotation_physical_ = physical;
1750 measured_rotation_basis_.resize(dimension, 0);
1751 measured_rotation_actions_.resize(dimension, 0);
1752 }
1753 auto& basis = measured_rotation_basis_;
1754 auto& actions = measured_rotation_actions_;
1755 const auto project = [&](const Eigen::VectorXd& vector) -> Eigen::VectorXd {
1756 return physical * (physical.transpose() * vector);
1757 };
1758 const auto evaluate = [&](gpr::Observation& candidate) {
1759 if (!evaluateAccurateProbe(candidate, potential))
1760 throw std::runtime_error("measured terminal dimer rotation failed");
1761 };
1762 const auto append = [&](const Eigen::VectorXd& direction,
1763 const gpr::Observation& endpoint) {
1764 const Eigen::Index column = basis.cols();
1765 basis.conservativeResize(Eigen::NoChange, column + 1);
1766 actions.conservativeResize(Eigen::NoChange, column + 1);
1767 basis.col(column) = direction;
1768 actions.col(column) = project(
1769 (endpoint.G.row(0) - midpoint.G.row(0)).transpose() / dimer_sep);
1770 };
1771 const auto certify = [&]() {
1772 broadcastDenseMatrix(orientation);
1773 broadcastObservation(image1);
1774 synchronizeObservedData();
1775 return recordMeasuredModeCertificate(midpoint, orientation, image1);
1776 };
1777 if (reset) {
1778 Eigen::VectorXd axis = project(orientation.row(0).transpose());
1779 const double norm = axis.stableNorm();
1780 if (!(norm > 0.0) || !std::isfinite(norm)) return false;
1781 axis /= norm;
1782 orientation = axis.transpose();
1783 const gpr::Coord location = midpoint.R + dimer_sep * orientation;
1784 if (!dimerGeometriesCoincide(image1.R, location) ||
1785 image1.G.rows() != 1 || image1.G.cols() != dimension ||
1786 !image1.G.allFinite()) {
1787 image1.R = location;
1788 evaluate(image1);
1789 append(axis, image1);
1790 return certify();
1791 }
1792 append(axis, image1);
1793 }
1794 // Reorthogonalized residual expansion retains every measured direction
1795 // at this geometry. Finite differences need not form a symmetric linear
1796 // map: its symmetric projection proposes a mode, never a certificate.
1797 const Eigen::VectorXd direction = gpr::optim::measuredModeExpansion(
1798 basis, physical,
1799 (image1.G.row(0) - midpoint.G.row(0)).transpose() / dimer_sep);
1800 if (direction.size()) {
1801 gpr::Observation endpoint;
1802 endpoint.R = midpoint.R + dimer_sep * direction.transpose();
1803 evaluate(endpoint);
1804 append(direction, endpoint);
1805 }
1806 const auto spectrum = gpr::optim::analyzeMeasuredCurvature(basis, actions);
1807 if (!spectrum.valid)
1808 throw std::runtime_error("measured terminal Ritz solve failed");
1809 Eigen::VectorXd proposed = spectrum.modes.col(0).normalized();
1810 if (proposed.dot(orientation.row(0).transpose()) < 0.0) proposed *= -1.0;
1811 orientation = proposed.transpose();
1812 const gpr::Coord location = midpoint.R + dimer_sep * orientation;
1813 if (!dimerGeometriesCoincide(image1.R, location)) {
1814 image1.R = location;
1815 evaluate(image1);
1816 }
1817 return certify();
1818}
1819
1820bool AtomicDimer::resolveAdditionalNegativeMode(
1821 const gpr::Observation& midpoint, const gpr::Coord& orientation,
1822 pot::PotentialWrapper& potential, gpr::Observation& recovery,
1823 gpr::Coord* measured_mode, bool complete_stencil_follows)
1824{
1825 recovery = midpoint;
1826 if (measured_mode) measured_mode->resize(0, 0);
1827 if (!want_second_negative_mode_) return true;
1828
1829 // The curvature hint belongs to this terminal geometry, including a
1830 // midpoint reached by measured rotation rather than GP translation.
1831 const auto mode = estimateLowestModeAndCurvatureFromGP(
1832 midpoint.R, &orientation, SurrogateSpectrumRequest::Spectrum);
1833 if (mode.first.size() != midpoint.R.size() || !std::isfinite(mode.second)) {
1834 curvature_requires_full_refit_ = true;
1835 return false;
1836 }
1837 // The GP sign does not certify the true transverse curvature. A system
1838 // with one physical degree of freedom has no transverse mode to test.
1839 if (additional_mode_.size() == 0) return true;
1840
1841 const Eigen::MatrixXd physical =
1843 Eigen::VectorXd axis = orientation.row(0).transpose().normalized();
1844 Eigen::VectorXd transverse = additional_mode_;
1845 const Eigen::MatrixXd transported = gpr::optim::transportPhysicalDirections(
1846 index_search_directions_, physical);
1847 if (transported.cols() == 2) {
1848 axis = transported.col(0);
1849 transverse = transported.col(1);
1850 } else {
1851 // Every stencil direction belongs to the physical subspace at this
1852 // midpoint. Omitting masses selects the Euclidean metric; it does
1853 // not retain rigid components from the dimer orientation.
1854 const double projection_roundoff =
1855 8.0 * std::numeric_limits<double>::epsilon() * physical.rows();
1856 const Eigen::VectorXd projected_axis =
1857 physical * (physical.transpose() * axis);
1858 // Preserve an already physical direction within projection roundoff.
1859 // Re-expressing it through the basis can rotate a nearly degenerate
1860 // complement and perturb an owned stencil's curvature evidence.
1861 if (!projected_axis.allFinite() ||
1862 (projected_axis - axis).norm() > projection_roundoff) {
1863 const double axis_norm = projected_axis.norm();
1864 if (!std::isfinite(axis_norm) ||
1865 axis_norm <=
1866 std::sqrt(std::numeric_limits<double>::epsilon())) {
1867 curvature_requires_full_refit_ = true;
1868 return false;
1869 }
1870 axis = projected_axis / axis_norm;
1871 }
1872 const Eigen::VectorXd projected_transverse =
1873 physical * (physical.transpose() * transverse);
1874 if (!projected_transverse.allFinite() ||
1875 (projected_transverse - transverse).norm() >
1876 projection_roundoff * transverse.norm())
1877 transverse = projected_transverse;
1878 }
1879 transverse -= axis * axis.dot(transverse);
1880 const double transverse_norm = transverse.norm();
1881 curvature_requires_full_refit_ = true;
1882 if (!std::isfinite(transverse_norm) ||
1883 transverse_norm <= std::sqrt(std::numeric_limits<double>::epsilon()))
1884 return false;
1885 transverse /= transverse_norm;
1886
1887 // Stencil probes certify curvature; they are not training rows. The
1888 // rows a certificate appended (86 on 14_hydro, 290 on 16_oxirane)
1889 // multiplied every later prediction and refit by their count.
1890 last_certificate_probe_calls_ = 0;
1891 const auto measure = [&](gpr::Observation& observation) {
1892 evaluateAccurateProbe(observation, potential);
1893 broadcastObservation(observation);
1894 last_certificate_probe_calls_ +=
1895 static_cast<std::size_t>(observation.R.rows());
1896 };
1897 // Escape trials are geometry along the mode and remain training rows.
1898 const auto measure_retained = [&](gpr::Observation& observation) {
1899 // Curvature observations must survive pair-distance coalescence.
1900 evaluateAccurateEnergyAndForce(observation, potential,
1901 /*apply_emd_dedup=*/false);
1902 broadcastObservation(observation);
1903 synchronizeObservedData();
1904 };
1905 const double separation = std::max(dimer_sep, 1.0e-3);
1906 gpr::Observation plus, minus;
1907 plus.R = midpoint.R + separation * transverse.transpose();
1908 minus.R = midpoint.R - separation * transverse.transpose();
1909 // Every column of the index stencil has second-order truncation. A
1910 // forward axis action would contaminate the matrix's asymmetry with
1911 // first-order error and obscure resolved positive transverse modes.
1912 gpr::Observation axis_plus, axis_minus;
1913 axis_plus.R = midpoint.R + separation * axis.transpose();
1914 axis_minus.R = midpoint.R - separation * axis.transpose();
1915 const bool owned_axis_plus =
1916 image1.R.rows() == axis_plus.R.rows() &&
1917 image1.R.cols() == axis_plus.R.cols() &&
1918 dimerGeometriesCoincide(image1.R, axis_plus.R) &&
1919 image1.G.rows() == 1 && image1.G.cols() == midpoint.R.cols() &&
1920 image1.G.allFinite();
1921 if (!(std::isfinite(dimer_sep) && dimer_sep > 0.0)) return false;
1922 // Independent stencil positions share one oracle dispatch. An owned
1923 // axis endpoint remains an exact-position observation, without a new call.
1924 gpr::Observation probes;
1925 probes.R.resize(owned_axis_plus ? 3 : 4, midpoint.R.cols());
1926 probes.R.row(0) = plus.R;
1927 probes.R.row(1) = minus.R;
1928 if (!owned_axis_plus) probes.R.row(2) = axis_plus.R;
1929 probes.R.bottomRows(1) = axis_minus.R;
1930 measure(probes);
1931 if (probes.G.rows() != probes.R.rows() ||
1932 probes.G.cols() != probes.R.cols() || !probes.G.allFinite() ||
1933 probes.E.rows() != probes.R.rows() || !probes.E.allFinite())
1934 return false;
1935 const auto copy_probe = [&](gpr::Observation& target, gpr::Index_t row) {
1936 target.resizeToMatch(probes, 1);
1937 target.copyRow(0, probes, row);
1938 };
1939 copy_probe(plus, 0);
1940 copy_probe(minus, 1);
1941 if (owned_axis_plus)
1942 axis_plus = image1;
1943 else
1944 copy_probe(axis_plus, 2);
1945 copy_probe(axis_minus, probes.R.rows() - 1);
1946
1947 Eigen::MatrixXd basis(midpoint.R.cols(), 2);
1948 basis.col(0) = axis;
1949 basis.col(1) = transverse;
1950 Eigen::MatrixXd action(midpoint.R.cols(), 2);
1951 action.col(0) =
1952 (axis_plus.G - axis_minus.G).transpose() / (2.0 * separation);
1953 action.col(1) = (plus.G - minus.G).transpose() / (2.0 * separation);
1954 const auto ritzSpectrum = [&](const Eigen::MatrixXd& measured_action) {
1955 Eigen::Matrix2d ritz = basis.transpose() * measured_action;
1956 ritz = (0.5 * (ritz + ritz.transpose())).eval();
1957 return Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d>(ritz);
1958 };
1959 Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> spectrum =
1960 ritzSpectrum(action);
1961 if (spectrum.info() != Eigen::Success ||
1962 !spectrum.eigenvalues().allFinite())
1963 return false;
1964 log_man << "Second negative mode: measured subspace curvatures "
1965 << spectrum.eigenvalues().transpose() << " (surrogate second "
1966 << additional_gp_curvature_ << ").\n";
1967
1968 // The Ritz vectors can mix the measured axes. Refine both columns and
1969 // carry their componentwise truncation and asymmetry into the matrix
1970 // bound; a stiff direction's error is not the weak eigenvalue's error.
1971 const Eigen::VectorXd even_residual =
1972 (0.5 * (plus.G + minus.G) - midpoint.G).row(0).transpose();
1973 const double anharmonic_scale = transverse.dot(even_residual) / separation;
1974 log_man << "Second negative mode: stencil anharmonicity scale "
1975 << anharmonic_scale << ".\n";
1976 bool refined_transverse = false;
1977 bool positive_transverse = false;
1978 double transverse_resolution = 0.0;
1979 Eigen::MatrixXd initial_truncation;
1980 // A screen, not a certificate: the even residual is the stencil's own
1981 // anharmonicity scale and does not bound the central-difference
1982 // truncation, which is the third derivative of the force
1983 // (curvatureResolvedByThirdDerivative). A coarse value below that scale
1984 // is refined here; one above it goes on to the measured complement and,
1985 // when a certificate is requested, to the complete stencil.
1986 if (!gpr::optim::curvatureResolvedByStencil(spectrum.eigenvalues()(1),
1987 anharmonic_scale)) {
1988 refined_transverse = true;
1989 Eigen::MatrixXd coarse = action;
1990 double fine_step = separation;
1991 bool resolved = false;
1992 for (int refinement = 0; refinement < 2 && !resolved; ++refinement) {
1993 fine_step *= 0.5;
1994 gpr::Observation fine_probes;
1995 fine_probes.R.resize(4, midpoint.R.cols());
1996 for (Eigen::Index column = 0; column < 2; ++column) {
1997 const Eigen::RowVectorXd offset =
1998 fine_step * basis.col(column).transpose();
1999 fine_probes.R.row(2 * column) = midpoint.R.row(0) + offset;
2000 fine_probes.R.row(2 * column + 1) = midpoint.R.row(0) - offset;
2001 }
2002 measure(fine_probes);
2003 if (fine_probes.G.rows() != 4 ||
2004 fine_probes.G.cols() != midpoint.R.cols() ||
2005 !fine_probes.G.allFinite())
2006 return false;
2007 Eigen::MatrixXd fine(midpoint.R.cols(), 2);
2008 for (Eigen::Index column = 0; column < 2; ++column)
2009 fine.col(column) = (fine_probes.G.row(2 * column) -
2010 fine_probes.G.row(2 * column + 1))
2011 .transpose() /
2012 (2.0 * fine_step);
2014 basis, fine, coarse);
2015 if (!refined.valid) return false;
2016 initial_truncation = (coarse - fine) / 3.0;
2017 action = (4.0 * fine - coarse) / 3.0;
2018 spectrum = ritzSpectrum(action);
2019 if (spectrum.info() != Eigen::Success ||
2020 !spectrum.eigenvalues().allFinite())
2021 return false;
2022 transverse_resolution = gpr::optim::refinedCurvatureResolution(
2023 refined.resolution, anharmonic_scale);
2024 const auto sign = gpr::optim::refinedCurvatureSign(
2025 refined.curvatures(1), refined.resolution, anharmonic_scale);
2026 // Within the stencil's resolution of zero the mode is flat as far
2027 // as any affordable stencil can tell: index one at that
2028 // resolution, as the validation stencil reads a soft mode.
2029 positive_transverse =
2031 const bool negative_transverse =
2033 refined.negative_pair_upper_bound < 0.0;
2034 resolved = positive_transverse || negative_transverse;
2035 log_man << "Second negative mode: refined Ritz curvatures "
2036 << refined.curvatures.transpose() << " at separation "
2037 << fine_step << ", resolution " << refined.resolution
2038 << " (stencil " << transverse_resolution << ")"
2039 << ", negative-pair upper bound "
2040 << refined.negative_pair_upper_bound
2042 ? ", unresolved: flat at this stencil"
2043 : "")
2044 << ".\n";
2045 coarse = std::move(fine);
2046 }
2047 // A second Ritz value that stays negative while the pair's bound
2048 // does not is no measured refusal of the midpoint.
2049 if (!resolved) positive_transverse = true;
2050 }
2051
2052 // Two negative Ritz values suffice to reject an index-one candidate.
2053 // Without them the curvature model proposes further directions, and a
2054 // proposal counts only once it is measured.
2055 Eigen::MatrixXd unstable = basis * spectrum.eigenvectors();
2056 Eigen::VectorXd escape = unstable.col(1);
2057 // A curvature softer than the frequency resolution is flat: the force
2058 // tolerance does not locate a stationary point along it, and its sign
2059 // here is not its sign there.
2060 const auto flat_curvature = [&](const Eigen::VectorXd& cartesian) {
2062 index_frequency_resolution_, cartesian, atoms_config.atomic_masses);
2063 };
2064 if (positive_transverse ||
2065 !(spectrum.eigenvalues()(1) < -flat_curvature(escape))) {
2066 const Eigen::Index dimension = physical.cols();
2067 if (dimension < basis.cols()) return false;
2068 // A transported pair can lose a weak negative mode through coupling
2069 // to its complement. Its measured Ritz residuals propose at most one
2070 // extra direction per retained direction before the full stencil.
2071 // Only the complete stencil decides acceptance in this case.
2072 const Eigen::Index column_limit =
2073 complete_stencil_follows ? std::min(dimension, 2 * basis.cols())
2074 : dimension;
2075 // The verdict rests on measured columns. Two negative Ritz values
2076 // of the measured span are two negative curvatures of the Hessian
2077 // (Cauchy interlacing), so a refined negative pair refuses the
2078 // midpoint and supplies the escape. Part of a spectrum cannot
2079 // certify index one; the curvature model, completed with every
2080 // measured column, proposes where a second negative mode would be,
2081 // and that direction is measured before it counts. The midpoint is
2082 // terminal when the completed model has one negative curvature.
2083 // Sorted eigenvalues of a posterior over the unmeasured block carry
2084 // no sign: their lower edge is negative under any broad prior,
2085 // whatever the Hessian is (two columns of 75 gave -515 eV/A^2
2086 // against a measured +2.9 in the same span).
2087 // The model is the last certificate Hessian while the midpoint is
2088 // still the geometry that Hessian was built for, else the
2089 // surrogate spectrum at this midpoint.
2090 Eigen::MatrixXd curvature_prior;
2091 if (last_certificate_hessian_.rows() == midpoint.R.cols() &&
2092 last_certificate_hessian_.cols() == midpoint.R.cols() &&
2093 last_certificate_hessian_.allFinite() &&
2094 last_certificate_positions_.rows() == midpoint.R.rows() &&
2095 last_certificate_positions_.cols() == midpoint.R.cols() &&
2096 dimerGeometriesCoincide(last_certificate_positions_, midpoint.R)) {
2097 curvature_prior = last_certificate_hessian_;
2098 } else if (surrogate_spectrum_.valid &&
2099 surrogate_spectrum_.R.rows() == midpoint.R.rows() &&
2100 surrogate_spectrum_.R.cols() == midpoint.R.cols() &&
2101 dimerGeometriesCoincide(surrogate_spectrum_.R, midpoint.R)) {
2102 curvature_prior = surrogate_spectrum_.modes *
2103 surrogate_spectrum_.curvatures.asDiagonal() *
2104 surrogate_spectrum_.modes.transpose();
2105 }
2106 Eigen::MatrixXd prior = Eigen::MatrixXd::Zero(dimension, dimension);
2107 if (curvature_prior.rows() == midpoint.R.cols())
2108 prior = physical.transpose() * curvature_prior * physical;
2109 if (auto* tracker = gpr::track::activeRun()) {
2110 gpr::track::JsonRecord record;
2111 record.add("oracle_calls", static_cast<long>(getNumEvaluations()))
2112 .add("positions",
2113 Eigen::VectorXd(midpoint.R.row(0).transpose()))
2114 .add("physical_basis", physical)
2115 .add("measured_basis", basis)
2116 .add("measured_action", action)
2117 .add("curvature_prior", curvature_prior)
2118 .add("separation", separation);
2119 tracker->appendRecord("dimer/index_probe", record);
2120 }
2121 const Eigen::MatrixXd physical_sq = physical.array().square().matrix();
2122 const auto physical_variance =
2123 [&](const Eigen::VectorXd& cartesian_error) -> Eigen::VectorXd {
2124 return physical_sq.transpose() *
2125 cartesian_error.array().square().matrix();
2126 };
2127 const double eps = std::numeric_limits<double>::epsilon();
2128 const double roundoff_scale =
2129 eps * std::max(action.norm(), midpoint.G.norm());
2130 // Roundoff of a central difference, entry by entry: the gradients'
2131 // magnitudes over the stencil width, above the actions' scale.
2132 const auto roundoff_error =
2133 [&](const Eigen::VectorXd& g_plus, const Eigen::VectorXd& g_minus,
2134 double step) -> std::optional<Eigen::VectorXd> {
2135 if (!(step > 0.0) || !std::isfinite(step) ||
2136 g_plus.size() != g_minus.size() || !g_plus.allFinite() ||
2137 !g_minus.allFinite())
2138 return std::nullopt;
2139 Eigen::VectorXd error =
2140 (eps * (g_plus.array().abs() + g_minus.array().abs()) /
2141 (2.0 * step))
2142 .max(roundoff_scale)
2143 .matrix();
2144 if (!error.allFinite()) return std::nullopt;
2145 return error;
2146 };
2147 // Entrywise error of a coarse column: the even residual over the
2148 // separation, the stencil's own cubic scale, above roundoff.
2149 const auto coarse_error = [&](const Eigen::VectorXd& even_residual,
2150 const Eigen::VectorXd& roundoff)
2151 -> std::optional<Eigen::VectorXd> {
2152 if (!(separation > 0.0) || !std::isfinite(separation) ||
2153 even_residual.size() != roundoff.size() ||
2154 !even_residual.allFinite() || !roundoff.allFinite())
2155 return std::nullopt;
2156 Eigen::VectorXd error = (even_residual.array().abs() / separation)
2157 .max(roundoff.array())
2158 .matrix();
2159 if (!error.allFinite()) return std::nullopt;
2160 return error;
2161 };
2162 struct ColumnStencil {
2163 Eigen::VectorXd cartesian;
2164 Eigen::VectorXd coarse_action;
2165 Eigen::VectorXd even_residual;
2166 Eigen::VectorXd refined_action;
2167 };
2168 std::vector<gpr::optim::MeasuredHessianColumn> columns;
2169 std::vector<ColumnStencil> stencils;
2170 const Eigen::VectorXd axis_even =
2171 (0.5 * (axis_plus.G + axis_minus.G) - midpoint.G)
2172 .row(0)
2173 .transpose();
2174 for (Eigen::Index j = 0; j < 2; ++j) {
2175 const Eigen::VectorXd even = j == 0 ? axis_even : even_residual;
2176 const auto roundoff = roundoff_error(
2177 (j == 0 ? axis_plus.G : plus.G).row(0).transpose(),
2178 (j == 0 ? axis_minus.G : minus.G).row(0).transpose(),
2179 separation);
2180 if (!roundoff) return false;
2181 auto error = coarse_error(even, *roundoff);
2182 if (!error) return false;
2183 if (refined_transverse && initial_truncation.cols() == 2) {
2184 const Eigen::VectorXd column = initial_truncation.col(j);
2185 if (!column.allFinite()) return false;
2186 *error = column.array().abs().max(roundoff->array()).matrix();
2187 }
2188 columns.push_back({physical.transpose() * basis.col(j),
2189 physical.transpose() * action.col(j),
2190 physical_variance(*error), refined_transverse});
2191 stencils.push_back({basis.col(j), action.col(j), even});
2192 }
2193 const auto measure_pair = [&](const Eigen::VectorXd& cartesian,
2194 double step, gpr::Observation& probes) {
2195 probes.R.resize(2, midpoint.R.cols());
2196 probes.R.row(0) = midpoint.R.row(0) + step * cartesian.transpose();
2197 probes.R.row(1) = midpoint.R.row(0) - step * cartesian.transpose();
2198 measure(probes);
2199 return probes.G.rows() == 2 &&
2200 probes.G.cols() == midpoint.R.cols() && probes.G.allFinite();
2201 };
2202 // A coarse column: two calls at the separation.
2203 const auto measure_column = [&](const Eigen::VectorXd& direction) {
2204 const Eigen::VectorXd cartesian = physical * direction;
2205 gpr::Observation probes;
2206 if (!measure_pair(cartesian, separation, probes)) return false;
2207 const Eigen::VectorXd coarse =
2208 (probes.G.row(0) - probes.G.row(1)).transpose() /
2209 (2.0 * separation);
2210 const Eigen::VectorXd even =
2211 (0.5 * (probes.G.row(0) + probes.G.row(1)) - midpoint.G.row(0))
2212 .transpose();
2213 const auto roundoff =
2214 roundoff_error(probes.G.row(0).transpose(),
2215 probes.G.row(1).transpose(), separation);
2216 if (!roundoff) return false;
2217 const auto error = coarse_error(even, *roundoff);
2218 if (!error) return false;
2219 log_man << "Measured dimer spectrum: column " << columns.size()
2220 << " model curvature " << direction.dot(prior * direction)
2221 << " measured "
2222 << direction.dot(physical.transpose() * coarse) << ".\n";
2223 columns.push_back({direction, physical.transpose() * coarse,
2224 physical_variance(*error), false});
2225 stencils.push_back({cartesian, coarse, even});
2226 return true;
2227 };
2228 // The verdict on the midpoint: no measured second negative mode,
2229 // or an escape along a measured negative pair.
2230 enum class IndexVerdict { Undecided, IndexOne, Escape };
2231 IndexVerdict verdict = IndexVerdict::Undecided;
2232 gpr::optim::NegativeRitzPairRefinement negative_ritz_refinement;
2233 Eigen::MatrixXd measured_negative_pair;
2234 Eigen::VectorXd measured_lowest_mode;
2235 Eigen::MatrixXd completed;
2236 // A second Ritz value within the coarse resolution of zero has no
2237 // sign until its pair is refined; that is done once per verdict.
2238 bool verdict_pair_refined = false;
2239 while (verdict == IndexVerdict::Undecided) {
2240 const Eigen::Index measured_count =
2241 static_cast<Eigen::Index>(columns.size());
2242 Eigen::MatrixXd measured_basis(dimension, measured_count);
2243 Eigen::MatrixXd measured_action(dimension, measured_count);
2244 for (Eigen::Index j = 0; j < measured_count; ++j) {
2245 measured_basis.col(j) = columns[j].direction;
2246 measured_action.col(j) = columns[j].action;
2247 }
2249 measured_basis, measured_action);
2250 if (!measured.valid) return false;
2251 // The lowest Ritz value bounds the lowest curvature from above,
2252 // so a span without a negative one does not refuse the
2253 // midpoint: the model's lowest mode is measured first, then
2254 // the Lanczos residuals below.
2255 const bool lowest_negative =
2256 measured.curvatures(0) < -measured.resolution;
2257 measured_lowest_mode = measured.modes.col(0);
2258 if (complete_stencil_follows && lowest_negative && measured_mode) {
2259 // The measured span supplies a rotation proposal even when
2260 // its complement still needs the complete index stencil.
2261 // The caller measures an endpoint along this proposal.
2262 *measured_mode = (physical * measured_lowest_mode).transpose();
2263 if (measured_mode->row(0).dot(orientation.row(0)) < 0.0)
2264 *measured_mode *= -1.0;
2265 }
2266 // Two negative Ritz values reject index one once their refined
2267 // bound is negative. The coarse and fine actions use the same
2268 // two directions: mixing coarse columns does not preserve
2269 // their truncation terms. A rejected pair lowers the threshold
2270 // a later Ritz value must cross, so it is not measured twice.
2271 const Eigen::MatrixXd pair = physical * measured.modes.leftCols(2);
2272 // The coarse stencil's error bounds what a coarse Ritz value
2273 // can sign. A second value inside it is unresolved, and the
2274 // index-one verdict would rest on it: the pair is refined
2275 // first, as the independent validation refines its weak
2276 // modes.
2277 double coarse_pair_error = 0.0;
2278 {
2279 const Eigen::VectorXd coefficients =
2280 measured_basis.transpose() * measured.modes.col(1);
2281 for (Eigen::Index j = 0; j < measured_count; ++j)
2282 coarse_pair_error += coefficients(j) * coefficients(j) *
2283 columns[j].variance.sum();
2284 coarse_pair_error = std::sqrt(coarse_pair_error);
2285 }
2286 const bool second_unresolved =
2287 std::abs(measured.curvatures(1)) <=
2288 std::max(measured.resolution, coarse_pair_error);
2289 if (lowest_negative &&
2290 ((!verdict_pair_refined && second_unresolved) ||
2291 measured.curvatures(1) <
2292 std::min(negative_ritz_refinement.threshold,
2293 -flat_curvature(pair.col(1))))) {
2294 verdict_pair_refined = true;
2295 gpr::optim::RefinedCurvatureActions refined_actions;
2296 gpr::Observation pair_rows;
2298 midpoint.R.row(0).transpose(), pair, separation,
2299 [&](const Eigen::MatrixXd& positions) {
2300 gpr::Observation probes;
2301 probes.R.resize(positions.rows(), positions.cols());
2302 probes.R = positions;
2303 measure(probes);
2304 pair_rows.append(probes);
2305 return Eigen::MatrixXd(probes.G);
2306 },
2307 &refined_actions);
2308 if (!refined.valid) return false;
2309 log_man << "Second negative mode: refined measured Ritz "
2310 "pair from "
2311 << measured_count << " of " << dimension
2312 << " directions, curvatures "
2313 << refined.curvatures.transpose()
2314 << ", negative-pair upper bound "
2315 << refined.negative_pair_upper_bound << ".\n";
2316 if (refined.negative_pair_upper_bound <
2317 -flat_curvature(refined.modes.col(1))) {
2318 // The measured pair certifies index at this point.
2319 // A cubic extrapolation can have no stationary root
2320 // while a measured downhill escape remains possible.
2321 // Its force target cannot veto that descent or replace
2322 // the configured convergence criterion.
2323 measured_negative_pair = refined.modes;
2324 {
2325 // The measured columns, completed by the scaled
2326 // model, are the Hessian the order-one escape
2327 // starts from.
2328 const double scale =
2330 prior, measured_basis, measured_action);
2331 const Eigen::MatrixXd block =
2333 scale * prior, measured_basis, measured_action);
2334 if (block.rows() == dimension)
2335 escape_hessian_ =
2336 physical * block * physical.transpose();
2337 }
2338 // The refit that follows the escape must see the
2339 // measured negative curvature along the pair: a
2340 // surrogate that never held these gradients places
2341 // the weak mode positive and returns the dimer to
2342 // the point it left. The pair's rows become training
2343 // rows and stop counting as certificate calls.
2344 if (pair_rows.R.rows() > 0 && pair_rows.G.allFinite()) {
2345 retainStructuralObservation(pair_rows);
2346 synchronizeObservedData();
2347 last_certificate_probe_calls_ -= std::min(
2348 last_certificate_probe_calls_,
2349 static_cast<std::size_t>(pair_rows.R.rows()));
2350 }
2351 verdict = IndexVerdict::Escape;
2352 break;
2353 }
2354 negative_ritz_refinement.rejected(measured, refined);
2355 }
2356 if (complete_stencil_follows && measured_count >= column_limit) {
2357 index_search_directions_ = pair;
2358 return true;
2359 }
2360 // The model keeps its own unmeasured block. Its scale is fitted
2361 // to the measured columns first: a model softer than the
2362 // measured actions, completed with them, has a spurious
2363 // negative Schur complement.
2364 const double model_scale = gpr::optim::measuredCurvaturePriorScale(
2365 prior, measured_basis, measured_action);
2367 model_scale * prior, measured_basis, measured_action);
2368 const auto second = gpr::optim::completedSecondMode(
2369 completed, measured_basis, lowest_negative ? 1 : 0);
2370 const double second_flat =
2371 second.valid ? flat_curvature(physical * second.mode) : 0.0;
2372 const double completed_roundoff =
2373 std::numeric_limits<double>::epsilon() * dimension *
2374 completed.norm();
2375 const double completed_resolution =
2376 std::max(measured.resolution, completed_roundoff);
2377 log_man << "Measured dimer spectrum: " << measured_count
2378 << " measured columns of " << dimension
2379 << ", measured curvatures " << measured.curvatures(0) << " "
2380 << measured.curvatures(1) << ", model scale " << model_scale
2381 << ", model " << (lowest_negative ? "second" : "lowest")
2382 << " curvature " << second.curvature << " (flat within "
2383 << second_flat << "), certificate calls "
2384 << last_certificate_probe_calls_ << ".\n";
2385 if (!complete_stencil_follows && second.valid &&
2386 second.curvature <
2387 -std::max(completed_resolution, second_flat) &&
2388 second.unmeasured.size() == dimension) {
2389 if (!measure_column(second.unmeasured)) return false;
2390 continue;
2391 }
2392 // The model can miss a soft mode it never saw. The measured
2393 // span is then extended as a Lanczos iteration on the second
2394 // Ritz pair, and on the lowest pair while the span holds no
2395 // negative value: the larger residual H u - theta u, outside
2396 // the span, is the next column. A pair is converged when its
2397 // residual is within the stencil resolution of its Ritz value,
2398 // so an eigenvalue of the Hessian lies there (Bauer-Fike), and
2399 // a nonnegative second value is index one at that resolution.
2400 // Converging the lowest pair once it is negative is the
2401 // rotation's work; here it measures stiff directions only.
2402 if (measured_count < dimension) {
2403 Eigen::VectorXd next;
2404 double largest = 0.0;
2405 for (Eigen::Index k = lowest_negative ? 1 : 0; k < 2; ++k) {
2406 const Eigen::VectorXd coefficients =
2407 measured_basis.transpose() * measured.modes.col(k);
2408 Eigen::VectorXd residual =
2409 measured_action * coefficients -
2410 measured.curvatures(k) * measured.modes.col(k);
2411 const double residual_norm = residual.norm();
2412 // The stencil error of each column, carried through
2413 // the Ritz combination, bounds what a residual can
2414 // resolve.
2415 double stencil_variance = 0.0;
2416 for (Eigen::Index j = 0; j < measured_count; ++j)
2417 stencil_variance += coefficients(j) * coefficients(j) *
2418 columns[j].variance.sum();
2419 // Below roundoff of the Ritz product a residual
2420 // carries no direction.
2421 const double roundoff =
2422 64.0 * std::numeric_limits<double>::epsilon() *
2423 static_cast<double>(dimension) * measured_action.norm();
2424 const double tolerance = std::max(
2425 {measured.resolution, std::sqrt(stencil_variance),
2426 roundoff, flat_curvature(pair.col(k))});
2427 for (int pass = 0; pass < 2; ++pass)
2428 residual -=
2429 measured_basis *
2430 (measured_basis.transpose() * residual).eval();
2431 log_man << "Measured dimer spectrum: Ritz pair " << k
2432 << " residual " << residual_norm
2433 << " against resolution " << tolerance << ".\n";
2434 const double outside = residual.norm();
2435 if (residual_norm > tolerance && outside > largest &&
2436 outside >
2437 std::sqrt(std::numeric_limits<double>::epsilon()) *
2438 residual_norm) {
2439 largest = outside;
2440 next = residual / outside;
2441 }
2442 }
2443 if (next.size() == dimension) {
2444 if (!measure_column(next)) return false;
2445 continue;
2446 }
2447 }
2448 if (complete_stencil_follows) {
2449 index_search_directions_ = pair;
2450 return true;
2451 }
2452 if (!lowest_negative) {
2453 log_man << "Measured dimer spectrum: lowest measured "
2454 "curvature "
2455 << measured.curvatures(0)
2456 << " is not negative; no saddle here.\n";
2457 return false;
2458 }
2459 // A negative eigenvalue can lie outside a converged measured
2460 // span, and only measuring the complement settles it. While
2461 // the completed Hessian resolves a second negative eigenvalue,
2462 // the softest unmeasured direction of the completion is
2463 // measured next, until the span is complete or the completion
2464 // holds one negative eigenvalue. The completion proposes an
2465 // unmeasured direction even when its curvature falls within the
2466 // uncertainty of the measured block.
2467 if (completed.rows() == dimension && measured_count < dimension) {
2468 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> whole(
2469 completed, Eigen::EigenvaluesOnly);
2470 if (whole.info() == Eigen::Success &&
2471 whole.eigenvalues()(1) <
2472 -std::max(completed_roundoff, second_flat)) {
2473 const Eigen::HouseholderQR<Eigen::MatrixXd> qr(
2474 measured_basis);
2475 const Eigen::MatrixXd full =
2476 qr.householderQ() *
2477 Eigen::MatrixXd::Identity(dimension, dimension);
2478 const Eigen::MatrixXd complement =
2479 full.rightCols(dimension - measured_count);
2480 const Eigen::MatrixXd block =
2481 complement.transpose() * completed * complement;
2482 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> soft(
2483 0.5 * (block + block.transpose()));
2484 if (soft.info() == Eigen::Success) {
2485 Eigen::VectorXd direction =
2486 complement * soft.eigenvectors().col(0);
2487 for (int pass = 0; pass < 2; ++pass)
2488 direction -=
2489 measured_basis *
2490 (measured_basis.transpose() * direction).eval();
2491 if (direction.norm() > 0.0) {
2492 log_man
2493 << "Measured dimer spectrum: the completion "
2494 "holds a second eigenvalue "
2495 << whole.eigenvalues()(1)
2496 << "; measuring its softest unmeasured "
2497 "direction.\n";
2498 if (!measure_column(direction.normalized()))
2499 return false;
2500 continue;
2501 }
2502 }
2503 }
2504 }
2505 verdict = IndexVerdict::IndexOne;
2506 }
2507 if (completed.rows() == dimension) {
2508 last_certificate_hessian_ =
2509 physical * completed * physical.transpose();
2510 last_certificate_positions_ = midpoint.R;
2511 }
2512 if (verdict == IndexVerdict::IndexOne) {
2513 // Measured actions are stored for the rotor when they span its
2514 // constraint. Every proposed orientation still receives an
2515 // oracle endpoint.
2516 const Eigen::MatrixXd rotation_physical =
2517 std::isfinite(transition_param.rotrem_thresh)
2519 midpoint.R, atoms_config, project_measured_rotations_,
2521 : Eigen::MatrixXd::Identity(midpoint.R.cols(),
2522 midpoint.R.cols());
2523 Eigen::MatrixXd directions(midpoint.R.cols(), stencils.size());
2524 Eigen::MatrixXd actions(midpoint.R.cols(), stencils.size());
2525 for (std::size_t j = 0; j < stencils.size(); ++j) {
2526 directions.col(j) = stencils[j].cartesian;
2527 actions.col(j) = stencils[j].refined_action.size() > 0
2528 ? stencils[j].refined_action
2529 : stencils[j].coarse_action;
2530 }
2531 const Eigen::MatrixXd rotation_actions =
2533 midpoint.R, midpoint.G, directions, actions,
2534 rotation_physical,
2536 if (rotation_actions.cols() == rotation_physical.cols() &&
2537 rotation_actions.rows() == midpoint.R.cols() &&
2538 rotation_actions.allFinite()) {
2539 measured_rotation_reference_ = midpoint;
2540 measured_rotation_separation_ = dimer_sep;
2541 measured_rotation_physical_ = rotation_physical;
2542 measured_rotation_basis_ = rotation_physical;
2543 measured_rotation_actions_ = rotation_actions;
2544 }
2545 if (measured_mode) {
2546 *measured_mode = (physical * measured_lowest_mode).transpose();
2547 if (measured_mode->row(0).dot(orientation.row(0)) < 0.0)
2548 *measured_mode *= -1.0;
2549 }
2550 index_search_directions_.resize(0, 0);
2551 return true;
2552 }
2553 unstable = std::move(measured_negative_pair);
2554 escape = unstable.col(1);
2555 }
2556
2557 index_search_directions_ = unstable;
2558 if (midpoint.G.row(0).dot(escape) < 0.0) escape = -escape;
2559 const double step = std::isfinite(transition_param.max_step_length) &&
2560 transition_param.max_step_length > 0.0
2561 ? transition_param.max_step_length
2562 : separation;
2563 if (midpoint.E.size() == 0 || !std::isfinite(midpoint.E(0, 0)))
2564 return false;
2565 // The order-one session follows the surrogate after a full fit on the
2566 // measured curvature rows. Its endpoint is measured and retained for
2567 // ordinary posterior conditioning. A failed surrogate escape uses a
2568 // measured descent whose rows enter the same refit policy.
2569 if (escapeByOrderOneSaddleSession(midpoint, potential, recovery)) {
2570 log_man << "Second negative mode: measured the order-one surrogate "
2571 "escape at "
2572 << (recovery.R - midpoint.R).norm()
2573 << " displacement for GP conditioning.\n";
2574 return false;
2575 }
2576 // Preserve unconsumed curvature. Active refits check every new descent
2577 // row; a policy using one witness requires a full fit of the escape.
2578 curvature_requires_full_refit_ = curvature_requires_full_refit_ ||
2579 !gpr_model->activePosteriorRefitsEnabled();
2580 // Negative curvature supplies an escape direction; the measured energy
2581 // sets its length. Halving finds the first downhill trial down to
2582 // separation*1e-3, the same floor as the higher-order restart, and the
2583 // displacement then doubles while the measured energy keeps falling.
2584 // A weak negative mode (a curvature of -0.03 eV/A^2 descends by 4e-5 eV
2585 // over 0.05 A) cannot be represented by a refit after one short step,
2586 // and the dimer climbs back to the point it left; walking the mode on
2587 // the true surface ends where its curvature has turned, and the retained
2588 // rows span the mode. An all-uphill search is not an escape.
2589 descendMeasuredNegativeMode(midpoint, escape, separation, step, potential,
2590 recovery);
2591 return false;
2592}
2593
2594bool AtomicDimer::descendMeasuredNegativeMode(const gpr::Observation& midpoint,
2595 const Eigen::VectorXd& escape,
2596 double separation, double step,
2597 pot::PotentialWrapper& potential,
2598 gpr::Observation& recovery)
2599{
2600 int rank = 0;
2601 int nprocs = 1;
2602 mpiWorld(rank, nprocs);
2603 separation = broadcastDouble(separation);
2604 step = broadcastDouble(step);
2605 // Rank zero owns the geometry and line-search decisions. Every rank
2606 // enters the same oracle collectives even when its local mode or
2607 // retraction would differ at roundoff.
2608 const auto propose = [&](double displacement, const gpr::Coord& previous,
2609 gpr::Observation& observation) {
2610 bool retracted = true;
2611 if (rank == 0) {
2612 observation.R = midpoint.R + displacement * escape.transpose();
2613 gpr::LBFGSInfo step_info;
2614 // True curvature and measured energy own this step. The GP
2615 // radius controls surrogate proposals only.
2616 (void)limitTranslationGeometry(midpoint.R, step_info,
2617 observation.R);
2618 if (midpoint.R.cols() >= 6 &&
2619 !retractTranslationGeometry(midpoint.R, observation.R)) {
2620 observation.R = midpoint.R;
2621 retracted = false;
2622 } else {
2623 (void)limitTranslationGeometry(midpoint.R, step_info,
2624 observation.R);
2625 }
2626 }
2627 broadcastDenseMatrix(observation.R);
2628 return broadcastBool(retracted && observation.R.allFinite() &&
2629 !dimerGeometriesCoincide(observation.R, previous));
2630 };
2631 const auto downhill = [](const gpr::Observation& observation,
2632 const gpr::Observation& reference) {
2633 return broadcastBool(observation.E.size() > 0 &&
2634 std::isfinite(observation.E(0, 0)) &&
2635 observation.G.allFinite() &&
2636 observation.E(0, 0) < reference.E(0, 0));
2637 };
2638 const auto measure_retained = [&](gpr::Observation& observation) {
2639 evaluateAccurateEnergyAndForce(observation, potential,
2640 /*apply_emd_dedup=*/false);
2641 broadcastObservation(observation);
2642 synchronizeObservedData();
2643 };
2644 bool escaped = false;
2645 last_escape_descent_calls_ = 0;
2646 for (double length = step; !escaped && length > separation * 1e-3;
2647 length *= 0.5) {
2648 bool distinct_trial = false;
2649 for (double sign: {-1.0, 1.0}) {
2650 gpr::Observation trial;
2651 if (!propose(sign * length, midpoint.R, trial)) continue;
2652 distinct_trial = true;
2653 measure_retained(trial);
2654 if (downhill(trial, midpoint)) {
2655 recovery = trial;
2656 escaped = true;
2657 for (double next = 2.0 * length;; next *= 2.0) {
2658 gpr::Observation further;
2659 if (!propose(sign * next, recovery.R, further)) break;
2660 measure_retained(further);
2661 ++last_escape_descent_calls_;
2662 if (!downhill(further, recovery)) break;
2663 recovery = further;
2664 }
2665 break;
2666 }
2667 }
2668 if (!distinct_trial) break;
2669 }
2670 if (!escaped) {
2671 recovery = midpoint;
2672 log_man << "Second negative mode: every measured trial was uphill; "
2673 "no escape retained.\n";
2674 return false;
2675 }
2676 if (measured_trial_trust_ &&
2677 !dimerGeometriesCoincide(recovery.R, midpoint.R)) {
2678 // The measured displacement supplies a local spread for the full
2679 // refit at its new anchor. Subsequent GP proposals retain their
2680 // force-agreement acceptance and radius contraction.
2681 const double spread = (recovery.R - midpoint.R).norm();
2682 if (measured_trial_trust_->tau() * spread >
2683 measured_trial_trust_->radius())
2684 measured_trial_trust_->initFromTrainingSpread(spread);
2685 setMeasuredTrialAnchor(recovery.R);
2686 }
2687 log_man << "Second negative mode: retaining the measured escape at "
2688 << (recovery.R - midpoint.R).norm()
2689 << " displacement for a full GP refit.\n";
2690 return true;
2691}
2692
2693rgsaddle_status_t AtomicDimer::orderOneSurface(
2694 void* user, gpr_rgsaddle_surface_request_t* request)
2695{
2696 auto* dimer = static_cast<AtomicDimer*>(user);
2697 if (dimer == nullptr || request == nullptr || request->n_images != 1)
2698 return RGSADDLE_NULL_SESSION;
2699 const Eigen::Index dof = 3 * request->n_atoms;
2700 gpr::Observation point;
2701 point.R.resize(1, dof);
2702 for (Eigen::Index k = 0; k < dof; ++k)
2703 point.R(0, k) = request->positions[k];
2704 dimer->calculateApproximatePotential(point);
2705 if (point.E.size() == 0 || point.G.cols() != dof || !point.G.allFinite())
2706 return RGSADDLE_NULL_SESSION;
2707 request->energies[0] = point.E(0, 0);
2708 for (Eigen::Index k = 0; k < dof; ++k)
2709 request->gradients[k] = point.G(0, k);
2710 return RGSADDLE_OK;
2711}
2712
2713bool AtomicDimer::escapeByOrderOneSaddleSession(
2714 const gpr::Observation& midpoint, pot::PotentialWrapper& potential,
2715 gpr::Observation& recovery)
2716{
2717 if (!kappa_dimer_client_) {
2718 auto client = std::make_unique<gpr::neb::RgsaddleClient>();
2719 if (!client->load()) return false;
2720 kappa_dimer_client_ = std::move(client);
2721 }
2722 auto& client = *kappa_dimer_client_;
2723 if (!client.hasSellaSaddle() || midpoint.R.rows() != 1 ||
2724 gpr_model == nullptr)
2725 return false;
2726 // The surrogate carries the measured pair once it is refit on those
2727 // rows; the order-one search then runs on the surrogate, and only the
2728 // point it returns is measured.
2729 curvature_requires_full_refit_ = true;
2730 refitGPRModel(false, midpoint, gpr::Coord(), false);
2731 const Eigen::Index dof = midpoint.R.cols();
2732 const int64_t n_atoms = static_cast<int64_t>(dof / 3);
2733 Eigen::VectorXd masses = Eigen::VectorXd::Ones(n_atoms);
2734 if (atoms_config.atomic_masses.size() == n_atoms)
2735 masses = atoms_config.atomic_masses;
2736 const Eigen::VectorXd start = midpoint.R.row(0).transpose();
2737 // The restricted-step partitioned RFO starts from the measured
2738 // Hessian and updates it by Bofill from the surrogate gradients.
2739 // Without that session or that Hessian the older order-one session,
2740 // which builds its own, is used.
2741 const bool measured_hessian =
2742 client.hasIndex1() && escape_hessian_.rows() == dof &&
2743 escape_hessian_.cols() == dof && escape_hessian_.allFinite();
2744 gpr::neb::RgSellaSaddle fallback;
2745 gpr::neb::RgsaddleClient::Index1 index1 = nullptr;
2746 if (measured_hessian) {
2747 Eigen::VectorXd coordinate_masses(dof);
2748 for (Eigen::Index k = 0; k < dof; ++k)
2749 coordinate_masses(k) = masses(k / 3);
2750 // Row-major, as the C entry point reads it.
2751 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
2752 hessian = 0.5 * (escape_hessian_ + escape_hessian_.transpose());
2754 config.version.major = GPR_RGSADDLE_ABI_MAJOR;
2755 config.update = 1;
2756 config.mode = 1;
2757 config.trust_radius = std::isfinite(transition_param.max_step_length) &&
2758 transition_param.max_step_length > 0.0
2759 ? transition_param.max_step_length
2760 : 0.1;
2761 config.force_tol = stop_citeria_dimer.force;
2762 config.fd_dr = std::max(dimer_sep, 1.0e-3);
2763 index1 = client.index1Create(&config, n_atoms, start.data(),
2764 hessian.data(), coordinate_masses.data());
2765 }
2766 if (index1 == nullptr &&
2767 !fallback.bind(client, n_atoms, start.data(), masses.data(),
2768 stop_citeria_dimer.force, /*force_gate=*/2,
2769 /*order=*/1))
2770 return false;
2771 const auto session_step = [&](gpr_rgsaddle_report_t& out) {
2772 if (index1 != nullptr)
2773 return client.index1Step(index1, &AtomicDimer::orderOneSurface,
2774 this, &out) == 0;
2775 return fallback.step(&AtomicDimer::orderOneSurface, this, out);
2776 };
2777 const auto session_position = [&](double* out) {
2778 if (index1 != nullptr) return client.index1Position(index1, out) == 0;
2779 return fallback.position(out);
2780 };
2781 gpr_rgsaddle_report_t report{};
2782 // The surrogate is a model of the surface only near its training rows.
2783 // Each iterate is checked against the same interatomic-distance trust
2784 // test every surrogate translation of the dimer passes; the search
2785 // stops at the last iterate inside it, and that point is measured.
2786 // The number of physical directions bounds the iteration.
2787 Eigen::VectorXd position(dof);
2788 Eigen::VectorXd accepted = start;
2789 for (Eigen::Index step = 0; step < dof; ++step) {
2790 if (!session_step(report) || !session_position(position.data()) ||
2791 !position.allFinite())
2792 break;
2793 gpr::Coord candidate(1, dof);
2794 candidate.row(0) = position.transpose();
2795 gpr::Index_t outside = 0;
2796 if (isInterAtomicDistanceTooBig(candidate, all_obs.R, outside)) break;
2797 accepted = position;
2798 if (report.status == 1 || report.max_force <= stop_citeria_dimer.force)
2799 break;
2800 }
2801 if (index1 != nullptr) client.index1Free(index1);
2802 escape_hessian_.resize(0, 0);
2803 recovery.R.resize(1, dof);
2804 recovery.R.row(0) = accepted.transpose();
2805 if (dimerGeometriesCoincide(recovery.R, midpoint.R)) return false;
2806 evaluateAccurateEnergyAndForce(recovery, potential,
2807 /*apply_emd_dedup=*/false);
2808 broadcastObservation(recovery);
2809 synchronizeObservedData();
2810 return recovery.G.allFinite();
2811}
2812
2814 const Eigen::MatrixXd& cartesian_hessian, const Eigen::VectorXd& kick,
2815 const gpr::Observation& measured_rows, pot::PotentialWrapper& potential)
2816{
2817 const Eigen::VectorXd final_position = getFinalCoordOfMidPoint();
2818 const Eigen::Index dof = final_position.size();
2819 if (dof == 0 || cartesian_hessian.rows() != dof ||
2820 cartesian_hessian.cols() != dof || kick.size() != dof ||
2821 !cartesian_hessian.allFinite() || !(kick.norm() > 0.0) ||
2822 gpr_model == nullptr)
2823 return false;
2824 if (measured_rows.R.rows() > 0 && measured_rows.G.allFinite()) {
2825 // The rows carry absolute oracle energies; the training set is
2826 // referenced to the search's zero level.
2827 gpr::Observation rows = measured_rows;
2828 aux::ProblemSetUp problem_setup;
2829 problem_setup.cutOffEnergy(E_zero_level, rows.E);
2830 retainStructuralObservation(rows);
2831 synchronizeObservedData();
2832 }
2833 gpr::Observation midpoint;
2834 midpoint.R.resize(1, dof);
2835 midpoint.R.row(0) = final_position.transpose();
2836 curvature_requires_full_refit_ = true;
2837 refitGPRModel(false, midpoint, gpr::Coord(), false);
2838 const double separation = std::max(dimer_sep, 1.0e-3);
2839 const Eigen::VectorXd direction = kick.normalized();
2840 gpr::Observation plus_side, minus_side;
2841 plus_side.R = midpoint.R + separation * direction.transpose();
2842 minus_side.R = midpoint.R - separation * direction.transpose();
2843 calculateApproximatePotential(plus_side);
2844 calculateApproximatePotential(minus_side);
2845 gpr::Observation start = midpoint;
2846 start.R =
2847 plus_side.E(0, 0) <= minus_side.E(0, 0) ? plus_side.R : minus_side.R;
2848 escape_hessian_ = 0.5 * (cartesian_hessian + cartesian_hessian.transpose());
2849 gpr::Observation recovery;
2850 // The session refits again; the rows above are already retained.
2851 if (!escapeByOrderOneSaddleSession(start, potential, recovery) ||
2852 dimerGeometriesCoincide(recovery.R, midpoint.R)) {
2853 // A prefit consumes the curvature even when the surrogate stays at
2854 // the midpoint. Without active row checks, the escape needs a full fit.
2855 curvature_requires_full_refit_ =
2856 curvature_requires_full_refit_ ||
2857 !gpr_model->activePosteriorRefitsEnabled();
2858 // A surrogate that still places the mode positive pulls the
2859 // session back. The escape is then measured: halving finds the
2860 // first downhill trial along the mode, and the displacement
2861 // doubles while the measured energy keeps falling.
2862 gpr::Observation centre;
2863 centre.R = midpoint.R;
2864 evaluateAccurateEnergyAndForce(centre, potential,
2865 /*apply_emd_dedup=*/false);
2866 if (centre.E.size() == 0 || !std::isfinite(centre.E(0, 0)))
2867 return false;
2868 const double step = std::isfinite(transition_param.max_step_length) &&
2869 transition_param.max_step_length > 0.0
2870 ? transition_param.max_step_length
2871 : separation;
2872 const double sign_choice =
2873 plus_side.E(0, 0) <= minus_side.E(0, 0) ? 1.0 : -1.0;
2874 bool escaped = false;
2875 recovery = centre;
2876 // Halving stops once the trial coincides with the midpoint in the
2877 // stored coordinates.
2878 for (double length = step; !escaped; length *= 0.5) {
2879 bool resolved = false;
2880 for (double sign: {sign_choice, -sign_choice}) {
2881 gpr::Observation trial;
2882 trial.R = midpoint.R + sign * length * direction.transpose();
2884 midpoint.R))
2885 continue;
2886 resolved = true;
2887 evaluateAccurateEnergyAndForce(trial, potential,
2888 /*apply_emd_dedup=*/false);
2889 if (trial.E.size() > 0 && trial.G.allFinite() &&
2890 trial.E(0, 0) < centre.E(0, 0)) {
2891 recovery = trial;
2892 escaped = true;
2893 for (double next = 2.0 * length;; next *= 2.0) {
2894 gpr::Observation further;
2895 further.R =
2896 midpoint.R + sign * next * direction.transpose();
2897 gpr::Index_t outside = 0;
2898 if (isInterAtomicDistanceTooBig(further.R, all_obs.R,
2899 outside))
2900 break;
2901 evaluateAccurateEnergyAndForce(
2902 further, potential, /*apply_emd_dedup=*/false);
2903 if (!(further.E.size() > 0 && further.G.allFinite() &&
2904 further.E(0, 0) < recovery.E(0, 0)))
2905 break;
2906 recovery = further;
2907 }
2908 break;
2909 }
2910 }
2911 if (!resolved) break;
2912 }
2913 if (!escaped) return false;
2914 broadcastObservation(recovery);
2915 synchronizeObservedData();
2916 }
2917 middle_point_init = recovery;
2918 retainMeasuredNegativeSubspace(cartesian_hessian, recovery.R);
2919 if (getFinalOrientation().size() == dof)
2920 orient_init = getFinalOrientation();
2921 log_man << "Higher-order restart: complete stencil refused the "
2922 "converged midpoint; order-one search moved "
2923 << (recovery.R - midpoint.R).norm() << ".\n";
2924 return true;
2925}
2926
2928{
2929 const Eigen::VectorXd origin = getFinalCoordOfMidPoint();
2930 const Eigen::Index dof = origin.size();
2931 if (dof < 6 || dof % 3 != 0 || gpr_model == nullptr || !origin.allFinite())
2932 return {};
2933 gpr::Coord R(1, dof);
2934 R.row(0) = origin.transpose();
2935 Eigen::MatrixXd hessian;
2936 if (!gpr_model->calculateMeanHessian(R, hessian)) return {};
2937 return 0.5 * (hessian + hessian.transpose());
2938}
2939
2941 const Eigen::MatrixXd& cartesian_hessian, pot::PotentialWrapper& potential,
2942 double resolution)
2943{
2944 return refineSaddleFromMeasuredHessian(cartesian_hessian, potential,
2945 nullptr, resolution);
2946}
2947
2949 const Eigen::MatrixXd& cartesian_hessian, pot::PotentialWrapper& potential,
2950 gpr::Observation* raw_candidate, double resolution, bool complete_stencil)
2951{
2952 if (raw_candidate != nullptr) *raw_candidate = gpr::Observation();
2953 last_refinement_reached_index_one_ = false;
2954 // A model curvature inside the resolution of the measurement that
2955 // seeded the model carries no sign of its own.
2956 const double unresolved =
2957 std::isfinite(resolution) && resolution > 0.0 ? resolution : 0.0;
2958 const Eigen::VectorXd origin = getFinalCoordOfMidPoint();
2959 const Eigen::Index dof = origin.size();
2960 if (dof < 6 || dof % 3 != 0 || cartesian_hessian.rows() != dof ||
2961 cartesian_hessian.cols() != dof || !cartesian_hessian.allFinite() ||
2962 gpr_model == nullptr)
2963 return false;
2964 const Eigen::VectorXd masses =
2966 Eigen::VectorXd root(dof);
2967 for (Eigen::Index k = 0; k < dof; ++k)
2968 root(k) = std::sqrt(masses(k / 3));
2969 const Eigen::MatrixXd inverse_mass_weight =
2970 root.cwiseInverse() * root.cwiseInverse().transpose();
2971 const Eigen::MatrixXd cartesian_model =
2972 0.5 * (cartesian_hessian + cartesian_hessian.transpose());
2973 const auto vibrational = [&](const Eigen::VectorXd& positions) {
2974 gpr::Coord geometry(1, positions.size());
2975 geometry.row(0) = positions.transpose();
2977 atoms_config);
2978 };
2979 // The model lives on all 3N mass-weighted coordinates; each step
2980 // projects it onto the vibrational complement of rigid motion at the
2981 // current geometry, so the rotation a long walk accumulates against a
2982 // basis fixed at the start does not appear as a flat mode.
2983 Eigen::MatrixXd model = cartesian_model.cwiseProduct(inverse_mass_weight);
2984 if (secant_config_.seed_curvature) {
2985 const gpr::optim::SecantSeedStatus seeded =
2987 model, secant_hessian_, inverse_mass_weight,
2990 std::cout << "[secant-seed] measured walk keeps the surrogate "
2991 "Hessian: "
2992 << gpr::optim::secantSeedStatusName(seeded) << "\n";
2993 }
2994 // Probes stay out of the training set; every rank uses the root's
2995 // measurement, so every rank takes the same steps.
2996 const auto probe = [&](const Eigen::VectorXd& position,
2998 gpr::Observation* raw = nullptr) {
2999 if (oracleBudgetSpent()) return false;
3001 out.R.resize(1, dof);
3002 out.R.row(0) = position.transpose();
3003 const bool ok = evaluateAccurateProbe(out, potential, raw);
3004 broadcastObservation(out);
3005 if (raw != nullptr) broadcastObservation(*raw);
3006 return ok && out.E.size() == 1 && std::isfinite(out.E(0, 0)) &&
3007 out.G.rows() == 1 && out.G.cols() == dof && out.G.allFinite();
3008 };
3009 // The terminal midpoint holds a measured energy and gradient in the
3010 // same energy gauge as each probe. Keep that measurement at unchanged
3011 // geometry and use the root's row on every rank.
3012 gpr::Observation current = middle_point_final;
3013 gpr::Observation current_raw;
3014 broadcastObservation(current);
3015 const bool measured_origin =
3016 current.R.rows() == 1 && current.R.cols() == dof &&
3017 current.R.allFinite() &&
3018 (current.R.row(0).transpose().array() == origin.array()).all() &&
3019 current.E.size() == 1 && current.E.allFinite() &&
3020 current.G.rows() == 1 && current.G.cols() == dof &&
3021 current.G.allFinite();
3022 if (!measured_origin && !probe(origin, current)) return false;
3023 const double start_energy = current.E(0, 0);
3024 double force = forceNormForConvergence(current.R.row(0), current.G.row(0));
3025 const double tolerance = stop_citeria_dimer.force;
3026 const double limit = std::isfinite(transition_param.max_step_length) &&
3027 transition_param.max_step_length > 0.0
3028 ? transition_param.max_step_length
3029 : std::max(dimer_sep, 1.0e-3);
3030 // The Cartesian radius starts at the translation limit. A Cartesian
3031 // step longer than that along a torsion stretches the bonds of the
3032 // turning fragment at second order, which a quadratic model carried
3033 // along the walk does not predict; the measured energy then departs
3034 // from the model. The energy-model score contracts and restores the
3035 // radius under the scale-free trust-region thresholds. That stretch
3036 // is set by how far each atom of the fragment moves, not by how many
3037 // atoms move. On an inferred model the limit bounds the whole step.
3038 // For a Hessian measured on every coordinate it bounds the largest
3039 // atomic displacement of the step, so the radius may reach the
3040 // length at which the most displaced atom moves by the limit.
3041 //
3042 // That atomic bound is itself a trust region and follows the same
3043 // rule. A walk down a torsion of 30 cm^-1 covers ångströms for a few
3044 // hundredths of an eV; at the fixed bound it took 168 measured steps
3045 // with none refused. A step that sat on the bound, whose energy the
3046 // model predicted and whose measured gradient the model reproduced to
3047 // within the force tolerance, doubles the bound; a refused step halves
3048 // it back toward the limit. The gradient is the witness on a flat mode,
3049 // where the energy change is below its own resolution.
3050 const gpr::ScaleFreeTrustConfig trust_config;
3051 double radius = limit;
3052 double cap_scale = 1.0;
3053 int cap_expansions = 0;
3054 log_man << "Measured partitioned RFO from the stencil Hessian: " << dof
3055 << " coordinates, step limit " << limit << ", radius " << radius
3056 << ", start energy " << start_energy << ", force " << force
3057 << ", tolerance " << tolerance << ", saddle energy floor "
3058 << (std::isfinite(saddle_energy_floor_) && E_zero_level.size() > 0
3059 ? saddle_energy_floor_ - E_zero_level(0, 0)
3060 : std::numeric_limits<double>::quiet_NaN())
3061 << " (relative to the zero level).\n";
3062 bool converged = false;
3063 bool abandoned = false;
3064 bool collapsed = false;
3065 Eigen::Index steps = 0;
3066 Eigen::Index rejected = 0;
3067 Eigen::Index expansions = 0;
3068 Eigen::Index refreshes = 0;
3069 Eigen::Index pair_checks = 0;
3070 bool pair_refused = false;
3071 // A rejected step proved the model wrong at the current point; the
3072 // steering modes are measured there before the next proposal.
3073 bool refresh_due = false;
3074 bool measured_here = false;
3075 Eigen::VectorXd lowest;
3076 const auto bofill = [&](const Eigen::VectorXd& s,
3077 const Eigen::VectorXd& y) {
3080 };
3081 // Each trial is one oracle call, as each outer iteration of the dimer
3082 // is; the walk takes the dimer's outer-iteration limit and its oracle
3083 // budget.
3084 for (Eigen::Index trials = 0;
3085 gpr::iterationAllowedByLimit(trials, max_iter_new_pairs.outer) &&
3086 !oracleBudgetSpent();
3087 ++trials) {
3088 const Eigen::VectorXd x = current.R.row(0).transpose();
3089 const Eigen::MatrixXd basis = vibrational(x);
3090 const Eigen::Index n = basis.cols();
3091 if (n < 2) break;
3092 Eigen::VectorXd curvature;
3093 Eigen::MatrixXd modes;
3094 const auto resolve = [&]() {
3095 const Eigen::MatrixXd reduced = basis.transpose() * model * basis;
3096 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> spectrum(
3097 0.5 * (reduced + reduced.transpose()));
3098 if (spectrum.info() != Eigen::Success) return false;
3099 curvature = spectrum.eigenvalues();
3100 modes = spectrum.eigenvectors();
3101 // The sign of an eigenvector is the solver's choice; a step
3102 // along a mode with no gradient component takes it. The entry
3103 // of largest magnitude is made positive, so every rank and
3104 // every linear-algebra build walks the same side.
3105 for (Eigen::Index k = 0; k < modes.cols(); ++k) {
3106 Eigen::Index pivot = 0;
3107 modes.col(k).cwiseAbs().maxCoeff(&pivot);
3108 if (modes(pivot, k) < 0.0) modes.col(k) *= -1.0;
3109 }
3110 return true;
3111 };
3112 if (!resolve()) break;
3113 // The walk steers by its two lowest modes. Measuring the Hessian
3114 // action along each of them, one oracle call per mode at the dimer
3115 // separation, corrects the model along those directions. Every
3116 // further mode whose curvature lies inside the resolution of the
3117 // seeding measurement is measured too: a secant model carried over
3118 // a long descent holds the sign of such a mode by inference alone,
3119 // and an inferred index-one point costs a complete stencil.
3120 const auto refresh = [&]() {
3121 // Without a dimer separation there is no displacement to
3122 // measure a Hessian action at; the secant model stands.
3123 if (!(dimer_sep > 0.0)) {
3124 refresh_due = false;
3125 measured_here = true;
3126 return true;
3127 }
3128 std::vector<Eigen::Index> columns{0, 1};
3129 for (Eigen::Index k = 2; k < n; ++k)
3130 if (std::abs(curvature(k)) <= unresolved) columns.push_back(k);
3131 const Eigen::Index measured_count =
3132 static_cast<Eigen::Index>(columns.size());
3133 Eigen::MatrixXd measured_basis(dof, measured_count);
3134 Eigen::MatrixXd measured_actions(dof, measured_count);
3135 for (Eigen::Index j = 0; j < measured_count; ++j) {
3136 const Eigen::Index k = columns[static_cast<std::size_t>(j)];
3137 const Eigen::VectorXd mode = basis * modes.col(k);
3138 Eigen::VectorXd direction = mode.cwiseQuotient(root);
3139 const double norm = direction.norm();
3140 if (!(norm > 0.0) || !std::isfinite(norm)) return false;
3141 direction *= dimer_sep / norm;
3142 gpr::Observation action;
3143 if (!probe(x + direction, action)) return false;
3144 const Eigen::VectorXd s = direction.cwiseProduct(root);
3145 const Eigen::VectorXd y = (action.G.row(0) - current.G.row(0))
3146 .transpose()
3147 .cwiseQuotient(root);
3148 const double length = mode.dot(s);
3149 if (!y.allFinite() || !(length > 0.0) || !std::isfinite(length))
3150 return false;
3151 measured_basis.col(j) = mode;
3152 measured_actions.col(j) = y / length;
3153 }
3154 // Fresh actions constrain their measured block and cross terms.
3155 // The unmeasured block retains its model curvature.
3156 Eigen::MatrixXd refreshed = gpr::optim::completeMeasuredHessian(
3157 model, measured_basis, measured_actions);
3158 if (refreshed.rows() != dof) return false;
3159 model = std::move(refreshed);
3160 refresh_due = false;
3161 measured_here = true;
3162 ++refreshes;
3163 if (!resolve()) return false;
3164 log_man << "Measured partitioned RFO: refreshed the model along "
3165 << columns.size() << " modes after step " << steps
3166 << "; curvatures now " << curvature(0) << " "
3167 << curvature(1) << ".\n";
3168 return true;
3169 };
3170 // An index-one model with the measured force inside the tolerance
3171 // ends the refinement; the complete stencil then judges the point.
3172 const auto index_one_candidate = [&]() {
3173 return steps > 0 && curvature(0) < 0.0 && curvature(1) > 0.0 &&
3174 force <= tolerance;
3175 };
3176 // The two lowest curvatures of a secant model carried over a long
3177 // descent are measured, not inferred, after a rejected step and
3178 // before the complete stencil is spent on an index-one point.
3179 if ((refresh_due || index_one_candidate()) && !measured_here) {
3180 if (!refresh()) break;
3181 }
3182 lowest = basis * modes.col(0);
3183 if (index_one_candidate()) {
3184 // A walk seeded by a complete stencil ends at a complete
3185 // stencil, which signs a weak mode by a four-point difference
3186 // along it. The walk meets a zero of its second curvature
3187 // first, where a one-sided action cannot sign it. The same
3188 // four-point difference along the two steering modes costs
3189 // eight calls, and a second curvature it finds negative
3190 // beyond its truncation error keeps the walk going instead of
3191 // spending the stencil on a point the stencil would refuse.
3192 // The stencil signs every mode inside its resolution, not the
3193 // steering pair alone: a floppy molecule has several, and the
3194 // walk has ended on a positive pair while another weak mode was
3195 // negative, which the stencil then refused. Each further weak
3196 // mode of the model takes the same four-point difference, four
3197 // calls where the refused stencil takes two per coordinate.
3198 if (unresolved > 0.0 && dimer_sep > 0.0) {
3199 std::vector<Eigen::Index> checked{0, 1};
3200 for (Eigen::Index k = 2; k < n; ++k)
3201 if (std::abs(curvature(k)) <= unresolved)
3202 checked.push_back(k);
3203 const Eigen::Index checked_count =
3204 static_cast<Eigen::Index>(checked.size());
3205 Eigen::MatrixXd steering(dof, checked_count);
3206 for (Eigen::Index j = 0; j < checked_count; ++j)
3207 steering.col(j) =
3208 basis * modes.col(checked[static_cast<std::size_t>(j)]);
3209 bool sampled = true;
3210 const auto sample = [&](const Eigen::MatrixXd& points) {
3211 Eigen::MatrixXd rows(points.cols(), dof);
3212 for (Eigen::Index j = 0; sampled && j < points.cols();
3213 ++j) {
3215 sampled = probe(points.col(j), at);
3216 if (sampled) rows.row(j) = at.G.row(0);
3217 }
3218 return sampled ? rows : Eigen::MatrixXd();
3219 };
3220 const auto refined = gpr::optim::refineWeakModes(
3221 x, masses, steering, dimer_sep, sample);
3222 if (!sampled) break;
3223 if (refined.valid &&
3224 refined.curvatures.size() == checked_count &&
3225 refined.action.allFinite()) {
3226 Eigen::MatrixXd measured =
3228 refined.action);
3229 if (measured.rows() == dof && measured.allFinite()) {
3230 model = std::move(measured);
3231 measured_here = true;
3232 ++pair_checks;
3233 if (!resolve()) break;
3234 lowest = basis * modes.col(0);
3235 }
3236 // The lowest of the measured curvatures beyond the
3237 // first decides: the second steering mode or a weak one.
3238 const double lowest_other =
3239 refined.curvatures.tail(checked_count - 1).minCoeff();
3240 const bool refused =
3241 std::isfinite(refined.error) &&
3242 lowest_other < -std::max(refined.error, 0.0);
3243 log_man << "Measured partitioned RFO: four-point "
3244 "curvatures of the steering pair after step "
3245 << steps << " are " << refined.curvatures(0) << " "
3246 << refined.curvatures(1) << " (error "
3247 << refined.error << "; " << checked_count - 2
3248 << " further weak mode(s), lowest of all but the "
3249 "first "
3250 << lowest_other << "); "
3251 << (refused ? "one beyond the first is negative, "
3252 "the walk continues.\n"
3253 : "none beyond the first is "
3254 "negative.\n");
3255 if (refused) pair_refused = true;
3256 }
3257 }
3258 // The model now holds the measured actions of the pair with
3259 // their cross terms, and its second curvature can lie below
3260 // the curvature measured along the earlier direction. The
3261 // walk ends only when that model is still index one: a pair
3262 // measured positive along an inexact direction has ended the
3263 // walk where the complete stencil still found a negative
3264 // second mode.
3265 if (!pair_refused && index_one_candidate()) {
3266 converged = true;
3267 break;
3268 }
3269 pair_refused = false;
3270 }
3271 // Both augmented partitions share a scaling chosen on the
3272 // Cartesian radius, retaining their stationarity equations
3273 // when the unrestricted step is too long.
3274 const Eigen::VectorXd gradient =
3275 basis.transpose() *
3276 current.G.row(0).transpose().cwiseQuotient(root);
3277 const Eigen::VectorXd projected = modes.transpose() * gradient;
3278 const Eigen::MatrixXd weighted_modes = basis * modes;
3279 Eigen::MatrixXd cartesian_modes = weighted_modes;
3280 for (Eigen::Index k = 0; k < dof; ++k)
3281 cartesian_modes.row(k) /= root(k);
3283 curvature, projected, cartesian_modes, radius);
3284 if (!proposal.valid) break;
3285 // Length of a step along the proposal at which its most displaced
3286 // atom moves by the translation limit.
3287 const auto atomic_cap = [&](const Eigen::VectorXd& step) {
3288 double largest = 0.0;
3289 for (Eigen::Index atom = 0; atom < dof / 3; ++atom)
3290 largest = std::max(largest, step.segment(3 * atom, 3).norm());
3291 const double length = step.norm();
3292 return largest > 0.0 && std::isfinite(largest)
3293 ? cap_scale * limit * length / largest
3294 : cap_scale * limit;
3295 };
3296 double radius_cap = limit;
3297 if (complete_stencil) {
3298 radius_cap = atomic_cap(proposal.cartesian_step);
3299 if (proposal.cartesian_step.norm() > radius_cap) {
3300 // The direction changed and an atom would pass the limit.
3301 radius = radius_cap;
3303 curvature, projected, cartesian_modes, radius);
3304 if (!proposal.valid) break;
3305 radius_cap =
3306 std::min(radius_cap, atomic_cap(proposal.cartesian_step));
3307 }
3308 }
3309 const bool clamped = proposal.boundary;
3310 const Eigen::VectorXd weighted = weighted_modes * proposal.eigen_step;
3311 const Eigen::VectorXd& displacement = proposal.cartesian_step;
3312 // Work at the requested force accuracy sets the model-error
3313 // allowance of the energy score. The dual displacement norm bounds
3314 // that work when the error of every atom lines up with its step;
3315 // summed over the atoms of a molecule it grows with their number
3316 // and, on a long step, absorbs a model that predicts the wrong sign
3317 // of the energy change, so the walk accepted and widened steps whose
3318 // force rose fortyfold. Errors of independent atoms add in
3319 // quadrature: the allowance is the tolerance times the Euclidean
3320 // length of the step.
3321 const Eigen::VectorXd predicted_change = model * weighted;
3322 const double predicted_energy_change =
3323 current.G.row(0).transpose().cwiseQuotient(root).dot(weighted) +
3324 0.5 * weighted.dot(predicted_change);
3325 const double energy_floor = tolerance * displacement.norm();
3326 gpr::Observation trial;
3327 gpr::Observation trial_raw;
3328 if (!probe(x + displacement, trial,
3329 raw_candidate != nullptr ? &trial_raw : nullptr))
3330 break;
3331 const double next =
3332 forceNormForConvergence(trial.R.row(0), trial.G.row(0));
3333 const Eigen::RowVectorXd cartesian_change =
3334 trial.G.row(0) - current.G.row(0);
3335 const Eigen::VectorXd change =
3336 cartesian_change.transpose().cwiseQuotient(root);
3337 const Eigen::RowVectorXd cartesian_prediction =
3338 predicted_change.cwiseProduct(root).transpose();
3339 if (!cartesian_change.allFinite() || !cartesian_prediction.allFinite())
3340 break;
3341 const double agreement = gpr::optim::gradientChangeAgreement(
3342 cartesian_change, cartesian_prediction);
3343 // Compare measured and modelled energy changes over the clamped
3344 // step.
3345 const double measured_energy_change = trial.E(0, 0) - current.E(0, 0);
3346 // The score is the two-sided defect of the model beyond that
3347 // allowance, relative to the predicted change; a signed ratio of
3348 // the changes would accept a step whose maximized mode fell while
3349 // the transverse modes fell further.
3350 const double defect = std::max(
3351 0.0, std::abs(measured_energy_change - predicted_energy_change) -
3352 energy_floor);
3353 const double ratio =
3354 defect == 0.0 ? 1.0
3355 : std::abs(predicted_energy_change) > 0.0
3356 ? 1.0 - defect / std::abs(predicted_energy_change)
3357 : 0.0;
3358 // The defect of the modelled gradient at the trial, g + B s, against
3359 // the measured one, in the configured norm, is recorded with the
3360 // step: on a flat mode it resolves the model where the energy
3361 // cannot.
3362 const double gradient_defect = forceNormForConvergence(
3363 trial.R.row(0), cartesian_change - cartesian_prediction);
3364 const bool accepted = ratio >= trust_config.rho_shrink;
3365 log_man << "Measured partitioned RFO step " << trials + 1
3366 << ": accepted " << steps << ", |x-x0| "
3367 << (trial.R.row(0).transpose() - origin).norm() << ", dE "
3368 << trial.E(0, 0) - start_energy << " (step measured "
3369 << measured_energy_change << ", model "
3370 << predicted_energy_change << "), force " << next
3371 << ", curvatures " << curvature(0) << " " << curvature(1)
3372 << ", mode gradients " << projected(0) << " "
3373 << (n > 1 ? projected(1) : 0.0) << ", step "
3374 << displacement.norm() << " of radius " << radius
3375 << ", RFO scaling " << proposal.scaling << ", hard case "
3376 << proposal.hard_case << ", agreement " << agreement
3377 << ", gradient defect " << gradient_defect << ", ratio "
3378 << ratio << (accepted ? ", accepted" : ", rejected") << "\n";
3379 if (!accepted) {
3380 radius *= trust_config.shrink_factor;
3381 cap_scale = std::max(1.0, cap_scale * trust_config.shrink_factor);
3382 ++rejected;
3383 refresh_due = true;
3384 // A trial the stored coordinates cannot tell from the current
3385 // point ends the walk: the radius is below coordinate
3386 // resolution.
3387 if (gpr::optim::coordinatesCoincideAtRoundoff(trial.R, current.R)) {
3388 log_man << "Measured partitioned RFO: the radius collapsed "
3389 "to coordinate resolution after "
3390 << rejected << " rejected steps; the walk ends.\n";
3391 collapsed = true;
3392 break;
3393 }
3394 continue;
3395 }
3396 // A first-order saddle between the endpoints lies above both.
3397 // A trial below the floor leaves the saddle region only when its
3398 // measured energy agrees with the model; inaccurate trials contract
3399 // the radius without moving the accepted point.
3400 if (std::isfinite(saddle_energy_floor_) && E_zero_level.size() > 0 &&
3401 trial.E(0, 0) + E_zero_level(0, 0) < saddle_energy_floor_) {
3402 log_man << "Measured partitioned RFO: step " << steps + 1
3403 << " measured " << trial.E(0, 0) + E_zero_level(0, 0)
3404 << " eV, below the saddle energy floor "
3405 << saddle_energy_floor_ << " eV; abandoning the walk.\n";
3406 abandoned = true;
3407 break;
3408 }
3409 // A clamped step the model predicted well restores the radius up
3410 // to the bound of this walk: the translation limit, or the length
3411 // at which the most displaced atom moves by it.
3412 if (clamped && ratio > trust_config.rho_grow) {
3413 const double next_radius =
3414 std::min(radius_cap, trust_config.grow_factor * radius);
3415 if (next_radius > radius) {
3416 radius = next_radius;
3417 ++expansions;
3418 } else if (complete_stencil && std::isfinite(gradient_defect) &&
3419 gradient_defect <= tolerance) {
3420 // On the atomic bound with a model that reproduced the
3421 // measured gradient: the bound grows for the next step.
3422 cap_scale *= trust_config.grow_factor;
3423 radius *= trust_config.grow_factor;
3424 ++cap_expansions;
3425 }
3426 }
3427 bofill(weighted, change);
3428 current = trial;
3429 if (raw_candidate != nullptr) current_raw = std::move(trial_raw);
3430 force = next;
3431 measured_here = false;
3432 ++steps;
3433 }
3434 // A walk that left the saddle region, or made no step, leaves the
3435 // refused midpoint to the order-one restart. Every other end hands
3436 // its end point to the next search.
3437 if (steps == 0 || abandoned) return false;
3438 last_refinement_reached_index_one_ = converged;
3439 retainStructuralObservation(current);
3440 synchronizeObservedData();
3441 curvature_requires_full_refit_ = true;
3442 middle_point_init = current;
3443 if (raw_candidate != nullptr && converged && force < tolerance)
3444 *raw_candidate = std::move(current_raw);
3445 if (lowest.size() == dof && lowest.norm() > 0.0) {
3446 orient_init.resize(1, dof);
3447 orient_init.row(0) =
3448 lowest.cwiseQuotient(root).normalized().transpose();
3449 } else if (getFinalOrientation().size() == dof) {
3450 orient_init = getFinalOrientation();
3451 }
3452 log_man << "Soft second negative mode: measured partitioned RFO from the "
3453 "stencil Hessian took "
3454 << steps << " steps (" << rejected << " rejected, " << expansions
3455 << " radius expansions, " << cap_expansions
3456 << " atomic bound expansions, " << refreshes
3457 << " measured mode refreshes, " << pair_checks
3458 << " four-point pair checks), moved "
3459 << (current.R.row(0).transpose() - origin).norm()
3460 << ", energy change " << current.E(0, 0) - start_energy
3461 << ", force " << force
3462 << (converged ? ", index-one model."
3463 : collapsed
3464 ? ", radius collapsed; the search continues from here."
3465 : ", index one not reached.")
3466 << "\n";
3467 return true;
3468}
3469
3471 const gpr::Observation& raw_center,
3472 const Eigen::MatrixXd& certified_cartesian_hessian,
3473 const Eigen::MatrixXd& certified_mass_weighted_basis,
3474 bool first_order_certificate)
3475{
3476 gpr::Observation relative_center;
3477 gpr::Coord orientation;
3478 Eigen::MatrixXd symmetric;
3479 double curvature = std::numeric_limits<double>::quiet_NaN();
3480 double resolution = std::numeric_limits<double>::infinity();
3481 const auto prepare = [&]() {
3482 const Eigen::Index dimension = raw_center.R.cols();
3483 const Eigen::Index physical_dimension =
3484 certified_mass_weighted_basis.cols();
3485 if (!external_terminal_certificate_ || !first_order_certificate ||
3486 !last_refinement_reached_index_one_ || gpr_model == nullptr ||
3487 !curvature_requires_full_refit_ ||
3488 hasOptimizedCurrentObservedData() || dimension < 6 ||
3489 dimension % 3 != 0 || raw_center.R.rows() != 1 ||
3490 !raw_center.R.allFinite() || raw_center.E.rows() != 1 ||
3491 raw_center.E.cols() != 1 || !raw_center.E.allFinite() ||
3492 raw_center.G.rows() != 1 || raw_center.G.cols() != dimension ||
3493 !raw_center.G.allFinite() || E_zero_level.rows() != 1 ||
3494 E_zero_level.cols() != 1 || !E_zero_level.allFinite() ||
3495 middle_point_init.R.rows() != 1 ||
3496 middle_point_init.R.cols() != dimension ||
3497 middle_point_init.E.rows() != 1 ||
3498 middle_point_init.E.cols() != 1 ||
3499 middle_point_init.G.rows() != 1 ||
3500 middle_point_init.G.cols() != dimension ||
3501 !(raw_center.R.array() == middle_point_init.R.array()).all() ||
3502 !(raw_center.G.array() == middle_point_init.G.array()).all() ||
3503 certified_cartesian_hessian.rows() != dimension ||
3504 certified_cartesian_hessian.cols() != dimension ||
3505 !certified_cartesian_hessian.allFinite() ||
3506 certified_mass_weighted_basis.rows() != dimension ||
3507 physical_dimension < 2 || physical_dimension > dimension ||
3508 !certified_mass_weighted_basis.allFinite())
3509 return false;
3510
3511 relative_center = raw_center;
3512 aux::ProblemSetUp setup;
3513 setup.cutOffEnergy(E_zero_level, relative_center.E);
3514 if (!relative_center.E.allFinite() ||
3515 !std::isfinite(relative_center.E(0, 0) + E_zero_level(0, 0)) ||
3516 relative_center.E(0, 0) + E_zero_level(0, 0) !=
3517 raw_center.E(0, 0) ||
3518 !(relative_center.E.array() == middle_point_init.E.array()).all() ||
3519 !(forceNormForConvergence(relative_center) <
3520 stop_citeria_dimer.force) ||
3521 (std::isfinite(saddle_energy_floor_) &&
3522 raw_center.E(0, 0) < saddle_energy_floor_) ||
3523 (std::isfinite(measured_energy_ceiling_) &&
3524 raw_center.E(0, 0) > measured_energy_ceiling_))
3525 return false;
3526
3527 Eigen::VectorXd masses;
3528 try {
3529 masses =
3531 } catch (const std::invalid_argument&) {
3532 return false;
3533 }
3534 Eigen::MatrixXd cartesian_basis = certified_mass_weighted_basis;
3535 for (Eigen::Index atom = 0; atom < masses.size(); ++atom)
3536 cartesian_basis.middleRows(3 * atom, 3) /= std::sqrt(masses(atom));
3537 if (!cartesian_basis.allFinite()) return false;
3538 const Eigen::ColPivHouseholderQR<Eigen::MatrixXd> frame_qr(
3539 certified_mass_weighted_basis);
3540 if (frame_qr.rank() != physical_dimension) return false;
3541 const Eigen::MatrixXd gram = certified_mass_weighted_basis.transpose() *
3542 certified_mass_weighted_basis;
3543 if (!gram.allFinite()) return false;
3544 const Eigen::LLT<Eigen::MatrixXd> gram_factor(gram);
3545 if (gram_factor.info() != Eigen::Success) return false;
3546 symmetric = 0.5 * certified_cartesian_hessian +
3547 0.5 * certified_cartesian_hessian.transpose();
3548 const Eigen::MatrixXd reduced =
3549 cartesian_basis.transpose() * symmetric * cartesian_basis;
3550 if (!reduced.allFinite()) return false;
3551 // The supplied chart spans the certifier's complete physical space.
3552 // Its mass-weighted Gram matrix keeps the selected mode independent
3553 // of normalization and mixing of the supplied chart columns.
3554 const Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd>
3555 spectrum(0.5 * (reduced + reduced.transpose()), gram);
3556 if (spectrum.info() != Eigen::Success ||
3557 !spectrum.eigenvalues().allFinite())
3558 return false;
3559 Eigen::MatrixXd physical =
3560 frame_qr.householderQ() *
3561 Eigen::MatrixXd::Identity(dimension, physical_dimension);
3562 for (Eigen::Index atom = 0; atom < masses.size(); ++atom)
3563 physical.middleRows(3 * atom, 3) /= std::sqrt(masses(atom));
3564 const Eigen::MatrixXd measured =
3565 physical.transpose() * certified_cartesian_hessian * physical;
3566 if (!measured.allFinite()) return false;
3567 const Eigen::MatrixXd skew = 0.5 * (measured - measured.transpose());
3568 const Eigen::JacobiSVD<Eigen::MatrixXd> error_spectrum(skew);
3569 if (!error_spectrum.singularValues().allFinite()) return false;
3570 const double weighted_resolution =
3571 std::max(error_spectrum.singularValues().maxCoeff(),
3572 std::numeric_limits<double>::epsilon() *
3573 static_cast<double>(physical_dimension) *
3574 spectrum.eigenvalues().cwiseAbs().maxCoeff());
3575 if (!(spectrum.eigenvalues()(0) < -weighted_resolution) ||
3576 !(spectrum.eigenvalues()(1) > weighted_resolution))
3577 return false;
3578 Eigen::VectorXd mode = cartesian_basis * spectrum.eigenvectors().col(0);
3579 const double norm = mode.stableNorm();
3580 if (!(norm > 0.0) || !std::isfinite(norm)) return false;
3581 mode /= norm;
3582 if (orient_init.rows() == 1 && orient_init.cols() == dimension &&
3583 orient_init.allFinite() && orient_init.row(0).dot(mode) < 0.0)
3584 mode = -mode;
3585 curvature = mode.dot(symmetric * mode);
3586 resolution = masses.maxCoeff() * weighted_resolution;
3587 if (!mode.allFinite() || !std::isfinite(curvature) ||
3588 !std::isfinite(resolution) || !(curvature < -resolution))
3589 return false;
3590 orientation.resize(1, dimension);
3591 orientation.row(0) = mode.transpose();
3592
3593 return true;
3594 };
3595 int accepted = prepare() ? 1 : 0;
3596#if defined(GPR_LINALG_SCALAPACK) || defined(GPR_HAVE_MPI)
3597 int mpi_active = 0;
3598 MPI_Initialized(&mpi_active);
3599 if (mpi_active && MPI_Allreduce(MPI_IN_PLACE, &accepted, 1, MPI_INT,
3600 MPI_MIN, MPI_COMM_WORLD) != MPI_SUCCESS)
3601 accepted = 0;
3602#endif
3603 if (accepted == 0) return false;
3604
3605 // A full-Hessian certificate commits measured state without claiming
3606 // that the retained endpoint has conditioned the surrogate posterior.
3607 assignFinalResults(relative_center, {curvature, orientation});
3608 latest_mode_curvature_resolution_ = resolution;
3609 final_converged_ = true;
3610 last_negative_mode_count_ = 1;
3611 converged_above_energy_ceiling_ = false;
3612 relaxation_termination_reason_ =
3614 final_rotation_omega_ = std::numeric_limits<double>::quiet_NaN();
3615 final_rotation_residual_ = std::numeric_limits<double>::infinity();
3616 measured_rotation_stationary_ = false;
3617 measured_rotation_rounds_ = 0;
3618 measured_rotation_reference_ = gpr::Observation();
3619 measured_rotation_separation_ = 0.0;
3620 measured_rotation_physical_.resize(0, 0);
3621 measured_rotation_basis_.resize(0, 0);
3622 measured_rotation_actions_.resize(0, 0);
3623 best_measured_rotation_residual_ = std::numeric_limits<double>::infinity();
3624 best_measured_rotation_angle_ = std::numeric_limits<double>::quiet_NaN();
3625 best_measured_rotation_curvature_ =
3626 std::numeric_limits<double>::quiet_NaN();
3627 best_measured_orientation_.resize(0, 0);
3628 best_measured_image1_ = gpr::Observation();
3629 measured_index_zero_midpoint_.resize(0, 0);
3630 measured_index_zero_hessian_.resize(0, 0);
3631 last_certificate_hessian_ = symmetric;
3632 last_certificate_positions_ = relative_center.R;
3633 return true;
3634}
3635
3636void AtomicDimer::retainMeasuredNegativeSubspace(
3637 const Eigen::MatrixXd& cartesian_hessian, const gpr::Coord& position)
3638{
3639 higher_order_restart_ = true;
3640 const Eigen::MatrixXd physical =
3642 index_search_directions_.resize(0, 0);
3643 if (physical.cols() >= 2) {
3644 const Eigen::MatrixXd restricted =
3645 physical.transpose() * cartesian_hessian * physical;
3646 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> measured_spectrum(
3647 0.5 * (restricted + restricted.transpose()));
3648 if (measured_spectrum.info() == Eigen::Success &&
3649 measured_spectrum.eigenvalues()(1) < 0.0) {
3650 // Restriction precedes diagonalization: projecting unrestricted
3651 // negative eigenvectors can lose their negative curvature. The
3652 // proposed pair still requires fresh measurements at this point.
3653 index_search_directions_ =
3654 physical * measured_spectrum.eigenvectors().leftCols(2);
3655 }
3656 }
3657}
3658
3659bool AtomicDimer::restartAlongWeakMode(const Eigen::VectorXd& direction,
3660 double length,
3661 const gpr::Observation& measured_rows,
3662 pot::PotentialWrapper& potential)
3663{
3664 return restartAlongWeakMode(direction, length, measured_rows, potential,
3665 Eigen::MatrixXd());
3666}
3667
3668bool AtomicDimer::restartAlongWeakMode(const Eigen::VectorXd& direction,
3669 double length,
3670 const gpr::Observation& measured_rows,
3671 pot::PotentialWrapper& potential,
3672 const Eigen::MatrixXd& cartesian_hessian)
3673{
3674 const Eigen::VectorXd final_position = getFinalCoordOfMidPoint();
3675 const Eigen::Index dof = final_position.size();
3676 if (dof == 0 || direction.size() != dof || !direction.allFinite() ||
3677 !(direction.norm() > 0.0) || !(length > 0.0) ||
3678 !std::isfinite(length) || gpr_model == nullptr ||
3679 (cartesian_hessian.size() != 0 &&
3680 (cartesian_hessian.rows() != dof || cartesian_hessian.cols() != dof ||
3681 !cartesian_hessian.allFinite())))
3682 return false;
3683 if (measured_rows.R.rows() > 0 && measured_rows.G.allFinite()) {
3684 // The rows carry absolute oracle energies; the training set is
3685 // referenced to the search's zero level.
3686 gpr::Observation rows = measured_rows;
3687 aux::ProblemSetUp problem_setup;
3688 problem_setup.cutOffEnergy(E_zero_level, rows.E);
3689 retainStructuralObservation(rows);
3690 synchronizeObservedData();
3691 }
3692 gpr::Observation moved;
3693 moved.R.resize(1, dof);
3694 moved.R.row(0) =
3695 (final_position + length * direction.normalized()).transpose();
3696 evaluateAccurateEnergyAndForce(moved, potential,
3697 /*apply_emd_dedup=*/false);
3698 if (moved.E.size() == 0 || !std::isfinite(moved.E(0, 0)) ||
3699 !moved.G.allFinite())
3700 return false;
3701 broadcastObservation(moved);
3702 synchronizeObservedData();
3703 curvature_requires_full_refit_ = true;
3704 middle_point_init = moved;
3705 if (cartesian_hessian.size() != 0)
3706 retainMeasuredNegativeSubspace(cartesian_hessian, moved.R);
3707 if (getFinalOrientation().size() == dof)
3708 orient_init = getFinalOrientation();
3709 // The step is a finished geometry. A force still under tolerance is
3710 // the result; the caller measures one stencil there instead of
3711 // opening another force loop.
3712 middle_point_final = moved;
3713 if (forceNormForConvergence(moved) < stop_citeria_dimer.force) {
3714 final_converged_ = true;
3715 relaxation_termination_reason_ =
3717 }
3718 log_man << "Weak-mode restart: the complete stencil cannot certify the "
3719 "weak modes positive; continuing "
3720 << length << " along the softest one.\n";
3721 return true;
3722}
3723
3724void AtomicDimer::resolveSurrogateNegativeModesBeforePhase(
3725 const gpr::Observation& midpoint, const gpr::Coord& orientation,
3726 pot::PotentialWrapper& potential)
3727{
3728 // A first-order saddle search acts on one unstable direction. A
3729 // surrogate with several negative modes at the phase start is asking the
3730 // dimer to descend along transverse directions nothing has measured; on
3731 // a band archive those modes came from the kernel's extrapolation off
3732 // the path and carried the search 0.1 A per phase into 2-5 eV/A forces.
3733 // Each surrogate negative direction beyond the lowest is measured by a
3734 // central difference before the phase acts on it. A measured negative
3735 // curvature is left to the terminal index stencil; a nonnegative one is
3736 // conditioned into the posterior, which removes the spurious direction
3737 // where it was claimed. Two calls per direction, at most the dimension
3738 // of the rigid complement.
3739 if (!want_second_negative_mode_ || gpr_model == nullptr ||
3740 midpoint.R.rows() != 1 || midpoint.R.cols() == 0 ||
3741 !(dimer_sep > 0.0) || !std::isfinite(dimer_sep))
3742 return;
3743 const Eigen::Index span =
3744 projectedCartesianBasis(midpoint.R, midpoint.R.cols(), atoms_config)
3745 .cols();
3746 const double separation = std::max(dimer_sep, 1.0e-3);
3747 std::vector<Eigen::VectorXd> measured_directions;
3748 for (Eigen::Index round = 0; round < span; ++round) {
3749 const auto mode = estimateLowestModeAndCurvatureFromGP(
3750 midpoint.R, &orientation, SurrogateSpectrumRequest::Spectrum);
3751 if (mode.first.size() != midpoint.R.size() ||
3752 !std::isfinite(mode.second) || last_negative_mode_count_ <= 1 ||
3753 additional_mode_.size() != midpoint.R.cols() ||
3754 !std::isfinite(additional_gp_curvature_) ||
3755 !(additional_gp_curvature_ < 0.0))
3756 return;
3757 const Eigen::VectorXd axis = mode.first.row(0).transpose().normalized();
3758 Eigen::VectorXd transverse = additional_mode_;
3759 transverse -= axis * axis.dot(transverse);
3760 const double transverse_norm = transverse.norm();
3761 if (!std::isfinite(transverse_norm) ||
3762 transverse_norm <=
3763 std::sqrt(std::numeric_limits<double>::epsilon()))
3764 return;
3765 transverse /= transverse_norm;
3766 // A direction measured in an earlier round and still claimed
3767 // negative, to within the dimer's own angular resolution, is one
3768 // the measured pair did not condition out; measuring it again adds
3769 // nothing and the phase proceeds with the rows it has.
3770 const double resolved_overlap =
3771 std::cos(std::isfinite(stop_citeria_dimer.angle_rotation) &&
3772 stop_citeria_dimer.angle_rotation > 0.0
3773 ? stop_citeria_dimer.angle_rotation
3774 : 0.0);
3775 for (const Eigen::VectorXd& measured: measured_directions) {
3776 if (std::abs(measured.dot(transverse)) >= resolved_overlap) {
3777 log_man << "Surrogate negative mode check: "
3778 << last_negative_mode_count_
3779 << " surrogate negative modes remain after " << round
3780 << " measured directions and the second mode was "
3781 "already measured; proceeding with the measured "
3782 "rows.\n";
3783 return;
3784 }
3785 }
3786 measured_directions.push_back(transverse);
3787
3788 gpr::Observation plus, minus;
3789 plus.R = midpoint.R + separation * transverse.transpose();
3790 minus.R = midpoint.R - separation * transverse.transpose();
3791 for (gpr::Observation* probe: {&plus, &minus}) {
3792 evaluateAccurateEnergyAndForce(*probe, potential,
3793 /*apply_emd_dedup=*/false);
3794 broadcastObservation(*probe);
3795 }
3796 synchronizeObservedData();
3797 if (!plus.G.allFinite() || !minus.G.allFinite() ||
3798 plus.G.cols() != midpoint.R.cols() ||
3799 minus.G.cols() != midpoint.R.cols())
3800 return;
3801 const double measured_curvature =
3802 (plus.G.row(0) - minus.G.row(0)).dot(transverse.transpose()) /
3803 (2.0 * separation);
3804 log_man << "Surrogate negative mode check: "
3805 << last_negative_mode_count_
3806 << " surrogate negative modes at the phase start; measured "
3807 "curvature "
3808 << measured_curvature << " along the second surrogate mode "
3809 << "(surrogate " << additional_gp_curvature_ << ").\n";
3810 if (!std::isfinite(measured_curvature) || measured_curvature < 0.0)
3811 return;
3812 // Force errors scale with probe separation, so pointwise agreement
3813 // cannot validate a contradicted curvature sign. Refit the full
3814 // model before retaining its kernel as an active correction's prior.
3815 curvature_requires_full_refit_ = true;
3816 refitGPRModel(false, plus, mode.first);
3817 }
3818}
3819
3820void AtomicDimer::resolveFlatResidualDirection(const gpr::Observation& midpoint,
3821 const gpr::Coord& orientation,
3822 pot::PotentialWrapper& potential)
3823{
3824 // The projected step left a transverse negative surrogate mode out and
3825 // that mode carried the residual: every phase then measured a step
3826 // that changed nothing (24_h2cnh: 37 phases, residual 0.29 along the
3827 // asserted second mode). Two calls settle the direction: a measured
3828 // negative curvature makes it a descent direction for the step, a
3829 // nonnegative one conditions the posterior on the pair and the claim
3830 // leaves the spectrum.
3831 if (pending_flat_direction_.size() != midpoint.R.cols() ||
3832 midpoint.R.rows() != 1 || !(dimer_sep > 0.0) ||
3833 !std::isfinite(dimer_sep)) {
3834 pending_flat_direction_.resize(0);
3835 return;
3836 }
3837 Eigen::VectorXd direction = pending_flat_direction_;
3838 const double surrogate_curvature = pending_flat_curvature_;
3839 pending_flat_direction_.resize(0);
3840 pending_flat_curvature_ = std::numeric_limits<double>::quiet_NaN();
3841 const double norm = direction.norm();
3842 if (!std::isfinite(norm) || !(norm > 0.0)) return;
3843 direction /= norm;
3844 if (!dimerGeometriesCoincide(midpoint.R, measured_negative_reference_)) {
3845 measured_negative_directions_.clear();
3846 measured_negative_reference_ = midpoint.R;
3847 }
3848 for (const auto& [measured, curvature]: measured_negative_directions_) {
3849 if (measured.size() != direction.size()) continue;
3850 const double overlap = measured.dot(direction);
3851 if (overlap * overlap > 0.5) return;
3852 }
3853 const double separation = std::max(dimer_sep, 1.0e-3);
3854 gpr::Observation plus, minus;
3855 plus.R = midpoint.R + separation * direction.transpose();
3856 minus.R = midpoint.R - separation * direction.transpose();
3857 for (gpr::Observation* probe: {&plus, &minus}) {
3858 evaluateAccurateEnergyAndForce(*probe, potential,
3859 /*apply_emd_dedup=*/false);
3860 broadcastObservation(*probe);
3861 }
3862 synchronizeObservedData();
3863 if (!plus.G.allFinite() || !minus.G.allFinite() ||
3864 plus.G.cols() != midpoint.R.cols() ||
3865 minus.G.cols() != midpoint.R.cols())
3866 return;
3867 const double measured_curvature =
3868 (plus.G.row(0) - minus.G.row(0)).dot(direction.transpose()) /
3869 (2.0 * separation);
3870 log_man << "Flat residual direction: measured curvature "
3871 << measured_curvature << " along the transverse surrogate mode "
3872 << "(surrogate " << surrogate_curvature << ").\n";
3873 if (!std::isfinite(measured_curvature)) return;
3874 if (measured_curvature < 0.0) {
3875 measured_negative_directions_.emplace_back(direction,
3876 measured_curvature);
3877 return;
3878 }
3879 if (surrogate_curvature < 0.0) curvature_requires_full_refit_ = true;
3880 refitGPRModel(false, plus, orientation);
3881}
3882
3883bool AtomicDimer::projectedTrustRegionStep(const gpr::Coord& R,
3884 const gpr::Coord& F, double radius,
3885 gpr::Coord& R_new)
3886{
3887 if (measured_trial_trust_)
3888 radius = std::min(radius, measured_trial_trust_->radius());
3889 // The surrogate's quadratic model at R in the eigenbasis of its
3890 // projected Hessian, with the selected curvature reversed, is the
3891 // model of the modified surface whose minimum the dimer follows; the
3892 // step is its exact trust-region minimizer on the spectrum
3893 // (gpr::optim::spectralTrustRegionStep). A steepest-descent first
3894 // step scaled by a constant (the two-loop's empty memory) is what a
3895 // stiff mode turns into a crawl.
3896 //
3897 // A transverse curvature at or below zero has no minimizer: the
3898 // trust-region answer there is the boundary along that direction, the
3899 // transverse descent a seeded surrogate's spurious negative modes
3900 // turned into 0.1 A phases measured at 0.5-3 eV/A (14_hydro, 19_sn2).
3901 // Such a mode is left out unless the oracle measured its direction
3902 // negative, and the one carrying the most residual is requested for
3903 // measurement when the left-out modes together carry more residual
3904 // than the modes the step acts on.
3905 const SurrogateSpectrum& spectrum = surrogate_spectrum_;
3906 last_step_descends_measured_negative_ = false;
3907 if (!spectrum.valid || R.rows() != 1 || F.rows() != 1 ||
3908 F.cols() != R.cols() || spectrum.R.cols() != R.cols() ||
3909 spectrum.modes.rows() != R.cols() || spectrum.mode_index < 0 ||
3910 spectrum.mode_index >= spectrum.curvatures.size() || !(radius > 0.0) ||
3911 !std::isfinite(radius) || !F.allFinite())
3912 return false;
3913 if (!(R.row(0) - spectrum.R.row(0)).isZero(0.0) &&
3914 !R.row(0).isApprox(spectrum.R.row(0), 1.0e-12))
3915 return false;
3916 if (!dimerGeometriesCoincide(R, measured_negative_reference_)) {
3917 measured_negative_directions_.clear();
3918 measured_negative_reference_.resize(0, 0);
3919 }
3920 const gpr::optim::SpectralTrustRegionStep solved =
3922 spectrum.curvatures, spectrum.modes, spectrum.mode_index,
3923 Eigen::VectorXd(F.row(0).transpose()), radius,
3924 measured_negative_directions_);
3925 if (!solved.valid) return false;
3926 last_step_descends_measured_negative_ = solved.descends_measured;
3927 pending_flat_direction_.resize(0);
3928 pending_flat_curvature_ = std::numeric_limits<double>::quiet_NaN();
3929 if (solved.request >= 0 &&
3930 solved.flat_residual_sq > solved.kept_residual_sq) {
3931 pending_flat_direction_ = spectrum.modes.col(solved.request);
3932 pending_flat_curvature_ = spectrum.curvatures(solved.request);
3933 }
3934 R_new = R;
3935 R_new.row(0) += solved.step.transpose();
3936 log_man << "Projected trust-region step: length=" << solved.length
3937 << " radius=" << radius << " sigma=" << solved.sigma
3938 << " selected_curvature="
3939 << spectrum.curvatures(spectrum.mode_index)
3940 << " modes=" << spectrum.curvatures.size()
3941 << " flat=" << solved.flat
3942 << " measured_descent=" << last_step_descends_measured_negative_
3943 << " flat_request=" << (pending_flat_direction_.size() > 0)
3944 << ".\n";
3945 return true;
3946}
3947
3948bool AtomicDimer::restartLocalTranslation(const gpr::Coord& R,
3949 const gpr::Coord& gradient,
3950 gpr::Coord& orientation,
3951 gpr::Coord& R_new, double& curvature)
3952{
3953 const auto [mode, eigenvalue] = estimateLowestModeAndCurvatureFromGP(
3954 R, &orientation, SurrogateSpectrumRequest::Spectrum);
3955 if (mode.rows() != 1 || mode.cols() != R.cols() || !mode.allFinite() ||
3956 !std::isfinite(eigenvalue) || !(eigenvalue < 0.0))
3957 return false;
3958 double radius = transition_param.max_step_length;
3959 if (measured_trial_trust_)
3960 radius = std::min(radius, measured_trial_trust_->radius());
3961 const Eigen::VectorXd step = gpr::optim::spectralResidualStep(
3962 surrogate_spectrum_.curvatures, surrogate_spectrum_.modes,
3963 gradient.row(0).transpose(), radius);
3964 if (step.size() != R.cols()) return false;
3965 R_new = R + step.transpose();
3966 last_step_descends_measured_negative_ = false;
3967 pending_flat_direction_.resize(0);
3968 pending_flat_curvature_ = std::numeric_limits<double>::quiet_NaN();
3969 orientation = gpr::field::flatDot(orientation, mode) < 0.0 ? -mode : mode;
3970 curvature = eigenvalue;
3971 log_man << "Local force-root step: length=" << step.stableNorm()
3972 << " radius=" << radius << ".\n";
3973 return true;
3974}
3975
3976double AtomicDimer::directionalCurvatureUncertainty(
3977 const gpr::Coord& R, const Eigen::VectorXd& direction)
3978{
3979 // The centered directional derivative is one linear functional of the
3980 // latent GP. Its variance includes both Cartesian and cross-point
3981 // correlations; independent measurement noise is not latent curvature.
3982 if (gpr_model == nullptr || R.rows() != 1 || direction.size() != R.cols() ||
3983 !direction.allFinite() || !(dimer_sep > 0.0) ||
3984 !std::isfinite(dimer_sep))
3985 return std::numeric_limits<double>::quiet_NaN();
3986 const auto start = std::chrono::steady_clock::now();
3987 gpr::Coord stencil(2, R.cols());
3988 stencil.row(0) = R.row(0) + dimer_sep * direction.transpose();
3989 stencil.row(1) = R.row(0) - dimer_sep * direction.transpose();
3990 const Eigen::Index channels = 2 * (R.cols() + 1);
3991 Eigen::VectorXd weights = Eigen::VectorXd::Zero(channels);
3992 for (Eigen::Index d = 0; d < R.cols(); ++d) {
3993 weights(2 * (d + 1)) = direction(d) / (2.0 * dimer_sep);
3994 weights(2 * (d + 1) + 1) = -weights(2 * (d + 1));
3995 }
3996 long double variance;
3997 long double roundoff = 0.0L;
3998 {
3999 gpr::ScopedPredictTimer timer;
4000 variance =
4001 gpr_model->calculateObservationFunctionalVariance(stencil, weights);
4002 if (std::isfinite(variance) && variance < 0.0L) {
4003 // A negative contraction requires the full posterior's roundoff
4004 // bound; the prior scale cannot resolve cancellation at zero.
4005 gpr::EigenMatrix covariance;
4006 gpr_model->calculateObservationPosteriorCovariance(
4007 stencil, covariance, false);
4008 variance = weights.cast<long double>().dot(
4009 covariance.cast<long double>() * weights.cast<long double>());
4010 const long double scale =
4011 weights.cast<long double>().cwiseAbs().dot(
4012 covariance.cast<long double>().cwiseAbs() *
4013 weights.cast<long double>().cwiseAbs());
4014 roundoff = 8.0L * channels *
4015 std::numeric_limits<double>::epsilon() * scale;
4016 }
4017 }
4018 const double seconds =
4019 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
4020 .count();
4021 gp_predict_seconds_ += seconds;
4022 gp_predict_variance_seconds_ += seconds;
4023 ++gp_predict_calls_;
4024 ++gp_predict_variance_calls_;
4025 if (!std::isfinite(variance) || variance < -roundoff)
4026 return std::numeric_limits<double>::quiet_NaN();
4027 return std::sqrt(static_cast<double>(std::max(0.0L, variance)) *
4028 gpr_model->reportedVarianceCalibrationFactor());
4029}
4030
4031void AtomicDimer::prepareIndexOneProjection(const gpr::Coord& R)
4032{
4033 index_one_clamped_modes_.clear();
4034 last_asserted_negative_modes_ = 0;
4035 const auto& spectrum = surrogate_spectrum_;
4036 if (!spectrum.valid || R.rows() != spectrum.R.rows() ||
4037 R.cols() != spectrum.R.cols() || !R.isApprox(spectrum.R, 1.0e-12))
4038 return;
4039 // Clamp only transverse negative curvatures that the posterior cannot
4040 // distinguish from zero. Asserted negative curvatures remain available
4041 // to the measured index stencil. This projection belongs to the contour
4042 // force; refinement uses the raw spectrum and measured negative modes.
4043 for (Eigen::Index k = 0; k < spectrum.curvatures.size(); ++k) {
4044 if (k == spectrum.mode_index || !(spectrum.curvatures(k) < 0.0))
4045 continue;
4046 const Eigen::VectorXd mode = spectrum.modes.col(k);
4047 const double sigma = directionalCurvatureUncertainty(R, mode);
4048 if (std::isfinite(sigma) && spectrum.curvatures(k) < -sigma) {
4049 ++last_asserted_negative_modes_;
4050 continue;
4051 }
4052 index_one_clamped_modes_.emplace_back(spectrum.curvatures(k), mode);
4053 }
4054}
4055
4056void AtomicDimer::applyIndexOneProjection(const Eigen::VectorXd& direction,
4057 Eigen::VectorXd& action) const
4058{
4059 // H_proj v = H v - sum_k lambda_k (u_k . v) u_k over the clamped
4060 // pairs: the action of the nearest index-one matrix.
4061 if (action.size() != direction.size()) return;
4062 for (const auto& [value, mode]: index_one_clamped_modes_) {
4063 if (mode.size() != direction.size()) continue;
4064 action -= value * mode.dot(direction) * mode;
4065 }
4066}
4067
4068double AtomicDimer::forceNormForConvergence(
4069 const Eigen::Ref<const Eigen::RowVectorXd>& gradient) const
4070{
4071 return gpr::forceNorm(gradient, convergence_force_norm);
4072}
4073
4074double AtomicDimer::forceNormForConvergence(
4075 const Eigen::Ref<const Eigen::RowVectorXd>& positions,
4076 const Eigen::Ref<const Eigen::RowVectorXd>& gradient) const
4077{
4078 if (!project_rigid_modes_for_convergence_ || is_subsystem(atoms_config) ||
4079 positions.size() != gradient.size() || positions.size() == 0 ||
4080 positions.size() % 3 != 0 || !positions.allFinite()) {
4081 return forceNormForConvergence(gradient);
4082 }
4083 gpr::Coord geometry(1, positions.size());
4084 geometry.row(0) = positions;
4085 Eigen::VectorXd projected = gradient.transpose();
4086 dimer::project_out_rot_trans_with_feedback(geometry, projected);
4087 const Eigen::RowVectorXd projected_row = projected.transpose();
4088 return forceNormForConvergence(projected_row);
4089}
4090
4091double AtomicDimer::forceNormForConvergence(const gpr::Observation& obs) const
4092{
4093 if (obs.R.rows() < 1 || obs.G.rows() < 1 || obs.R.cols() != obs.G.cols()) {
4094 return std::numeric_limits<double>::infinity();
4095 }
4096 return forceNormForConvergence(obs.R.row(0), obs.G.row(0));
4097}
4098
4099double AtomicDimer::surrogateForceTolerance(
4100 const gpr::Observation& oracle_middle_point) const
4101{
4102 const double floor = stop_citeria_dimer.force * 0.1;
4103 if (!(std::isfinite(divisor_stop_criteria_gpr) &&
4104 divisor_stop_criteria_gpr > 0.0)) {
4105 return floor;
4106 }
4107 const double force = forceNormForConvergence(oracle_middle_point);
4108 if (!std::isfinite(force)) return floor;
4109 return std::max(force / divisor_stop_criteria_gpr, floor);
4110}
4111
4112double AtomicDimer::bestObservedForceNorm() const
4113{
4114 double best = std::numeric_limits<double>::infinity();
4115 for (Eigen::Index row = 0; row < all_obs.G.rows(); ++row) {
4116 if (row < all_obs.R.rows()) {
4117 best = std::min(best, forceNormForConvergence(all_obs.R.row(row),
4118 all_obs.G.row(row)));
4119 }
4120 }
4121 return best;
4122}
4123
4125 gpr::Observation& middle_point)
4126{
4128 dimer.bindRgminTranslation(rgmin_trans_.get());
4129 gpr::Coord F_rot;
4130 gpr::Coord G01_loc;
4131 bool is_convergence_rached = false;
4132
4133 G01_loc = middle_point.G;
4134 gpr::field::appendRows(G01_loc, image1.G);
4135
4136 dimer.rotateForce(G01_loc, orient, F_rot);
4137
4138 double omega = dimer.estimateRotationalAngle(orient, G01_loc, F_rot);
4139
4140 if (omega <= stop_citeria_dimer.angle_rotation)
4141 is_convergence_rached = true;
4142 else
4143 is_convergence_rached = false;
4144
4145 return is_convergence_rached;
4146}
4147
4149 const gpr::Coord& orient, const gpr::Observation& approx_obs,
4150 const double stop_criteria)
4151{
4152 if (stop_criteria <= 0.0 || !std::isfinite(stop_criteria)) return false;
4153 if (orient.rows() != 1 || orient.cols() == 0) return false;
4154 if (approx_obs.G.rows() < 2 || approx_obs.G.cols() != orient.cols())
4155 return false;
4156 if (!orient.allFinite() || !approx_obs.G.allFinite()) return false;
4157
4159 dimer.bindRgminTranslation(rgmin_trans_.get());
4160 gpr::Coord F_rot;
4161 dimer.rotateForce(approx_obs.G, orient, F_rot);
4162 const double omega =
4163 dimer.estimateRotationalAngle(orient, approx_obs.G, F_rot);
4164
4165 return std::isfinite(omega) && omega <= stop_criteria;
4166}
4167
4168bool AtomicDimer::rotateDimer(const double stop_criteria, gpr::Coord& orient,
4169 gpr::LBFGSInfo& rot_info,
4170 gpr::Observation& middle_point,
4171 gpr::Observation& approx_obs)
4172{
4174 dimer.bindRgminTranslation(rgmin_trans_.get());
4175 // UA-Dimer: hand the rotation the surrogate's per-degree-of-freedom force
4176 // variance at THIS geometry, so it removes the axial component in the
4177 // Sigma^{-1} metric. Probed fresh rather than reusing the gate's scratch:
4178 // that buffer belongs to whatever query last filled it, and a variance
4179 // from the wrong geometry would steer the rotation with stale anisotropy.
4180 if (uncertainty_aware_rotation_ && gpr_model != nullptr &&
4181 middle_point.R.rows() == 1 && middle_point.R.cols() > 0) {
4182 gpr::Observation rotation_variance;
4183 rotation_variance.R = middle_point.R;
4184 calculateApproximateVariance(rotation_variance);
4185 if (rotation_variance.G.rows() >= 1 &&
4186 rotation_variance.G.cols() == orient.cols() &&
4187 rotation_variance.G.row(0).allFinite()) {
4188 dimer.setForceVariance(rotation_variance.G.row(0).transpose());
4189 }
4190 }
4191 gpr::Observation observed{
4192 middle_point}; // observed coordinates, energy and gradient of
4193 // the middle point and the image 1
4194 // For starters it can just be the approx_obs
4195 gpr::Observation reduced_obs;
4196 gpr::Coord orient_old;
4197 double curv_dummy = 0; // dummy variable
4198 bool terminate_loop = false;
4199
4200 // if necessary, rotate the dimer and re-calculate approximated energy and
4201 // gradient at image 1
4202 orient_old = orient;
4203
4204 bool used_analytic_hessian = false;
4205 bool endpoint_is_measured = false;
4206 const bool can_use_analytic_hessian =
4207 gpr_model != nullptr && gpr_model->hasReusableHssvdPosterior() &&
4208 middle_point.R.rows() == 1 && middle_point.R.cols() > 0 &&
4209 approx_obs.G.rows() >= 1 &&
4210 approx_obs.G.cols() == middle_point.R.cols() &&
4211 approx_obs.E.rows() >= 1 && approx_obs.E.cols() >= 1 &&
4212 approx_obs.G.row(0).allFinite() && approx_obs.E.allFinite();
4213 if (can_use_analytic_hessian) {
4215 prepared_hssvd;
4216 const bool have_prepared_hssvd =
4217 gpr_model->prepareMeanHessianVectorHssvd(middle_point.R,
4218 prepared_hssvd);
4219 auto apply_hssvd_hvp = [&](const Eigen::VectorXd& dx,
4220 Eigen::VectorXd& hv) -> bool {
4221 if (have_prepared_hssvd)
4222 return gpr_model->applyMeanHessianVectorHssvd(prepared_hssvd,
4223 dx, hv);
4224 return gpr_model->calculateMeanHessianVectorDispatched(
4225 middle_point.R, dx, hv);
4226 };
4227 auto image1_evaluator = [&](gpr::Observation& candidate) -> bool {
4228 if (candidate.R.rows() != 1 ||
4229 candidate.R.cols() != middle_point.R.cols() ||
4230 !candidate.R.allFinite())
4231 return false;
4232 calculateApproximatePotential(candidate);
4233 return candidate.G.rows() == 1 &&
4234 candidate.G.cols() == middle_point.R.cols() &&
4235 candidate.E.rows() == 1 && candidate.E.cols() == 1 &&
4236 candidate.G.allFinite() && candidate.E.allFinite();
4237 };
4238
4239 gpr::Observation trial_observed{middle_point};
4240 gpr::Coord trial_orient = orient;
4241 double trial_curv = 0.0;
4242 const dimer::Dimer::RotationStepResult result = dimer.rotateWithHessian(
4243 middle_point.R, orient_old, approx_obs.G, false, image1_evaluator,
4244 trial_orient, trial_curv, trial_observed, apply_hssvd_hvp);
4246 observed = trial_observed;
4247 orient = trial_orient;
4248 curv_dummy = trial_curv;
4249 used_analytic_hessian = true;
4250 endpoint_is_measured = true;
4251 }
4252 }
4253
4254 if (!used_analytic_hessian) {
4255 dimer.rotate(middle_point.R, orient_old, approx_obs.G, POTENTIAL_GP,
4256 stop_criteria, false, all_obs, gpr_model, rot_info, orient,
4257 curv_dummy, observed);
4258 endpoint_is_measured = true;
4259 }
4260
4261 if (observed.R.size() != 0) {
4262 // NOTE: inline updateLocation for image 1
4263 for (gpr::Index_t n = 0; n < approx_obs.R.cols(); ++n) {
4264 approx_obs.R(1, n) =
4265 middle_point.R(0, n) + orient(0, n) * dimer_sep;
4266 }
4267
4268 const bool matching_endpoint =
4269 endpoint_is_measured && observed.R.rows() == 1 &&
4270 observed.R.cols() == approx_obs.R.cols() &&
4271 observed.G.rows() == 1 &&
4272 observed.G.cols() == approx_obs.G.cols() &&
4273 observed.E.rows() == 1 && observed.E.cols() == 1 &&
4274 observed.G.allFinite() && observed.E.allFinite() &&
4275 (observed.R.row(0) - approx_obs.R.row(1)).squaredNorm() == 0.0;
4276 if (matching_endpoint) {
4277 reduced_obs = std::move(observed);
4278 } else {
4279 gpr::field::appendRow(reduced_obs.R, approx_obs.R, 1);
4280 calculateApproximatePotential(reduced_obs);
4281 }
4282
4283 for (gpr::Index_t j = 0; j < approx_obs.R.cols(); ++j) {
4284 approx_obs.R(1, j) = reduced_obs.R(0, j);
4285 approx_obs.G(1, j) = reduced_obs.G(0, j);
4286 }
4287 approx_obs.E(0, 1) = reduced_obs.E(0, 0);
4288
4289 terminate_loop =
4290 checkRotationalConvergence(orient, orient_old, stop_criteria);
4291 } else {
4292 terminate_loop = true;
4293 log_man << "Dimer rotation converged (omega < T_anglerot); "
4294 "skipping image-1 update\n";
4295 }
4296
4297 return terminate_loop;
4298}
4299
4300bool AtomicDimer::checkRotationalConvergence(const gpr::Coord& orient,
4301 const gpr::Coord& orient_old,
4302 const double stop_criteria)
4303{
4304 const Eigen::Map<const Eigen::VectorXd> v(orient.data(), orient.size());
4305 const Eigen::Map<const Eigen::VectorXd> v_old(orient_old.data(),
4306 orient_old.size());
4307 if (v.size() != v_old.size() || v.size() == 0) return false;
4308 const double n = v.norm();
4309 const double n_old = v_old.norm();
4310 if (!(n > 0.0) || !(n_old > 0.0)) return false;
4311 // Dimer axis is unsigned; use the acute angle between unit axes.
4312 // Check the raw cosine before min(): min(1, NaN) is 1 and would
4313 // report a zero angle.
4314 const double raw = v.dot(v_old) / (n * n_old);
4315 if (!std::isfinite(raw)) return false;
4316 const double cosine = std::min(1.0, std::abs(raw));
4317 return std::acos(cosine) < stop_criteria;
4318}
4319
4320bool AtomicDimer::isRotationCurvatureInformative(
4321 const double curvature) const noexcept
4322{
4323 return std::isfinite(curvature) && curvature < 0.0;
4324}
4325
4326double AtomicDimer::exactEmdDuplicateThreshold(
4327 const gpr::Coord& query) const noexcept
4328{
4329 if (query.size() == 0 || !query.allFinite())
4330 return std::sqrt(std::numeric_limits<double>::epsilon());
4331 return std::sqrt(std::numeric_limits<double>::epsilon()) *
4332 std::max(1.0, query.norm());
4333}
4334
4336{
4337 if (!std::isfinite(beta) || beta < 0.0)
4338 throw std::invalid_argument(
4339 "kappa dimer beta must be finite and nonnegative");
4340 if (beta == 0.0) {
4341 kappa_dimer_beta_ = 0.0;
4342 kappa_dimer_client_.reset();
4343 return;
4344 }
4345 if (!kappa_dimer_client_) {
4346 auto client = std::make_unique<gpr::neb::RgsaddleClient>();
4347 if (!client->load() || !client->hasKappaDimer())
4348 throw std::runtime_error(
4349 "kappa dimer requires the linked rgsaddle kappa force ABI: " +
4350 client->lastMessage());
4351 kappa_dimer_client_ = std::move(client);
4352 }
4353 kappa_dimer_beta_ = beta;
4354 if (rgmin_trans_) rgmin_trans_->forget();
4355}
4356
4357void AtomicDimer::resetTranslationHistory(gpr::LBFGSInfo& history)
4358{
4359 // Secants belong to one posterior, active coordinate space and accepted
4360 // translation sequence, independently of the selected L-BFGS backend.
4361 history.clear();
4362 if (rgmin_trans_) rgmin_trans_->forget();
4363}
4364
4366 const gpr::Coord& orient,
4367 const gpr::Observation& approx_obs,
4368 const double curvature,
4369 gpr::LBFGSInfo& trans_info, gpr::Coord& R_new)
4370{
4372 dimer.setProjectRotations(
4374 dimer.bindRgminTranslation(rgmin_trans_.get());
4375 gpr::Coord G01_approx_negative;
4376
4377 gpr::field::appendRow(G01_approx_negative, approx_obs.G, 0);
4378 G01_approx_negative *= -1.;
4379
4380 if (kappa_dimer_beta_ == 0.0) {
4381 if (kappa_dimer_refining_) resetTranslationHistory(trans_info);
4382 kappa_dimer_refining_ = false;
4383 if (curvature < 0.0 &&
4384 projectedTrustRegionStep(middle_point.R, G01_approx_negative,
4385 transition_param.max_step_length, R_new))
4386 return;
4387 dimer.translate(middle_point.R, orient, G01_approx_negative, curvature,
4388 transition_param, trans_info, R_new);
4389 return;
4390 }
4391 const Eigen::Index dof = middle_point.R.cols();
4392 Eigen::MatrixXd excluded(dof, 0);
4394 excluded = dimer::rigid_motion_basis(
4395 middle_point.R,
4397 const Eigen::VectorXd gradient = approx_obs.G.row(0).transpose();
4398 // The contour force is a basin constraint: it keeps a dimer that has
4399 // not yet reached a ridge from converging to a saddle of another basin.
4400 // At certified negative curvature along the dimer the search is on the
4401 // ridge, and Xiao's near-saddle protocol sets both switching
4402 // coefficients to unity, the ordinary dimer force. Near a saddle the
4403 // contour mode is the dimer mode itself: kappa = -nu/|g| diverges as
4404 // the gradient vanishes, the parallel coefficient tends to -1, and the
4405 // contour force walks the dimer back down its own mode. A gradient
4406 // threshold on the switch (12_h2co: 55 of 57 phases measured a step
4407 // that raised the residual, the search alternating between the two
4408 // forces) only moves where that happens.
4409 const bool refine = curvature < 0.0;
4410 if (refine != kappa_dimer_refining_) resetTranslationHistory(trans_info);
4411 kappa_dimer_refining_ = refine;
4412 if (refine) {
4413 log_man << "Kappa dimer refinement: curvature=" << curvature
4414 << " hessian_actions=0\n";
4415 if (projectedTrustRegionStep(middle_point.R, G01_approx_negative,
4416 transition_param.max_step_length, R_new))
4417 return;
4418 dimer.translate(middle_point.R, orient, G01_approx_negative, curvature,
4419 transition_param, trans_info, R_new);
4420 return;
4421 }
4422 prepareIndexOneProjection(middle_point.R);
4423 const auto hessian = gpr_model->prepareMeanHessian(middle_point.R);
4424 std::function<bool(const Eigen::VectorXd&, Eigen::VectorXd&)> action =
4425 [&](const Eigen::VectorXd& v, Eigen::VectorXd& hv) {
4426 const bool ok = hessian && hessian(v, hv);
4427 if (ok) applyIndexOneProjection(v, hv);
4428 return ok;
4429 };
4430 const auto callback = [](void* user, int64_t n, const double* v,
4431 double* hv) -> int {
4432 auto& apply = *static_cast<decltype(action)*>(user);
4433 try {
4434 Eigen::VectorXd result;
4435 if (!apply(Eigen::Map<const Eigen::VectorXd>(v, n), result) ||
4436 result.size() != n || !result.allFinite())
4437 return -1;
4438 Eigen::Map<Eigen::VectorXd>(hv, n) = result;
4439 return 0;
4440 } catch (...) {
4441 return -1;
4442 }
4443 };
4444 // The linked client is ABI minor 71 or later. Pass its minor.
4445 const std::uint32_t kappa_abi_minor =
4446 std::max(kappa_dimer_client_->abiMinor(),
4449 {GPR_RGSADDLE_ABI_MAJOR, kappa_abi_minor},
4450 kappa_dimer_beta_,
4451 1e-5,
4452 100,
4453 12,
4454 14};
4456 gpr::Coord force(1, dof);
4457 const int status = kappa_dimer_client_->kappaDimerForce(
4458 &config, dof, gradient.data(), orient.data(), excluded.cols(),
4459 excluded.data(), callback, &action, force.data(), &report);
4460 if (status != 0) {
4461 // A refused kappa force (a non-finite surrogate Hessian action at
4462 // this midpoint, a solver failure) is a statement about the
4463 // surrogate here, not a reason to end the search: the plain dimer
4464 // translation on the surrogate gradient takes the step, and the
4465 // measured checks of the outer loop judge it. A non-finite
4466 // gradient leaves the midpoint in place for the same judgement.
4467 log_man << "Kappa dimer force unavailable (rgsaddle status " << status
4468 << "); plain dimer translation on the surrogate gradient.\n";
4469 if (!G01_approx_negative.allFinite()) {
4470 R_new = middle_point.R;
4471 return;
4472 }
4473 dimer.translate(middle_point.R, orient, G01_approx_negative, curvature,
4474 transition_param, trans_info, R_new);
4475 return;
4476 }
4477 log_man << "Kappa dimer: kappa=" << report.kappa
4478 << " tangent_curvature=" << report.tangent_curvature
4479 << " hessian_actions=" << report.hessian_actions << "\n";
4480 dimer.translateWithForce(middle_point.R, force, transition_param,
4481 trans_info, R_new);
4482}
4483
4485 gpr::LBFGSInfo& rot_info,
4486 gpr::LBFGSInfo& trans_info)
4487{
4488 aux::ProblemSetUp setup;
4489 bool atoms_were_updated = false;
4490
4491 if (debug_level == DEBUG_L1 || debug_level == DEBUG_L2 ||
4492 debug_level == DEBUG_L3) {
4493 log_man << "Frozen:: "
4494 << atoms_config.atoms_froz_active.positions.size()
4495 << " active, "
4496 << atoms_config.atoms_froz_inactive.positions.size()
4497 << " inactive\n"
4498 << "Moving:: " << atoms_config.atoms_mov.positions.size()
4499 << " Total:: " << atoms_config.positions.size() << "\n";
4500 }
4501
4502 if (std::isfinite(actdist_fro)) {
4503 atoms_were_updated =
4504 setup.activateFrozenAtoms(R_new, actdist_fro, atoms_config);
4505 active_frozen_count_ = static_cast<gpr::Index_t>(
4506 atoms_config.atoms_froz_active.positions.cols() / 3);
4507 if (atoms_were_updated) {
4508 ++active_set_change_count_;
4509 if (profile_phase_timing_) {
4510 log_man << "Active-frozen-set change #"
4511 << active_set_change_count_ << ": now "
4512 << active_frozen_count_ << " active frozen atoms.\n";
4513 }
4514 log_man << "More frozen atoms activated. Syncing GPR.\n";
4515
4516 // Keep the GPR model descriptor tables aligned with the
4517 // active/frozen atom partition used by the dimer.
4518 gpr_model->updateConfiguration(atoms_config);
4519
4520 // The optimizer histories depend on the active coordinate
4521 // subspace and are reset when that subspace changes.
4522 rot_info.clear();
4523 resetTranslationHistory(trans_info);
4524
4525 // Hyperparameters are re-optimized after the configuration is
4526 // synchronized in performRotationAndTranslationWithGPR.
4527 }
4528 }
4529 return atoms_were_updated;
4530}
4531
4532void AtomicDimer::setMeasuredTrialAnchor(const gpr::Coord& measured)
4533{
4534 measured_trial_anchor_ = measured;
4535 measured_trial_region_.setTrainingData(measured_trial_anchor_);
4536}
4537
4538void AtomicDimer::shrinkMeasuredTrialTrust(double displacement,
4539 const gpr::Coord& accepted)
4540{
4541 if (!measured_trial_trust_) {
4543 trust.tau = 1.0;
4544 // The acquisition radius is independent of the roundoff criterion
4545 // for numerical stagnation.
4546 trust.radius_floor = 1e-6;
4547 trust.radius_ceiling =
4548 std::max(displacement, transition_param.max_step_length);
4549 measured_trial_trust_.emplace(trust);
4550 measured_trial_trust_->initFromTrainingSpread(displacement);
4551 } else if (displacement < measured_trial_trust_->radius()) {
4552 measured_trial_trust_->initFromTrainingSpread(displacement);
4553 }
4554 measured_trial_trust_->updateRadiusFromRhoValue(0.0);
4555 setMeasuredTrialAnchor(accepted);
4556}
4557
4558void AtomicDimer::recordOracleTrialFailure(const std::string& what)
4559{
4560 ++consecutive_oracle_failures_;
4561 log_man << "True-PES evaluation failed (" << consecutive_oracle_failures_
4562 << " of at most " << kMaxConsecutiveOracleFailures
4563 << " in a row): " << what << "; rejecting the trial.\n";
4564 if (consecutive_oracle_failures_ > kMaxConsecutiveOracleFailures)
4565 throw std::runtime_error(
4566 "the oracle failed at " +
4567 std::to_string(consecutive_oracle_failures_) +
4568 " consecutive trial geometries, past the bound of " +
4569 std::to_string(kMaxConsecutiveOracleFailures) + "; last: " + what);
4570}
4571
4572bool AtomicDimer::limitMeasuredTrial(const gpr::Coord& current,
4573 gpr::Coord& proposed)
4574{
4575 if (!measured_trial_trust_ || current.rows() != 1 || proposed.rows() != 1 ||
4576 measured_trial_anchor_.rows() != 1 ||
4577 current.cols() != proposed.cols() ||
4578 measured_trial_anchor_.cols() != current.cols())
4579 return false;
4580 const double radius = measured_trial_trust_->radius();
4581 Eigen::VectorXd start = current.row(0).transpose();
4582 if (!measured_trial_region_.isWithinTrust(start, radius))
4583 start = measured_trial_anchor_.row(0).transpose();
4584 Eigen::VectorXd bounded = proposed.row(0).transpose();
4585 measured_trial_region_.projectLineToTrustBoundary(
4586 start, proposed.row(0).transpose(), radius, bounded);
4587 if ((bounded.array() == proposed.row(0).transpose().array()).all())
4588 return false;
4589 proposed.row(0) = bounded.transpose();
4590 return true;
4591}
4592
4593std::vector<int> AtomicDimer::contactDomainAtomicNumbers(
4594 Eigen::Index moving_count, Eigen::Index frozen_active_count) const
4595{
4596 // Moving atoms first, then the active frozen atoms, matching the
4597 // coordinate layout the contact limiter assembles. Frozen atoms get
4598 // their numbers only when every frozen atom is active, so the order
4599 // is the frame's; otherwise their pairs keep the scalar floor.
4600 std::vector<int> numbers;
4601 const Eigen::Index n_atoms = atoms_config.atomicNrs.size();
4602 if (n_atoms <= 0 || atoms_config.is_frozen.size() != n_atoms)
4603 return numbers;
4604 std::vector<int> moving, frozen;
4605 for (Eigen::Index a = 0; a < n_atoms; ++a) {
4606 const int z = static_cast<int>(atoms_config.atomicNrs(0, a));
4607 if (atoms_config.is_frozen(0, a) == MOVING_ATOM)
4608 moving.push_back(z);
4609 else
4610 frozen.push_back(z);
4611 }
4612 if (static_cast<Eigen::Index>(moving.size()) != moving_count)
4613 return numbers;
4614 numbers = moving;
4615 if (static_cast<Eigen::Index>(frozen.size()) == frozen_active_count)
4616 numbers.insert(numbers.end(), frozen.begin(), frozen.end());
4617 return numbers;
4618}
4619
4620bool AtomicDimer::limitTranslation(const gpr::Coord& R,
4621 gpr::LBFGSInfo& trans_info,
4622 gpr::Coord& R_new, bool* measured_boundary)
4623{
4624 const bool limited = limitTranslationGeometry(R, trans_info, R_new);
4625 const bool measured_limited = limitMeasuredTrial(R, R_new);
4626 if (measured_boundary) *measured_boundary = measured_limited;
4627 if (measured_limited) {
4628 resetTranslationHistory(trans_info);
4629 return true;
4630 }
4631 return limited;
4632}
4633
4634bool AtomicDimer::limitTranslationGeometry(const gpr::Coord& R,
4635 gpr::LBFGSInfo& trans_info,
4636 gpr::Coord& R_new)
4637{
4638 aux::Distance distance;
4639 gpr::FieldMatrixd R_diff;
4640 gpr::FieldMatrixd dist;
4641 gpr::FieldMatrixd step_length_atomwise;
4642 double tmp = 0.;
4643 double step_coeff = 0.;
4644 gpr::FieldMatrixd steplength_atomwise_limit;
4645 bool step_length_is_larger_than_limit = false;
4646
4647 R_diff = R_new - R;
4648
4649 // atom-wise step lengths
4650 step_length_atomwise.resize(R.rows(), R.cols() / 3);
4651 step_length_atomwise.setZero();
4652 for (gpr::Index_t i = 0; i < R_new.rows(); ++i) {
4653 for (gpr::Index_t j = 0; j < R_new.cols(); j += 3) {
4654 double x = R_new(i, j) - R(i, j);
4655 double y = R_new(i, j + 1) - R(i, j + 1);
4656 double z = R_new(i, j + 2) - R(i, j + 2);
4657 *(step_length_atomwise.data() + j / 3) +=
4658 sqrt(x * x + y * y + z * z);
4659 }
4660 }
4661
4662 distance.mindist_interatomic(R, atoms_config, dist);
4663 steplength_atomwise_limit.resize(1, dist.size());
4664 tmp = 0.5 * (1. - ratio_at_limit);
4665 for (gpr::Index_t n = 0; n < steplength_atomwise_limit.size(); ++n) {
4666 *(steplength_atomwise_limit.data() + n) = tmp * *(dist.data() + n);
4667 }
4668
4669 for (gpr::Index_t n = 0; n < steplength_atomwise_limit.size(); ++n) {
4670 if (*(step_length_atomwise.data() + n) >
4671 0.99 * *(steplength_atomwise_limit.data() + n)) {
4672 step_length_is_larger_than_limit = true;
4673 break;
4674 }
4675 }
4676
4677 if (step_length_is_larger_than_limit) {
4678 step_coeff = std::numeric_limits<double>::max();
4679 for (gpr::Index_t n = 0; n < steplength_atomwise_limit.size(); ++n) {
4680 tmp = *(steplength_atomwise_limit.data() + n) /
4681 *(step_length_atomwise.data() + n);
4682 if (tmp < step_coeff) {
4683 step_coeff = tmp;
4684 }
4685 }
4686 step_coeff *= 0.99;
4687
4688 R_new = R + (R_new - R) * step_coeff;
4689
4690 resetTranslationHistory(trans_info);
4691 }
4692
4693 if (ratio_at_limit > 0.0 && ratio_at_limit < 1.0 &&
4694 std::isfinite(seed_min_interatomic_) && seed_min_interatomic_ > 0.0) {
4695 std::array<double, 9> cell{};
4696 std::copy_n(atoms_config.cell, cell.size(), cell.begin());
4697 const auto& frozen = atoms_config.atoms_froz_active.positions;
4698 const Eigen::Index moving_count = R.cols() / 3;
4699 gpr::geometry::ElementPairContactFloor floor(
4700 ratio_at_limit * seed_min_interatomic_,
4701 contactDomainAtomicNumbers(moving_count, frozen.size() / 3));
4702 const auto assemble = [&](const Eigen::VectorXd& point) {
4703 Eigen::VectorXd all_positions(point.size() + frozen.size());
4704 all_positions.head(point.size()) = point;
4705 if (frozen.size() > 0)
4706 all_positions.tail(frozen.size()) = frozen.row(0).transpose();
4707 return all_positions;
4708 };
4709 // The starting midpoint is a geometry the user supplied as ordinary;
4710 // an element floor it violates (a Lennard-Jones solid under a
4711 // chemical label) takes its scale from it.
4712 if (contact_reference_geometries_.cols() == R.cols()) {
4713 std::vector<Eigen::VectorXd> references;
4714 references.reserve(
4715 static_cast<std::size_t>(contact_reference_geometries_.rows()));
4716 for (Eigen::Index i = 0; i < contact_reference_geometries_.rows();
4717 ++i)
4718 references.push_back(
4719 assemble(contact_reference_geometries_.row(i).transpose()));
4720 floor.calibrateToGeometries(references, cell, moving_count);
4721 }
4722 const Eigen::VectorXd constrained =
4724 R.row(0).transpose(), R_new.row(0).transpose(), 1.0,
4725 [&](const Eigen::VectorXd& point) {
4726 return floor.minimumRatio(assemble(point), cell,
4727 moving_count);
4728 });
4729 if ((constrained.array() != R_new.row(0).transpose().array()).any()) {
4730 R_new.row(0) = constrained.transpose();
4731 resetTranslationHistory(trans_info);
4732 step_length_is_larger_than_limit = true;
4733 }
4734 }
4735 return step_length_is_larger_than_limit;
4736}
4737
4738bool AtomicDimer::retractTranslation(const gpr::Coord& R, gpr::Coord& R_new,
4739 bool* measured_boundary)
4740{
4741 const bool retracted = retractTranslationGeometry(R, R_new);
4742 const bool measured_limited = retracted && limitMeasuredTrial(R, R_new);
4743 if (measured_boundary) *measured_boundary = measured_limited;
4744 return retracted;
4745}
4746
4747bool AtomicDimer::retractTranslationGeometry(const gpr::Coord& R,
4748 gpr::Coord& R_new)
4749{
4750 if (R.rows() != 1 || R_new.rows() != 1 || R.cols() != R_new.cols() ||
4751 R.cols() < 6 || R.cols() % 3 != 0 || !R.allFinite() ||
4752 !R_new.allFinite()) {
4753 if (R.rows() == 1 && R.cols() >= 6 && R.cols() % 3 == 0 &&
4754 R.allFinite()) {
4755 R_new = R;
4756 }
4757 return false;
4758 }
4759 const int n_atoms = static_cast<int>(R.cols() / 3);
4760 const Eigen::VectorXd positions = R.row(0).transpose();
4761 const Eigen::VectorXd step = (R_new - R).row(0).transpose();
4762 if ((step.array() == 0.0).all()) {
4763 R_new = R;
4764 return true;
4765 }
4766 std::array<double, 9> cell{};
4767 std::copy_n(atoms_config.cell, cell.size(), cell.begin());
4768 std::vector<char> moving(static_cast<std::size_t>(n_atoms), 1);
4769 if (atoms_config.is_frozen.rows() == 1 &&
4770 atoms_config.is_frozen.cols() == n_atoms) {
4771 for (int atom = 0; atom < n_atoms; ++atom) {
4772 moving[static_cast<std::size_t>(atom)] =
4773 atoms_config.is_frozen(0, atom) == 0 ? 1 : 0;
4774 }
4775 }
4776 try {
4778 n_atoms, positions, moving, gpr::geometry::BondGraphKind::Gabriel,
4779 cell);
4780 if (primitives.empty()) {
4781 R_new = R;
4782 return false;
4783 }
4784 const gpr::geometry::InternalCoordinateSet coords(
4785 n_atoms, std::move(moving), std::move(primitives), cell);
4786 const Eigen::VectorXd retracted =
4787 gpr::geometry::retractRestrictedStep(coords, positions, step);
4788 if (retracted.size() != positions.size() || !retracted.allFinite()) {
4789 log_man << "Internal-coordinate retraction failed; the trial "
4790 "was not replaced.\n";
4791 R_new = R;
4792 return false;
4793 }
4794 if ((retracted.array() == positions.array()).all()) {
4795 R_new = R;
4796 return true;
4797 }
4798 R_new.row(0) = retracted.transpose();
4799 return true;
4800 } catch (const gpr::geometry::InternalCoordinateRetractionFailed&) {
4801 log_man << "Internal-coordinate retraction failed; the trial "
4802 "was not replaced.\n";
4803 R_new = R;
4804 return false;
4805 } catch (const gpr::geometry::UndefinedInternalCoordinate&) {
4806 log_man << "Internal-coordinate retraction failed; a primitive is "
4807 "undefined and the trial was not replaced.\n";
4808 R_new = R;
4809 return false;
4810 } catch (const std::invalid_argument&) {
4811 log_man << "Internal-coordinate retraction failed; the trial "
4812 "was not replaced.\n";
4813 R_new = R;
4814 return false;
4815 } catch (const std::runtime_error&) {
4816 log_man << "Internal-coordinate retraction failed; the trial "
4817 "was not replaced.\n";
4818 R_new = R;
4819 return false;
4820 }
4821}
4822
4823double AtomicDimer::shortestKernelLengthScale() const noexcept
4824{
4825 if (gpr_model == nullptr) return std::numeric_limits<double>::quiet_NaN();
4826 const auto& scales =
4827 gpr_model->getSexpAtCovarianceFunction().getLengthScaleRef();
4828 double shortest = std::numeric_limits<double>::infinity();
4829 for (Eigen::Index i = 0; i < scales.size(); ++i) {
4830 const double value = scales(i);
4831 if (std::isfinite(value) && value > 0.0)
4832 shortest = std::min(shortest, value);
4833 }
4834 return std::isfinite(shortest) ? shortest
4835 : std::numeric_limits<double>::quiet_NaN();
4836}
4837
4838void AtomicDimer::recordPredictedMeasuredAgreement(
4839 const gpr::Observation& predicted, const gpr::Observation& measured)
4840{
4841 if (predicted.E.size() == 0 || measured.E.size() == 0 ||
4842 predicted.G.rows() < 1 || measured.G.rows() < 1 ||
4843 predicted.G.cols() != measured.G.cols() || measured.R.rows() < 1)
4844 return;
4845 const double energy_error = std::abs(predicted.E(0, 0) - measured.E(0, 0));
4846 gpr::Coord error(1, measured.G.cols());
4847 error.row(0) = measured.G.row(0) - predicted.G.row(0);
4848 const double force_error =
4849 forceNormForConvergence(measured.R.row(0), error.row(0));
4850 const double force_scale = dimerPosteriorActionForceScale(
4851 forceNormForConvergence(measured), stop_citeria_dimer.force);
4852 const double length_scale = shortestKernelLengthScale();
4853 if (!std::isfinite(energy_error) || !std::isfinite(force_error) ||
4854 !std::isfinite(force_scale) || !std::isfinite(length_scale))
4855 return;
4856 model_force_error_ = force_error;
4857 model_force_scale_ = force_scale;
4858 model_energy_error_ = energy_error;
4859 model_energy_scale_ = force_scale * length_scale;
4860}
4861
4862AtomicDimer::InterAtomicTrustDistance
4863AtomicDimer::evaluateInterAtomicTrustDistance(const gpr::Coord& R_new,
4864 const gpr::Coord& R_all) const
4865{
4866 InterAtomicTrustDistance trust;
4867 aux::Distance distance;
4868 gpr::FieldMatrixd dist;
4869 if (early_params._use_adaptive_threshold) {
4870 const int num_data_points = static_cast<int>(all_obs.E.size());
4871
4872 const double t_min = early_params._adaptive_t_min;
4873 const double delta_t_explore = early_params._adaptive_delta_explore;
4874 const int n_half = std::max(1, early_params._adaptive_half_life);
4875
4876 const double k = std::log(2.0) / n_half;
4877 const double earned_thresh =
4878 t_min + delta_t_explore * (1.0 - std::exp(-k * num_data_points));
4879
4880 const double num_atoms = std::max(
4881 1.0, static_cast<double>(atoms_config.atoms_mov.type.size()));
4882 const double adaptive_A = early_params._adaptive_A;
4883 const double adaptive_floor = early_params._adaptive_floor;
4884 const double physical_limit =
4885 std::max(adaptive_floor, adaptive_A / std::sqrt(num_atoms));
4886
4887 trust.threshold = std::min(earned_thresh, physical_limit);
4888
4889 } else {
4890 trust.threshold = early_params._threshold;
4891 }
4892 // Now get the actual distance
4893 switch (early_params._dist_metric) {
4895 distance.dist_max1Dlog(R_new, R_all, atoms_config, dist);
4896 trust.threshold = fabs(log(ratio_at_limit));
4897 break;
4898 }
4900 distance.dist_emd(R_new, R_all, atoms_config, dist);
4901 break;
4902 }
4904 distance.dist_rmsd(R_new, R_all, atoms_config, dist);
4905 break;
4906 }
4907 default:
4908 throw("Shouldn't be here");
4909 }
4910 if (early_params._dist_metric == DistanceMetricType::EMD ||
4911 early_params._dist_metric == DistanceMetricType::RMSD) {
4912 trust.threshold = modelAgreementTrustDistance(
4913 trust.threshold, shortestKernelLengthScale(), model_force_error_,
4914 model_force_scale_, model_energy_error_, model_energy_scale_);
4915 }
4916 trust.distance = dist.minCoeff();
4917 return trust;
4918}
4919
4920bool AtomicDimer::isInterAtomicDistanceTooBig(const gpr::Coord& R_new,
4921 const gpr::Coord& R_all,
4922 gpr::Index_t& num_es1)
4923{
4924 const InterAtomicTrustDistance trust =
4925 evaluateInterAtomicTrustDistance(R_new, R_all);
4926 const bool res = trust.distance > trust.threshold;
4927
4928 if (res) {
4929 ++num_es1;
4930 }
4931
4932 log_man << "NOTE: got " << trust.distance << " compared to "
4933 << trust.threshold << ".\n";
4934 return res;
4935}
4936
4937bool AtomicDimer::projectInterAtomicTrustBoundary(const gpr::Coord& R_current,
4938 const gpr::Coord& R_trial,
4939 const gpr::Coord& R_all,
4940 gpr::Coord& R_projected) const
4941{
4942 const InterAtomicTrustDistance trial_trust =
4943 evaluateInterAtomicTrustDistance(R_trial, R_all);
4944 if (!std::isfinite(trial_trust.distance) ||
4945 !(trial_trust.distance > trial_trust.threshold)) {
4946 R_projected = R_trial;
4947 return false;
4948 }
4949
4950 const InterAtomicTrustDistance current_trust =
4951 evaluateInterAtomicTrustDistance(R_current, R_all);
4952 if (!std::isfinite(current_trust.distance) ||
4953 current_trust.distance > current_trust.threshold) {
4954 R_projected = R_current;
4955 return false;
4956 }
4957
4958 gpr::TrustRadius trust_policy;
4959 trust_policy.setTrainingData(R_all);
4960 trust_policy.setAtomsConfiguration(atoms_config);
4961 trust_policy.setDistanceMetric(early_params._dist_metric);
4962 const Eigen::VectorXd current = R_current.row(0).transpose();
4963 const Eigen::VectorXd trial = R_trial.row(0).transpose();
4964 Eigen::VectorXd projected;
4965 if (!trust_policy.projectLineToTrustBoundary(
4966 current, trial, trial_trust.threshold, projected)) {
4967 R_projected = R_current;
4968 return false;
4969 }
4970 R_projected.resize(1, projected.size());
4971 R_projected.row(0) = projected.transpose();
4972 return true;
4973}
4974
4975gpr::Index_t AtomicDimer::getNumEvaluations()
4976{
4977 // The accurate evaluations this search paid. The row count of
4978 // ~all_obs~ is not that number: an attached session GP hands over a
4979 // deduplicated set, and near-duplicate acquisitions coalesce into
4980 // existing rows, so ~rows - N_obs_init~ went negative in the escape
4981 // log (4294967277 image evaluations).
4982 return num_of_gen_potential_calls;
4983}
4984
4985void AtomicDimer::checkIfMaxIterReachedAndPrintWarning(
4986 const gpr::Index_t iter_counter, const gpr::Index_t iter_limit,
4987 const std::string& message)
4988{
4989 // Call sites pass the post-loop counter of a `for (i = 0; i < limit;
4990 // ++i)` loop: exhaustion leaves it AT the limit, a final-iteration
4991 // convergence break leaves it at limit - 1.
4992 if (iter_counter == iter_limit) {
4993 log_man << "WARNING: Maximum number of iterations " << iter_counter
4994 << " is reached during the " << message << ".\n";
4995 }
4996}
4997
4998void AtomicDimer::defineStartPath(
4999 const gpr::Coord& R_latest_conv, const gpr::Coord& orient_latest_conv,
5000 const gpr::Coord& orient_init_gpr, const gpr::Index_t outer_iter_idx,
5001 gpr::Coord& R_previous, gpr::Coord& orient_previous,
5002 gpr::Observation& middle_point, gpr::Coord& orient)
5003{
5004 if (outer_iter_idx < num_bigiter_initloc) {
5005 middle_point.R = middle_point_init.R;
5006 orient = orient_init_gpr;
5007 log_man << "Started relaxation phase from the initial location.\n";
5008 return;
5009 }
5010
5011 const bool has_latest_converged_dimer = R_latest_conv.size() != 0;
5012 const bool has_stored_stop_point = R_previous.size() != 0;
5013
5014 if (has_stored_stop_point) {
5015 middle_point.R = R_previous;
5016 orient = orient_previous;
5017 log_man << "Started relaxation phase from the stored stop point.\n";
5018 R_previous.resize(0, 0);
5019 orient_previous.resize(0, 0);
5020 } else if (has_latest_converged_dimer) {
5021 middle_point.R = R_latest_conv;
5022 orient = orient_latest_conv;
5023 log_man << "Started relaxation phase from the latest converged "
5024 "dimer.\n";
5025 } else {
5026 middle_point.R = middle_point_init.R;
5027 orient = orient_init_gpr;
5028 log_man << "Started relaxation phase from the initial location.\n";
5029 }
5030}
5031
5032double AtomicDimer::performRotationAndTranslationWithGPR(
5033 const double stop_dimer_gp, gpr::Observation& middle_point,
5034 gpr::Coord& orient, gpr::Coord& R_latest_conv, gpr::Coord& R_previous,
5035 gpr::Coord& orient_latest_conv, gpr::Coord& orient_previous,
5036 gpr::Coord& R_new, gpr::Index_t& num_esmax, gpr::Index_t& num_es1,
5037 const size_t& outer_iter_idx, bool& require_midpoint_oracle,
5038 DimerSurrogateActionCertificate* first_action, bool stop_after_first_action,
5039 const gpr::Observation* measured_reference)
5040{
5041 LocalPotentialReference local_reference;
5042 local_reference.measured = measured_reference;
5043 struct RestoreReference {
5044 LocalPotentialReference*& slot;
5045 LocalPotentialReference* previous;
5046 ~RestoreReference()
5047 {
5048 slot = previous;
5049 }
5050 } restore{local_potential_reference_, local_potential_reference_};
5051 local_potential_reference_ =
5052 measured_reference ? &local_reference : nullptr;
5053 (void)outer_iter_idx;
5054 (void)R_latest_conv;
5055 (void)orient_latest_conv;
5056 // gpr::LBFGSInfo rot_info; // Information on rotation
5057 // gpr::LBFGSInfo trans_info; // Information on translation
5058 gpr::LBFGSInfo rot_info;
5059 gpr::LBFGSInfo trans_info;
5060 gpr::Observation approx_obs;
5061 gpr::Coord temp;
5062 gpr::Index_t inner_iter;
5063 double curvature = 0.;
5064 require_midpoint_oracle = false;
5065 DimerSurrogateActionCertificate* action_sink = first_action;
5066 if (action_sink == nullptr && outer_iter_idx == 0)
5067 action_sink = &first_surrogate_action_;
5068 if (action_sink != nullptr) *action_sink = {};
5069 const auto record_first_action =
5070 [&](DimerSurrogateActionTermination termination,
5071 double action_curvature,
5072 DimerProposalGlobalizationAction proposal_action,
5073 DimerResidualGlobalizationAction residual_action,
5074 const gpr::Coord& action_positions) {
5075 if (action_sink == nullptr || action_sink->valid) return;
5076 action_sink->termination = termination;
5077 action_sink->proposal_action = proposal_action;
5078 action_sink->residual_action = residual_action;
5079 action_sink->mode = orient;
5080 action_sink->trial_positions = action_positions;
5081 action_sink->curvature = action_curvature;
5082 action_sink->rotation_tolerance = stop_citeria_gpr.angle_rotation;
5083 action_sink->force_norm = convergence_force_norm;
5084 action_sink->valid =
5086 action_positions.rows() == 1 &&
5087 action_positions.cols() == middle_point.R.cols() &&
5088 action_positions.cols() > 0 && action_positions.allFinite();
5089 };
5090
5091 rot_info.clear();
5092 rot_info.num_cg_iter = middle_point.R.cols();
5093 rot_info.num_lbfgs_iter = middle_point.R.cols();
5094
5095 resetTranslationHistory(trans_info);
5096 trans_info.num_cg_iter = middle_point.R.cols();
5097 trans_info.num_lbfgs_iter = middle_point.R.cols();
5098
5099 // Preceding accepted geometry for the period-two cycle certificate.
5100 // Empty until the first step is accepted; force scale uses the configured
5101 // dimer convergence norm, matching the surrogate force stop criterion.
5102 gpr::Coord R_cycle_preceding;
5103 gpr::Coord orient_cycle_preceding;
5104 double force_cycle_preceding = std::numeric_limits<double>::infinity();
5105 bool translation_restarted_at_current_point = false;
5106 gpr::Coord previous_inner_step;
5107 double previous_inner_curvature = std::numeric_limits<double>::quiet_NaN();
5108
5109 // A stationary-curvature target tightens final force acceptance within
5110 // the local root basin. Its smaller value does not turn local steps
5111 // into unrestricted global proposals. Posterior resolution still uses
5112 // the live force and the tightened target below.
5113 const double local_force_tolerance =
5114 std::isfinite(last_certificate_force_target_) &&
5115 std::isfinite(configured_force_criterion_)
5116 ? std::max(stop_citeria_dimer.force, configured_force_criterion_)
5117 : stop_citeria_dimer.force;
5118
5119 for (inner_iter = 0;
5120 gpr::iterationAllowedByLimit(inner_iter, max_iter_new_pairs.inner);
5121 ++inner_iter) {
5122 requireWallClock();
5123 log_man << " Inner relaxation iteration: " << inner_iter << "\n";
5124
5125 // Calculate approximated energy and gradient at the middle point
5126 // and image 1 of the dimer
5127 approx_obs.R = middle_point.R;
5128 updateLocation(orient, middle_point.R, temp);
5129 gpr::field::appendRows(approx_obs.R, temp);
5130 calculateApproximatePotential(approx_obs);
5131
5132 const double force_now =
5133 forceNormForConvergence(middle_point.R.row(0), approx_obs.G.row(0));
5134
5135 // Force convergence fixes the midpoint, but its terminal stencil
5136 // still needs the mode of the fitted surrogate at these coordinates.
5137 if (force_now < stop_dimer_gp) {
5138 curvature = performSurrogateRotation(middle_point, approx_obs,
5139 orient, rot_info);
5140 R_new = middle_point.R;
5141 record_first_action(
5145 R_previous = middle_point.R;
5146 orient_previous = orient;
5147 log_man
5148 << "Stopped relaxation phase: GP surrogate force "
5149 "criterion met after "
5150 << inner_iter + 1 << " inner iterations (surrogate force "
5151 << force_now << " < " << stop_dimer_gp
5152 << ", raw surrogate gradient norm "
5153 << approx_obs.G.row(0).norm() << ", divisor "
5154 << divisor_stop_criteria_gpr << ", T_dimer "
5155 << stop_citeria_dimer.force
5156 << "; residual vs midpoint's true gradient "
5157 << ((middle_point.G.rows() > 0 &&
5158 middle_point.G.cols() == approx_obs.G.cols())
5159 ? (approx_obs.G.row(0) - middle_point.G.row(0)).norm()
5160 : std::numeric_limits<double>::quiet_NaN())
5161 << ", rows " << all_obs.R.rows() << ", sigma2 "
5162 << gpr_model->getSigma2() << ", mag2 "
5163 << gpr_model->getSexpAtCovarianceFunction().getMagnSigma2()
5164 << ", ls "
5165 << gpr_model->getSexpAtCovarianceFunction()
5166 .getLengthScaleRef()
5167 .minCoeff()
5168 << ".."
5169 << gpr_model->getSexpAtCovarianceFunction()
5170 .getLengthScaleRef()
5171 .maxCoeff()
5172 << ", E_zero "
5173 << (E_zero_level.size() > 0 ? E_zero_level(0, 0) : 0.0)
5174 << ", E_mid "
5175 << (middle_point.E.size() > 0 ? middle_point.E(0, 0) : 0.0)
5176 << ", E_all_mean "
5177 << (all_obs.E.size() > 0 ? all_obs.E.mean() : 0.0) << ").\n";
5178 break;
5179 }
5180
5181 // E_R_gp.appendScalarAsSlice(approx_obs.E(0, 0));
5182 // maxF_R_gp.push_back(middle_point.G.getMaxAbsElt());
5183
5184 // Stop the relaxation phase if maximum number of inner iterations
5185 // reached
5186 if (max_iter_new_pairs.inner > 0 &&
5187 inner_iter == max_iter_new_pairs.inner - 1) {
5188 record_first_action(
5190 std::numeric_limits<double>::quiet_NaN(),
5193 middle_point.R);
5194 if (!assume_many_iterations) {
5195 R_previous = middle_point.R;
5196 orient_previous = orient;
5197 }
5198 log_man << "Stopped relaxation phase: maximum number of inner "
5199 "iterations "
5200 << inner_iter + 1 << " reached.\n";
5201 ++num_esmax;
5202 break;
5203 }
5204
5205 // A failed inverse approximation requests a fresh local quadratic
5206 // step. Ordinary proposals retain the configured translator.
5207 if (!translation_restarted_at_current_point ||
5208 !restartLocalTranslation(middle_point.R, approx_obs.G.topRows(1),
5209 orient, R_new, curvature))
5210 curvature = performRotationAndTranslationPure(
5211 middle_point, approx_obs, orient, R_new, rot_info, trans_info);
5212
5213 // Bail out cleanly on degenerate GP states. A non-finite curvature
5214 // (e.g. harmonic-no-saddle test fixtures, or a near-singular GP
5215 // Hessian on tiny training sets) cascades into NaN R_new via the
5216 // LBFGS rotor/translator, which then hangs the Hungarian-algorithm
5217 // EMD solve in isInterAtomicDistanceTooBig (std::abs(NaN) < 1e-9
5218 // is false, so the Kuhn-Munkres `match` lambda never returns true
5219 // and `delta = min(delta, NaN)` stays NaN forever). Treat as if
5220 // the relaxation phase reached its iteration cap.
5221 if (!std::isfinite(curvature) || !R_new.allFinite()) {
5222 log_man << "Stopped relaxation phase: non-finite curvature ("
5223 << curvature
5224 << ") or non-finite step from the GP "
5225 "surrogate after "
5226 << inner_iter + 1 << " inner iterations.\n";
5227 if (!assume_many_iterations) {
5228 R_previous = middle_point.R;
5229 orient_previous = orient;
5230 }
5231 ++num_esmax;
5232 break;
5233 }
5234
5235 // Check if new active frozen atoms and update 'atoms_config' and
5236 // 'atoms_config'
5237 if (updateActiveFrozenAtoms(R_new, rot_info, trans_info)) {
5238 log_man << "updateActiveFrozenAtoms\n";
5239 optimized_all_obs_revision_ = kUnoptimizedObservationRevision;
5240 optimizeGPRModel();
5241 }
5242
5243 // Limit the move if any atom-wise step length is larger than
5244 // 99 % of 0.5*(1-'ratio_at_limit') times the minimum inter-atomic
5245 // distance
5246 bool measured_translation_boundary = false;
5247 if (limitTranslation(middle_point.R, trans_info, R_new,
5248 &measured_translation_boundary)) {
5249 log_man << "Warning: the step length of inner iteration "
5250 << inner_iter + 1 << " limited.\n";
5251 }
5252 bool measured_retraction_boundary = false;
5253 if (retractTranslation(middle_point.R, R_new,
5254 &measured_retraction_boundary)) {
5255 log_man << "Retracted the inner trial onto the linearized "
5256 "internal-coordinate chart.\n";
5257 } else if (middle_point.R.cols() >= 6) {
5258 R_new = middle_point.R;
5259 if (!assume_many_iterations) {
5260 R_previous = middle_point.R;
5261 orient_previous = orient;
5262 }
5263 log_man << "Stopped the relaxation phase after " << inner_iter + 1
5264 << " inner iterations: internal-coordinate retraction "
5265 "failed; rejected the Cartesian trial.\n";
5266 break;
5267 }
5268
5269 // Condition-driven cycle terminality: if the deterministic
5270 // relaxation map returns to the current geometry (period-one) or
5271 // the preceding geometry (period-two) at coordinate resolution,
5272 // stop and hand the lower-force cycle member to the outer oracle.
5273 {
5274 const gpr::Coord* preceding_ptr =
5275 (R_cycle_preceding.size() != 0) ? &R_cycle_preceding : nullptr;
5276 const DimerRelaxationCycleCertificate cycle =
5277 certifyDimerRelaxationCycle(middle_point.R, R_new,
5278 preceding_ptr, force_now,
5279 force_cycle_preceding);
5280 if (cycle.terminate) {
5281 if (!cycle.retain_current) {
5282 middle_point.R = R_cycle_preceding;
5283 orient = orient_cycle_preceding;
5284 }
5285 record_first_action(
5289 middle_point.R);
5290 R_previous = middle_point.R;
5291 orient_previous = orient;
5292 log_man << "Stopped the relaxation phase after "
5293 << inner_iter + 1
5294 << " inner iterations: condition-driven dimer map "
5295 "returned to a "
5296 << (cycle.kind == DimerRelaxationCycleKind::PeriodOne
5297 ? "period-one"
5298 : "period-two")
5299 << " geometry cycle; retained lower-force member for "
5300 "oracle acquisition.\n";
5301 break;
5302 }
5303 const gpr::Coord inner_step = R_new - middle_point.R;
5304 if (previous_inner_step.size() != 0 &&
5305 repeatedProjectedTrustStep(inner_step, curvature,
5306 previous_inner_step,
5307 previous_inner_curvature)) {
5308 record_first_action(
5312 middle_point.R);
5313 R_previous = middle_point.R;
5314 orient_previous = orient;
5315 log_man << "Stopped the relaxation phase after "
5316 << inner_iter + 1
5317 << " inner iterations: the projected trust step "
5318 "repeated at the stable-basis cutoff.\n";
5319 break;
5320 }
5321 previous_inner_step = inner_step;
5322 previous_inner_curvature = curvature;
5323 }
5324
5325 // STOPPING CRITERION FOR INTER-ATOMIC DISTANCES
5326 // reject the step and stop the relaxation phase if the following
5327 // does not hold:
5328 // there is an observed data point so that all inter-atomic distances
5329 // of the current image are more than 'ratio_at_limit' (by default 2/3)
5330 // but less than 1/'ratio_at_limit' (3/2) times the corresponding
5331 // inter-atomic distance of the observed data point, i.e.,
5332 // |log(r_im/r_nearobs)| < |log(ratio_at_limit)| ( = |log(2/3)| = 0.4055
5333 // )
5334 // Measure the early-stop EMD distance against the observations
5335 // that existed when the burst started, not the growing all_obs.
5336 // The dimer appends every probe to all_obs, so checking against
5337 // the full set lets a run-away ratchet outward -- each probe is
5338 // ~es_threshold from the dimer's own previous probe and never
5339 // from a fixed reference. Slicing to the first N_obs_init rows
5340 // pins the bound to the pre-burst data so a dephased burst that
5341 // walks off the reaction path is caught.
5342 // The trusted region is every observed geometry: the dimer's own
5343 // measurements extend it. Measured against the seed rows alone,
5344 // a start placed by a loose band sat past the boundary of a
5345 // region that never grew, every step projected back onto the
5346 // same measured point, and the admission rejected it 925 times
5347 // (Birkholz 05_cpht, 06_cycbut, 09_dfcp at the 500-phase cap).
5348 const gpr::Coord& es_reference = all_obs.R;
5349 if (isInterAtomicDistanceTooBig(R_new, es_reference, num_es1)) {
5350 gpr::Coord R_projected;
5351 if (projectInterAtomicTrustBoundary(middle_point.R, R_new,
5352 es_reference, R_projected)) {
5353 middle_point.R = R_projected;
5354 const InterAtomicTrustDistance projected_trust =
5355 evaluateInterAtomicTrustDistance(middle_point.R,
5356 es_reference);
5357 log_man << "Projected relaxation step to inter-atomic trust "
5358 "boundary: got "
5359 << projected_trust.distance << " compared to "
5360 << projected_trust.threshold << ".\n";
5361 }
5362 R_previous = middle_point.R;
5363 orient_previous = orient;
5364 record_first_action(
5368 middle_point.R);
5369 log_man << "Stopped the relaxation phase after " << inner_iter + 1
5370 << " inner iterations: inter-atomic distance changes too"
5371 " much compared to 'nearest' observed data point.\n";
5372 break;
5373 }
5374
5375 // Posterior force resolution globalizes the saddle search away from
5376 // the local root basin. Inside the live convergence tolerance,
5377 // residual descent supplies the stronger local certificate. An
5378 // under-resolved endpoint becomes the next oracle target.
5379 const auto translated_force_residual = [&](const auto& gradient_row) {
5380 gpr::Coord force(1, gradient_row.size());
5381 force.row(0) = -gradient_row;
5382 gpr::Coord translated_force;
5383 dimer::Dimer progress_dimer(dimer_sep, is_subsystem(atoms_config));
5384 progress_dimer.translateForce(force, orient, translated_force);
5385 return translated_force.norm();
5386 };
5387 const double current_residual =
5388 approx_obs.G.rows() > 0 &&
5389 approx_obs.G.cols() == middle_point.R.cols() &&
5390 approx_obs.G.row(0).allFinite()
5391 ? translated_force_residual(approx_obs.G.row(0))
5392 : std::numeric_limits<double>::infinity();
5393 variance_probe_scratch_.R = R_new;
5394 calculateApproximateVariance(variance_probe_scratch_);
5395 // The walk stops where the posterior force variance reaches the
5396 // action scale. The last measured trial calibrates that variance:
5397 // where the model's error at its trial was twice the reported
5398 // uncertainty, the next walk stops at a quarter of the reported
5399 // variance (17_claisen: 3-26 boundary steps per phase on a model
5400 // whose trials measured 0.08-0.10 eV/A of error against a reported
5401 // uncertainty of 0.03-0.05).
5402 double proposed_force_variance =
5403 maxPredictiveForceVariance(variance_probe_scratch_.G,
5404 convergence_force_norm) *
5405 trial_variance_calibration_;
5406 const double reported_variance_calibration =
5407 gpr_model->reportedVarianceCalibrationFactor();
5408 double latent_force_variance =
5409 std::isfinite(reported_variance_calibration) &&
5410 reported_variance_calibration > 1.0
5411 ? proposed_force_variance / reported_variance_calibration
5412 : proposed_force_variance;
5413 const double posterior_action_force_scale =
5414 dimerPosteriorActionForceScale(force_now, stop_citeria_dimer.force);
5415 // Convergence and posterior resolution use the configured physical
5416 // force norm. The Euclidean translated residual is the smooth merit
5417 // for line search; it grows with the number of active coordinates.
5418 // A clip onto the measured-trial radius is an oracle only while
5419 // the clipped point is unresolved. A resolved clip is a step the
5420 // model already covers, and measuring it pins the walk on the
5421 // sphere of the last radius.
5422 const bool measured_boundary =
5423 measured_translation_boundary || measured_retraction_boundary;
5424 const bool boundary_requests_oracle = measuredRadiusClipRequestsOracle(
5425 measured_boundary, proposed_force_variance,
5426 posterior_action_force_scale);
5427 DimerProposalGlobalizationAction proposal_action =
5428 boundary_requests_oracle
5431 curvature, force_now, local_force_tolerance,
5432 proposed_force_variance, posterior_action_force_scale);
5433 bool have_residual_slope = false;
5434 bool transverse_instability = false;
5435 double residual_slope = std::numeric_limits<double>::quiet_NaN();
5436 const auto proposal_residual_slope = [&]() {
5437 if (have_residual_slope) return residual_slope;
5438 have_residual_slope = true;
5439 // Reflection in the dimer axis preserves the force norm, so
5440 // d(||F_translated||^2 / 2)/dt = g^T H s. Anchoring the mean
5441 // gradient leaves its Hessian unchanged.
5442 const auto slope_start = std::chrono::steady_clock::now();
5443 Eigen::VectorXd hstep;
5444 bool have_action = false;
5445 {
5446 gpr::ScopedPredictTimer timer;
5447 const auto hessian =
5448 gpr_model->prepareMeanHessian(middle_point.R);
5449 have_action =
5450 hessian &&
5451 hessian((R_new - middle_point.R).row(0).transpose(),
5452 hstep) &&
5453 hstep.size() == middle_point.R.cols() && hstep.allFinite();
5454 if (have_action) {
5455 residual_slope = approx_obs.G.row(0).dot(hstep);
5456 if (proposal_action == DimerProposalGlobalizationAction::
5458 std::isfinite(residual_slope) &&
5459 residual_slope >= 0.0) {
5460 // Retained modes propose a subspace; fresh Hessian
5461 // actions establish its signs at this geometry. The
5462 // translation can mix stable and unstable components
5463 // and need not span both negative directions itself.
5464 const auto& modes = surrogate_spectrum_.modes;
5465 if (modes.rows() == middle_point.R.cols() &&
5466 modes.cols() >= 2)
5467 transverse_instability =
5468 directionsSpanTwoNegativeCurvatures(
5469 hessian, middle_point.R, modes.col(0),
5470 modes.col(1), atoms_config);
5471 if (!transverse_instability)
5472 transverse_instability =
5473 directionsSpanTwoNegativeCurvatures(
5474 hessian, middle_point.R,
5475 orient.row(0).transpose(),
5476 (R_new - middle_point.R).row(0).transpose(),
5477 atoms_config);
5478 }
5479 }
5480 }
5481 const double slope_seconds =
5482 std::chrono::duration<double>(std::chrono::steady_clock::now() -
5483 slope_start)
5484 .count();
5485 gp_predict_seconds_ += slope_seconds;
5486 gp_predict_mean_seconds_ += slope_seconds;
5487 ++gp_predict_calls_;
5488 ++gp_predict_mean_calls_;
5489 return residual_slope;
5490 };
5491 if (proposal_action ==
5493 // A small force can coexist with several unstable modes. The
5494 // saddle merit controls overshoot while allowing transverse
5495 // descent whose force residual increases.
5496 const double slope = proposal_residual_slope();
5497 if (std::isfinite(slope) && slope >= 0.0 && inner_iter > 0 &&
5498 !translation_restarted_at_current_point) {
5499 // A positive inverse approximation can still send the force
5500 // residual uphill. Resolve the current quadratic model
5501 // before classifying transverse escape.
5502 resetTranslationHistory(trans_info);
5503 trans_info.num_cg_iter = middle_point.R.cols();
5504 trans_info.num_lbfgs_iter = middle_point.R.cols();
5505 rot_info.clear();
5506 translation_restarted_at_current_point = true;
5507 log_man << "Restarted local dimer translation after "
5508 "nonnegative force-residual slope "
5509 << slope << ".\n";
5510 continue;
5511 }
5512 if (std::isfinite(slope) && slope >= 0.0 &&
5513 transverse_instability && approx_obs.E.size() > 0 &&
5514 std::isfinite(approx_obs.E(0, 0))) {
5515 const double reference_energy = approx_obs.E(0, 0);
5516 const auto energy_change = [&](const gpr::Coord& positions) {
5517 gpr::Observation candidate;
5518 candidate.R = positions;
5519 calculateApproximatePotential(candidate);
5520 return candidate.E.size() > 0
5521 ? candidate.E(0, 0) - reference_energy
5522 : std::numeric_limits<double>::infinity();
5523 };
5524 auto merit = backtrackDimerSaddleMerit(
5525 middle_point.R, R_new, approx_obs.G.topRows(1), orient,
5526 curvature, energy_change);
5527 if (merit.accepted) {
5528 const bool shortened =
5529 !dimerGeometriesCoincide(R_new, merit.positions);
5530 R_new = std::move(merit.positions);
5531 if (shortened) {
5532 have_residual_slope = false;
5533 variance_probe_scratch_.R = R_new;
5534 calculateApproximateVariance(variance_probe_scratch_);
5535 proposed_force_variance = maxPredictiveForceVariance(
5536 variance_probe_scratch_.G,
5537 convergence_force_norm) *
5538 trial_variance_calibration_;
5539 latent_force_variance =
5540 std::isfinite(reported_variance_calibration) &&
5541 reported_variance_calibration > 1.0
5542 ? proposed_force_variance /
5543 reported_variance_calibration
5544 : proposed_force_variance;
5545 resetTranslationHistory(trans_info);
5546 trans_info.num_cg_iter = middle_point.R.cols();
5547 trans_info.num_lbfgs_iter = middle_point.R.cols();
5548 }
5549 proposal_action =
5551 curvature, force_now, local_force_tolerance,
5552 proposed_force_variance,
5553 posterior_action_force_scale) ==
5554 DimerProposalGlobalizationAction::
5555 OracleTrustedTrial
5556 ? DimerProposalGlobalizationAction::
5557 OracleTrustedTrial
5558 : DimerProposalGlobalizationAction::
5559 AcceptTrustedTrial;
5560 log_man << "Trusted transverse dimer step satisfies "
5561 "saddle merit descent (change="
5562 << merit.change
5563 << ", evaluations=" << merit.evaluations
5564 << ", shortened=" << shortened << ").\n";
5565 }
5566 }
5567 }
5568 const auto evaluate_residual = [&](const gpr::Coord& positions) {
5569 gpr::Observation candidate;
5570 candidate.R = positions;
5571 calculateApproximatePotential(candidate);
5572 if (candidate.G.rows() == 0 ||
5573 candidate.G.cols() != middle_point.R.cols() ||
5574 !candidate.G.row(0).allFinite())
5575 return std::numeric_limits<double>::infinity();
5576 return translated_force_residual(candidate.G.row(0));
5577 };
5578 DimerRelaxationBacktrackResult backtrack;
5579 if (proposal_action ==
5582 curvature, current_residual)) {
5584 middle_point.R, R_new, current_residual, evaluate_residual);
5585 }
5586 DimerResidualGlobalizationAction residual_action =
5588 proposal_action, curvature, current_residual,
5589 backtrack.accepted);
5590 // Contract a residual-descent direction when its endpoint overshoots.
5591 // A global dimer direction can instead increase the force norm at
5592 // every positive length, so residual backtracking needs its slope.
5593 double proposed_residual = std::numeric_limits<double>::infinity();
5594 if (residual_action == DimerResidualGlobalizationAction::AcceptTrial &&
5595 std::isfinite(curvature) && curvature < 0.0) {
5596 gpr::Observation proposed;
5597 proposed.R = R_new;
5598 calculateApproximatePotential(proposed);
5599 if (proposed.G.rows() > 0 &&
5600 proposed.G.cols() == middle_point.R.cols() &&
5601 proposed.G.row(0).allFinite())
5602 proposed_residual =
5603 translated_force_residual(proposed.G.row(0));
5604 if (last_step_descends_measured_negative_ &&
5605 std::isfinite(proposed_residual)) {
5606 // Along a measured negative transverse direction the
5607 // translated force grows with every step by the measured
5608 // curvature; the descent, not the residual, is the
5609 // progress, and the trust bound ends the phase.
5610 log_man << "Trusted step descends along a measured negative "
5611 "transverse direction (current="
5612 << current_residual
5613 << ", proposed=" << proposed_residual << ").\n";
5615 curvature, current_residual, proposed_residual)) {
5616 const double slope = proposal_residual_slope();
5617 if (!std::isfinite(slope) ||
5618 !std::isfinite(proposed_residual)) {
5619 residual_action = resolvedPointKeepsTheSurrogateWalk(
5621 proposed_force_variance, posterior_action_force_scale);
5622 } else if (slope < 0.0) {
5624 middle_point.R,
5625 middle_point.R + 0.5 * (R_new - middle_point.R),
5626 current_residual, evaluate_residual);
5627 residual_action = resolvedPointKeepsTheSurrogateWalk(
5629 curvature, current_residual, backtrack.accepted),
5630 proposed_force_variance, posterior_action_force_scale);
5631 } else {
5632 log_man << "Trusted global dimer step has nonnegative "
5633 "force-residual slope "
5634 << slope << " (current=" << current_residual
5635 << ", proposed=" << proposed_residual << ").\n";
5636 }
5637 }
5638 }
5639 if (residual_action ==
5641 const bool shortened =
5642 !dimerGeometriesCoincide(R_new, backtrack.positions);
5643 R_new = std::move(backtrack.positions);
5644 if (shortened) {
5645 // The GP variance need not be monotone on a proposal segment.
5646 // Resolve the retained geometry against the same action scale.
5647 variance_probe_scratch_.R = R_new;
5648 calculateApproximateVariance(variance_probe_scratch_);
5649 proposed_force_variance =
5650 maxPredictiveForceVariance(variance_probe_scratch_.G,
5651 convergence_force_norm) *
5652 trial_variance_calibration_;
5653 latent_force_variance =
5654 std::isfinite(reported_variance_calibration) &&
5655 reported_variance_calibration > 1.0
5656 ? proposed_force_variance /
5657 reported_variance_calibration
5658 : proposed_force_variance;
5660 curvature, force_now, local_force_tolerance,
5661 proposed_force_variance,
5662 posterior_action_force_scale) ==
5664 residual_action =
5666 resetTranslationHistory(trans_info);
5667 trans_info.num_cg_iter = middle_point.R.cols();
5668 trans_info.num_lbfgs_iter = middle_point.R.cols();
5669 log_man << "Backtracked trusted GP MMF proposal to strict "
5670 "residual descent after "
5671 << backtrack.evaluations
5672 << " evaluations (current=" << current_residual
5673 << ", accepted=" << backtrack.residual << ").\n";
5674 }
5675 }
5676 record_first_action(
5677 boundary_requests_oracle
5680 curvature, proposal_action, residual_action, R_new);
5681 if (residual_action ==
5683 middle_point.R = R_new;
5684 R_previous = R_new;
5685 orient_previous = orient;
5686 require_midpoint_oracle = true;
5687 last_trial_force_variance_ = proposed_force_variance;
5688 log_man << "Stopped the relaxation phase after " << inner_iter + 1
5689 << " inner iterations: handing the trust-bounded GP MMF "
5690 "trial to the true oracle after posterior/residual "
5691 "globalization requested measurement (current="
5692 << current_residual << ", last=" << backtrack.residual
5693 << ", convergence_force=" << force_now
5694 << ", curvature=" << curvature
5695 << ", force_variance=" << proposed_force_variance
5696 << ", latent_force_variance=" << latent_force_variance
5697 << ", variance_calibration="
5698 << reported_variance_calibration
5699 << ", measured_boundary=" << boundary_requests_oracle
5700 << ", force_variance_tolerance="
5701 << posterior_action_force_scale *
5702 posterior_action_force_scale
5703 << ", convergence_force_variance_tolerance="
5704 << stop_citeria_dimer.force * stop_citeria_dimer.force
5705 << ", evaluations=" << backtrack.evaluations << ").\n";
5706 break;
5707 }
5708
5709 // Otherwise accept the step and continue the relaxation
5710 R_cycle_preceding = middle_point.R;
5711 orient_cycle_preceding = orient;
5712 force_cycle_preceding = force_now;
5713 middle_point.R = R_new;
5714 translation_restarted_at_current_point = false;
5715
5716 if (stop_after_first_action) break;
5717
5718 if (debug_level == DEBUG_L3) writeLatticeData(middle_point);
5719 writeTraceFrame(middle_point, "inner_loop", inner_iter);
5720 }
5721 if (debug_level == DEBUG_L2) writeLatticeData(middle_point);
5722 writeTraceFrame(middle_point, "outer_loop", outer_iter_idx);
5723
5724 if (std::isfinite(curvature)) latest_mode_curvature_ = curvature;
5725 return curvature;
5726}
5727
5729 const gpr::Observation& oracle_middle_point,
5730 const gpr::Coord& initial_orientation)
5731{
5733 if (gpr_model == nullptr || oracle_middle_point.R.rows() != 1 ||
5734 oracle_middle_point.R.cols() == 0 ||
5735 oracle_middle_point.G.rows() != 1 ||
5736 oracle_middle_point.G.cols() != oracle_middle_point.R.cols() ||
5737 initial_orientation.rows() != 1 ||
5738 initial_orientation.cols() != oracle_middle_point.R.cols() ||
5739 !oracle_middle_point.R.allFinite() ||
5740 !oracle_middle_point.G.allFinite() ||
5741 !initial_orientation.allFinite() ||
5742 !(initial_orientation.norm() > 0.0)) {
5743 return action;
5744 }
5745
5746 gpr::Observation middle_point = oracle_middle_point;
5747 gpr::Coord orient = initial_orientation / initial_orientation.norm();
5748 gpr::Coord R_latest_conv;
5749 gpr::Coord R_previous;
5750 gpr::Coord orient_latest_conv;
5751 gpr::Coord orient_previous;
5752 gpr::Coord R_new;
5753 gpr::Index_t num_esmax = 0;
5754 gpr::Index_t num_es1 = 0;
5755 bool require_midpoint_oracle = false;
5756 const double stop_dimer_gp = surrogateForceTolerance(oracle_middle_point);
5757 try {
5758 (void)performRotationAndTranslationWithGPR(
5759 stop_dimer_gp, middle_point, orient, R_latest_conv, R_previous,
5760 orient_latest_conv, orient_previous, R_new, num_esmax, num_es1,
5761 /*outer_iter_idx=*/0, require_midpoint_oracle, &action,
5762 /*stop_after_first_action=*/true, &oracle_middle_point);
5763 } catch (const std::runtime_error& error) {
5764 log_man << "GP action preview could not certify a step: "
5765 << error.what() << "\n";
5766 first_surrogate_action_ = {};
5767 return {};
5768 }
5769 return action;
5770}
5771
5772#ifdef WITH_HDF5
5773// Dimer traces append to an existing file or create it when absent.
5774void AtomicDimer::writeHDF5(const gpr::Observation& middle_point,
5775 const std::string& addl_group, const size_t& idx)
5776{
5777 if (!hdf5_trace_enabled_) return;
5778#ifdef GPR_LINALG_SCALAPACK
5779 // Rank-gate so concurrent ranks do not race on the shared H5 file.
5780 int mpi_up = 0;
5781 MPI_Initialized(&mpi_up);
5782 if (mpi_up) {
5783 int rank = 0;
5784 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
5785 if (rank != 0) return;
5786 }
5787#endif
5788 // The dimer trace is a debug artifact. An I/O failure on it -- a stale
5789 // truncated gpridge_out.h5 left by an earlier crashed run, a locked
5790 // file, a full disk -- must never abort the optimization: the burst
5791 // result is valid whether or not the trace was recorded. (Baker 02 at
5792 // np16 aborted on 'H5Dump: failed to open/create gpridge_out.h5,
5793 // File has been truncated'.)
5794 try {
5795 gpr::io::H5Dumper file(hdf5_trace_path_,
5796 gpr::io::H5Dumper::Mode::OpenOrCreate);
5797 const std::string base = "/" + addl_group + "/" + std::to_string(idx);
5798 file.dump(base + "/positions", middle_point.R.data(),
5799 middle_point.R.size());
5800 file.dump(base + "/gradients", middle_point.G.data(),
5801 middle_point.G.size());
5802 file.dump(base + "/energy", middle_point.E.data(),
5803 middle_point.E.size());
5804 } catch (const std::exception& e) {
5805 std::cerr << "[dimer] HDF5 trace write skipped: " << e.what() << "\n";
5806 }
5807}
5808#endif
5809
5810#ifdef USE_READCON_DB
5811void AtomicDimer::setTraceCorpus(const std::string& db_path)
5812{
5813 trace_corpus_.reset();
5814 trace_con_path_.clear();
5815 // A mismatched library is an error, not a skipped corpus.
5817 try {
5818 std::filesystem::create_directories(db_path);
5819 trace_corpus_ = std::make_unique<readcon_db::Corpus>(db_path.c_str());
5820 trace_con_path_ = db_path + "/trace.con";
5821 } catch (const std::exception& e) {
5822 std::cerr << "[dimer] trace corpus open skipped: " << e.what() << "\n";
5823 trace_corpus_.reset();
5824 }
5825}
5826#endif
5827
5829 const std::string& phase, size_t idx)
5830{
5831#ifdef USE_READCON_DB
5832 if (trace_corpus_) {
5833 try {
5834 const uint64_t traj = dimerTraceTrajId(phase);
5835 if (traj == 0 || obs.R.rows() < 1 || obs.R.cols() < 3) return;
5836 readcon::RKRConFrame* frame = buildDimerTraceFrame(
5837 obs, phase, idx, atoms_config, cell_dimensions);
5838 if (!frame) return;
5839 // readcon-db's frame ingest casts this handle to its own
5840 // copy of ConFrame. That copy does not share the cdylib's
5841 // column arena, and the cast aborts in the hash table.
5842 // A one-frame file is parsed inside the corpus instead.
5843 uint32_t n_frames = 0;
5844 int st = RKRDB_ERR;
5845 const auto staging =
5846 std::filesystem::temp_directory_path() /
5847 ("gpr-dimer-trace-" + std::to_string(traj) + "-" +
5848 std::to_string(idx) + "-" +
5849 std::to_string(reinterpret_cast<uintptr_t>(frame)) + ".con");
5850 const std::string staging_path = staging.string();
5851 readcon::RKRConFrameWriter* staging_writer =
5852 readcon::create_writer_from_path_c(staging_path.c_str());
5853 if (staging_writer) {
5854 const readcon::RKRConFrame* frames[] = {frame};
5855 const bool wrote =
5856 readcon::rkr_writer_extend(staging_writer, frames, 1) ==
5857 readcon::RKR_STATUS_SUCCESS;
5858 // Close before the corpus reads the path. The writer
5859 // flushes on free.
5860 readcon::free_rkr_writer(staging_writer);
5861 if (wrote) {
5862 st = rkrdb_extend_trajectory(trace_corpus_->id(), traj,
5863 staging_path.c_str(),
5864 &n_frames);
5865 }
5866 }
5867 std::error_code remove_ec;
5868 std::filesystem::remove(staging, remove_ec);
5869 if (!trace_con_path_.empty()) {
5870 readcon::RKRConFrameWriter* writer =
5871 readcon::create_writer_from_path_append_c(
5872 trace_con_path_.c_str());
5873 if (writer) {
5874 const readcon::RKRConFrame* frames[] = {frame};
5875 (void)readcon::rkr_writer_extend(writer, frames, 1);
5876 readcon::free_rkr_writer(writer);
5877 }
5878 }
5879 readcon::free_rkr_frame(frame);
5880 if (st != RKRDB_OK) {
5881 std::cerr << "[dimer] trace corpus extend skipped\n";
5882 }
5883 } catch (const std::exception& e) {
5884 std::cerr << "[dimer] trace corpus write skipped: " << e.what()
5885 << "\n";
5886 }
5887 return;
5888 }
5889#endif
5890#ifdef WITH_HDF5
5891 writeHDF5(obs, phase, idx);
5892#else
5893 (void)obs;
5894 (void)phase;
5895 (void)idx;
5896#endif
5897}
5898
5899void AtomicDimer::writeLatticeData(gpr::Observation& middle_point)
5900{
5901 // Print the lattice (forget about the last point if they are falling
5902 // beyond the cell)
5903 gpr::Observation tmp_obs;
5904 gpr::io::FileManager file_man;
5905 std::string full_file_name_E;
5906 std::string full_file_name_R;
5907 std::string full_file_name_G;
5908 gpr::vector3_reg orig_coord = gpr::coord::at(middle_point.R, 0);
5909 gpr::vector3_reg current_coord;
5910 gpr::Index_t Jmax;
5911 gpr::Index_t Kmax;
5912
5913 orig_coord = gpr::coord::at(middle_point.R, 0);
5914 orig_coord(1) -= debug_output_info.offset;
5915 orig_coord(2) -= debug_output_info.offset;
5916 current_coord = orig_coord;
5917
5918 // NOTE: Debug output assumes a 2D grid around a single moving atom
5919 Jmax = debug_output_info.offset * 2. / debug_output_info.dy + 1;
5920 Kmax = debug_output_info.offset * 2. / debug_output_info.dz + 1;
5921
5922 // Make sure the output folder exists (portable, no shell dependency)
5923 std::filesystem::create_directories(debug_output_info.out_dir);
5924
5925 log_man << "...Writing output files: " << file_counter << "\n";
5926
5927 gpr::FieldMatrixd loc_E;
5928 gpr::Coord loc_R, loc_G;
5929 gpr::Coord loc_grid;
5930
5931 loc_grid.resize(Jmax, 3 * Kmax);
5932 loc_E.resize(Jmax, Kmax);
5933 loc_R.resize(Jmax * Kmax, middle_point.R.cols());
5934 loc_G.resize(Jmax * Kmax, middle_point.G.cols());
5935
5936 // Assuming only 1 moving atom!
5937 gpr::Index_t counter = 0;
5938 for (gpr::Index_t j = 0; j < Jmax; ++j) {
5939 current_coord(1) = orig_coord(1) + j * debug_output_info.dy;
5940 current_coord(2) = orig_coord(2);
5941 for (gpr::Index_t k = 0; k < Kmax; ++k) {
5942 tmp_obs = middle_point;
5943 current_coord(2) = orig_coord(2) + k * debug_output_info.dz;
5944 gpr::coord::set(tmp_obs.R, 0, 0, current_coord);
5945
5946 calculateApproximatePotential(tmp_obs);
5947
5948 loc_R.row(counter) = Eigen::Map<Eigen::RowVectorXd>(
5949 tmp_obs.R.data(), tmp_obs.R.size());
5950 loc_G.row(counter) = Eigen::Map<Eigen::RowVectorXd>(
5951 tmp_obs.G.data(), tmp_obs.G.size());
5952 *(loc_E.data() + counter) = *(tmp_obs.E.data());
5953 gpr::coord::set(loc_grid, j, k, current_coord);
5954 ++counter;
5955 }
5956 }
5957
5958 full_file_name_E =
5959 debug_output_info.out_dir + "/" + debug_output_info.file_name_E +
5960 std::to_string(file_counter) + "." + debug_output_info.file_extension;
5961
5962 full_file_name_R =
5963 debug_output_info.out_dir + "/" + debug_output_info.file_name_R +
5964 std::to_string(file_counter) + "." + debug_output_info.file_extension;
5965
5966 full_file_name_G =
5967 debug_output_info.out_dir + "/" + debug_output_info.file_name_G +
5968 std::to_string(file_counter) + "." + debug_output_info.file_extension;
5969
5970 file_man.writeXYZFile(full_file_name_R, loc_grid, std::ios::app);
5971 // file_man.writeXYZFile(full_file_name_R, loc_R, std::ios::app);
5972 file_man.writeXYZFile(full_file_name_G, loc_G, std::ios::app);
5973 file_man.writePlainFile(full_file_name_E, loc_E, std::ios::app);
5974
5975 ++file_counter;
5976}
5977
5978double AtomicDimer::performSurrogateRotation(gpr::Observation& middle_point,
5979 gpr::Observation& approx_obs,
5980 gpr::Coord& orient,
5981 gpr::LBFGSInfo& rot_info)
5982{
5983 double curvature = 0.;
5984 if (!use_hssvd_analytic_curvature_) {
5985 // A terminal index certificate cannot select a different translator.
5986 // Finite-dimer rotation supplies the configured rgmin step with its
5987 // mode; the complete spectrum belongs to terminal verification.
5988 surrogate_spectrum_.valid = false;
5989 index_one_clamped_modes_.clear();
5990 }
5991
5992 bool hssvd_mode_ready = false;
5993 gpr::Coord hssvd_orient;
5994 gpr::Observation hssvd_approx_obs;
5995 gpr::LBFGSInfo hssvd_rot_info;
5996 double hssvd_ritz_curvature = std::numeric_limits<double>::quiet_NaN();
5997
5998 // The requested translation model needs the complete analytic spectrum.
5999 // Its Hessian action supports every covariance backend and active
6000 // residuals.
6001 const bool analytic_mode_required =
6002 use_hssvd_analytic_curvature_ && gpr_model != nullptr;
6003 const bool finite_stencil_rotated =
6004 !analytic_mode_required && max_iter_relax_rot.inner <= 0 &&
6006 orient, approx_obs, stop_citeria_gpr.angle_rotation);
6007
6008 const gpr::Coord& hssvd_mode_reference = selectHssvdModeReference(
6009 orient_init, orient, hssvd_mode_selection_policy_,
6010 preserve_initial_alignment_reference_);
6011
6012 const std::pair<gpr::Coord, double> hssvd_mode_estimate =
6013 finite_stencil_rotated
6014 ? std::make_pair(gpr::Coord{},
6015 std::numeric_limits<double>::quiet_NaN())
6016 : estimateLowestModeAndCurvatureFromGP(
6017 middle_point.R, &hssvd_mode_reference,
6018 use_hssvd_analytic_curvature_
6019 ? SurrogateSpectrumRequest::Spectrum
6020 : SurrogateSpectrumRequest::ModeOnly);
6021 const gpr::Coord& hssvd_mode = hssvd_mode_estimate.first;
6022 if (!finite_stencil_rotated && hssvd_mode.size() == orient.size()) {
6023 const gpr::Coord aligned_hssvd_mode =
6024 (gpr::field::flatDot(orient, hssvd_mode) < 0.0) ? -hssvd_mode
6025 : hssvd_mode;
6026 const double alignment_norm = orient.norm() * hssvd_mode.norm();
6027 const double seed_mode_overlap =
6028 alignment_norm > 0.0
6029 ? std::abs(gpr::field::flatDot(orient, hssvd_mode)) /
6030 alignment_norm
6031 : 0.0;
6032 const double reference_alignment_norm =
6033 hssvd_mode_reference.norm() * hssvd_mode.norm();
6034 const double reference_mode_overlap =
6035 hssvd_mode_reference.size() == hssvd_mode.size() &&
6036 reference_alignment_norm > 0.0
6037 ? std::abs(
6038 gpr::field::flatDot(hssvd_mode_reference, hssvd_mode)) /
6039 reference_alignment_norm
6040 : 0.0;
6041 const bool have_midpoint_prediction =
6042 approx_obs.R.rows() >= 1 && approx_obs.G.rows() >= 1 &&
6043 approx_obs.R.cols() == middle_point.R.cols() &&
6044 approx_obs.G.cols() == middle_point.R.cols() &&
6045 approx_obs.E.rows() >= 1 && approx_obs.E.cols() >= 1 &&
6046 approx_obs.R.row(0).isApprox(middle_point.R.row(0));
6047 Eigen::RowVectorXd midpoint_gradient;
6048 double midpoint_energy = 0.0;
6049 if (have_midpoint_prediction) {
6050 midpoint_gradient = approx_obs.G.row(0);
6051 midpoint_energy = approx_obs.E(0, 0);
6052 }
6053
6054 orient = aligned_hssvd_mode;
6055 gpr::Coord temp;
6056 updateLocation(orient, middle_point.R, temp);
6057 const bool have_image1_prediction =
6058 have_midpoint_prediction && approx_obs.R.rows() >= 2 &&
6059 approx_obs.G.rows() >= 2 && approx_obs.E.rows() >= 1 &&
6060 approx_obs.E.cols() >= 2 &&
6061 approx_obs.R.row(1).isApprox(temp.row(0));
6062 Eigen::RowVectorXd image1_gradient;
6063 double image1_energy = 0.0;
6064 if (have_image1_prediction) {
6065 image1_gradient = approx_obs.G.row(1);
6066 image1_energy = approx_obs.E(0, 1);
6067 }
6068 approx_obs.R = middle_point.R;
6069 gpr::field::appendRows(approx_obs.R, temp);
6070 if (have_midpoint_prediction) {
6071 if (have_image1_prediction) {
6072 approx_obs.G.resize(2, middle_point.R.cols());
6073 approx_obs.G.row(0) = midpoint_gradient;
6074 approx_obs.G.row(1) = image1_gradient;
6075 approx_obs.E.resize(1, 2);
6076 approx_obs.E(0, 0) = midpoint_energy;
6077 approx_obs.E(0, 1) = image1_energy;
6078 } else {
6079 gpr::Observation image1_only;
6080 image1_only.R = temp;
6081 calculateApproximatePotential(image1_only);
6082 if (image1_only.G.rows() == 1 &&
6083 image1_only.G.cols() == middle_point.R.cols() &&
6084 image1_only.E.rows() >= 1 && image1_only.E.cols() >= 1) {
6085 approx_obs.G.resize(2, middle_point.R.cols());
6086 approx_obs.G.row(0) = midpoint_gradient;
6087 approx_obs.G.row(1) = image1_only.G.row(0);
6088 approx_obs.E.resize(1, 2);
6089 approx_obs.E(0, 0) = midpoint_energy;
6090 approx_obs.E(0, 1) = image1_only.E(0, 0);
6091 } else {
6092 calculateApproximatePotential(approx_obs);
6093 }
6094 }
6095 } else {
6096 calculateApproximatePotential(approx_obs);
6097 }
6098 hssvd_mode_ready = true;
6099 hssvd_orient = orient;
6100 hssvd_ritz_curvature = hssvd_mode_estimate.second;
6101 hssvd_approx_obs = approx_obs;
6102 hssvd_rot_info = rot_info;
6103 if (hssvd_mode_selection_policy_ ==
6105 if (std::isfinite(hssvd_ritz_curvature) &&
6106 hssvd_ritz_curvature < 0.0) {
6107 log_man << "Installed HS-SVD reference-connected negative mode "
6108 << "for dimer rotation";
6109 } else {
6110 log_man << "Installed HS-SVD lowest-curvature fallback; no "
6111 "negative reference-connected mode";
6112 }
6113 log_man << " (reference overlap=" << reference_mode_overlap
6114 << ", continuation overlap=" << seed_mode_overlap
6115 << ", curvature=" << hssvd_ritz_curvature << ").\n";
6116 } else {
6117 log_man << "Installed HS-SVD minimum mode for dimer rotation.\n";
6118 }
6119 }
6120
6121 // Rotate the dimer and re-calculate approximated energy and gradient
6122 // at image 1 when the finite trial requests a stencil update.
6123 if (!finite_stencil_rotated && hssvd_mode_ready &&
6124 max_iter_relax_rot.inner > 0) {
6126 log_man << " Inner rotational iteration: 0\n";
6127 bool terminate_loop =
6128 rotateDimer(stop_citeria_gpr.angle_rotation, orient, rot_info,
6129 middle_point, approx_obs);
6130
6131 if (!terminate_loop) {
6132 orient = hssvd_orient;
6133 approx_obs = hssvd_approx_obs;
6134 rot_info = hssvd_rot_info;
6135 }
6136 } else if (!finite_stencil_rotated) {
6137 for (gpr::Index_t inner_iter_rot = 0;
6138 inner_iter_rot < max_iter_relax_rot.inner; ++inner_iter_rot) {
6140 log_man << " Inner rotational iteration: " << inner_iter_rot
6141 << "\n";
6142 bool terminate_loop =
6143 rotateDimer(stop_citeria_gpr.angle_rotation, orient, rot_info,
6144 middle_point, approx_obs);
6145
6146 if (terminate_loop) break;
6147 }
6148 }
6149
6150 // The curvature belongs to the refreshed mode at the fixed midpoint.
6151 double cached_hssvd_curvature = std::numeric_limits<double>::quiet_NaN();
6152 if (use_hssvd_analytic_curvature_ && hssvd_mode_ready &&
6153 std::isfinite(hssvd_ritz_curvature) && orient.size() > 0 &&
6154 orient.rows() == hssvd_orient.rows() &&
6155 orient.cols() == hssvd_orient.cols() && orient.allFinite() &&
6156 hssvd_orient.allFinite()) {
6157 const double orient_norm = orient.norm();
6158 const double mode_norm = hssvd_orient.norm();
6159 const double norm_product = orient_norm * mode_norm;
6160 const double alignment =
6161 std::abs(gpr::field::flatDot(orient, hssvd_orient));
6162 const double orientation_tol =
6163 std::sqrt(std::numeric_limits<double>::epsilon()) *
6164 std::max(1.0, norm_product);
6165 if (norm_product > 0.0 &&
6166 std::abs(norm_product - alignment) <= orientation_tol)
6167 cached_hssvd_curvature = hssvd_ritz_curvature;
6168 }
6169 curvature =
6170 calculateCurvature(orient, approx_obs, use_hssvd_analytic_curvature_,
6171 cached_hssvd_curvature);
6172
6173 return curvature;
6174}
6175
6176double AtomicDimer::performRotationAndTranslationPure(
6177 gpr::Observation& middle_point, gpr::Observation& approx_obs,
6178 gpr::Coord& orient, gpr::Coord& R_new, gpr::LBFGSInfo& rot_info,
6179 gpr::LBFGSInfo& trans_info)
6180{
6181 const double curvature =
6182 performSurrogateRotation(middle_point, approx_obs, orient, rot_info);
6183 // The caller ends the relaxation phase on a non-finite curvature.
6184 if (std::isfinite(curvature))
6185 translateDimer(middle_point, orient, approx_obs, curvature, trans_info,
6186 R_new);
6187
6188 return curvature;
6189}
6190
6191gpr::Coord AtomicDimer::lowestModeFromGradientJacobian(
6192 const gpr::FieldMatrixd& gradient_jacobian, const gpr::Coord& R) const
6193{
6194 if (gradient_jacobian.rows() != gradient_jacobian.cols() ||
6195 gradient_jacobian.rows() == 0)
6196 return {};
6197
6198 const Eigen::Index dof = gradient_jacobian.cols();
6199 const Eigen::MatrixXd Q = projectedCartesianBasis(R, dof, atoms_config);
6200 if (Q.cols() == 0) return {};
6201
6202 const Eigen::MatrixXd H =
6203 0.5 * (Eigen::MatrixXd(gradient_jacobian) +
6204 Eigen::MatrixXd(gradient_jacobian).transpose());
6205 Eigen::MatrixXd Hsub = Q.transpose() * H * Q;
6206 Hsub = (0.5 * (Hsub + Hsub.transpose())).eval();
6207 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(Hsub);
6208 if (es.info() != Eigen::Success || es.eigenvectors().cols() == 0) return {};
6209
6210 return rowModeFromVector(Q * es.eigenvectors().col(0));
6211}
6212
6213std::pair<gpr::Coord, double> AtomicDimer::estimateLowestModeAndCurvatureFromGP(
6214 const gpr::Coord& R, const gpr::Coord* seed_orient,
6215 SurrogateSpectrumRequest request)
6216{
6217 gpr::ScopedPhaseTimer mode_timer(gp_mode_seconds_);
6218 if (profile_phase_timing_) ++gp_mode_calls_;
6219 const bool resolve_full_spectrum =
6220 request != SurrogateSpectrumRequest::ModeOnly;
6221 const double no_curvature = std::numeric_limits<double>::quiet_NaN();
6222 auto empty_mode = [&]() -> std::pair<gpr::Coord, double> {
6223 return {gpr::Coord{}, no_curvature};
6224 };
6225 surrogate_spectrum_.valid = false;
6226 index_one_clamped_modes_.clear();
6227 last_asserted_negative_modes_ = 0;
6228 if (gpr_model == nullptr || R.rows() != 1 || R.cols() == 0)
6229 return empty_mode();
6230
6231 const Eigen::Index dof = R.cols();
6232 const Eigen::MatrixXd Q = projectedCartesianBasis(R, dof, atoms_config);
6233 if (Q.cols() == 0) return empty_mode();
6234
6236 bool have_prepared_hssvd =
6237 gpr_model->prepareMeanHessianVectorHssvd(R, prepared_hssvd);
6238 const auto scoped_hessian =
6239 have_prepared_hssvd
6241 : gpr_model->prepareMeanHessian(R);
6242 auto apply_hssvd_hessian = [&](const Eigen::VectorXd& q_cart,
6243 Eigen::VectorXd& hv_cart) -> bool {
6244 if (have_prepared_hssvd)
6245 return gpr_model->applyMeanHessianVectorHssvd(prepared_hssvd,
6246 q_cart, hv_cart);
6247 return scoped_hessian && scoped_hessian(q_cart, hv_cart);
6248 };
6249
6250 auto projected_seed = [&](const gpr::Coord* seed) -> Eigen::VectorXd {
6251 if (seed == nullptr || seed->rows() != 1 || seed->cols() != dof ||
6252 !seed->allFinite())
6253 return Eigen::VectorXd{};
6254 Eigen::VectorXd q = Q.transpose() * seed->transpose();
6255 if (!q.allFinite()) return Eigen::VectorXd{};
6256 return q;
6257 };
6258
6259 Eigen::VectorXd q0 = projected_seed(seed_orient);
6260 if (q0.size() != Q.cols() || !q0.allFinite() || q0.norm() == 0.0) {
6261 q0 = projected_seed(&orient_init);
6262 if (q0.size() != Q.cols() || !q0.allFinite() || q0.norm() == 0.0) {
6263 q0 = Eigen::VectorXd::Zero(Q.cols());
6264 q0(0) = 1.0;
6265 }
6266 }
6267
6268 auto full_subspace_solve = [&]() -> std::pair<gpr::Coord, double> {
6269 Eigen::MatrixXd HQ;
6270 const bool have_hessian_block =
6271 have_prepared_hssvd &&
6272 gpr_model->applyMeanHessianBlockHssvd(prepared_hssvd, Q, HQ) &&
6273 HQ.rows() == dof && HQ.cols() == Q.cols() && HQ.allFinite();
6274 if (!have_hessian_block) {
6275 HQ.resize(dof, Q.cols());
6276 for (Eigen::Index c = 0; c < Q.cols(); ++c) {
6277 Eigen::VectorXd hv;
6278 if (!apply_hssvd_hessian(Q.col(c), hv) || hv.size() != dof ||
6279 !hv.allFinite())
6280 return empty_mode();
6281 HQ.col(c) = hv;
6282 }
6283 }
6284
6285 Eigen::MatrixXd Hsub = Q.transpose() * HQ;
6286 Hsub = (0.5 * (Hsub + Hsub.transpose())).eval();
6287 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(Hsub);
6288 if (es.info() != Eigen::Success || es.eigenvectors().cols() == 0)
6289 return empty_mode();
6290 // The projected Hessian is solved by whichever LAPACK the build
6291 // linked. Canonical pairs make the mode, and the negative count,
6292 // the same for OpenBLAS and the reference library.
6293 Eigen::VectorXd evals = es.eigenvalues();
6294 Eigen::MatrixXd evecs = es.eigenvectors();
6296
6297 const Eigen::Index mode_index = selectHssvdModeIndex(
6298 evals, evecs, q0, hssvd_mode_selection_policy_);
6299 if (!resolve_full_spectrum)
6300 return {rowModeFromVector(Q * evecs.col(mode_index)),
6301 evals(mode_index)};
6302 double curvature_scale = 0.0;
6303 for (Eigen::Index i = 0; i < evals.size(); ++i)
6304 if (std::isfinite(evals(i)))
6305 curvature_scale = std::max(curvature_scale, std::abs(evals(i)));
6306 Eigen::Index negative_mode_count = 0;
6307 for (Eigen::Index i = 0; i < evals.size(); ++i)
6308 if (gpr::linalg::curvatureIsNegative(evals(i), curvature_scale,
6309 evals.size()))
6310 ++negative_mode_count;
6311 last_negative_mode_count_ = negative_mode_count;
6312 surrogate_spectrum_.valid = true;
6313 surrogate_spectrum_.R = R;
6314 surrogate_spectrum_.curvatures = evals;
6315 surrogate_spectrum_.modes = Q * evecs;
6316 surrogate_spectrum_.mode_index = mode_index;
6317 if (request == SurrogateSpectrumRequest::ContourProjection)
6318 prepareIndexOneProjection(R);
6319 additional_mode_.resize(0);
6320 additional_gp_curvature_ = std::numeric_limits<double>::quiet_NaN();
6321 if (evecs.cols() >= 2) {
6322 const Eigen::Index transverse_index = mode_index == 0 ? 1 : 0;
6323 additional_mode_ = Q * evecs.col(transverse_index);
6324 additional_gp_curvature_ = evals(transverse_index);
6325 }
6326 const double first_nonnegative_curvature =
6327 negative_mode_count < evals.size()
6328 ? evals(negative_mode_count)
6329 : std::numeric_limits<double>::quiet_NaN();
6330 log_man << "HS-SVD projected Hessian spectrum (dimension="
6331 << Hsub.rows() << ", negative_modes=" << negative_mode_count
6332 << ", lowest_curvature=" << evals(0)
6333 << ", selected_curvature=" << evals(mode_index)
6334 << ", first_nonnegative_curvature="
6335 << first_nonnegative_curvature
6336 << ", contour_projection_evaluated="
6337 << (request == SurrogateSpectrumRequest::ContourProjection)
6338 << ", index_one_clamped=" << index_one_clamped_modes_.size()
6339 << ", asserted_negative=" << last_asserted_negative_modes_
6340 << ").\n";
6341 gpr::Coord mode = rowModeFromVector(Q * evecs.col(mode_index));
6342 if (mode.size() != dof) return empty_mode();
6343 return {mode, evals(mode_index)};
6344 };
6345
6346 const Eigen::Index sub_dim = Q.cols();
6347 if ((want_second_negative_mode_ || use_hssvd_analytic_curvature_) &&
6348 resolve_full_spectrum) {
6349 if (!have_prepared_hssvd) {
6350 have_prepared_hssvd =
6351 gpr_model->prepareMeanHessianVectorHssvd(R, prepared_hssvd);
6352 }
6353 return full_subspace_solve();
6354 }
6355 if (hssvd_mode_selection_policy_ ==
6356 HssvdModeSelectionPolicy::ReferenceConnectedNegative) {
6357 if (!have_prepared_hssvd) {
6358 have_prepared_hssvd =
6359 gpr_model->prepareMeanHessianVectorHssvd(R, prepared_hssvd);
6360 }
6361 return full_subspace_solve();
6362 }
6363 if (sub_dim <= 2) return full_subspace_solve();
6364
6365 auto apply_projected_hessian = [&](const Eigen::VectorXd& q_sub,
6366 Eigen::VectorXd& out_sub) -> bool {
6367 const Eigen::VectorXd q_cart = Q * q_sub;
6368 Eigen::VectorXd hv_cart;
6369 if (!apply_hssvd_hessian(q_cart, hv_cart) || hv_cart.size() != dof ||
6370 !hv_cart.allFinite())
6371 return false;
6372 out_sub = Q.transpose() * hv_cart;
6373 return out_sub.allFinite();
6374 };
6375
6376 const double spectral_residual_floor =
6377 std::sqrt(std::numeric_limits<double>::epsilon());
6378 double eigenvector_angle_tol = spectral_residual_floor;
6379 double eigenvalue_relative_residual_tol = 0.0;
6380 if (std::isfinite(stop_citeria_gpr.angle_rotation) &&
6381 stop_citeria_gpr.angle_rotation > 0.0) {
6382 const double right_angle = 0.5 * std::acos(-1.0);
6383 double mode_angle_budget = stop_citeria_gpr.angle_rotation;
6384 if (max_iter_relax_rot.inner > 0) {
6385 const double rotation_iterations =
6386 static_cast<double>(max_iter_relax_rot.inner);
6387 // The finite-dimer rotation estimator is omega = atan(ratio) / 2;
6388 // reserve that half-angle budget across configured rotations.
6389 mode_angle_budget = std::min(
6390 stop_citeria_gpr.angle_rotation,
6391 2.0 * stop_citeria_gpr.angle_rotation / rotation_iterations);
6392 }
6393 eigenvector_angle_tol =
6394 std::sin(std::min(mode_angle_budget, right_angle));
6395 // The dimer sees F_rot = 2r for Ritz residual r, so its convergence
6396 // estimator is omega = 0.5 * atan(||r|| / |lambda|).
6397 const double maximum_dimer_angle = 0.5 * right_angle;
6398 eigenvalue_relative_residual_tol =
6399 mode_angle_budget >= maximum_dimer_angle
6400 ? std::numeric_limits<double>::max()
6401 : std::tan(2.0 * mode_angle_budget);
6402 }
6403
6404 Eigen::Index configured_subspace = 1;
6405 if (max_iter_new_pairs.inner > 0)
6406 configured_subspace +=
6407 static_cast<Eigen::Index>(max_iter_new_pairs.inner);
6408 if (max_iter_relax_rot.inner > 0)
6409 configured_subspace +=
6410 static_cast<Eigen::Index>(max_iter_relax_rot.inner);
6411
6412 // A physical angle target and a budget spanning the projected space admit
6413 // an exact mode certificate with one batched HSSVD kernel contraction.
6414 const bool use_full_budget_block = resolve_full_spectrum &&
6415 eigenvalue_relative_residual_tol > 0.0 &&
6416 configured_subspace >= sub_dim;
6417 if (use_full_budget_block && !have_prepared_hssvd)
6418 have_prepared_hssvd =
6419 gpr_model->prepareMeanHessianVectorHssvd(R, prepared_hssvd);
6420 if (use_full_budget_block && have_prepared_hssvd)
6421 return full_subspace_solve();
6422
6424 rr_options.max_subspace = std::min(sub_dim, configured_subspace);
6425 rr_options.relative_residual_tolerance = spectral_residual_floor;
6427 eigenvalue_relative_residual_tol;
6428 rr_options.eigenvector_angle_tolerance = eigenvector_angle_tol;
6429 rr_options.allow_full_subspace_fallback = true;
6430
6431 const auto result = gpr::linalg::lowestEigenpairRayleighRitz(
6432 sub_dim, apply_projected_hessian, q0, rr_options);
6433 if (result.converged && result.eigenvector.size() == sub_dim &&
6434 result.eigenvector.allFinite() && std::isfinite(result.eigenvalue)) {
6435 gpr::Coord mode = rowModeFromVector(Q * result.eigenvector);
6436 if (mode.size() == dof) return {mode, result.eigenvalue};
6437 }
6438
6439 return full_subspace_solve();
6440}
6441
6442gpr::Coord AtomicDimer::estimateLowestModeFromGP(const gpr::Coord& R,
6443 const gpr::Coord* seed_orient)
6444{
6445 return estimateLowestModeAndCurvatureFromGP(R, seed_orient).first;
6446}
6447
6449 const gpr::vector3_reg (&cell_dimensions)[3], gpr::Observation& mid_point,
6450 pot::PotentialWrapper& potential)
6451{
6452 long N;
6453 const double* R;
6454 const int* atomicNrs;
6455 double* F;
6456 double* U;
6457 const double box[9] = {
6458 cell_dimensions[0](0), cell_dimensions[0](1), cell_dimensions[0](2),
6459 cell_dimensions[1](0), cell_dimensions[1](1), cell_dimensions[1](2),
6460 cell_dimensions[2](0), cell_dimensions[2](1), cell_dimensions[2](2)};
6461
6462 // One energy per configuration, gradient same shape as coordinates
6463 mid_point.E.resize(mid_point.R.rows(), 1);
6464 mid_point.G.resize(mid_point.R.rows(), mid_point.R.cols());
6465
6466 // Total number of moving atoms
6467 N = gpr::coord::numPoints(mid_point.R);
6468
6469 // Position at middle point
6470 R = mid_point.R.data();
6471
6472 // Force at middle point
6473 F = mid_point.G.data();
6474
6475 // Energy at middle point
6476 U = mid_point.E.data();
6477
6478 // eOn and rgpot pass one species per coordinate atom, the moving set.
6479 // A loaded configuration stores frozen atoms first, so the full
6480 // atomicNrs pointer would compare those species with the moving ones.
6481 std::vector<int> moving_species;
6482 const Eigen::Index species_n = atoms_config.atomicNrs.size();
6483 if (species_n > 0 && atoms_config.is_frozen.size() == species_n) {
6484 moving_species.reserve(static_cast<std::size_t>(species_n));
6485 for (Eigen::Index atom = 0; atom < species_n; ++atom) {
6486 if (atoms_config.is_frozen(0, atom) != MOVING_ATOM) continue;
6487 moving_species.push_back(atoms_config.atomicNrs(0, atom));
6488 }
6489 atomicNrs = moving_species.data();
6490 } else {
6491 atomicNrs = atoms_config.atomicNrs.data();
6492 }
6493
6494 // Call for the potential calculations
6495 gpr::requireWallClock(wall_clock_limit_);
6496 {
6498 potential.force(N, R, atomicNrs, F, U, nullptr /*variance*/, box);
6499 }
6500}
6501
6503 double step, int& calls)
6504{
6505 calls = 0;
6506 if (!(step > 0.0) || !std::isfinite(step)) return false;
6507 const Eigen::VectorXd origin = getFinalCoordOfMidPoint();
6508 const Eigen::Index dof = origin.size();
6509 if (dof == 0 || dof % 3 != 0 || !origin.allFinite()) return false;
6510 const Eigen::Index n_atoms = dof / 3;
6511 Eigen::VectorXd masses = Eigen::VectorXd::Ones(n_atoms);
6512 if (atoms_config.atomic_masses.size() == n_atoms)
6513 masses = atoms_config.atomic_masses;
6514 // Rigid motions are zero modes only of a free system. Frozen atoms, or
6515 // a single atom with no internal coordinate, anchor every direction.
6516 const bool anchored = is_subsystem(atoms_config) || n_atoms == 1;
6517 const auto counted = [&](const auto& evaluate) {
6518 const gpr::Index_t before = getNumEvaluations();
6519 const bool ok = evaluate();
6520 calls += static_cast<int>(getNumEvaluations() - before);
6521 return ok;
6522 };
6523 const bool periodic = gpr::geometry::cellIsMicLattice(atoms_config.cell);
6525 double measured_curvature = curvature_final;
6526 const auto measure = [&]() {
6528 const Eigen::VectorXd center = getFinalCoordOfMidPoint();
6529 const Eigen::MatrixXd directions = gpr::optim::stencilDirectionsForMode(
6530 vibrational_stencil_, center, masses, periodic, anchored);
6531 const Eigen::Index count = directions.cols();
6532 // The removed rigid columns are rebuilt about the center gradient.
6533 // The midpoint already holds it unless it was never evaluated.
6534 const bool center_held =
6535 count == dof || (middle_point_final.G.rows() == 1 &&
6536 middle_point_final.G.cols() == dof &&
6537 middle_point_final.G.allFinite());
6538 gpr::Observation probes;
6539 probes.R.resize(2 * count + (center_held ? 0 : 1), dof);
6540 probes.R.topRows(2 * count) =
6541 gpr::optim::centralDifferencePoints(center, step, directions)
6542 .transpose();
6543 if (!center_held) probes.R.row(2 * count) = center.transpose();
6544 const gpr::Index_t before = getNumEvaluations();
6545 std::string failure;
6546 const bool ok = acquireAccurateProbe(probes, potential,
6547 oracle_batch_chunk_, failure);
6548 measured.calls = static_cast<int>(getNumEvaluations() - before);
6549 calls += measured.calls;
6550 if (!ok) {
6551 log_man << "Force-stop certificate: stencil failed: " << failure
6552 << "\n";
6553 return measured;
6554 }
6555 broadcastObservation(probes);
6556 Eigen::MatrixXd actions(dof, count);
6557 for (Eigen::Index k = 0; k < count; ++k)
6558 actions.col(k) =
6559 (probes.G.row(2 * k) - probes.G.row(2 * k + 1)).transpose() /
6560 (2.0 * step);
6561 const Eigen::VectorXd center_gradient =
6562 center_held && count < dof
6563 ? Eigen::VectorXd(middle_point_final.G.row(0).transpose())
6564 : (center_held
6565 ? Eigen::VectorXd()
6566 : Eigen::VectorXd(probes.G.row(2 * count).transpose()));
6567 const Eigen::MatrixXd columns =
6568 gpr::optim::hessianColumnsFromDirections(center, center_gradient,
6569 directions, actions);
6570 if (columns.rows() != dof) {
6571 log_man << "Force-stop certificate: Hessian columns cannot be "
6572 "formed\n";
6573 return measured;
6574 }
6575 latest = gpr::neb::indexFromCartesianColumns(columns, center, masses,
6576 step, nullptr, nullptr,
6577 anchored, &directions);
6578 if (latest.pass && orient_final.rows() == 1 &&
6579 orient_final.cols() == dof) {
6580 const Eigen::VectorXd direction = orient_final.row(0).transpose();
6581 const double norm_squared = direction.squaredNorm();
6582 if (norm_squared > 0.0 && std::isfinite(norm_squared))
6583 measured_curvature =
6584 direction.dot(columns * direction) / norm_squared;
6585 }
6586 log_man << "Force-stop certificate: " << latest.negative
6587 << " negative, " << latest.unresolved << " unresolved, "
6588 << latest.positive << " positive modes (resolution "
6589 << latest.resolution << ")\n";
6590 measured.measured = latest.measured;
6591 measured.first_order = latest.pass;
6592 measured.higher_order = latest.negative > 1;
6593 return measured;
6594 };
6595 const auto move_to = [&](const Eigen::VectorXd& point) {
6596 gpr::Observation moved;
6597 moved.R = point.transpose();
6598 if (!counted([&]() { return evaluateAccurateProbe(moved, potential); }))
6599 return false;
6600 broadcastObservation(moved);
6601 middle_point_final = moved;
6602 middle_point_init = moved;
6603 return true;
6604 };
6607 /*requested=*/true);
6609 measure,
6610 [&]() {
6611 if (latest.step.size() != dof) return -1;
6612 return move_to(getFinalCoordOfMidPoint() + latest.step) ? 1 : -1;
6613 },
6614 plan);
6615 if (outcome.needs_min_mode_escape && latest.step.size() == dof &&
6616 latest.step.norm() > 0.0) {
6617 // Same escape the band and the gprd force stop take: leave the
6618 // higher-order point along the extra negative mode and certify
6619 // the geometry that is reached.
6620 double length = latest.step.norm();
6621 Eigen::VectorXd direction = latest.step / length;
6622 for (int escape = 0; outcome.needs_min_mode_escape &&
6624 ++escape) {
6625 length *= 2.0;
6626 if (!move_to(getFinalCoordOfMidPoint() + length * direction)) break;
6628 measure, [&]() { return -1; }, plan);
6629 if (latest.step.size() == dof && latest.step.norm() > 0.0)
6630 direction = latest.step / latest.step.norm();
6631 }
6632 }
6633 const bool certified =
6634 outcome.certified &&
6635 forceNormForConvergence(middle_point_final) < stop_citeria_dimer.force;
6636 if (certified) curvature_final = measured_curvature;
6637 return certified;
6638}
6639
6640bool AtomicDimer::requireOracleBudget(Eigen::Index rows)
6641{
6642 requireWallClock();
6643 if (max_oracle_calls_ == 0 || rows <= 0) return true;
6644 const gpr::Index_t used = getNumEvaluations();
6645 if (used < max_oracle_calls_ &&
6646 static_cast<gpr::Index_t>(rows) <= max_oracle_calls_ - used)
6647 return true;
6648 if (!oracle_budget_unwinds_) return false;
6650 "the oracle budget of " + std::to_string(max_oracle_calls_) +
6651 " calls does not cover " + std::to_string(rows) + " more (" +
6652 std::to_string(used) + " used)");
6653}
6654
6655void AtomicDimer::certifyExecuteForceStop(pot::PotentialWrapper& potential)
6656{
6657 force_stop_certified_ = false;
6658 force_stop_certificate_calls_ = 0;
6659 if (!final_converged_ || !(force_stop_certificate_step_ > 0.0) ||
6660 external_terminal_certificate_)
6661 return;
6662 const auto before = getNumEvaluations();
6663 int calls = 0;
6664 bool certified = false;
6665 try {
6666 certified =
6667 certifyStoppedForce(potential, force_stop_certificate_step_, calls);
6668 } catch (const gpr::WallClockLimitReached&) {
6669 force_stop_certificate_calls_ =
6670 static_cast<int>(getNumEvaluations() - before);
6671 final_converged_ = false;
6672 relaxation_termination_reason_ =
6673 DimerRelaxationTerminationReason::WallClockLimit;
6674 log_man << "Force-stop certificate not completed: wall-clock limit "
6675 "reached; not converged.\n";
6676 return;
6677 } catch (const OracleBudgetExhausted& stop) {
6678 force_stop_certificate_calls_ =
6679 static_cast<int>(getNumEvaluations() - before);
6680 final_converged_ = false;
6681 relaxation_termination_reason_ =
6682 DimerRelaxationTerminationReason::OracleBudget;
6683 log_man << "Force-stop certificate not completed: " << stop.what()
6684 << "; not converged.\n";
6685 return;
6686 }
6687 force_stop_certificate_calls_ =
6688 static_cast<int>(getNumEvaluations() - before);
6689 force_stop_certified_ = certified;
6690 if (certified) {
6691 log_man << "Force-stop certificate: one negative mode at the "
6692 "returned midpoint ("
6693 << calls << " oracle calls).\n";
6694 return;
6695 }
6696 final_converged_ = false;
6697 relaxation_termination_reason_ =
6698 DimerRelaxationTerminationReason::UncertifiedForceStop;
6699 log_man << "Force-stop certificate refused the midpoint: the true force "
6700 "is under tolerance but the stencil does not measure exactly "
6701 "one negative mode ("
6702 << calls << " oracle calls); not a saddle, not converged.\n";
6703}
6704
6705void AtomicDimer::evaluateAccurateEnergyAndForceAtMidPoint(
6706 gpr::Observation& middle_point, pot::PotentialWrapper& general_potential)
6707{
6708 aux::ProblemSetUp problem_setup;
6709
6710 // Helper: call potential (MPI distribution handled in
6711 // calculateGeneralPotential)
6712 auto callPotential = [&](gpr::Observation& obs) {
6713 problem_setup.calculateGeneralPotential(
6714 atoms_config, cell_dimensions, obs, general_potential,
6715 num_of_gen_potential_calls, oracle_batch_chunk_);
6716 };
6717
6718 const bool supplied_measurement =
6719 middle_point.R.rows() == 1 && middle_point.R.cols() > 0 &&
6720 middle_point_init.R.rows() == 1 &&
6721 middle_point_init.R.cols() == middle_point.R.cols() &&
6722 middle_point_init.R.allFinite() &&
6723 (middle_point_init.R.array() == middle_point.R.array()).all() &&
6724 middle_point_init.E.rows() == 1 && middle_point_init.E.cols() == 1 &&
6725 middle_point_init.E.allFinite() && middle_point_init.G.rows() == 1 &&
6726 middle_point_init.G.cols() == middle_point.R.cols() &&
6727 middle_point_init.G.allFinite();
6728 if (supplied_measurement) {
6729 middle_point.E = middle_point_init.E;
6730 middle_point.G = middle_point_init.G;
6731 } else {
6732 const auto start = std::chrono::steady_clock::now();
6733 // The search starts from a measured point; without one there is no
6734 // accepted state to fall back to, so a failure here ends the run.
6735 if (!requireOracleBudget(middle_point.R.rows()))
6736 throw std::runtime_error("the oracle budget is spent");
6737 try {
6738 callPotential(middle_point);
6739 } catch (const std::exception& error) {
6740 throw std::runtime_error(
6741 std::string("the oracle failed at the start geometry: ") +
6742 error.what());
6743 }
6744 if (!middle_point.E.allFinite() || !middle_point.G.allFinite())
6745 throw std::runtime_error(
6746 "the oracle returned a non-finite energy or force at the "
6747 "start geometry");
6748 archiveObservations(middle_point);
6749 if (profile_phase_timing_) {
6750 accurate_potential_seconds_ +=
6751 std::chrono::duration<double>(std::chrono::steady_clock::now() -
6752 start)
6753 .count();
6754 ++accurate_potential_calls_;
6755 }
6756 }
6757
6758 // Every training energy shares its model's origin. Imported kernels,
6759 // attached models, and physical prior means retain absolute energies.
6760 E_zero_level = middle_point.E;
6761 if (keepsAbsoluteEnergies()) E_zero_level.setZero();
6762 bool observations_changed = (E_zero_level.array() != 0.0).any();
6763 problem_setup.cutOffEnergy(E_zero_level, middle_point.E);
6764 problem_setup.cutOffEnergy(E_zero_level, all_obs.E);
6765 // A supplied midpoint was measured, and counted, by whoever supplied it.
6766 recordTrueForceSecant(middle_point,
6767 supplied_measurement
6770
6771 bool retained_seed = false;
6772 if (all_obs.R.cols() == middle_point.R.cols() &&
6773 all_obs.E.rows() == all_obs.R.rows() && all_obs.E.cols() == 1 &&
6774 all_obs.G.rows() == all_obs.R.rows() &&
6775 all_obs.G.cols() == middle_point.G.cols()) {
6776 for (Eigen::Index row = 0; row < all_obs.R.rows(); ++row) {
6777 if ((all_obs.R.row(row).array() == middle_point.R.row(0).array())
6778 .all()) {
6779 observations_changed |= (all_obs.E.row(row).array() !=
6780 middle_point.E.row(0).array())
6781 .any() ||
6782 (all_obs.G.row(row).array() !=
6783 middle_point.G.row(0).array())
6784 .any();
6785 all_obs.E.row(row) = middle_point.E.row(0);
6786 all_obs.G.row(row) = middle_point.G.row(0);
6787 retained_seed = true;
6788 }
6789 }
6790 }
6791 if (!retained_seed) {
6792 all_obs.append(middle_point);
6793 observations_changed = true;
6794 }
6795 // An identical measurement at an owned geometry preserves its fitted
6796 // posterior. Changed values and changes of energy origin require a refit.
6797 if (observations_changed) {
6798 if (gpr_model->activePosteriorRefitsEnabled())
6799 refit_oracle_batch_.append(middle_point);
6800 markObservedDataChanged();
6801 }
6802}
6803
6804void AtomicDimer::recordImspeQueryHistory(const gpr::Coord& R_query)
6805{
6806 if (variance_gate_.imspe_history_size <= 0 || R_query.rows() != 1) return;
6807 const int D = static_cast<int>(R_query.cols());
6808 const int K = variance_gate_.imspe_history_size;
6809 if (imspe_query_history_.cols() != D || imspe_query_history_.rows() != K) {
6810 imspe_query_history_ = Eigen::MatrixXd::Zero(K, D);
6811 imspe_query_history_count_ = 0;
6812 imspe_query_history_head_ = 0;
6813 }
6814 imspe_query_history_.row(imspe_query_history_head_) =
6815 R_query.row(0).template cast<double>();
6816 imspe_query_history_head_ = (imspe_query_history_head_ + 1) % K;
6817 if (imspe_query_history_count_ < K) ++imspe_query_history_count_;
6818}
6819
6820bool AtomicDimer::computeImspeAdmissionScore(const gpr::Coord& R_query,
6821 double& score,
6822 double& relative_gain,
6823 const bool allow_hssvd_local)
6824{
6825 score = std::numeric_limits<double>::quiet_NaN();
6826 relative_gain = std::numeric_limits<double>::quiet_NaN();
6827 if (gpr_model == nullptr || variance_gate_.imspe_history_size <= 0 ||
6828 R_query.rows() != 1 || R_query.cols() == 0)
6829 return false;
6830
6831 const Eigen::Index D = R_query.cols();
6832 std::vector<Eigen::VectorXd> rows;
6833 rows.reserve(static_cast<std::size_t>(imspe_query_history_count_ + 5));
6834 const double duplicate_tol =
6835 std::sqrt(std::numeric_limits<double>::epsilon()) *
6836 std::sqrt(static_cast<double>(std::max<Eigen::Index>(D, 1)));
6837
6838 auto push_row = [&](const gpr::Coord& R) {
6839 if (R.rows() != 1 || R.cols() != D) return;
6840 Eigen::VectorXd row = R.row(0).transpose();
6841 if (!row.allFinite()) return;
6842 if ((row - R_query.row(0).transpose()).norm() <= duplicate_tol) return;
6843 for (const auto& existing: rows) {
6844 if ((row - existing).norm() <= duplicate_tol) return;
6845 }
6846 rows.push_back(std::move(row));
6847 };
6848
6849 for (int i = 0; i < imspe_query_history_count_; ++i) {
6850 gpr::Coord hist(1, D);
6851 hist.row(0) = imspe_query_history_.row(i);
6852 push_row(hist);
6853 }
6854 push_row(middle_point_init.R);
6855 push_row(image1.R);
6856
6857 const gpr::Coord mode =
6858 estimateLowestModeAndCurvatureFromGP(R_query, nullptr,
6859 SurrogateSpectrumRequest::Spectrum)
6860 .first;
6861 if (mode.rows() == 1 && mode.cols() == D && mode.allFinite()) {
6862 gpr::Coord plus = R_query + dimer_sep * mode;
6863 gpr::Coord minus = R_query - dimer_sep * mode;
6864 push_row(plus);
6865 push_row(minus);
6866 }
6867
6868 if (rows.empty()) return false;
6869
6870 Eigen::MatrixXd chain_pos(static_cast<Eigen::Index>(rows.size()) + 1, D);
6871 for (Eigen::Index i = 0; i < static_cast<Eigen::Index>(rows.size()); ++i)
6872 chain_pos.row(i) = rows[static_cast<std::size_t>(i)].transpose();
6873 chain_pos.row(static_cast<Eigen::Index>(rows.size())) =
6874 R_query.row(0).template cast<double>();
6875
6876 const Eigen::Index query_idx = chain_pos.rows() - 1;
6877 const double sigma_n2 = gpr_model->getLikGaussian().getSigma2();
6878 std::vector<Eigen::Index> target_queries(
6879 static_cast<std::size_t>(query_idx));
6880 std::iota(target_queries.begin(), target_queries.end(), Eigen::Index{0});
6881 std::optional<gpr::JointObservationVarianceReduction> reduction;
6882 try {
6883 reduction = gpr_model->calculateObservationForceVarianceReduction(
6884 chain_pos, query_idx, target_queries, sigma_n2, allow_hssvd_local);
6885 } catch (...) {
6886 return false;
6887 }
6888 if (!reduction || !(reduction->target_variance > 0.0)) return false;
6889 score = reduction->variance_reduction;
6890 relative_gain = score / reduction->target_variance;
6891 return std::isfinite(relative_gain);
6892}
6893
6894bool AtomicDimer::maybeSoftSkipViaImspe(const gpr::Coord& R_query)
6895{
6896 const bool soft_skip_enabled =
6897 variance_gate_.imspe_soft_threshold > 0.0 &&
6898 std::isfinite(variance_gate_.imspe_soft_threshold);
6899 if (!soft_skip_enabled) return false;
6900
6901 double score = 0.0;
6902 double relative_gain = 0.0;
6903 const bool scored =
6904 computeImspeAdmissionScore(R_query, score, relative_gain, true);
6905 recordImspeQueryHistory(R_query);
6906
6907 if (scored && score < variance_gate_.imspe_soft_threshold) {
6908 ++imspe_soft_skipped_calls_;
6909 return true;
6910 }
6911 return false;
6912}
6913
6914double AtomicDimer::effectiveEmdDedupThreshold() const
6915{
6916 // Geometric floor: a midpoint inside the dimer finite-difference
6917 // stencil re-samples the local region rather than visiting a
6918 // distinct training location.
6919 double threshold = emd_dedup_threshold_;
6920 if (gpr_model == nullptr) return threshold;
6921 // Information floor: the resolution limit of the gradient GP. The
6922 // posterior saddle curvature recoverable from observations spaced
6923 // d apart halves at d = l * sigma_rel / 2 (model-problem law,
6924 // verified over six decades of noise), so rows closer than that
6925 // carry no curvature information at the live noise level and only
6926 // degrade conditioning. Both floors derive from the run's own
6927 // state; whichever binds, applies.
6928 const auto& cov = gpr_model->getSexpAtCovarianceFunction();
6929 const double magn = cov.getMagnSigma2();
6930 const double noise = gpr_model->getSigma2();
6931 const auto& ls = cov.getLengthScaleRef();
6932 double d_min = -1.0;
6933 if (ls.size() > 0 && std::isfinite(magn) && magn > 0.0 &&
6934 std::isfinite(noise) && noise > 0.0) {
6935 const double l_min = ls.minCoeff();
6936 if (std::isfinite(l_min) && l_min > 0.0) {
6937 const double d = 0.5 * l_min * std::sqrt(noise / magn);
6938 if (std::isfinite(d) && d > 0.0) d_min = d;
6939 }
6940 }
6941 // The geometric stencil floor keeps a dense (Cholesky) backend out of the
6942 // near-duplicate-row regime that wrecks its conditioning, so non-HS-SVD
6943 // runs keep whichever of {stencil, information floor} binds.
6944 if (!gpr_model->getHssvdBackend()) {
6945 if (d_min > 0.0) threshold = std::max(threshold, d_min);
6946 return threshold;
6947 }
6948 // Under the HS-SVD stable basis conditioning is handled directly
6949 // (cond(Psi)=1), so the stencil controls how finely the saddle is
6950 // resolved. The binding scale is the saddle-localization length
6951 // d_loc = tolerance / |mode curvature|: the minimum-mode force changes
6952 // by the convergence tolerance over d_loc, so spacing coarser than d_loc
6953 // cannot sample the sub-tolerance force-zero crossing, while spacing
6954 // finer than d_loc carries no convergence information and overfits the
6955 // gradient rows. The stencil shrinks toward d_loc, clamped not below the
6956 // GP information limit. Without a finite curvature estimate, the
6957 // localization scale is undefined and the geometric stencil stands.
6958 double eff = threshold;
6959 const double tol = stop_citeria_dimer.force;
6960 const double curv = std::abs(latest_mode_curvature_);
6961 if (std::isfinite(tol) && tol > 0.0 && std::isfinite(curv) && curv > 0.0) {
6962 const double d_loc = tol / curv;
6963 if (std::isfinite(d_loc) && d_loc > 0.0) eff = std::min(eff, d_loc);
6964 }
6965 if (d_min > 0.0) eff = std::max(eff, d_min);
6966 return eff;
6967}
6968
6969double AtomicDimer::initialRotationStopCriterion() const
6970{
6971 const double criterion = stop_citeria_dimer.angle_rotation;
6972 return (criterion > 0.0 && std::isfinite(criterion)) ? criterion : 0.0;
6973}
6974
6975bool AtomicDimer::shouldSkipOracleByImspeAdmission(const gpr::Coord& R_query)
6976{
6977 if (gpr_model == nullptr || R_query.rows() != 1 || all_obs.R.rows() == 0)
6978 return false;
6979
6980 aux::Distance distance;
6981 gpr::FieldMatrixd dist;
6982 distance.dist_emd(R_query, all_obs.R, atoms_config, dist);
6983 if (dist.size() == 0) return false;
6984 const double min_emd = dist.minCoeff();
6985 if (!std::isfinite(min_emd) || min_emd >= effectiveEmdDedupThreshold() ||
6986 min_emd <= exactEmdDuplicateThreshold(R_query))
6987 return false;
6988
6989 double score = 0.0;
6990 double relative_gain = 0.0;
6991 if (!computeImspeAdmissionScore(R_query, score, relative_gain, true))
6992 return false;
6993
6994 const double sigma_n2 = gpr_model->getLikGaussian().getSigma2();
6995 double exact_score = score;
6996 double exact_relative_gain = relative_gain;
6997 if (score > sigma_n2) {
6998 const bool needs_exact_confirmation =
6999 gpr_model->getHssvdLocalPosteriorActiveSetSize() > 0;
7000 if (!needs_exact_confirmation ||
7001 !computeImspeAdmissionScore(R_query, exact_score,
7002 exact_relative_gain, false) ||
7003 exact_score > sigma_n2)
7004 return false;
7005 }
7006
7007 ++imspe_soft_skipped_calls_;
7008 ++dedup_rejected_observations_;
7009 ++consecutive_degenerate_probes_;
7010 recordImspeQueryHistory(R_query);
7011 log_man << "IMSPE admission: skipped EMD-gray oracle (min EMD " << min_emd
7012 << " < " << effectiveEmdDedupThreshold() << ", score "
7013 << exact_score << " <= noise " << sigma_n2 << ", relative gain "
7014 << exact_relative_gain << ").\n";
7015 return true;
7016}
7017
7018bool AtomicDimer::shouldSkipMidpointOracleByEmdNear(const gpr::Observation& obs)
7019{
7020 const gpr::Coord& R_query = obs.R;
7021 if (R_query.rows() != 1 || all_obs.R.rows() == 0) return false;
7022
7023 aux::Distance distance;
7024 gpr::FieldMatrixd dist;
7025 distance.dist_emd(R_query, all_obs.R, atoms_config, dist);
7026 if (dist.size() == 0) return false;
7027
7028 const double min_emd = dist.minCoeff();
7029 if (!std::isfinite(min_emd) || min_emd >= effectiveEmdDedupThreshold())
7030 return false;
7031
7032 const double candidate_force = forceNormForConvergence(obs);
7033 const double best_force = bestObservedForceNorm();
7034 if (std::isfinite(candidate_force) && candidate_force < best_force) {
7035 log_man << "EMD admission: keeping midpoint oracle for new best "
7036 "force candidate (force "
7037 << candidate_force << " < " << best_force << ", min EMD "
7038 << min_emd << " < " << effectiveEmdDedupThreshold() << ").\n";
7039 return false;
7040 }
7041
7042 gpr::Observation mean_obs;
7043 mean_obs.R = R_query;
7044 calculateApproximatePotential(mean_obs);
7045 const double mean_force = forceNormForConvergence(mean_obs);
7046 if (std::isfinite(mean_force) && mean_force < stop_citeria_dimer.force) {
7047 log_man << "EMD admission: keeping midpoint oracle for GP "
7048 "convergence candidate (force "
7049 << mean_force << " < " << stop_citeria_dimer.force
7050 << ", min EMD " << min_emd << " < "
7051 << effectiveEmdDedupThreshold() << ").\n";
7052 return false;
7053 }
7054
7055 ++dedup_rejected_observations_;
7056 ++consecutive_degenerate_probes_;
7057 recordImspeQueryHistory(R_query);
7058 log_man << "EMD admission: skipped midpoint oracle (min EMD " << min_emd
7059 << " < " << effectiveEmdDedupThreshold()
7060 << "); consecutive degenerate probes "
7061 << consecutive_degenerate_probes_ << ".\n";
7062 return true;
7063}
7064
7065bool AtomicDimer::maybeSkipAccurateViaVariance(gpr::Observation& obs,
7066 DimerOracleProbeRole role)
7067{
7068 // Returns true iff the GPR posterior energy variance at obs.R is
7069 // below the configured acceptance threshold and the predictive
7070 // force variance is below the dimer force convergence scale. On
7071 // skip, the obs is filled with the GPR mean prediction (so the
7072 // caller sees a valid middle_point / image1 Observation without
7073 // having invoked the true potential). Non-skip preserves obs
7074 // unchanged.
7075 //
7076 // Threshold resolution order:
7077 // 1. variance_gate_.accept_tau > 0 -> absolute eV^2 cap
7078 // 2. variance_gate_.accept_tau_relative > 0 -> tau_rel * magnSigma2
7079 // 3. neither set -> gate disabled
7080 //
7081 // Path 2 is system-adaptive: the SCG re-fit updates magnSigma2 each
7082 // outer iteration, so the effective cap tracks the current GP
7083 // signal variance without operator intervention.
7084 // A feasible posterior from a failed hyperparameter fit can report small
7085 // variance despite a large force error. It cannot certify an oracle skip.
7086 if (gpr_model == nullptr || gpr_model->failedOptim()) return false;
7087 const auto suppress_call = [&]() {
7088 if (training_policy_ == nullptr ||
7089 !policySuppressesAccurateCall(obs, role))
7090 return false;
7091 calculateApproximatePotential(obs);
7092 ++variance_skipped_accurate_calls_;
7093 return true;
7094 };
7095 const bool emd_near_midpoint_skip_enabled =
7096 role == DimerOracleProbeRole::Midpoint &&
7097 variance_gate_.pre_oracle_emd_near_skip;
7098 if (emd_near_midpoint_skip_enabled &&
7099 shouldSkipMidpointOracleByEmdNear(obs)) {
7100 calculateApproximatePotential(obs);
7101 ++variance_skipped_accurate_calls_;
7102 return true;
7103 }
7104 const bool allow_imspe_soft_skip =
7105 role == DimerOracleProbeRole::StructuralImage1;
7106 const bool imspe_soft_skip_enabled =
7107 allow_imspe_soft_skip && variance_gate_.imspe_soft_threshold > 0.0 &&
7108 std::isfinite(variance_gate_.imspe_soft_threshold);
7109 if (imspe_soft_skip_enabled && shouldSkipOracleByImspeAdmission(obs.R)) {
7110 calculateApproximatePotential(obs);
7111 return true;
7112 }
7113 double tau = variance_gate_.accept_tau;
7114 if (tau <= 0.0) {
7115 const double tau_rel = variance_gate_.accept_tau_relative;
7116 if (tau_rel <= 0.0) {
7117 if (allow_imspe_soft_skip) (void)maybeSoftSkipViaImspe(obs.R);
7118 if (suppress_call()) return true;
7119 return false;
7120 }
7121 const double magn_sigma2 =
7122 gpr_model->getSexpAtCovarianceFunction().getMagnSigma2();
7123 if (!(magn_sigma2 > 0.0)) {
7124 if (allow_imspe_soft_skip) (void)maybeSoftSkipViaImspe(obs.R);
7125 if (suppress_call()) return true;
7126 return false;
7127 }
7128 tau = tau_rel * magn_sigma2;
7129 }
7130
7131 // Probe variance at the query. calculateVarianceDispatched writes
7132 // variance (not mean) into the Observation's E / G fields -- MAP
7133 // writes the point-estimate variance, LAPLACE writes the mixture
7134 // variance (calibrated posterior including hyperparameter
7135 // uncertainty). The force-variance certificate uses the same norm
7136 // family as the final dimer force convergence test.
7137 //
7138 // Uses a reusable member scratch buffer (`variance_probe_scratch_`)
7139 // to avoid per-call heap allocations for .R / .E / .G on the hot
7140 // dimer path.
7141 variance_probe_scratch_.R = obs.R;
7142 calculateApproximateVariance(variance_probe_scratch_);
7143 if (variance_probe_scratch_.E.size() == 0 ||
7144 variance_probe_scratch_.G.size() == 0 ||
7145 !variance_probe_scratch_.E.allFinite()) {
7146 if (suppress_call()) return true;
7147 return false;
7148 }
7149
7150 const double var_max = variance_probe_scratch_.E.cwiseAbs().maxCoeff();
7151 const double force_tau =
7152 stop_citeria_dimer.force * stop_citeria_dimer.force;
7153 if (!(force_tau > 0.0)) {
7154 if (suppress_call()) return true;
7155 return false;
7156 }
7157 const double force_var_max = maxPredictiveForceVariance(
7158 variance_probe_scratch_.G, convergence_force_norm);
7159 if (force_var_max >= force_tau) {
7160 if (suppress_call()) return true;
7161 return false;
7162 }
7163
7164 if (var_max >= tau) {
7165 // Variance gate says "fire oracle". Try the IMSPE soft-skip
7166 // path: when the candidate is EMD-novel against the training
7167 // set AND its IMSPE score over the recent-query ring buffer
7168 // is below imspe_soft_threshold, oracling at this point
7169 // would not collapse summed variance over the dimer's recent
7170 // novel exploration neighborhood. Suppress and use the GP
7171 // mean. Disabled by default (imspe_soft_threshold = 0);
7172 // identical behaviour to the absolute / relative gate alone
7173 // when disabled.
7174 if (allow_imspe_soft_skip && maybeSoftSkipViaImspe(obs.R)) {
7175 calculateApproximatePotential(obs);
7176 return true;
7177 }
7178 if (suppress_call()) return true;
7179 return false;
7180 }
7181
7182 // GP is confident; install the GPR mean prediction into obs (in
7183 // place of the true potential call).
7184 calculateApproximatePotential(obs);
7185 ++variance_skipped_accurate_calls_;
7186 return true;
7187}
7188
7189bool AtomicDimer::appendObservationIfInformative(const gpr::Observation& obs)
7190{
7191 if (training_policy_ != nullptr && !policy_admission_passthrough_ &&
7192 obs.R.rows() > 0) {
7193 std::vector<gpr::policy::CandidatePoint> candidates;
7194 candidates.reserve(static_cast<std::size_t>(obs.R.rows()));
7195 for (Eigen::Index row = 0; row < obs.R.rows(); ++row) {
7197 point.positions = obs.R.row(row).transpose();
7198 if (row < obs.E.rows() && obs.E.cols() > 0)
7199 point.energy = obs.E(row, 0);
7200 if (row < obs.G.rows()) point.gradient = obs.G.row(row).transpose();
7201 candidates.push_back(std::move(point));
7202 }
7203 std::vector<Eigen::VectorXd> current;
7204 current.reserve(static_cast<std::size_t>(all_obs.R.rows()));
7205 for (Eigen::Index row = 0; row < all_obs.R.rows(); ++row)
7206 current.emplace_back(all_obs.R.row(row).transpose());
7207 const std::vector<int> indices =
7209 candidates, current);
7211 indices, static_cast<int>(candidates.size()))) {
7212 if (indices.empty()) return false;
7213 gpr::Observation kept;
7214 const Eigen::Index n = static_cast<Eigen::Index>(indices.size());
7215 kept.R.resize(n, obs.R.cols());
7216 kept.E.resize(n, obs.E.cols() > 0 ? obs.E.cols() : 1);
7217 kept.G.resize(n, obs.G.cols() > 0 ? obs.G.cols() : obs.R.cols());
7218 Eigen::Index out = 0;
7219 for (const int index: indices) {
7220 if (index < 0 || index >= obs.R.rows()) continue;
7221 kept.R.row(out) = obs.R.row(index);
7222 if (index < obs.E.rows()) kept.E.row(out) = obs.E.row(index);
7223 if (index < obs.G.rows()) kept.G.row(out) = obs.G.row(index);
7224 ++out;
7225 }
7226 if (out == 0) return false;
7227 if (out != n) {
7228 kept.R.conservativeResize(out, kept.R.cols());
7229 kept.E.conservativeResize(out, kept.E.cols());
7230 kept.G.conservativeResize(out, kept.G.cols());
7231 }
7232 struct Passthrough {
7233 bool& flag;
7234 explicit Passthrough(bool& flag) : flag(flag)
7235 {
7236 flag = true;
7237 }
7238 ~Passthrough()
7239 {
7240 flag = false;
7241 }
7242 } passthrough(policy_admission_passthrough_);
7243 return appendObservationIfInformative(kept);
7244 }
7245 }
7246 // First row is always kept: there is nothing to dedup against, and
7247 // an empty all_obs would leave the GP without conditioning data.
7248 if (all_obs.R.rows() == 0 || obs.R.rows() == 0) {
7249 all_obs.append(obs);
7250 markObservedDataChanged();
7251 recordImspeQueryHistory(obs.R);
7252 consecutive_degenerate_probes_ = 0;
7253 return true;
7254 }
7255
7256 // Minimum EMD distance from the new row to every existing
7257 // observation. dist_emd returns one distance per existing row
7258 // (1 x N_obs); the smallest is the distance to the nearest
7259 // neighbour. Same metric and call shape as the early-stop
7260 // trust-region check isInterAtomicDistanceTooBig.
7261 aux::Distance distance;
7262 gpr::FieldMatrixd dist;
7263 distance.dist_emd(obs.R, all_obs.R, atoms_config, dist);
7264
7265 Eigen::Index min_row = 0;
7266 Eigen::Index min_col = 0;
7267 const double min_emd = (dist.size() > 0)
7268 ? dist.minCoeff(&min_row, &min_col)
7269 : std::numeric_limits<double>::infinity();
7270 if (!std::isfinite(min_emd) || min_emd >= effectiveEmdDedupThreshold()) {
7271 all_obs.append(obs);
7272 markObservedDataChanged();
7273 recordImspeQueryHistory(obs.R);
7274 consecutive_degenerate_probes_ = 0;
7275 return true;
7276 }
7277
7278 double score = 0.0;
7279 double relative_gain = 0.0;
7280 const double sigma_n2 = gpr_model ? gpr_model->getLikGaussian().getSigma2()
7281 : std::numeric_limits<double>::infinity();
7282 const bool exact_degenerate = min_emd <= exactEmdDuplicateThreshold(obs.R);
7283 const Eigen::Index nearest_row =
7284 (dist.cols() == all_obs.R.rows()) ? min_col : min_row;
7285 const bool have_nearest_gradient =
7286 nearest_row >= 0 && nearest_row < all_obs.G.rows() &&
7287 obs.G.rows() == 1 && obs.G.cols() == all_obs.G.cols();
7288 const double live_mode_curvature = std::abs(latest_mode_curvature_);
7289 if (gpr_model != nullptr && gpr_model->getHssvdBackend() &&
7290 std::isfinite(live_mode_curvature) && live_mode_curvature > 0.0 &&
7291 !exact_degenerate && have_nearest_gradient &&
7292 stop_citeria_dimer.force > 0.0) {
7293 const Eigen::RowVectorXd residual =
7294 obs.G.row(0) - all_obs.G.row(nearest_row);
7295 const double residual_norm = forceNormForConvergence(residual);
7296 if (std::isfinite(residual_norm) &&
7297 residual_norm > stop_citeria_dimer.force) {
7298 all_obs.append(obs);
7299 markObservedDataChanged();
7300 recordImspeQueryHistory(obs.R);
7301 consecutive_degenerate_probes_ = 0;
7302 log_man << "EMD admission: accepted force-residual observation "
7303 "(min EMD "
7304 << min_emd << " < " << effectiveEmdDedupThreshold()
7305 << ", force residual " << residual_norm << " > "
7306 << stop_citeria_dimer.force << ").\n";
7307 return true;
7308 }
7309 }
7310 // A dense factor keeps the force by replacing the nearest
7311 // representative. Appending that step would add a rank-poor column.
7312 // The degenerate-probe count resets only when the new force is lower
7313 // than the representative's.
7314 if (gpr_model != nullptr && !gpr_model->getHssvdBackend() &&
7315 std::isfinite(live_mode_curvature) && live_mode_curvature > 0.0 &&
7316 !exact_degenerate && have_nearest_gradient &&
7317 stop_citeria_dimer.force > 0.0) {
7318 const Eigen::RowVectorXd residual =
7319 obs.G.row(0) - all_obs.G.row(nearest_row);
7320 const double residual_norm = forceNormForConvergence(residual);
7321 if (std::isfinite(residual_norm) &&
7322 residual_norm > stop_citeria_dimer.force) {
7323 const double representative_force = forceNormForConvergence(
7324 all_obs.R.row(nearest_row), all_obs.G.row(nearest_row));
7325 const double candidate_force = forceNormForConvergence(obs);
7326 if (coalesceObservationIntoNearestEmdRepresentative(obs)) {
7327 if (std::isfinite(candidate_force) &&
7328 std::isfinite(representative_force) &&
7329 candidate_force < representative_force)
7330 consecutive_degenerate_probes_ = 0;
7331 log_man
7332 << "EMD admission: coalesced force-residual observation "
7333 "into the nearest representative (min EMD "
7334 << min_emd << " < " << effectiveEmdDedupThreshold()
7335 << ", force residual " << residual_norm << " > "
7336 << stop_citeria_dimer.force
7337 << "); consecutive degenerate probes "
7338 << consecutive_degenerate_probes_ << ".\n";
7339 return true;
7340 }
7341 }
7342 }
7343 const bool imspe_informative =
7344 !exact_degenerate &&
7345 computeImspeAdmissionScore(obs.R, score, relative_gain, true) &&
7346 score > sigma_n2;
7347
7348 double exact_score = score;
7349 double exact_relative_gain = relative_gain;
7350 const bool needs_exact_confirmation =
7351 gpr_model && gpr_model->getHssvdLocalPosteriorActiveSetSize() > 0;
7352 // A local active-set posterior conditions on a training subset, so
7353 // its IMSPE score is a screening value for EMD-gray candidates. The
7354 // full posterior remains the admission certificate for appending a
7355 // near-duplicate observation.
7356 // Relative-gain floor: a near-duplicate (EMD-gray) row is only worth an
7357 // appended observation if its posterior-variance reduction beats the
7358 // noise-to-signal ratio in RELATIVE terms. exact_score > sigma_n2 alone is
7359 // too weak -- sigma_n2 is a tiny absolute floor, so a flat-variance system
7360 // (e.g. an over-smoothed length-scale on the simplest cases) admits a
7361 // stream of zero-information near-duplicates (relative_gain ~ 1e-9) and
7362 // never makes progress. relative_gain = score/chain_trace and the floor
7363 // sigma_n2/magn are both GP-derived (no magic constant); informative rows
7364 // clear it by orders.
7365 const double magn_for_gain =
7366 (gpr_model != nullptr)
7367 ? gpr_model->getSexpAtCovarianceFunction().getMagnSigma2()
7368 : 0.0;
7369 const double rel_gain_floor =
7370 (magn_for_gain > 0.0 && std::isfinite(magn_for_gain))
7371 ? sigma_n2 / magn_for_gain
7372 : 0.0;
7373 const bool exact_informative =
7374 imspe_informative &&
7375 (!needs_exact_confirmation ||
7376 computeImspeAdmissionScore(obs.R, exact_score, exact_relative_gain,
7377 false)) &&
7378 exact_score > sigma_n2 && std::isfinite(exact_relative_gain) &&
7379 exact_relative_gain > rel_gain_floor;
7380
7381 if (!exact_informative) {
7382 // The oracle call is already paid for. A low IMSPE score says the
7383 // row's *location* adds no posterior-variance reduction, but its
7384 // observed energy/gradient can still contradict the model -- and
7385 // a GP that never receives the residual at the point where it is
7386 // wrong relaxes to the same wrong point every phase. Fold the row
7387 // into the nearest EMD representative (same mechanism as the
7388 // nonterminal convergence certificate) so the residual conditions
7389 // the model without adding a rank-poor row.
7390 if (coalesceObservationIntoNearestEmdRepresentative(obs)) {
7391 return true;
7392 }
7393 ++dedup_rejected_observations_;
7394 ++consecutive_degenerate_probes_;
7395 recordImspeQueryHistory(obs.R);
7396 log_man << "IMSPE admission: rejected EMD-near observation (min EMD "
7397 << min_emd << " < " << effectiveEmdDedupThreshold()
7398 << ", score " << exact_score << ", noise " << sigma_n2
7399 << ", relative gain " << exact_relative_gain
7400 << "); consecutive degenerate probes "
7401 << consecutive_degenerate_probes_ << ".\n";
7402 return false;
7403 }
7404
7405 all_obs.append(obs);
7406 markObservedDataChanged();
7407 recordImspeQueryHistory(obs.R);
7408 ++imspe_admitted_near_duplicate_observations_;
7409 consecutive_degenerate_probes_ = 0;
7410 log_man << "IMSPE admission: accepted EMD-gray observation (min EMD "
7411 << min_emd << " < " << effectiveEmdDedupThreshold() << ", score "
7412 << exact_score << " > noise " << sigma_n2 << ", relative gain "
7413 << exact_relative_gain << ").\n";
7414 return true;
7415}
7416
7417bool AtomicDimer::coalesceObservationIntoNearestEmdRepresentative(
7418 const gpr::Observation& obs)
7419{
7420 if (all_obs.R.rows() == 0 || obs.R.rows() != 1 ||
7421 obs.R.cols() != all_obs.R.cols() || obs.G.rows() != 1 ||
7422 obs.G.cols() != all_obs.G.cols() || obs.E.rows() != 1 ||
7423 obs.E.cols() != all_obs.E.cols())
7424 return false;
7425
7426 aux::Distance distance;
7427 gpr::FieldMatrixd dist;
7428 distance.dist_emd(obs.R, all_obs.R, atoms_config, dist);
7429 if (dist.size() == 0) return false;
7430
7431 Eigen::Index min_row = 0;
7432 Eigen::Index min_col = 0;
7433 const double min_emd = dist.minCoeff(&min_row, &min_col);
7434 if (!std::isfinite(min_emd) || min_emd >= effectiveEmdDedupThreshold() ||
7435 min_emd <= exactEmdDuplicateThreshold(obs.R))
7436 return false;
7437
7438 const Eigen::Index nearest_row =
7439 (dist.cols() == all_obs.R.rows()) ? min_col : min_row;
7440 if (nearest_row < 0 || nearest_row >= all_obs.R.rows()) return false;
7441
7442 all_obs.R.row(nearest_row) = obs.R.row(0);
7443 all_obs.E.row(nearest_row) = obs.E.row(0);
7444 all_obs.G.row(nearest_row) = obs.G.row(0);
7445 markObservedDataChanged();
7446 recordImspeQueryHistory(obs.R);
7447 // The residual conditions the model, but the probe was still a
7448 // re-visit of a region the data already resolves: it counts toward the
7449 // degenerate-probe handback like a skipped or rejected near-duplicate.
7450 // Resetting the counter here let a dimer bounce on one representative
7451 // for 200 outer iterations (16_h2po4_anion, 148 coalesced rows at a
7452 // force of 0.06-0.12 eV/A) with the handback never armed.
7453 ++consecutive_degenerate_probes_;
7454 log_man << "EMD admission: coalesced near-duplicate observation into "
7455 "nearest representative (min EMD "
7456 << min_emd << " < " << effectiveEmdDedupThreshold()
7457 << "); consecutive degenerate probes "
7458 << consecutive_degenerate_probes_ << ".\n";
7459 return true;
7460}
7461
7462void AtomicDimer::appendConvergenceCertificateObservation(
7463 const gpr::Observation& obs)
7464{
7465 if (obs.R.rows() == 0) return;
7466 const double certificate_force = forceNormForConvergence(obs);
7467 if (!(std::isfinite(certificate_force) &&
7468 certificate_force < stop_citeria_dimer.force)) {
7469 const Eigen::VectorXd r_now = obs.R.row(0).transpose();
7470 if (last_nonterminal_certificate_r_.size() == r_now.size() &&
7471 (last_nonterminal_certificate_r_ - r_now).norm() == 0.0) {
7472 certificate_fixed_point_ = true;
7473 log_man << "Final convergence certificate: identical nonterminal "
7474 "witness twice (|F| = "
7475 << certificate_force
7476 << "); the surrogate is at a fixed point below its noise "
7477 "resolution and cannot move the dimer. Stopping.\n";
7478 return;
7479 }
7480 last_nonterminal_certificate_r_ = r_now;
7481 if (coalesceObservationIntoNearestEmdRepresentative(obs)) return;
7482 log_man << "Final convergence certificate: true midpoint witness is "
7483 "nonterminal; preserving EMD/IMSPE admission state.\n";
7484 return;
7485 }
7486 last_nonterminal_certificate_r_.resize(0);
7487
7488 bool exact_duplicate = false;
7489 if (all_obs.R.rows() > 0) {
7490 aux::Distance distance;
7491 gpr::FieldMatrixd dist;
7492 distance.dist_emd(obs.R, all_obs.R, atoms_config, dist);
7493 if (dist.size() > 0) {
7494 const double min_emd = dist.minCoeff();
7495 exact_duplicate = std::isfinite(min_emd) &&
7496 min_emd <= exactEmdDuplicateThreshold(obs.R);
7497 }
7498 }
7499 if (exact_duplicate) {
7500 log_man << "Final convergence certificate: true midpoint witness "
7501 "already present in training set.\n";
7502 return;
7503 }
7504
7505 all_obs.append(obs);
7506 markObservedDataChanged();
7507 recordImspeQueryHistory(obs.R);
7508 consecutive_degenerate_probes_ = 0;
7509 log_man << "Final convergence certificate: appended true midpoint "
7510 "witness.\n";
7511}
7512
7513bool AtomicDimer::evaluateAccurateEnergyAndForce(
7514 gpr::Observation& obs, pot::PotentialWrapper& general_potential,
7515 bool apply_emd_dedup)
7516{
7517 return evaluateAccurateObservation(obs, general_potential, apply_emd_dedup)
7518 .appended;
7519}
7520
7522 pot::PotentialWrapper& potential,
7523 gpr::Observation& raw)
7524{
7525 gpr::Observation measured;
7526 measured.R = positions;
7527 raw = gpr::Observation();
7528 broadcastDenseMatrix(measured.R);
7529 const Eigen::Index atoms = atoms_config.is_frozen.size();
7530 bool valid = measured.R.rows() > 0 && atoms > 0 &&
7531 atoms_config.atomicNrs.size() == atoms &&
7532 (atoms_config.is_frozen.array() == MOVING_ATOM).all() &&
7533 measured.R.cols() == 3 * atoms && measured.R.allFinite();
7534 if (max_oracle_calls_ > 0) {
7535 const auto used = getNumEvaluations();
7536 valid = valid && used < max_oracle_calls_ &&
7537 measured.R.rows() <=
7538 static_cast<Eigen::Index>(max_oracle_calls_ - used);
7539 }
7542 valid ? std::string{}
7543 : "curvature probe batch has invalid coordinates or exceeds "
7544 "the remaining oracle budget",
7546 if (status.status != pot::OracleBatchStatus::Ok) return false;
7547 std::string failure;
7548 if (!acquireAccurateProbe(measured, potential, 1, failure)) {
7549 log_man << "Curvature probe batch failed: " << failure << "\n";
7550 return false;
7551 }
7552 raw = std::move(measured);
7553 broadcastObservation(raw);
7554 return true;
7555}
7556
7557bool AtomicDimer::evaluateAccurateProbe(
7558 gpr::Observation& obs, pot::PotentialWrapper& general_potential)
7559{
7560 return evaluateAccurateProbe(obs, general_potential, nullptr);
7561}
7562
7563bool AtomicDimer::evaluateAccurateProbe(
7564 gpr::Observation& obs, pot::PotentialWrapper& general_potential,
7565 gpr::Observation* raw_observation)
7566{
7567 if (raw_observation != nullptr) *raw_observation = gpr::Observation();
7568 std::string failure;
7569 if (!acquireAccurateProbe(obs, general_potential, oracle_batch_chunk_,
7570 failure)) {
7571 recordOracleTrialFailure("probe: " + failure);
7572 return false;
7573 }
7574 consecutive_oracle_failures_ = 0;
7575 if (raw_observation != nullptr) *raw_observation = obs;
7576 aux::ProblemSetUp problem_setup;
7577 problem_setup.cutOffEnergy(E_zero_level, obs.E);
7578 recordTrueForceSecant(obs);
7579 return obs.E.allFinite() && obs.G.allFinite();
7580}
7581
7582bool AtomicDimer::acquireAccurateProbe(gpr::Observation& obs,
7583 pot::PotentialWrapper& general_potential,
7584 Eigen::Index batch_chunk,
7585 std::string& failure)
7586{
7587 failure.clear();
7588 if (!requireOracleBudget(obs.R.rows())) {
7589 obs.E.setConstant(std::numeric_limits<double>::quiet_NaN());
7590 obs.G.setConstant(std::numeric_limits<double>::quiet_NaN());
7591 failure = "the oracle budget is spent";
7592 return false;
7593 }
7594 aux::ProblemSetUp problem_setup;
7595 const auto start = std::chrono::steady_clock::now();
7596 const auto calls_before = num_of_gen_potential_calls;
7597 try {
7599 problem_setup.calculateGeneralPotential(
7600 atoms_config, cell_dimensions, obs, general_potential,
7601 num_of_gen_potential_calls, batch_chunk);
7602 } catch (const std::exception& error) {
7603 obs.E.setConstant(std::numeric_limits<double>::quiet_NaN());
7604 obs.G.setConstant(std::numeric_limits<double>::quiet_NaN());
7605 failure = error.what();
7606 return false;
7607 }
7608 if (!obs.E.allFinite() || !obs.G.allFinite()) {
7609 failure = "non-finite energy or force";
7610 return false;
7611 }
7612 archiveObservations(obs);
7613 if (profile_phase_timing_) {
7614 accurate_potential_seconds_ +=
7615 std::chrono::duration<double>(std::chrono::steady_clock::now() -
7616 start)
7617 .count();
7618 accurate_potential_calls_ += num_of_gen_potential_calls - calls_before;
7619 }
7620 return true;
7621}
7622
7623void AtomicDimer::retainStructuralObservation(const gpr::Observation& obs)
7624{
7625 if (gpr_model->activePosteriorRefitsEnabled())
7626 refit_oracle_batch_.append(obs);
7627 all_obs.append(obs);
7628 markObservedDataChanged();
7629 recordImspeQueryHistory(obs.R);
7630 consecutive_degenerate_probes_ = 0;
7631}
7632
7633AtomicDimer::AccurateObservationResult AtomicDimer::evaluateAccurateObservation(
7634 gpr::Observation& obs, pot::PotentialWrapper& general_potential,
7635 bool apply_emd_dedup)
7636{
7637 aux::ProblemSetUp problem_setup;
7638
7639 // Force eval: MPI image-wise distribution lives inside
7640 // calculateGeneralPotential. All ranks must enter the call so the
7641 // collective Allreduce there sees every rank.
7642 auto callPotential = [&](gpr::Observation& o) {
7643 problem_setup.calculateGeneralPotential(
7644 atoms_config, cell_dimensions, o, general_potential,
7645 num_of_gen_potential_calls, oracle_batch_chunk_);
7646 };
7647
7648 const auto start = std::chrono::steady_clock::now();
7649 // A raised oracle error and a non-finite energy or force are the same
7650 // failed measurement: the values are marked non-finite for callers that
7651 // read them, no row is kept, and the failure counts toward the bound.
7652 const auto rejectTrial = [&](const std::string& what) {
7653 obs.E.setConstant(std::numeric_limits<double>::quiet_NaN());
7654 obs.G.setConstant(std::numeric_limits<double>::quiet_NaN());
7655 recordOracleTrialFailure(what);
7656 return AccurateObservationResult{false, false};
7657 };
7658 if (!requireOracleBudget(obs.R.rows())) {
7659 obs.E.setConstant(std::numeric_limits<double>::quiet_NaN());
7660 obs.G.setConstant(std::numeric_limits<double>::quiet_NaN());
7661 return AccurateObservationResult{false, false};
7662 }
7663 try {
7665 callPotential(obs);
7666 } catch (const std::exception& error) {
7667 return rejectTrial(error.what());
7668 }
7669 if (!obs.E.allFinite() || !obs.G.allFinite())
7670 return rejectTrial("non-finite energy or force");
7671 consecutive_oracle_failures_ = 0;
7672 archiveObservations(obs);
7673 if (profile_phase_timing_) {
7674 accurate_potential_seconds_ +=
7675 std::chrono::duration<double>(std::chrono::steady_clock::now() -
7676 start)
7677 .count();
7678 ++accurate_potential_calls_;
7679 }
7680 problem_setup.cutOffEnergy(E_zero_level, obs.E);
7681 recordTrueForceSecant(obs);
7682 if (!apply_emd_dedup) {
7683 // Structural companion probe (image 1): always appended.
7684 retainStructuralObservation(obs);
7685 return {true, true};
7686 }
7687 if (gpr_model->activePosteriorRefitsEnabled())
7688 refit_oracle_batch_.append(obs);
7689 // EMD dedup at the all_obs entry point: a near-duplicate row makes
7690 // the GP covariance singular and per-burst SCG diverge. Reject it
7691 // here so the dimer's own hyperparameter optimisation always runs
7692 // on an EMD-distinct training set.
7693 return {true, appendObservationIfInformative(obs)};
7694}
7695
7696bool AtomicDimer::image1CarriesOracleGradient() const
7697{
7698 if (image1.R.rows() != 1 || image1.G.rows() != 1 || image1.R.cols() == 0 ||
7699 image1.G.cols() != image1.R.cols() || !image1.R.allFinite() ||
7700 !image1.G.allFinite())
7701 return false;
7702 const Eigen::Index cols = image1.R.cols();
7703 for (Eigen::Index row = 0; row < all_obs.R.rows(); ++row) {
7704 if (row >= all_obs.G.rows() || all_obs.R.cols() != cols ||
7705 all_obs.G.cols() != cols)
7706 continue;
7707 if (!gpr::optim::coordinatesCoincideAtRoundoff(all_obs.R.row(row),
7708 image1.R.row(0)))
7709 continue;
7710 if ((all_obs.G.row(row) - image1.G.row(0)).squaredNorm() == 0.0)
7711 return true;
7712 }
7713 return false;
7714}
7715
7716void AtomicDimer::performInitialRotations(gpr::Observation& middle_point,
7717 gpr::Coord& orient,
7718 pot::PotentialWrapper& potential)
7719{
7720 gpr::Coord temp;
7721 gpr::Index_t outer_iter;
7722 gpr::Coord orient_old;
7723 gpr::LBFGSInfo rot_info; // Information on rotation
7724 gpr::Observation approx_obs;
7725 const double stop_citeria_gpr_init = initialRotationStopCriterion();
7726
7727 for (outer_iter = 0; outer_iter < max_iter_init_rot.outer; ++outer_iter) {
7729 log_man << "Outer rotational iteration: " << outer_iter << "\n";
7730
7731 // A variance or IMSPE skip stores a surrogate mean in image 1 and
7732 // does not append it. True-PES rotation needs the oracle gradient.
7733 if (image1CarriesOracleGradient() &&
7734 isRotationalConvergenceReached(orient, middle_point)) {
7735 log_man << "Rotated the initial dimer in " << outer_iter + 1
7736 << " outer"
7737 " iterations (total number of image evaluations: "
7738 << getNumEvaluations() << ").\n";
7739 break;
7740 }
7741
7742 if (!use_gpr_initial_rotations_) {
7743 dimer::Dimer rotation(dimer_sep, is_subsystem(atoms_config));
7744 gpr::Coord gradients = middle_point.G;
7745 gpr::field::appendRows(gradients, image1.G);
7746 gpr::Coord proposed_orientation;
7747 gpr::Observation proposed_image;
7748 double proposed_curvature = 0.0;
7749 const auto evaluate_image = [&](gpr::Observation& candidate) {
7750 evaluateAccurateEnergyAndForce(candidate, potential,
7751 /*apply_emd_dedup=*/false);
7752 return candidate.G.allFinite() && candidate.E.allFinite();
7753 };
7754 const auto step = rotation.rotateWithImage1Evaluator(
7755 middle_point.R, orient, gradients,
7756 stop_citeria_dimer.angle_rotation, true, evaluate_image,
7757 rot_info, proposed_orientation, proposed_curvature,
7758 proposed_image);
7760 throw std::runtime_error(
7761 "accurate initial dimer rotation failed");
7762 }
7763 orient = proposed_orientation;
7764 updateLocation(orient, middle_point.R, image1.R);
7765 // The accepted stencil carries measured forces; an in-plane
7766 // Hessian interpolation only supplies the rotation proposal.
7767 evaluateAccurateEnergyAndForce(image1, potential,
7768 /*apply_emd_dedup=*/false);
7769 gradients = middle_point.G;
7770 gpr::field::appendRows(gradients, image1.G);
7771 latest_mode_curvature_ =
7772 rotation.calculateCurvature(gradients, orient);
7773 gpr::Observation measured_pair = middle_point;
7774 measured_pair.append(image1);
7775 writeTraceFrame(measured_pair, "initial_rotations",
7776 static_cast<size_t>(outer_iter));
7777 continue;
7778 }
7779
7780 if (curvature_requires_full_refit_ ||
7781 !hasOptimizedCurrentObservedData()) {
7782 // A fitted model retains its parameter origin and posterior;
7783 // acquired forces choose the active, expanded, or full refit.
7784 const bool reseed =
7785 (!uses_external_gp_ && !preserve_seed_kernel_ &&
7786 !gpr_model->hasBeenOptimized()) ||
7787 atoms_config.n_pt != gpr_model->getSexpAtCovarianceFunction()
7788 .getLengthScaleRef()
7789 .size();
7790 refitGPRModel(reseed, middle_point, orient);
7791 } else if (profile_phase_timing_) {
7792 log_man << "GP optimize skipped: observation data unchanged.\n";
7793 }
7794
7795 orient_old = orient;
7796 orient = orient_init;
7797
7798 approx_obs.R = middle_point.R;
7799 updateLocation(orient, middle_point.R, temp);
7800 gpr::field::appendRows(approx_obs.R, temp);
7801 calculateApproximatePotential(approx_obs);
7802 writeTraceFrame(approx_obs, "initial_rotations",
7803 static_cast<size_t>(outer_iter));
7804
7805 rot_info.clear();
7806 rot_info.num_cg_iter = middle_point.R.cols();
7807 rot_info.num_lbfgs_iter = middle_point.R.cols();
7808
7809 gpr::Index_t inner_iter;
7810 for (inner_iter = 0; inner_iter < max_iter_init_rot.inner;
7811 ++inner_iter) {
7813 log_man << " Inner rotational iteration: " << inner_iter << "\n";
7814 bool terminate_loop =
7815 rotateDimer(stop_citeria_gpr_init, orient, rot_info,
7816 middle_point, approx_obs);
7817 if (terminate_loop) break;
7818 }
7819 checkIfMaxIterReachedAndPrintWarning(
7820 inner_iter, max_iter_init_rot.inner, "dimer rotation");
7821
7822 if (inner_iter == 0) {
7823 log_man << "Rotated the initial dimer in " << outer_iter + 1
7824 << " outer iterations (total number of image evaluations: "
7825 << getNumEvaluations() << ").\n";
7826 log_man << "WARNING: Dimer orientation converged on the GP surface "
7827 "(stop criteria = "
7828 << stop_citeria_gpr_init
7829 << "), but not on the true PES (stop criteria = "
7830 << stop_citeria_dimer.angle_rotation << ").\n";
7831 break;
7832 } else {
7833 if (outer_iter > 0) {
7834 if (checkRotationalConvergence(
7835 orient, orient_old,
7836 stop_citeria_dimer.angle_rotation)) {
7837 log_man << "Rotated the initial dimer in " << outer_iter + 1
7838 << " outer iterations (total number of image "
7839 "evaluations: "
7840 << getNumEvaluations() << ".\n";
7841 break;
7842 }
7843 }
7844 updateLocation(orient, middle_point.R, image1.R);
7845 if (!maybeSkipAccurateViaVariance(
7846 image1, DimerOracleProbeRole::StructuralImage1)) {
7847 // Structural image-1 companion: never EMD-deduped.
7848 evaluateAccurateEnergyAndForce(image1, potential,
7849 /*apply_emd_dedup=*/false);
7850 }
7851 }
7852 }
7853 checkIfMaxIterReachedAndPrintWarning(outer_iter, max_iter_init_rot.outer,
7854 "initial rotations");
7855}
7856
7857void AtomicDimer::recordContactReferences(const gpr::Observation& middle_point)
7858{
7859 seed_min_interatomic_ = std::numeric_limits<double>::quiet_NaN();
7860 if (middle_point.R.cols() > 0) {
7861 aux::Distance distance;
7862 gpr::FieldMatrixd dist;
7863 distance.mindist_interatomic(middle_point.R, atoms_config, dist);
7864 if (dist.size() > 0) seed_min_interatomic_ = dist.minCoeff();
7865 }
7866 // Only the starting midpoint calibrates the contact floor. Seed
7867 // observations can hold collapsed geometries an earlier search
7868 // measured, the very contacts the floor exists to block.
7869 if (middle_point.R.rows() > 0)
7870 contact_reference_geometries_ = middle_point.R.topRows(1);
7871 else
7872 contact_reference_geometries_.resize(0, 0);
7873}
7874
7875std::pair<double, gpr::Coord> AtomicDimer::performGPRIterations(
7876 gpr::Observation& middle_point, gpr::Coord& orient,
7877 pot::PotentialWrapper& potential)
7878{
7879 gpr::Coord orient_init_gpr;
7880 gpr::Coord R_previous;
7881 gpr::Coord R_latest_conv;
7882 gpr::Coord orient_previous;
7883 gpr::Coord orient_latest_conv;
7884 gpr::Coord R_new;
7885 gpr::Observation approx_obs;
7886 double stop_dimer_gp = 0.;
7887 gpr::Index_t outer_iter;
7888 gpr::Index_t num_esmax = 0;
7889 gpr::Index_t num_es1 = 0;
7890 double curvature = 0.;
7891
7892 if (secant_config_.consistency_check) purchaseSecantConsistency(potential);
7893 if (secant_config_.seed_curvature) seedOrientationFromSecant(orient);
7894 orient_init_gpr = orient;
7895 gpr::Coord alignment_reference = orient_init_gpr;
7896 converged_above_energy_ceiling_ = false;
7897 recordContactReferences(middle_point);
7898 const bool path_leashed_recovery =
7899 hssvd_mode_selection_policy_ ==
7900 HssvdModeSelectionPolicy::ReferenceConnectedNegative &&
7901 preserve_initial_alignment_reference_;
7902 double best_oracle_force = forceNormForConvergence(middle_point);
7903 // The progress reference belongs to the seed or an explicitly measured
7904 // index escape. Leaving a higher-index stationary point increases force
7905 // from zero, so the refused point cannot constrain that recovery phase.
7906 double progress_reference_force = best_oracle_force;
7907 // Members, so a budget stop raised inside a phase still reports them.
7908 gpr::Observation& best_oracle_midpoint = budget_stop_midpoint_;
7909 best_oracle_midpoint = middle_point;
7910 gpr::Observation accepted_oracle_midpoint = middle_point;
7911 measured_trial_trust_.reset();
7912 measured_trial_anchor_.resize(0, 0);
7913 gpr::Observation refit_oracle_midpoint = middle_point;
7914 gpr::Coord& best_oracle_orientation = budget_stop_orientation_;
7915 best_oracle_orientation = orient;
7916 bool use_first_hssvd_mode_as_alignment_reference =
7917 use_hssvd_analytic_curvature_ && !preserve_initial_alignment_reference_;
7918 relaxation_termination_reason_ =
7919 DimerRelaxationTerminationReason::Unspecified;
7920 first_surrogate_action_ = {};
7921 bool measured_rotation_pending = false;
7922 bool measured_recovery_pending = false;
7923 bool measured_trial_refit_pending = false;
7924 gpr::Observation certified_index_midpoint;
7925 bool certified_index_complete = false;
7926 const auto resolve_terminal_index =
7927 [&](gpr::Observation& recovery, bool complete_stencil_follows = true) {
7928 if (external_terminal_certificate_ && !higher_order_restart_ &&
7929 complete_stencil_follows)
7930 return true;
7931 const bool preliminary =
7932 external_terminal_certificate_ && complete_stencil_follows;
7933 const auto identical = [](const auto& first, const auto& second) {
7934 return first.rows() == second.rows() &&
7935 first.cols() == second.cols() &&
7936 (first.array() == second.array()).all();
7937 };
7938 // An index certificate belongs to this measured midpoint. Rotation
7939 // changes its mode proposal without changing the Hessian's inertia.
7940 // The cache is local to one search with one oracle and
7941 // configuration.
7942 if ((preliminary || certified_index_complete) &&
7943 identical(certified_index_midpoint.R, middle_point.R) &&
7944 identical(certified_index_midpoint.G, middle_point.G))
7945 return true;
7946 gpr::Coord measured_mode;
7947 if (!resolveAdditionalNegativeMode(middle_point, orient, potential,
7948 recovery, &measured_mode,
7949 preliminary))
7950 return false;
7951 certified_index_midpoint = middle_point;
7952 certified_index_complete = !preliminary;
7953 // A resolved negative direction suffices when the external
7954 // stencil determines the index, even with incomplete rotation.
7955 const bool mode_ready =
7956 preliminary ? terminalModeIsReady() : measuredModeIsCertified();
7957 if (!mode_ready && measured_mode.size() == orient.size() &&
7958 measured_mode.allFinite()) {
7959 // The index stencil uses a mass-weighted rigid constraint;
7960 // Cartesian dimer rotation uses its own physical subspace.
7961 if (std::isfinite(transition_param.rotrem_thresh)) {
7962 const Eigen::MatrixXd physical =
7963 gpr::optim::physicalCurvatureBasis(
7964 middle_point.R, atoms_config,
7965 project_measured_rotations_,
7966 gpr::optim::RigidMotionMetric::Cartesian);
7967 const Eigen::MatrixXd projected =
7968 gpr::optim::transportPhysicalDirections(
7969 measured_mode.transpose(), physical);
7970 if (projected.cols() != 1) return true;
7971 measured_mode = projected.col(0).transpose();
7972 if (measured_mode.row(0).dot(orient.row(0)) < 0.0)
7973 measured_mode *= -1.0;
7974 }
7975 orient = measured_mode;
7976 updateLocation(orient, middle_point.R, image1.R);
7977 evaluateAccurateEnergyAndForce(image1, potential,
7978 /*apply_emd_dedup=*/false);
7979 broadcastObservation(image1);
7980 synchronizeObservedData();
7981 recordMeasuredModeCertificate(middle_point, orient, image1);
7982 }
7983 return true;
7984 };
7985 const auto retain_measured_recovery =
7986 [&](const gpr::Observation& recovery) {
7987 refit_oracle_midpoint = recovery;
7988 accepted_oracle_midpoint = recovery;
7989 // A measured escape leaves the midpoint whose index-zero
7990 // expansion was recorded.
7991 measured_index_zero_hessian_.resize(0, 0);
7992 measured_index_zero_midpoint_.resize(0, 0);
7993 if (!dimerGeometriesCoincide(recovery.R, middle_point.R)) {
7994 best_oracle_force = forceNormForConvergence(recovery);
7995 progress_reference_force = best_oracle_force;
7996 best_oracle_midpoint = recovery;
7997 best_oracle_orientation = orient;
7998 }
7999 R_previous = recovery.R;
8000 orient_previous = orient;
8001 measured_recovery_pending = true;
8002 measured_rotation_pending = false;
8003 consecutive_degenerate_probes_ = 0;
8004 certificate_fixed_point_ = false;
8005 last_nonterminal_certificate_r_.resize(0);
8006 };
8007 measured_rotation_basis_.resize(0, 0);
8008
8009 for (outer_iter = 0;
8010 dimerPhaseBudgetAllows(outer_iter, max_iter_new_pairs.outer);
8011 ++outer_iter) {
8013 if (oracleBudgetSpent()) {
8014 relaxation_termination_reason_ =
8015 DimerRelaxationTerminationReason::OracleBudget;
8016 log_man << "Stopped the search: the oracle budget of "
8017 << max_oracle_calls_ << " calls is spent ("
8018 << getNumEvaluations() << " used) after " << outer_iter
8019 << " relaxation phases; not converged.\n";
8020 middle_point = best_oracle_midpoint;
8021 orient = best_oracle_orientation;
8022 break;
8023 }
8024 totalIterations = outer_iter + 1;
8025 log_man
8026 << "Outer relaxation iteration: " << outer_iter
8027 << " (oracle_calls=" << getNumEvaluations() << ")"
8030 << " pt_grad=" << gpr::PhaseTimers::gradient_seconds
8031 << " pt_corr=" << gpr::PhaseTimers::correction_seconds
8032 << " pt_resid=" << gpr::PhaseTimers::residual_seconds
8033 << " pt_subset=" << gpr::PhaseTimers::subset_seconds
8034 << " pt_cond=" << gpr::PhaseTimers::condition_seconds
8035 << " pt_chol=" << gpr::PhaseTimers::cholesky_seconds
8036 << " pt_asm=" << gpr::PhaseTimers::assembly_seconds
8039 << " pair_rows=" << gpr::PhaseTimers::pair_max_joint_rows
8040 << " pt_pair_cov=" << gpr::PhaseTimers::pair_covariance_seconds
8041 << " pt_pair_contract="
8045 << " chart_rows=" << gpr::PhaseTimers::chart_max_joint_rows
8046 << " pt_support=" << gpr::PhaseTimers::support_seconds
8047 << " nsupport=" << gpr::PhaseTimers::support_expansions
8048 << " pt_support_refit=" << gpr::PhaseTimers::support_refit_seconds
8049 << " nsupport_refit=" << gpr::PhaseTimers::support_refit_count
8050 << " pt_anchor_asm="
8052 << " pt_anchor_factor="
8054 << " pt_anchor_cross=" << gpr::PhaseTimers::projection_cross_seconds
8055 << " pt_anchor_solve=" << gpr::PhaseTimers::projection_solve_seconds
8056 << " pt_anchor_schur=" << gpr::PhaseTimers::projection_schur_seconds
8057 << " nprojection=" << gpr::PhaseTimers::projection_count
8059 << " rss_peak_mb=" << gpr::PhaseTimers::rss_peak_mb
8060 << " rss_peak_phase=" << gpr::PhaseTimers::rss_peak_phase
8061 << " pt_pred=" << gpr::PhaseTimers::predict_seconds
8062 << " npred=" << gpr::PhaseTimers::predict_count
8063 << " gp_mean_total=" << gp_predict_mean_seconds_
8064 << " gp_variance_total=" << gp_predict_variance_seconds_
8065 << " gp_mode_total=" << gp_mode_seconds_
8066 << " pt_oracle=" << gpr::PhaseTimers::oracle_seconds << "\n";
8067 if (auto* tracker = gpr::track::activeRun()) {
8068 // The dimer's state at every outer boundary: where the midpoint
8069 // is, what the oracle said there, which way the lowest mode
8070 // points, and how far the surrogate's trial prediction was from
8071 // the measurement it was checked against.
8073 record.add("outer", static_cast<long>(outer_iter))
8074 .add("oracle_calls", static_cast<long>(getNumEvaluations()))
8075 .add("curvature", curvature)
8076 .add("force", forceNormForConvergence(middle_point))
8077 .add("trial_variance_calibration", trial_variance_calibration_)
8078 .add("trial_force_variance", last_trial_force_variance_)
8079 .add("positions",
8080 Eigen::VectorXd(middle_point.R.row(0).transpose()))
8081 .add("orientation", Eigen::VectorXd(orient.row(0).transpose()));
8082 if (middle_point.G.rows() > 0)
8083 record.add("gradient",
8084 Eigen::VectorXd(middle_point.G.row(0).transpose()));
8085 if (middle_point.E.size() > 0)
8086 record.add("energy", middle_point.E(0));
8087 tracker->appendRecord("dimer/outer", record);
8088 const long step = static_cast<long>(outer_iter);
8089 tracker->logMetric("dimer.force",
8090 forceNormForConvergence(middle_point), step);
8091 tracker->logMetric("dimer.curvature", curvature, step);
8092 tracker->logMetric("dimer.oracle_calls",
8093 static_cast<double>(getNumEvaluations()), step);
8094 tracker->logMetric("dimer.trial_variance_calibration",
8095 trial_variance_calibration_, step);
8096 tracker->logMetric("dimer.seconds_objective",
8098 tracker->logMetric("dimer.seconds_gradient",
8100 tracker->logMetric("dimer.seconds_correction",
8102 tracker->logMetric("dimer.seconds_residual",
8104 tracker->logMetric("dimer.seconds_condition",
8106 tracker->logMetric("dimer.seconds_predict",
8108 tracker->logMetric("dimer.seconds_oracle",
8110 tracker->flush();
8111 }
8112 // The timers are per outer iteration, as in the band.
8114
8115 if (measured_rotation_pending) {
8116 bool certified =
8117 refineMeasuredMode(middle_point, orient, potential);
8118 if (external_terminal_certificate_)
8119 certified = terminalModeIsReady();
8120 curvature = latest_mode_curvature_;
8121 R_previous = middle_point.R;
8122 orient_previous = orient;
8123 refit_oracle_midpoint = middle_point;
8124 gpr::Observation measured_pair = middle_point;
8125 measured_pair.append(image1);
8126 writeTraceFrame(measured_pair, "terminal_rotation",
8127 static_cast<std::size_t>(outer_iter));
8128 ++measured_rotation_rounds_;
8129 log_man << "Measured terminal rotation: curvature " << curvature
8130 << ", rotation angle " << final_rotation_omega_
8131 << ", residual " << final_rotation_residual_
8132 << ", fixed midpoint force "
8133 << forceNormForConvergence(middle_point) << ".\n";
8134 // Krylov eigen-residuals need not decrease as their subspace
8135 // grows. Continue while the measured action supplies an
8136 // independent direction; an invariant or complete subspace
8137 // hands the sign question to the measured index stencil.
8138 const bool can_expand =
8140 measured_rotation_basis_, measured_rotation_physical_,
8141 (image1.G.row(0) - middle_point.G.row(0)).transpose() /
8142 dimer_sep)
8143 .size() > 0;
8144 const bool negative_curvature =
8145 std::isfinite(curvature) && curvature < 0.0;
8146 const bool best_is_negative =
8147 std::isfinite(best_measured_rotation_curvature_) &&
8148 best_measured_rotation_curvature_ < 0.0;
8149 const bool improved =
8150 negative_curvature && std::isfinite(final_rotation_residual_) &&
8151 (!best_is_negative ||
8152 final_rotation_residual_ < best_measured_rotation_residual_);
8153 // A resolvably negative measured curvature contradicts a recorded
8154 // index-zero expansion near this midpoint.
8155 if (negative_curvature &&
8156 curvature < -latest_mode_curvature_resolution_) {
8157 measured_index_zero_hessian_.resize(0, 0);
8158 measured_index_zero_midpoint_.resize(0, 0);
8159 }
8160 if (improved) {
8161 best_measured_rotation_residual_ = final_rotation_residual_;
8162 best_measured_rotation_angle_ = final_rotation_omega_;
8163 best_measured_rotation_curvature_ = curvature;
8164 best_measured_orientation_ = orient;
8165 best_measured_image1_ = image1;
8166 }
8167 if (!certified && negative_curvature && !can_expand &&
8168 best_measured_rotation_curvature_ < 0.0 &&
8169 best_measured_orientation_.size() == orient.size()) {
8170 orient = best_measured_orientation_;
8171 image1 = best_measured_image1_;
8172 curvature = best_measured_rotation_curvature_;
8173 latest_mode_curvature_ = curvature;
8174 final_rotation_omega_ = best_measured_rotation_angle_;
8175 final_rotation_residual_ = best_measured_rotation_residual_;
8176 measured_rotation_stationary_ = true;
8177 updateLocation(orient, middle_point.R, image1.R);
8178 log_man << "Measured terminal rotation: "
8179 << "the measured action has no independent direction"
8180 << " after " << measured_rotation_rounds_
8181 << " rounds (best residual "
8182 << best_measured_rotation_residual_ << ", curvature "
8183 << curvature
8184 << "); resolving the index with the measured mode.\n";
8185 certified = true;
8186 }
8187 if (certified && isFinalConvergenceReached(
8188 middle_point, stop_citeria_dimer.force)) {
8189 retainStructuralObservation(image1);
8190 synchronizeObservedData();
8191 gpr::Observation recovery;
8192 if (resolve_terminal_index(recovery)) {
8193 curvature = latest_mode_curvature_;
8194 if (!terminalModeIsReady()) {
8195 continue;
8196 }
8197 R_latest_conv = middle_point.R;
8198 orient_latest_conv = orient;
8199 final_converged_ = true;
8200 relaxation_termination_reason_ =
8201 DimerRelaxationTerminationReason::ForceConverged;
8202 break;
8203 }
8204 // An unmoved midpoint is not a measured escape.
8205 if (!dimerGeometriesCoincide(recovery.R, middle_point.R))
8206 retain_measured_recovery(recovery);
8207 else
8208 measured_rotation_pending = false;
8209 } else {
8210 // A positive Rayleigh value can mix stable and unstable
8211 // modes. Independent measured actions can resolve the sign.
8212 const bool positive_rotation_progress =
8213 std::isfinite(curvature) && curvature >= 0.0 &&
8214 can_expand && std::isfinite(final_rotation_omega_) &&
8215 final_rotation_omega_ > stop_citeria_dimer.angle_rotation;
8216 measured_rotation_pending =
8217 negative_curvature || positive_rotation_progress;
8218 if (measured_rotation_pending) continue;
8219 if (!can_expand) {
8220 measured_index_zero_hessian_ =
8222 measured_rotation_basis_,
8223 measured_rotation_physical_,
8224 measured_rotation_actions_);
8225 if (measured_index_zero_hessian_.size() > 0) {
8226 measured_index_zero_midpoint_ = middle_point.R;
8227 measured_index_zero_resolution_ =
8229 middle_point.R, atoms_config,
8230 measured_rotation_basis_,
8231 measured_rotation_actions_);
8232 log_man << "Measured terminal rotation: the complete "
8233 << measured_rotation_basis_.cols()
8234 << "-direction expansion resolves no negative "
8235 "curvature at this midpoint.\n";
8236 }
8237 }
8238 retainStructuralObservation(image1);
8239 synchronizeObservedData();
8240 }
8241 }
8242
8243 const bool reinitialize_hyperparameters =
8244 (!uses_external_gp_ && !preserve_seed_kernel_ &&
8245 (!gpr_model->hasBeenOptimized() ||
8246 outer_iter < num_bigiter_initparam)) ||
8247 atoms_config.n_pt > gpr_model->getSexpAtCovarianceFunction()
8248 .getLengthScaleRef()
8249 .cols();
8250 if (measured_trial_refit_pending ||
8251 !hasOptimizedCurrentObservedData()) {
8252 refitGPRModel(reinitialize_hyperparameters, refit_oracle_midpoint,
8253 orient, measured_trial_refit_pending);
8254 if (secant_config_.consistency_check)
8255 purchaseSecantConsistency(potential);
8256 measured_trial_refit_pending = false;
8257 } else if (profile_phase_timing_) {
8258 log_man << "GP optimize skipped: observation data unchanged.\n";
8259 }
8260
8261 stop_dimer_gp = surrogateForceTolerance(middle_point);
8262
8263 middle_point.R = middle_point_init.R;
8264 orient = orient_init_gpr;
8265
8266 if (measured_recovery_pending) {
8267 middle_point = refit_oracle_midpoint;
8268 orient = orient_previous;
8269 R_previous.resize(0, 0);
8270 orient_previous.resize(0, 0);
8271 measured_recovery_pending = false;
8272 } else {
8273 defineStartPath(R_latest_conv, orient_latest_conv, orient_init_gpr,
8274 outer_iter, R_previous, orient_previous,
8275 middle_point, orient);
8276 }
8277 const gpr::Coord R_phase_start = middle_point.R;
8278 resolveFlatResidualDirection(middle_point, orient, potential);
8279
8280 bool require_midpoint_oracle = false;
8281 curvature = performRotationAndTranslationWithGPR(
8282 stop_dimer_gp, middle_point, orient, R_latest_conv, R_previous,
8283 orient_latest_conv, orient_previous, R_new, num_esmax, num_es1,
8284 outer_iter, require_midpoint_oracle,
8285 outer_iter == 0 ? &first_surrogate_action_ : nullptr,
8286 /*stop_after_first_action=*/false, &accepted_oracle_midpoint);
8287 broadcastObservation(middle_point);
8288 broadcastDenseMatrix(orient);
8289 broadcastDenseMatrix(R_latest_conv);
8290 broadcastDenseMatrix(R_previous);
8291 broadcastDenseMatrix(orient_latest_conv);
8292 broadcastDenseMatrix(orient_previous);
8293 broadcastDenseMatrix(R_new);
8294 curvature = broadcastDouble(curvature);
8295 broadcastIndex(num_esmax);
8296 broadcastIndex(num_es1);
8297 require_midpoint_oracle = broadcastBool(require_midpoint_oracle);
8298 if (use_first_hssvd_mode_as_alignment_reference && orient.size() > 0 &&
8299 orient.allFinite()) {
8300 alignment_reference = orient;
8301 use_first_hssvd_mode_as_alignment_reference = false;
8302 }
8303
8304 // Oracle the midpoint of this phase. A variance-gated skip is
8305 // not a degenerate probe (no oracle call was made), so it does
8306 // not advance the handback counter; only an actual EMD-rejected
8307 // oracle row does.
8308 gpr::Observation predicted_endpoint;
8309 predicted_endpoint.R = middle_point.R;
8310 calculateApproximatePotential(predicted_endpoint);
8311 gpr::Observation predicted_reference;
8312 if (!path_leashed_recovery) {
8313 // Freeze both model gradients before the trial is measured.
8314 predicted_reference.R = accepted_oracle_midpoint.R;
8315 calculateApproximatePotential(predicted_reference);
8316 }
8317 bool midpoint_appended = false;
8318 bool midpoint_from_surrogate =
8319 !require_midpoint_oracle &&
8320 maybeSkipAccurateViaVariance(middle_point);
8321 midpoint_from_surrogate = broadcastBool(midpoint_from_surrogate);
8322 bool midpoint_oracle_certified = !midpoint_from_surrogate;
8323 if (!midpoint_from_surrogate) {
8324 // Mean, variance and oracle force refer to the same endpoint.
8325 // Each surrogate step enforces its trial constraints before
8326 // the completed burst reaches this measurement boundary.
8327 gpr::Observation trial = middle_point;
8328 const auto evaluation =
8329 evaluateAccurateObservation(trial, potential);
8330 midpoint_appended = evaluation.appended;
8331 if (evaluation.measured) {
8332 middle_point = std::move(trial);
8333 } else {
8334 // A failed evaluation is a rejected trial: no row, the
8335 // accepted midpoint back, and a shorter next step, so the
8336 // surrogate does not propose the same geometry again.
8337 log_man << "Oracle trial SCF/potential failed; restoring "
8338 "the last accepted midpoint.\n";
8339 const double displacement =
8340 (trial.R - accepted_oracle_midpoint.R).norm();
8341 if (std::isfinite(displacement) && displacement > 0.0)
8342 shrinkMeasuredTrialTrust(displacement,
8343 accepted_oracle_midpoint.R);
8344 middle_point = accepted_oracle_midpoint;
8345 midpoint_oracle_certified = false;
8346 }
8347 }
8348 midpoint_appended = broadcastBool(midpoint_appended);
8349 broadcastObservation(middle_point);
8350 synchronizeObservedData();
8351
8352 bool rotation_uninformative =
8353 alignment_abort_tol_ > 0.0 &&
8354 !isRotationCurvatureInformative(curvature);
8355 const bool degenerate_midpoint_probe =
8356 shouldProbeImage1ForDegenerateMidpoint();
8357
8358 bool final_force_converged =
8359 isFinalConvergenceReached(middle_point, stop_citeria_dimer.force);
8360 // Force convergence requests the terminal oracle stencil. A GP phase
8361 // can stop before computing curvature; only the measured pair below
8362 // determines whether the candidate has a negative saddle direction.
8363 if (midpoint_from_surrogate && final_force_converged) {
8364 log_man << "Final convergence certificate: confirming GP-filled "
8365 "midpoint with accurate force.\n";
8366 const bool certificate_appended =
8367 evaluateAccurateEnergyAndForce(middle_point, potential);
8368 midpoint_oracle_certified = true;
8369 final_force_converged = isFinalConvergenceReached(
8370 middle_point, stop_citeria_dimer.force);
8371 if (!final_force_converged && !certificate_appended) {
8372 appendConvergenceCertificateObservation(middle_point);
8373 }
8374 }
8375 final_force_converged = broadcastBool(final_force_converged);
8376 broadcastObservation(middle_point);
8377 synchronizeObservedData();
8378
8379 // Refit trust uses measured data at the trial, including a trial
8380 // rejected by the accepted-center policy. Surrogate-filled values
8381 // cannot establish agreement with the true surface.
8382 if (midpoint_oracle_certified) {
8383 recordPredictedMeasuredAgreement(predicted_endpoint, middle_point);
8384 refit_oracle_midpoint = middle_point;
8385 }
8386
8387 const double trial_oracle_force = forceNormForConvergence(middle_point);
8388 bool energy_ceiling_rejected = false;
8389 if (midpoint_oracle_certified && final_force_converged &&
8390 std::isfinite(measured_energy_ceiling_) &&
8391 middle_point.E.size() > 0 && E_zero_level.size() > 0) {
8392 const double e_abs = middle_point.E(0, 0) + E_zero_level(0, 0);
8393 if (std::isfinite(e_abs) && e_abs > measured_energy_ceiling_) {
8394 log_man << "Measured-energy ceiling: the force-converged "
8395 "midpoint at "
8396 << e_abs << " eV lies above the ceiling "
8397 << measured_energy_ceiling_
8398 << " eV; not accepted as the sought saddle.\n";
8399 converged_above_energy_ceiling_ = true;
8400 energy_ceiling_rejected = true;
8401 final_force_converged = false;
8402 }
8403 }
8404 if (midpoint_oracle_certified && !final_force_converged &&
8405 abort_on_interatomic_collapse_ && ratio_at_limit > 0.0 &&
8406 std::isfinite(seed_min_interatomic_) &&
8407 seed_min_interatomic_ > 0.0) {
8408 aux::Distance distance;
8409 gpr::FieldMatrixd dist;
8410 distance.mindist_interatomic(middle_point.R, atoms_config, dist);
8411 const double dmin = dist.size() > 0
8412 ? dist.minCoeff()
8413 : std::numeric_limits<double>::quiet_NaN();
8414 if (std::isfinite(dmin) &&
8415 dmin < ratio_at_limit * seed_min_interatomic_) {
8416 log_man << "Interatomic collapse: measured midpoint's "
8417 "shortest interatomic distance "
8418 << dmin << " A below " << ratio_at_limit
8419 << " x the seed's " << seed_min_interatomic_
8420 << " A after " << outer_iter + 1
8421 << " phases; the search left the channel, "
8422 "aborting.\n";
8423 relaxation_termination_reason_ =
8424 DimerRelaxationTerminationReason::InteratomicCollapse;
8425 break;
8426 }
8427 }
8428 const bool measured_descent_certified =
8429 midpoint_oracle_certified && std::isfinite(trial_oracle_force) &&
8430 trial_oracle_force < best_oracle_force;
8431
8432 double phase_reference_alignment =
8433 std::numeric_limits<double>::quiet_NaN();
8434 if (orient.cols() > 0 && orient.cols() == alignment_reference.cols()) {
8435 const double dot = gpr::field::flatDot(orient, alignment_reference);
8436 const double norm_product =
8437 orient.norm() * alignment_reference.norm();
8438 if (std::isfinite(dot) && std::isfinite(norm_product) &&
8439 norm_product > 0.0) {
8440 phase_reference_alignment = std::abs(dot) / norm_product;
8441 }
8442 }
8443
8444 // The history contains every measured phase, including a rejected
8445 // non-descent trial. Recovery consumers need its curvature and oracle
8446 // certificate even when the live midpoint is restored below.
8447 {
8448 DimerPhaseRecord rec;
8449 rec.position = middle_point.R;
8450 rec.gradient = middle_point.G;
8451 rec.energy =
8452 (middle_point.E.size() > 0) ? middle_point.E(0, 0) : 0.0;
8453 rec.curvature = curvature;
8454 rec.reference_alignment = phase_reference_alignment;
8455 rec.oracle_certified = midpoint_oracle_certified;
8456 rec.measured_descent_certified = measured_descent_certified;
8457 phase_history_.push_back(rec);
8458 }
8459
8460 if (energy_ceiling_rejected) {
8461 // Force stationarity cannot repair an incompatible energy
8462 // bound by taking more force-reduction steps. A measured
8463 // higher-index escape can change the stationary point; an
8464 // unresolved or index-one point belongs to path recovery.
8465 gpr::Observation recovery;
8466 if (want_second_negative_mode_ &&
8467 !resolve_terminal_index(recovery, false) &&
8468 !dimerGeometriesCoincide(recovery.R, middle_point.R)) {
8469 retain_measured_recovery(recovery);
8470 continue;
8471 }
8472 log_man << "Measured-energy ceiling: stationary candidate "
8473 "requires path recovery.\n";
8474 relaxation_termination_reason_ =
8475 DimerRelaxationTerminationReason::MeasuredNonDescent;
8476 break;
8477 }
8478
8479 const DimerOracleProgressAction oracle_progress_action =
8481 path_leashed_recovery, midpoint_oracle_certified,
8482 progress_reference_force, trial_oracle_force);
8483 if (!final_force_converged &&
8484 oracle_progress_action ==
8485 DimerOracleProgressAction::RestoreBestAndHandBack) {
8486 log_man << "True-PES trust handback: measured force "
8487 << trial_oracle_force << " regressed past reference force "
8488 << progress_reference_force << " after " << outer_iter + 1
8489 << " phases; restored best oracle midpoint for outer "
8490 "path refresh.\n";
8491 middle_point = best_oracle_midpoint;
8492 orient = best_oracle_orientation;
8493 relaxation_termination_reason_ =
8494 DimerRelaxationTerminationReason::MeasuredNonDescent;
8495 break;
8496 }
8497 if (measured_descent_certified) {
8498 best_oracle_force = trial_oracle_force;
8499 best_oracle_midpoint = middle_point;
8500 best_oracle_orientation = orient;
8501 }
8502 bool oracle_trial_requires_refit = false;
8503 if (midpoint_oracle_certified && !path_leashed_recovery) {
8504 double prediction_error = std::numeric_limits<double>::infinity();
8505 double measured_change = std::numeric_limits<double>::infinity();
8506 if (predicted_endpoint.G.rows() == middle_point.G.rows() &&
8507 predicted_endpoint.G.cols() == middle_point.G.cols() &&
8508 predicted_reference.G.rows() == middle_point.G.rows() &&
8509 predicted_reference.G.cols() == middle_point.G.cols() &&
8510 accepted_oracle_midpoint.G.rows() == middle_point.G.rows() &&
8511 accepted_oracle_midpoint.G.cols() == middle_point.G.cols() &&
8512 predicted_endpoint.G.allFinite() &&
8513 predicted_reference.G.allFinite() &&
8514 accepted_oracle_midpoint.G.allFinite()) {
8515 // Rejection and variance calibration judge the anchored
8516 // model that supplies the trial, including its measured
8517 // reference force. A constant GP bias cancels from a step.
8518 const Eigen::RowVectorXd prediction =
8520 accepted_oracle_midpoint.G.row(0),
8521 predicted_reference.G.row(0),
8522 predicted_endpoint.G.row(0));
8523 const Eigen::RowVectorXd error =
8524 middle_point.G.row(0) - prediction;
8525 const gpr::Coord change =
8526 middle_point.G - accepted_oracle_midpoint.G;
8527 prediction_error =
8528 forceNormForConvergence(middle_point.R.row(0), error);
8529 measured_change = forceNormForConvergence(middle_point.R.row(0),
8530 change.row(0));
8531 }
8532 const double reference_force =
8533 forceNormForConvergence(accepted_oracle_midpoint);
8534 const bool trial_moved = !dimerGeometriesCoincide(
8535 middle_point.R, accepted_oracle_midpoint.R);
8536 if (trial_moved && std::isfinite(prediction_error) &&
8537 std::isfinite(last_trial_force_variance_) &&
8538 last_trial_force_variance_ > 0.0) {
8539 trial_variance_calibration_ =
8540 std::max(1.0, prediction_error * prediction_error /
8541 last_trial_force_variance_);
8542 log_man << "Trial variance calibration: prediction error "
8543 << prediction_error << " against the stop variance "
8544 << last_trial_force_variance_ << " gives "
8545 << trial_variance_calibration_ << ".\n";
8546 }
8547 const double trial_force_sigma =
8548 std::isfinite(last_trial_force_variance_) &&
8549 last_trial_force_variance_ > 0.0
8550 ? std::sqrt(last_trial_force_variance_)
8551 : 0.0;
8552 last_trial_force_variance_ =
8553 std::numeric_limits<double>::quiet_NaN();
8554 if (!final_force_converged && trial_moved &&
8555 dimerOracleTrialNeedsRefit(reference_force, trial_oracle_force,
8556 measured_change, prediction_error,
8557 stop_citeria_dimer.force)) {
8558 log_man << "GP trial requires refit: measured force "
8559 << trial_oracle_force << " exceeds " << reference_force
8560 << ", prediction error " << prediction_error
8561 << ", measured force change " << measured_change
8562 << "; retaining the observation and accepted center.\n";
8563 oracle_trial_requires_refit = true;
8564 // A rejected measured step requires a fit even when its
8565 // error lies inside a broad posterior uncertainty interval.
8566 measured_trial_refit_pending = true;
8567 const double displacement =
8568 (middle_point.R - accepted_oracle_midpoint.R).norm();
8569 shrinkMeasuredTrialTrust(displacement,
8570 accepted_oracle_midpoint.R);
8571 if (measured_trial_trust_) {
8572 const double held = rejectedTrialRadius(
8573 measured_trial_trust_->radius(), displacement,
8574 trial_force_sigma, curvature, prediction_error,
8575 trial_oracle_force - reference_force,
8576 pending_flat_direction_.size() > 0);
8577 if (held > measured_trial_trust_->radius()) {
8578 measured_trial_trust_->raiseCeiling(held);
8579 measured_trial_trust_->initFromTrainingSpread(held);
8580 }
8581 }
8582 log_man << "Measured trial trust: rejected displacement "
8583 << displacement << ", radius "
8584 << measured_trial_trust_->radius() << ".\n";
8585 middle_point = accepted_oracle_midpoint;
8586 R_previous = middle_point.R;
8587 orient_previous = orient;
8588 } else {
8589 if (measured_trial_trust_ && trial_moved) {
8590 const Eigen::RowVectorXd consistent_gradient =
8592 accepted_oracle_midpoint.G.row(0),
8593 predicted_reference.G.row(0),
8594 predicted_endpoint.G.row(0));
8595 const double predicted_force = forceNormForConvergence(
8596 predicted_endpoint.R.row(0), consistent_gradient);
8597 const double predicted_reduction =
8598 reference_force * reference_force -
8599 predicted_force * predicted_force;
8600 const double actual_reduction =
8601 reference_force * reference_force -
8602 trial_oracle_force * trial_oracle_force;
8603 const Eigen::RowVectorXd measured_force_change =
8604 middle_point.G.row(0) -
8605 accepted_oracle_midpoint.G.row(0);
8606 const Eigen::RowVectorXd predicted_force_change =
8607 predicted_endpoint.G.row(0) -
8608 predicted_reference.G.row(0);
8610 measured_force_change, predicted_force_change);
8611 const double displacement =
8612 (middle_point.R - accepted_oracle_midpoint.R).norm();
8613 if (displacement < 0.9 * measured_trial_trust_->radius() &&
8614 rho > measured_trial_trust_->config().rho_grow)
8615 rho = measured_trial_trust_->config().rho_grow;
8616 const Eigen::RowVectorXd change_error =
8617 measured_force_change - predicted_force_change;
8618 const double change_error_norm = forceNormForConvergence(
8619 middle_point.R.row(0), change_error);
8620 const double change_force_scale =
8622 reference_force, stop_citeria_dimer.force);
8623 const double noise = gpr_model->getSigma2();
8624 gpr::Coord change_variance = gpr::Coord::Constant(
8625 1, middle_point.R.cols(), 2.0 * noise);
8626 double change_force_variance = maxPredictiveForceVariance(
8627 change_variance, convergence_force_norm);
8628 // The likelihood floor alone can resolve agreement for
8629 // tiny changes, without assembling a joint covariance.
8630 // Larger discrepancies use the variance of the same
8631 // difference whose mean supplies the radius agreement.
8632 if (std::isfinite(noise) && noise >= 0.0 &&
8633 change_error_norm <= change_force_scale &&
8634 change_error_norm * change_error_norm >
8635 change_force_variance) {
8636 gpr::Coord queries(2, middle_point.R.cols());
8637 queries.row(0) = accepted_oracle_midpoint.R.row(0);
8638 queries.row(1) = middle_point.R.row(0);
8639 const auto variance_start =
8640 std::chrono::steady_clock::now();
8641 try {
8642 gpr::ScopedVarianceTimer variance_timer;
8643 gpr::ScopedPredictTimer predict_timer;
8644 gpr::EigenMatrix covariance;
8645 gpr_model->calculateObservationPosteriorCovariance(
8646 queries, covariance, false);
8647 covariance *=
8648 gpr_model->reportedVarianceCalibrationFactor();
8649 change_variance.row(0) =
8651 covariance, queries.cols(), noise);
8652 change_force_variance = maxPredictiveForceVariance(
8653 change_variance, convergence_force_norm);
8654 } catch (const std::exception& error) {
8655 change_force_variance =
8656 std::numeric_limits<double>::quiet_NaN();
8657 log_man << "Force-change uncertainty unavailable: "
8658 << error.what() << ".\n";
8659 }
8660 const double variance_seconds =
8661 std::chrono::duration<double>(
8662 std::chrono::steady_clock::now() -
8663 variance_start)
8664 .count();
8665 gp_predict_seconds_ += variance_seconds;
8666 gp_predict_variance_seconds_ += variance_seconds;
8667 ++gp_predict_calls_;
8668 ++gp_predict_variance_calls_;
8669 }
8670 const bool calibrated =
8671 std::isfinite(noise) && noise >= 0.0 &&
8673 change_error_norm, change_force_variance,
8674 change_force_scale);
8676 rho, calibrated, displacement,
8677 measured_trial_trust_->radius(),
8678 measured_trial_trust_->config().rho_grow);
8679 measured_trial_trust_->updateRadiusFromRhoValue(rho);
8680 const double energy_error =
8681 predicted_endpoint.E.size() > 0 &&
8682 middle_point.E.size() > 0
8683 ? std::abs(predicted_endpoint.E(0, 0) -
8684 middle_point.E(0, 0))
8685 : std::numeric_limits<double>::quiet_NaN();
8686 const double length_scale = shortestKernelLengthScale();
8687 const double energy_scale =
8688 std::isfinite(change_force_scale) &&
8689 std::isfinite(length_scale)
8690 ? change_force_scale * length_scale
8691 : std::numeric_limits<double>::quiet_NaN();
8692 const double model_reach = modelAgreementTrustDistance(
8693 transition_param.max_step_length, length_scale,
8694 change_error_norm, change_force_scale, energy_error,
8695 energy_scale);
8696 // Open the radius to the length scale only after a
8697 // descent the posterior already resolves. A short
8698 // non-descent must not pin the ceiling, or the next
8699 // clip sits on that sphere and is measured again.
8700 const bool descended = std::isfinite(actual_reduction) &&
8701 actual_reduction > 0.0;
8702 if (calibrated && descended && std::isfinite(model_reach) &&
8703 model_reach > measured_trial_trust_->radius()) {
8704 measured_trial_trust_->raiseCeiling(model_reach);
8705 measured_trial_trust_->initFromTrainingSpread(
8706 model_reach);
8707 }
8708 setMeasuredTrialAnchor(middle_point.R);
8709 log_man << "Measured trial trust: accepted displacement "
8710 << displacement << ", agreement " << rho
8711 << ", calibrated " << calibrated
8712 << ", change error " << change_error_norm
8713 << ", change variance " << change_force_variance
8714 << ", force scale " << change_force_scale
8715 << ", predicted reduction " << predicted_reduction
8716 << ", actual reduction " << actual_reduction
8717 << ", radius " << measured_trial_trust_->radius()
8718 << ".\n";
8719 }
8720 accepted_oracle_midpoint = middle_point;
8721 }
8722 }
8723
8724 // A measured force above tolerance can expose a surrogate fixed
8725 // point. Its rescue proposal needs a true observation before another
8726 // relaxation, or the unchanged surrogate can undo the same step.
8727 const bool surrogate_did_not_move =
8728 R_phase_start.size() == middle_point.R.size() &&
8729 dimerGeometriesCoincide(R_phase_start, middle_point.R);
8730 const bool probe_coalesced = consecutive_degenerate_probes_ > 0;
8731 // A rejected trial must enter the refit with its measured row.
8732 // Restoring the accepted center does not establish a fixed point.
8733 if (!oracle_trial_requires_refit && midpoint_oracle_certified &&
8734 !final_force_converged &&
8735 (surrogate_did_not_move || probe_coalesced) &&
8736 middle_point.G.rows() > 0 &&
8737 middle_point.G.cols() == middle_point.R.cols() &&
8738 std::isfinite(curvature)) {
8739 gpr::LBFGSInfo step_info;
8740 resetTranslationHistory(step_info);
8741 step_info.num_cg_iter = middle_point.R.cols();
8742 step_info.num_lbfgs_iter = middle_point.R.cols();
8743 gpr::Coord R_step;
8744 translateDimer(middle_point, orient, middle_point, curvature,
8745 step_info, R_step);
8746 if (R_step.size() == middle_point.R.size() && R_step.allFinite()) {
8747 (void)limitTranslation(middle_point.R, step_info, R_step);
8748 if (middle_point.R.cols() >= 6 &&
8749 !retractTranslation(middle_point.R, R_step)) {
8750 R_step = middle_point.R;
8751 }
8752 }
8753 if (R_step.size() == middle_point.R.size() && R_step.allFinite() &&
8754 !dimerGeometriesCoincide(R_step, middle_point.R)) {
8755 log_man << "Measured-force step: the surrogate "
8756 << (surrogate_did_not_move
8757 ? "converged without moving"
8758 : "returned to a measured row")
8759 << " while the oracle measured " << trial_oracle_force
8760 << " at the midpoint; translated on the measured "
8761 "force (curvature "
8762 << curvature << ", displacement "
8763 << (R_step - middle_point.R).norm() << ").\n";
8764 gpr::Observation rescue;
8765 rescue.R = R_step;
8766 // A distinct Cartesian rescue can be close in pair distance
8767 // while carrying unresolved bending-force information.
8768 evaluateAccurateEnergyAndForce(rescue, potential,
8769 /*apply_emd_dedup=*/false);
8770 broadcastObservation(rescue);
8771 synchronizeObservedData();
8772 refit_oracle_midpoint = rescue;
8773 R_previous = rescue.R;
8774 orient_previous = orient;
8775 consecutive_degenerate_probes_ = 0;
8776 certificate_fixed_point_ = false;
8777 last_nonterminal_certificate_r_.resize(0);
8778 }
8779 }
8780
8781 if (certificate_fixed_point_) {
8782 log_man << "Surrogate fixed point at outer " << outer_iter
8783 << ": stopping the relaxation unconverged.\n";
8784 relaxation_termination_reason_ =
8785 DimerRelaxationTerminationReason::MeasuredNonDescent;
8786 break;
8787 }
8788 bool final_image1_measured = false;
8789 if (final_force_converged) {
8790 // The midpoint's true force is already under the final tolerance.
8791 // Return that geometry. An image-1 sample or another refit would
8792 // be a force call the search no longer needs.
8793 R_latest_conv = middle_point.R;
8794 orient_latest_conv = orient;
8795 final_converged_ = true;
8796 relaxation_termination_reason_ =
8797 DimerRelaxationTerminationReason::ForceConverged;
8798 log_man << "Final convergence obtained after " << outer_iter + 1
8799 << " relaxation phases (total number of image evaluations: "
8800 << getNumEvaluations()
8801 << "). Returning the measured geometry.\n";
8802 break;
8803 }
8804
8805 // AtomicGPDimer interleave. A GP-surrogate rotation that ends
8806 // with a non-negative (or non-finite) curvature carries no
8807 // usable rotational information: the rotation force is a finite
8808 // difference of the GP gradient across the dimer separation and
8809 // vanishes on a flat / over-smoothed surrogate, so the rotation
8810 // "converges" (omega < T_anglerot) onto its starting axis
8811 // without ever rotating. Spend one true evaluation at image 1 so
8812 // the next phase's rotation has a real curvature sample. The
8813 // image-1 row goes through the same EMD/IMSPE admission as every
8814 // steady-state oracle row: an EMD-distinct companion appends, an
8815 // EMD-near one folds its residual into the nearest
8816 // representative. An unconditional append here re-samples the
8817 // stuck region, grows the training set with rank-poor rows, and
8818 // resets the degenerate-probe counter that the burst handback
8819 // needs to fire.
8820 if (!final_image1_measured &&
8821 (evaluate_image1_each_phase_ || rotation_uninformative ||
8822 degenerate_midpoint_probe)) {
8823 if (degenerate_midpoint_probe) {
8824 log_man << "Degenerate-midpoint recovery: acquiring "
8825 "structural image-1 probe.\n";
8826 }
8827 updateLocation(orient, middle_point.R, image1.R);
8828 const bool must_oracle_structural_image1 = !midpoint_appended;
8829 bool image1_from_surrogate =
8830 !must_oracle_structural_image1 &&
8831 maybeSkipAccurateViaVariance(
8832 image1, DimerOracleProbeRole::StructuralImage1);
8833 image1_from_surrogate = broadcastBool(image1_from_surrogate);
8834 if (!image1_from_surrogate) {
8835 evaluateAccurateEnergyAndForce(image1, potential);
8836 }
8837 broadcastObservation(image1);
8838 synchronizeObservedData();
8839 }
8840 if (rotation_uninformative) {
8841 ++consecutive_uninformative_rotations_;
8842 } else {
8843 consecutive_uninformative_rotations_ = 0;
8844 }
8845
8846 // OCI-NEB degenerate-probe handback. When successive burst
8847 // phases keep oracling EMD near-duplicate geometries, the dimer
8848 // is re-probing one region without gathering distinct data: the
8849 // GP has nothing new to condition on and SCG cannot move theta
8850 // usefully. Rather than thrash, abort the burst early and hand
8851 // control back to the NEB (the dimer can re-trigger later). This
8852 // is a Skipped-equivalent termination, alongside the alignment
8853 // and positive-curvature handback criteria; the OCI-NEB
8854 // controller restores the pre-burst CI position.
8855 if (!shouldAbortDegenerateProbeBurst() &&
8856 searchStalledOnDegenerateProbes()) {
8857 relaxation_termination_reason_ =
8858 DimerRelaxationTerminationReason::DegenerateProbe;
8859 log_man << "Stopped the search: " << consecutive_degenerate_probes_
8860 << " consecutive probes added no distinct observation "
8861 "after "
8862 << outer_iter + 1
8863 << " relaxation phases; the surrogate cannot move the "
8864 "dimer here. Not converged.\n";
8865 break;
8866 }
8867 if (shouldAbortDegenerateProbeBurst()) {
8868 relaxation_termination_reason_ =
8869 DimerRelaxationTerminationReason::DegenerateProbe;
8870 log_man << "Degenerate-probe handback: "
8871 << consecutive_degenerate_probes_
8872 << " consecutive EMD near-duplicate probes after "
8873 << outer_iter + 1
8874 << " phases; aborting burst, handing back to NEB.\n";
8875 break;
8876 }
8877
8878 // OCI-NEB uninformative-rotation handback. Successive phases
8879 // ending with a non-negative GP curvature -- each having already
8880 // spent a true image-1 evaluation -- mean those true samples
8881 // failed to expose a saddle mode: the dimer cannot resolve an
8882 // unstable direction at this geometry. Translating further would
8883 // follow a curvature-free surrogate off the reaction path (the
8884 // messy-PES failure mode). Abort the burst and hand control back
8885 // to the NEB, alongside the degenerate-probe and alignment
8886 // criteria.
8887 if (consecutive_uninformative_rotations_ >=
8888 kMaxUninformativeRotations) {
8889 relaxation_termination_reason_ =
8890 DimerRelaxationTerminationReason::UninformativeRotation;
8891 log_man << "Uninformative-rotation handback: "
8892 << consecutive_uninformative_rotations_
8893 << " phases with no negative-curvature GP mode after "
8894 << outer_iter + 1
8895 << " phases; aborting burst, handing back to NEB.\n";
8896 break;
8897 }
8898
8899 // OCI-NEB alignment-governed termination. The dimer axis stays
8900 // aligned with the active alignment reference; a low alignment
8901 // means the burst is following a different mode.
8902 if (alignment_abort_tol_ > 0.0 &&
8903 std::isfinite(phase_reference_alignment)) {
8904 // The controller suspends the band-tangent leash for this burst
8905 // only where the chain tangent is an unreliable saddle-mode seed:
8906 // the GP is over-confident-but-inaccurate at the CI, or the CI has
8907 // reached the adaptive acceptance threshold (it is close to
8908 // convergence). In that regime the true unstable mode legitimately
8909 // diverges from the coarse chain tangent, so aborting on alignment
8910 // discards a converging burst on a high-DOF system. Outside that
8911 // regime the leash holds, so a burst cannot wander onto a wrong
8912 // saddle.
8913 if (phase_reference_alignment < alignment_abort_tol_ &&
8914 !leash_relax_when_close_) {
8915 relaxation_termination_reason_ =
8916 DimerRelaxationTerminationReason::AlignmentLoss;
8917 log_man << "Alignment-governed termination: |d.tau| = "
8918 << phase_reference_alignment << " < "
8919 << alignment_abort_tol_ << " after " << outer_iter + 1
8920 << " phases.\n";
8921 break;
8922 }
8923 }
8924 }
8925
8926 if (max_iter_new_pairs.outer > 0 &&
8927 outer_iter == max_iter_new_pairs.outer) {
8928 relaxation_termination_reason_ =
8929 DimerRelaxationTerminationReason::PhaseBudget;
8930 log_man << "Maximum number of outer iterations ("
8931 << max_iter_new_pairs.outer << ") reached.\n";
8932 }
8933 totalIterations = outer_iter + 1;
8934
8935 // A requested comparison that the search never formed is not a result.
8936 // Deferral while the posterior is still missing is retried here; a model
8937 // that still cannot act with its Hessian throws rather than returning.
8938 if (secant_config_.consistency_check && secant_hessian_.available() &&
8939 secant_pairs_checked_ == 0) {
8940 purchaseSecantConsistency(potential);
8941 if (secant_pairs_checked_ == 0)
8942 throw std::runtime_error(
8943 "secant consistency requested but GP Hessian action is "
8944 "unavailable");
8945 }
8946
8947 return {curvature, orient};
8948}
8949
8951{
8952 struct RequireImprovingFallback {
8953 gpr::GaussianProcessRegression* model = nullptr;
8954 bool prior = false;
8955 explicit RequireImprovingFallback(gpr::GaussianProcessRegression* gp)
8956 : model(gp)
8957 {
8958 if (model == nullptr) return;
8959 prior = model->requiresScgFallbackImprovement();
8961 }
8962 ~RequireImprovingFallback()
8963 {
8964 if (model != nullptr)
8966 }
8967 RequireImprovingFallback(const RequireImprovingFallback&) = delete;
8968 RequireImprovingFallback& operator=(const RequireImprovingFallback&) =
8969 delete;
8970 } require_improving_fallback(gpr_model);
8971
8972 gpr::Observation middle_point;
8973
8974 gpr::FieldMatrixd E_gp;
8975 gpr::Coord orient;
8976 gpr::Coord orient_old;
8977 std::chrono::duration<double> elp_time;
8978 auto start = std::chrono::steady_clock::now();
8979 std::pair<double, gpr::Coord> eigen_data;
8980
8981 if (!isAtomsConfigurationCorrect()) {
8982 final_converged_ = false;
8983 relaxation_termination_reason_ =
8985 log_man
8986 << "Error! The structure of atoms configuration is incorrect!\n";
8987 return;
8988 }
8989 // Curvature priors belong to one search. A higher-order restart carries
8990 // its negative subspace as a proposal for fresh measurements.
8991 last_certificate_hessian_.resize(0, 0);
8992 last_certificate_positions_.resize(0, 0);
8993 if (!higher_order_restart_) index_search_directions_.resize(0, 0);
8994 measured_negative_directions_.clear();
8995 measured_negative_reference_.resize(0, 0);
8996 // Restore the configured tolerance when a certificate tightened it.
8997 if (std::isfinite(last_certificate_force_target_))
8998 stop_citeria_dimer.force = configured_force_criterion_;
8999 last_certificate_force_target_ = std::numeric_limits<double>::infinity();
9000 final_converged_ = false;
9001 final_rotation_omega_ = std::numeric_limits<double>::quiet_NaN();
9002 final_rotation_residual_ = std::numeric_limits<double>::infinity();
9003 measured_rotation_rounds_ = 0;
9004 measured_rotation_basis_.resize(0, 0);
9005 measured_index_zero_midpoint_.resize(0, 0);
9006 measured_index_zero_hessian_.resize(0, 0);
9007 measured_rotation_stationary_ = false;
9008 best_measured_rotation_residual_ = std::numeric_limits<double>::infinity();
9009 best_measured_orientation_.resize(0, 0);
9010 latest_mode_curvature_ = 0.0;
9011 inexact_curvature_logged_ = false;
9012 phase_history_.clear();
9013 dedup_rejected_observations_ = 0;
9014 consecutive_degenerate_probes_ = 0;
9015 consecutive_uninformative_rotations_ = 0;
9016
9017 gpr::coord::normalizeRow(orient_init, 0);
9018 middle_point.R = middle_point_init.R;
9019 orient = orient_init;
9020
9021 force_stop_certified_ = false;
9022 force_stop_certificate_calls_ = 0;
9023 budget_stop_midpoint_ = gpr::Observation();
9024 budget_stop_orientation_.resize(0, 0);
9025 struct BudgetUnwinds {
9026 bool& flag;
9027 explicit BudgetUnwinds(bool& f) : flag(f)
9028 {
9029 flag = true;
9030 }
9031 ~BudgetUnwinds()
9032 {
9033 flag = false;
9034 }
9035 } budget_unwinds(oracle_budget_unwinds_);
9036 try {
9037 // 1) Evaluate accurate energy E0 and force F0 at the middle point R0
9038 evaluateAccurateEnergyAndForceAtMidPoint(middle_point,
9039 general_potential);
9040
9041 // A midpoint already under the final tolerance needs no search; the
9042 // force-stop certificate below decides whether it is a saddle.
9043 const bool force_converged_at_start =
9044 isFinalConvergenceReached(middle_point, stop_citeria_dimer.force);
9045 if (force_converged_at_start) {
9046 final_converged_ = true;
9047 relaxation_termination_reason_ =
9049 log_man << "Force below tolerance at the start ("
9050 << getNumEvaluations()
9051 << " image evaluations); certifying the measured "
9052 "geometry.\n";
9053 eigen_data.first = latest_mode_curvature_;
9054 eigen_data.second = orient;
9055 } else {
9056 if (max_iter_init_rot.outer > 0) {
9057 // 3) Evaluate energy E1 and force F1 at R1
9058 updateLocation(orient, middle_point.R, image1.R);
9059 // Structural image-1 companion for the initial GP model:
9060 // never EMD-deduped.
9061 evaluateAccurateEnergyAndForce(image1, general_potential,
9062 /*apply_emd_dedup=*/false);
9063
9064 // 5) Repeat initial rotations until rotational convergence
9065 performInitialRotations(middle_point, orient,
9066 general_potential);
9067 }
9068
9069 if (max_iter_init_rot.outer == 0 &&
9070 (evaluate_image1_each_phase_ || all_obs.R.rows() < 2)) {
9071 updateLocation(orient, middle_point.R, image1.R);
9072 // Structural image-1 companion for the initial GP model:
9073 // never EMD-deduped.
9074 evaluateAccurateEnergyAndForce(image1, general_potential,
9075 /*apply_emd_dedup=*/false);
9076 log_man << "Evaluated image 1 of the dimer for the initial GP "
9077 "model.\n";
9078 }
9079
9080 eigen_data =
9081 performGPRIterations(middle_point, orient, general_potential);
9082 }
9083 } catch (const gpr::WallClockLimitReached&) {
9084 // Every completed accurate measurement updates this witness. A
9085 // deadline inside surrogate work or immediately before the next
9086 // oracle therefore returns measured state, never a partial trial.
9087 if (budget_stop_midpoint_.R.size() > 0) {
9088 middle_point = budget_stop_midpoint_;
9089 orient = budget_stop_orientation_;
9090 }
9091 final_converged_ = false;
9092 relaxation_termination_reason_ =
9094 log_man << "wall-clock limit reached; returning the best measured "
9095 "state; not converged.\n";
9096 eigen_data.first = latest_mode_curvature_;
9097 eigen_data.second = orient;
9098 if (middle_point.E.size() != 1 ||
9099 middle_point.G.cols() != middle_point.R.cols()) {
9100 middle_point.E = gpr::FieldMatrixd::Constant(
9101 1, 1, std::numeric_limits<double>::quiet_NaN());
9102 middle_point.G =
9103 gpr::Coord::Constant(1, middle_point.R.cols(),
9104 std::numeric_limits<double>::quiet_NaN());
9105 }
9106 } catch (const OracleBudgetExhausted& stop) {
9107 // Report the best measured midpoint of the relaxation; before it
9108 // starts, the midpoint is still the measured start.
9109 if (budget_stop_midpoint_.R.size() > 0) {
9110 middle_point = budget_stop_midpoint_;
9111 orient = budget_stop_orientation_;
9112 }
9113 final_converged_ = false;
9114 relaxation_termination_reason_ =
9116 log_man << "Stopped the search: " << stop.what()
9117 << "; not converged.\n";
9118 eigen_data.first = latest_mode_curvature_;
9119 eigen_data.second = orient;
9120 if (middle_point.E.size() != 1 ||
9121 middle_point.G.cols() != middle_point.R.cols()) {
9122 // No measurement at all: report none rather than a stale value.
9123 middle_point.E = gpr::FieldMatrixd::Constant(
9124 1, 1, std::numeric_limits<double>::quiet_NaN());
9125 middle_point.G =
9126 gpr::Coord::Constant(1, middle_point.R.cols(),
9127 std::numeric_limits<double>::quiet_NaN());
9128 }
9129 }
9130
9131 assignFinalResults(middle_point, eigen_data);
9132 certifyExecuteForceStop(general_potential);
9133
9134 if (debug_level == DEBUG_L1) {
9135 log_man << "\n";
9136 log_man << "Call statistics:\n";
9137 log_man << " General potential: " << getTotalForceCalls() << "\n";
9138 log_man << " GPR potential: " << getTotalGPRForceCalls() << "\n";
9139 log_man << "\n";
9140 }
9141
9142 elp_time = std::chrono::steady_clock::now() - start;
9143 log_man << "Elapsed time: " << elp_time.count() << "s\n";
9144 logPhaseTimingSummary(elp_time.count());
9145 if (middle_point_final.E.size() > 0) {
9146 std::ostringstream summary;
9147 const double energy_zero =
9148 (E_zero_level.size() > 0) ? E_zero_level(0, 0) : 0.0;
9149 double energy = getFinalEnergy() + energy_zero;
9150 writeDimerCampaignSummary(summary, energy, getConverged(), energy_zero);
9151 log_man << summary.str();
9152 }
9153
9154 if (shouldLogDimerFinalState(debug_level)) {
9155 log_man << "Final midpoint positions:\n"
9156 << middle_point_final.R << '\n';
9157 log_man << "Final midpoint energy:\n" << middle_point_final.E << '\n';
9158 log_man << "Final midpoint gradient:\n" << middle_point_final.G << '\n';
9159 }
9160}
9161
9163{
9164 if (budget_stop_midpoint_.R.size() > 0) {
9165 middle_point_final = budget_stop_midpoint_;
9166 orient_final = budget_stop_orientation_;
9167 }
9168 final_converged_ = false;
9169 relaxation_termination_reason_ =
9171}
9172
9173} /* namespace atmd */
Implementation-independent symmetric eigenpairs.
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
@ DEBUG_L1
Definition Enums.h:41
@ DEBUG_L2
Definition Enums.h:42
@ DEBUG_L3
Definition Enums.h:43
@ MOVING_ATOM
Definition Enums.h:35
ConvergenceNormType
Definition Enums.h:48
@ POTENTIAL_GP
Definition Enums.h:16
One step's oracle points shared out over the ranks of a communicator, with a layout-independent owner...
The curvature of a mode at the stationary point the search converges to, from the cubic model along t...
Trust radius for GP surrogate validity.
gpr::optim::SecantCurvatureCounts secantCounts() const
bool restartAlongWeakMode(const Eigen::VectorXd &direction, double length, const gpr::Observation &measured_rows, pot::PotentialWrapper &potential)
bool isApproximateRotationalConvergenceReached(const gpr::Coord &orient, const gpr::Observation &approx_obs, const double stop_criteria)
GP-stencil rotational convergence test.
void translateDimer(const gpr::Observation &middle_point, const gpr::Coord &orient, const gpr::Observation &approx_obs, const double curvature, gpr::LBFGSInfo &trans_info, gpr::Coord &R_new)
Translate the dimer.
void refineMeasuredModeCurvature(const gpr::Observation &midpoint, const gpr::Coord &orientation, pot::PotentialWrapper &potential, double surrogate_curvature)
Eigen::VectorXd getFinalCoordOfMidPoint() const
Return final coordinates of the middle point.
bool commitExternallyCertifiedRefinement(const gpr::Observation &raw_center, const Eigen::MatrixXd &certified_cartesian_hessian, const Eigen::MatrixXd &certified_mass_weighted_basis, bool first_order_certificate)
bool rotateDimer(const double stop_criteria, gpr::Coord &orient, gpr::LBFGSInfo &rot_info, gpr::Observation &middle_point, gpr::Observation &approx_obs)
Rotate the dimer.
bool restartFromHigherOrderPoint(const Eigen::MatrixXd &cartesian_hessian, const Eigen::VectorXd &kick, const gpr::Observation &measured_rows, pot::PotentialWrapper &potential)
Eigen::MatrixXd gpMeanHessianAtMidpoint()
gpr::Index_t getTotalGPRForceCalls() const
Return the total number of force calls.
gpr::AtomsConfiguration atoms_config
void writeTraceFrame(const gpr::Observation &obs, const std::string &phase, size_t idx)
bool terminalModeIsReady() const noexcept
bool measureCurvatureProbes(const gpr::Coord &positions, pot::PotentialWrapper &potential, gpr::Observation &raw)
const gpr::Coord & getFinalOrientation() const
Return final orientation of the dimer.
void setKappaDimer(double beta)
void setTrainingPolicy(const gpr::policy::TrainingPolicy *policy)
Not owned. The pointer must outlive execute(). Null is the engine.
bool certifyStoppedForce(pot::PotentialWrapper &potential, double step, int &calls)
DimerSurrogateActionCertificate previewFirstSurrogateAction(const gpr::Observation &oracle_middle_point, const gpr::Coord &initial_orientation)
gpr::Index_t getTotalForceCalls() const
Return the total number of force calls.
void attachExternalGP(gpr::GaussianProcessRegression *external_gp) noexcept
Attach an externally-owned GPR model. Must be called BEFORE ~initialize~. The dimer will use this GP ...
bool isFinalConvergenceReached(const gpr::Observation &middle_point, const double stop_criteria)
Final convergence test for force.
double getFinalEnergy() const
Return final energy.
void callGeneralPotentialFromEON(const gpr::vector3_reg(&cell_dimensions)[3], gpr::Observation &mid_point, pot::PotentialWrapper &potential)
Call for a potential defined in a Matter object.
bool refineSaddleFromMeasuredHessian(const Eigen::MatrixXd &cartesian_hessian, pot::PotentialWrapper &potential, double resolution=0.0)
void setSecantHessianConfig(const gpr::optim::SecantHessianConfig &config)
Replace the true-force secant and drop its history.
bool getConverged() const
Return true when the final force convergence criterion is met.
AtomicDimer()
Default constructor.
void execute(pot::PotentialWrapper &general_potential)
This function uses the atomic GP-dimer method to converge to a saddle point, starting from somewhere ...
bool measuredModeIsCertified() const noexcept
bool updateActiveFrozenAtoms(const gpr::Coord &R_new, gpr::LBFGSInfo &rot_info, gpr::LBFGSInfo &trans_info)
Update active frozen atoms.
bool isRotationalConvergenceReached(const gpr::Coord &orient, gpr::Observation &middle_point)
Rotational convergence test.
const char * what() const noexcept override
Methods to calculate distances between atoms.
Definition Distance.h:154
void dist_max1Dlog(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Give the maximum difference in the logarithmic inter-atomic distances between atomic configurations C...
Definition Distance.cpp:462
void mindist_interatomic(const gpr::Coord &x, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Give the distance from each moving atom to its nearest neighbour atom in configuration C.
Definition Distance.cpp:958
void dist_emd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the Earth Mover's Distance between sets of configurations.
void dist_rmsd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the aligned Root Mean Square Deviation (RMSD) between sets of configurations.
Definition Distance.cpp:410
Set up the GP-dimer problem.
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 calculateGeneralPotential(const gpr::AtomsConfiguration &atoms_config, const gpr::vector3_reg(&cell_dimensions)[3], gpr::Observation &mid_point, pot::PotentialWrapper &general_potential, gpr::Index_t &num_of_calls, Eigen::Index batch_chunk=0)
Invoke potential calculation.
void cutOffEnergy(const gpr::FieldMatrixd &E_reference, gpr::FieldMatrixd &E_R)
Subtract reference energy value from E_R.
Dimer method.
Definition Dimer.h:59
RotationStepResult
Definition Dimer.h:65
MeasuredRowVerdict
Agreement between measured rows and the current posterior.
bool physicalPriorMeanActive() const noexcept
True when the ZBL or Morse prior mean is the one evaluation uses.
bool requiresScgFallbackImprovement() const noexcept
std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> MeanHessianAction
void setRequireScgFallbackImprovement(bool enabled) noexcept
void setDistanceMetric(DistanceMetricType metric)
Select the atomic distance metric for trust checks.
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.
Responsible for generic IO operations.
Definition FileManager.h:34
bool writePlainFile(const std::string file_name, const T &field, std::ios::openmode mode)
bool writeXYZFile(const std::string file_name, const gpr::Coord &field, std::ios::openmode mode)
bool bind(RgsaddleClient &client, int64_t n_atoms, const double *position, const double *masses, double force_tol, int32_t force_gate=2, int64_t order=1)
bool position(double *out)
bool step(rgsaddle_surface_fn surface, void *user, rgsaddle_report_t &report)
RgsaddleIndex1 * Index1
static constexpr uint32_t kMinimumAbiMinor
bool available() const noexcept
bool hasReferenceEnergy() const noexcept
const Eigen::VectorXd & referenceGradient() const noexcept
const Eigen::MatrixXd & hessian() const noexcept
const Eigen::VectorXd & referencePosition() const noexcept
double referenceEnergy() const
static bool update(Eigen::MatrixXd &matrix, SecantHessianMethod method, const Eigen::VectorXd &step, const Eigen::VectorXd &gradient_change)
A JSON object assembled field by field; one line of a record stream.
JsonRecord & add(std::string_view key, double value)
Type-erased wrapper around any potential that provides a force() interface.
void force(long N, const double *R, const int *atomicNrs, double *F, double *U, double *energy_noise_rms, const double *box)
Invoke the wrapped potential.
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
eon_relax_band_t eon_relax_surface_fn void * user
The atomic dimer search (class AtomicDimer) and its status types.
DimerRelaxationBacktrackResult backtrackDimerRelaxationForResidualDecrease(const gpr::Coord &current, const gpr::Coord &proposed, double current_residual, const std::function< double(const gpr::Coord &)> &evaluate_residual)
void writeDimerCampaignSummary(std::ostream &os, double energy, bool converged, double energy_zero)
DimerOracleProgressAction selectDimerOracleProgressAction(bool path_leashed_recovery, bool oracle_certified, double best_oracle_force, double trial_oracle_force) noexcept
DimerProposalGlobalizationAction
constexpr int kMaxConsecutiveOracleFailures
double dimerPosteriorActionForceScale(double current_residual, double force_tolerance) noexcept
DimerResidualGlobalizationAction selectDimerResidualGlobalizationAction(double curvature, double current_residual, bool backtrack_accepted) noexcept
bool shouldTerminateDimerRelaxationForLostProgress(double curvature, double current_residual, double proposed_residual) noexcept
HssvdModeSelectionPolicy
Definition AtomicDimer.h:75
bool shouldLogDimerFinalState(const gpr::Index_t debug_level) noexcept
bool is_subsystem(const gpr::AtomsConfiguration &atoms_config)
bool shouldBacktrackDimerRelaxationForResidualDecrease(double curvature, double current_residual) noexcept
bool repeatedProjectedTrustStep(const gpr::Coord &step, double curvature, const gpr::Coord &previous_step, double previous_curvature) noexcept
DimerResidualGlobalizationAction resolvedPointKeepsTheSurrogateWalk(DimerResidualGlobalizationAction action, double proposed_force_variance, double action_scale) noexcept
const gpr::Coord & selectHssvdModeReference(const gpr::Coord &initial_reference, const gpr::Coord &current_orientation, HssvdModeSelectionPolicy policy, bool preserve_initial_reference) noexcept
DimerResidualGlobalizationAction
DimerSurrogateActionTermination
bool dimerOracleTrialNeedsRefit(double reference_force, double trial_force, double measured_change, double prediction_error, double force_tolerance) noexcept
DimerOracleProgressAction
DimerProposalGlobalizationAction selectDimerProposalGlobalizationAction(double curvature, double current_residual, double force_tolerance, double proposed_force_variance, double posterior_action_force_scale) noexcept
DimerSaddleMeritBacktrackResult backtrackDimerSaddleMerit(const gpr::Coord &current, const gpr::Coord &proposed, const gpr::Coord &gradient, const gpr::Coord &orientation, double curvature, const std::function< double(const gpr::Coord &)> &energy_change)
DimerResidualGlobalizationAction selectDimerPosteriorResidualGlobalizationAction(DimerProposalGlobalizationAction proposal_action, double curvature, double current_residual, bool backtrack_accepted) noexcept
bool dimerGeometriesCoincide(const gpr::Coord &a, const gpr::Coord &b) noexcept
Numerical geometry identity for cycle detection and measured-force rescue.
bool measuredRadiusClipRequestsOracle(bool clipped, double proposed_force_variance, double action_scale) noexcept
bool dimerPhaseBudgetAllows(gpr::Index_t phase, gpr::Index_t limit) noexcept
Definition AtomicDimer.h:96
Eigen::Index selectHssvdModeIndex(const Eigen::VectorXd &eigenvalues, const Eigen::MatrixXd &eigenvectors, const Eigen::VectorXd &reference, HssvdModeSelectionPolicy policy) noexcept
DimerRelaxationCycleCertificate certifyDimerRelaxationCycle(const gpr::Coord &current, const gpr::Coord &proposed, const gpr::Coord *preceding, double force_current, double force_preceding) noexcept
double modelAgreementTrustDistance(double configured, double length_scale, double force_error, double force_scale, double energy_error, double energy_scale) noexcept
@ WallClockLimit
The shared monotonic wall-clock deadline was reached.
@ InvalidAtomsConfiguration
execute() rejected the atom configuration before any search step.
@ OracleBudget
The caller's oracle-call budget was spent.
double rejectedTrialRadius(double shrunk, double displacement, double force_sigma, double curvature, double prediction_error, double force_increase=std::numeric_limits< double >::quiet_NaN(), bool transverse_residual_exceeds_step=false) noexcept
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 project_out_rot_trans_with_feedback(const gpr::Coord &R, Eigen::VectorXd &step)
Project rigid-body motion out of a Cartesian optimization step.
Definition Dimer.cpp:116
void normalizeRow(FieldMatrixd &mat, Index_t i)
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
void set(FieldMatrixd &mat, Index_t i, const Eigen::Vector3d &vec)
Index_t numPoints(const FieldMatrixd &mat)
DoubleDouble sqrt(DoubleDouble a)
DoubleDouble abs(DoubleDouble a)
double flatDot(const Eigen::MatrixBase< DerivedA > &a, const Eigen::MatrixBase< DerivedB > &b)
void appendRow(Eigen::PlainObjectBase< Derived > &mat, const Eigen::PlainObjectBase< Derived > &other, Eigen::Index i)
void appendRows(Eigen::PlainObjectBase< Derived > &mat, const Eigen::PlainObjectBase< Derived > &other)
bool cellIsMicLattice(const double cell[9]) noexcept
Nonzero ASE 3x3 that is not the 25 A vacuum convention.
Definition MinImage.h:56
Eigen::VectorXd retractRestrictedStep(const InternalCoordinateSet &coordinates, const Eigen::VectorXd &positions, const Eigen::VectorXd &cartesian_step, const Eigen::VectorXd &internal_trust_per_primitive)
std::vector< PrimitiveInternal > primitiveTopologyFromGeometry(int n_atoms, const Eigen::VectorXd &positions, const std::vector< char > &moving_atoms, BondGraphKind kind, const std::array< double, 9 > &cell)
Eigen::VectorXd limitPairDistanceStep(const Eigen::VectorXd &positions, const Eigen::VectorXd &proposed, double floor, Distance &&distance)
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)
int addAtomWithOptionalForce(readcon::RKRConFrameBuilder *builder, const char *symbol, double x, double y, double z, bool fixed, std::uint64_t atom_id, double mass, const double *force)
Add one atom. force is three doubles, or null when the atom has none.
double maxAtomicForce(const double *forces, std::size_t n_atoms) noexcept
Largest atomic force norm. NaN when any component is non-finite.
Eigen::VectorXd assemble(const DeviceEnvironments &left_environments, const DeviceEnvironments &right_environments, const gpr::detail::EnvironmentPairBatch &batch, std::size_t scratch_bytes)
void canonicalizeEigenpairs(Eigen::Ref< Eigen::VectorXd > evals, Eigen::Ref< Eigen::MatrixXd > evecs)
evals has one entry per leading column of evecs. Both are rewritten.
RayleighRitzResult lowestEigenpairRayleighRitz(const Eigen::Index dimension, Apply &&apply, const Eigen::VectorXd &seed, RayleighRitzOptions options)
bool curvatureIsNegative(double lambda, double scale, Eigen::Index n) noexcept
bool signedEigenvectorLess(const Eigen::Ref< const Eigen::VectorXd > &left, const Eigen::Ref< const Eigen::VectorXd > &right)
VibrationalIndexMeasurement indexFromCartesianColumns(const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double move, const Eigen::VectorXd *center_gradient=nullptr, const Eigen::VectorXi *frozen=nullptr, bool anchored=false, const Eigen::MatrixXd *measured=nullptr)
double log(double x) 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)
Eigen::MatrixXd hessianColumnsFromDirections(const Eigen::VectorXd &center, const Eigen::VectorXd &center_gradient, const Eigen::MatrixXd &directions, const Eigen::MatrixXd &actions)
bool measuredForceChangeCalibrated(double error, double variance, double force_scale) noexcept
Eigen::MatrixXd physicalCurvatureBasis(const gpr::Coord &positions, const gpr::AtomsConfiguration &config, bool exclude_rotations=true, RigidMotionMetric metric=RigidMotionMetric::MassWeighted)
CompletedSecondMode completedSecondMode(const Eigen::MatrixXd &completed, const Eigen::MatrixXd &basis, Eigen::Index k=1)
SecantHessian secantFittedToResidual(SecantHessianMethod method, const std::vector< SecantForceSample > &samples, Prior &&prior)
Eigen::VectorXd spectralResidualStep(const Eigen::VectorXd &eigenvalues, const Eigen::MatrixXd &modes, const Eigen::VectorXd &gradient, double radius)
Eigen::MatrixXd completeMeasuredHessian(const Eigen::MatrixXd &prior, const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action)
double richardsonForwardTruncation(double at_h, double at_2h) noexcept
void recordSecantObservation(SecantHessian &secant, const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, double energy, SecantCurvatureCounts &counts, SecantAccounting accounting=SecantAccounting::Count)
double measuredTrialTrustAgreement(double rho, bool calibrated, double displacement, double radius, double rho_grow)
Eigen::MatrixXd massWeightedPhysicalCurvatureBasis(const gpr::Coord &positions, const gpr::AtomsConfiguration &config, bool exclude_rotations=true)
MeasuredCurvatureSpectrum analyzeRefinedMeasuredCurvature(const Eigen::MatrixXd &basis, const Eigen::MatrixXd &at_h, const Eigen::MatrixXd &at_2h)
MeasuredCurvatureSpectrum analyzeMeasuredCurvature(const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action)
Eigen::MatrixXd measuredIndexZeroHessian(const Eigen::MatrixXd &basis, const Eigen::MatrixXd &physical, const Eigen::MatrixXd &action)
Eigen::VectorXd measuredModeExpansion(const Eigen::MatrixXd &basis, const Eigen::MatrixXd &physical, const Eigen::VectorXd &action)
SecantSeed secantSeedDirection(const SecantHessian &secant, const Eigen::VectorXd &current_direction)
SecantSeedStatus seedHessianFromSecant(Eigen::MatrixXd &model, const SecantHessian &secant, const Eigen::MatrixXd &weight, SecantSeedSupport support=SecantSeedSupport::WholeHessian)
Eigen::VectorXd movingAtomicMasses(const gpr::AtomsConfiguration &config, Eigen::Index n_moving)
Eigen::MatrixXd transportPhysicalDirections(const Eigen::MatrixXd &directions, const Eigen::MatrixXd &physical)
Eigen::MatrixXd transportMeasuredHessianActions(const gpr::Coord &positions, const gpr::Coord &gradient, const Eigen::MatrixXd &measured_basis, const Eigen::MatrixXd &measured_action, const Eigen::MatrixXd &physical, bool include_rotations=true)
RestrictedPartitionedRfoStep restrictedPartitionedRfoStep(const Eigen::VectorXd &curvatures, const Eigen::VectorXd &gradient, const Eigen::MatrixXd &cartesian_modes, double radius)
double curvatureAtWavenumber(double wavenumber, const Eigen::VectorXd &direction, const Eigen::VectorXd &atomic_masses)
Eigen::MatrixXd stencilDirectionsForMode(VibrationalStencil mode, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, bool periodic, bool anchored, const Eigen::VectorXi *frozen=nullptr)
Eigen::RowVectorXd gradientChangeVariance(const Eigen::MatrixXd &covariance, Eigen::Index dimension, double likelihood_variance)
double refinedCurvatureResolution(double refined_resolution, double anharmonic_scale) noexcept
const char * secantSeedStatusName(SecantSeedStatus status) noexcept
double massWeightedMeasuredCurvatureResolution(const gpr::Coord &positions, const gpr::AtomsConfiguration &configuration, const Eigen::MatrixXd &basis, const Eigen::MatrixXd &actions)
MeasuredCurvatureSpectrum refineMeasuredCurvature(const Eigen::VectorXd &center, const Eigen::MatrixXd &basis, double step, Evaluate &&evaluate, RefinedCurvatureActions *actions=nullptr)
double measuredCurvaturePriorScale(const Eigen::MatrixXd &prior, const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action)
bool curvatureResolvedBySurrogate(double measured, double surrogate) noexcept
ForceStopStencilPlan planForceStopStencil(ForceStopStencilQuery query)
RefinedWeakModes refineWeakModes(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, const Eigen::MatrixXd &weak, double step, const Gradients &gradients, double noise_multiplier=0.0)
RefinedCurvatureSign refinedCurvatureSign(double curvature, double refined_resolution, double anharmonic_scale) noexcept
bool curvatureResolvedByStencil(double measured, double anharmonic_scale) noexcept
double richardsonForwardExtrapolate(double at_h, double at_2h) noexcept
Eigen::RowVectorXd consistentGradientPrediction(const Eigen::Ref< const Eigen::RowVectorXd > &measured_reference, const Eigen::Ref< const Eigen::RowVectorXd > &predicted_reference, const Eigen::Ref< const Eigen::RowVectorXd > &predicted_trial)
double gradientChangeAgreement(const Eigen::Ref< const Eigen::RowVectorXd > &measured_change, const Eigen::Ref< const Eigen::RowVectorXd > &predicted_change)
constexpr int forceStopMinModeEscapes() noexcept
Min-mode escapes after a higher-order certificate, for every search.
Eigen::MatrixXd centralDifferencePoints(const Eigen::VectorXd &center, double step, const Eigen::MatrixXd &directions)
ForceStopCertificateResult runForceStopCertificate(Measure measure, Refine refine, ForceStopStencilPlan plan, const ForceStopMeasurement *prior=nullptr)
bool coordinatesCoincideAtRoundoff(const Eigen::MatrixBase< Left > &left, const Eigen::MatrixBase< Right > &right) noexcept
std::vector< int > canonicalizeRetainedIndices(const std::vector< int > &keep, int n)
std::vector< int > consensusRetainTrainingRows(const TrainingPolicy &policy, const std::vector< Eigen::VectorXd > &rows)
bool indexListIsIdentity(const std::vector< int > &indices, int n)
bool consensusShouldRebuildFactor(const TrainingPolicy &policy, const SearchState &state)
bool consensusShouldCallOracle(const TrainingPolicy &policy, const SearchState &state)
std::vector< int > consensusSelectTrainingPoints(const TrainingPolicy &policy, const std::vector< CandidatePoint > &candidates, const std::vector< Eigen::VectorXd > &current_set)
bool consensusShouldRetrainHyperparameters(const TrainingPolicy &policy, const SearchState &state)
double variance(const Weights &w, const Matrix &covariance)
void requireCompatibleLibrary()
Definition ReadconAbi.h:76
void requireCompatibleLibrary()
MlflowRun * activeRun() noexcept
VecchiaResult evaluate(const Eigen::MatrixXd &points, const Eigen::VectorXd &y, double lengthscale, double noise, int max_neighbours)
Eigen::Vector3d vector3_reg
Definition Macros.h:36
FieldMatrixd Coord
Definition Macros.h:35
void requireWallClock(const std::shared_ptr< const WallClockLimit > &limit)
Definition PhaseTimers.h:73
uint32_t Index_t
Definition Macros.h:17
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
@ 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)
bool resolved(Dual value, Dual error, const BridgeResidualOptions &options)
STL namespace.
rgsaddle_kappa_config_t gpr_rgsaddle_kappa_config_t
rgsaddle_report_t gpr_rgsaddle_report_t
rgsaddle_kappa_report_t gpr_rgsaddle_kappa_report_t
rgsaddle_index1_config_t gpr_rgsaddle_index1_config_t
#define GPR_RGSADDLE_ABI_MAJOR
rgsaddle_surface_request_t gpr_rgsaddle_surface_request_t
Stores configurations of all atoms in the system.
Definition Structures.h:832
FieldMatrixi atomicNrs
Atomic Number of each atom.
Definition Structures.h:836
AtomsPositionAndType atoms_froz_inactive
Info on inactive frozen atoms.
Definition Structures.h:843
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
Definition Structures.h:834
FieldMatrixIdx id
ID of each atom (we do not use it).
Definition Structures.h:835
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841
Structure with information for the LBFGS method.
Definition Structures.h:977
Index_t num_cg_iter
Definition Structures.h:981
Index_t num_lbfgs_iter
Definition Structures.h:984
Observation data: energy, gradient and positions.
void resizeToMatch(const Observation &other, const Index_t num_rows)
FieldMatrixd E
void append(const Observation &other)
void copyRow(const Index_t dest_row_idx, const Observation &other, const Index_t src_row_idx)
static long chart_max_joint_rows
static int support_expansions
static void reset() noexcept
static double cholesky_seconds
static int predict_count
static const char * rss_peak_phase
static double projection_cross_seconds
static int pair_objective_count
static double condition_seconds
static double projection_schur_seconds
static double pair_contraction_seconds
static double oracle_seconds
static long projection_max_anchor_rows
static double support_seconds
static double chart_objective_seconds
static double subset_seconds
static double objective_seconds
static double support_refit_seconds
static double pair_objective_seconds
static int projection_count
static double projection_factor_seconds
static int support_refit_count
static double projection_assembly_seconds
static double assembly_seconds
static double gradient_seconds
static int chart_objective_count
static double correction_seconds
static double rss_peak_mb
static long pair_max_joint_rows
static double projection_solve_seconds
static double pair_covariance_seconds
static double residual_seconds
Residual-kernel candidate fits of the active correction.
static double predict_seconds
static int objective_count
Dimensionless knobs. All O(1) and metric-independent by construction.
double shrink_factor
0 < shrink_factor < 1
double tau
radius = tau * median spread (dimensionless)
double rho_grow
grow when rho > rho_grow (TREGO)
double rho_shrink
shrink when rho < rho_shrink (TREGO)
std::vector< int > measured
1 for a mode at least 99% inside the measured directions.
Float64 central-difference index of one geometry.
void rejected(const MeasuredCurvatureSpectrum &measured, const MeasuredCurvatureSpectrum &refined)
bool enabled() const noexcept
Eigen::VectorXd direction
SecantSeedStatus status
bool descends_measured
The step descends along a measured negative transverse direction.
Eigen::Index flat
Transverse modes with nonpositive curvature the step left out.
Eigen::Index request
The left-out mode carrying the most residual, or -1.
const GaussianProcessRegression * gp
static OracleBatchLayout world(Eigen::Index chunk=0, int owner_offset=0)
The layout of the running communicator (rank 0 of 1 without MPI).