103double finiteAbsOrInf(
const double value)
105 if (!std::isfinite(value))
return std::numeric_limits<double>::infinity();
106 return std::abs(value);
109double maxPredictiveForceVariance(
const gpr::Coord& gradient_variance,
112 if (gradient_variance.size() == 0)
113 return std::numeric_limits<double>::infinity();
115 double max_variance = 0.0;
118 for (Eigen::Index i = 0; i < gradient_variance.size(); ++i) {
120 std::max(max_variance,
121 finiteAbsOrInf(*(gradient_variance.data() + i)));
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));
135 max_variance = std::max(max_variance, atom_trace);
142 for (Eigen::Index row = 0; row < gradient_variance.rows(); ++row) {
144 for (Eigen::Index col = 0; col < gradient_variance.cols();
146 trace += finiteAbsOrInf(gradient_variance(row, col));
148 max_variance = std::max(max_variance, trace);
154bool mpiWorld(
int& rank,
int& nprocs)
158#if defined(GPR_LINALG_SCALAPACK) || defined(GPR_HAVE_MPI)
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);
170template <
typename Matrix>
171void broadcastDenseMatrix(Matrix& matrix,
int root_rank = 0)
175 if (!mpiWorld(rank, nprocs))
return;
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());
183 MPI_Bcast(shape, 2, MPI_INT, root_rank, MPI_COMM_WORLD);
184 if (rank != root_rank) {
185 matrix.resize(shape[0], shape[1]);
187 const int count = shape[0] * shape[1];
189 MPI_Bcast(matrix.data(), count, MPI_DOUBLE, root_rank, MPI_COMM_WORLD);
196 broadcastDenseMatrix(obs.
R, root_rank);
197 broadcastDenseMatrix(obs.
E, root_rank);
198 broadcastDenseMatrix(obs.
G, root_rank);
201bool broadcastBool(
bool value,
int root_rank = 0)
205 if (!mpiWorld(rank, nprocs))
return value;
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);
216double broadcastDouble(
double value,
int root_rank = 0)
220 if (!mpiWorld(rank, nprocs))
return value;
222#if defined(GPR_LINALG_SCALAPACK) || defined(GPR_HAVE_MPI)
223 MPI_Bcast(&value, 1, MPI_DOUBLE, root_rank, MPI_COMM_WORLD);
228void broadcastIndex(
gpr::Index_t& value,
int root_rank = 0)
232 if (!mpiWorld(rank, nprocs))
return;
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);
241Eigen::MatrixXd projectedCartesianBasis(
const gpr::Coord& R, Eigen::Index dof,
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)));
250 Eigen::MatrixXd excluded(dof, 0);
253 if (!anchored && R.size() > 0 && R.rows() == 1 && R.cols() == dof &&
257 for (Eigen::Index c = 0; c < dof; ++c) {
258 Eigen::VectorXd v = Eigen::VectorXd::Zero(dof);
260 v -= excluded * (excluded.transpose() * v);
261 for (
const Eigen::VectorXd& q: basis)
263 const double norm = v.norm();
264 if (norm > threshold) basis.push_back(v / norm);
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)];
273bool directionsSpanTwoNegativeCurvatures(
275 const gpr::Coord& positions,
const Eigen::VectorXd& first,
278 if (first.size() != positions.cols() || second.size() != first.size() ||
279 !first.allFinite() || !second.allFinite())
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;
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())
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())
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);
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;
319gpr::Coord rowModeFromVector(
const Eigen::VectorXd& mode)
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;
327 out.row(0) = normalized.transpose();
342 os <<
"Saddle energy (eV): " << energy <<
"\n";
343 os <<
"Saddle energy zero-level (eV): " << energy_zero <<
"\n";
344 os <<
"Converged: " << (converged ?
"yes" :
"no") <<
"\n";
348 const Eigen::MatrixXd& eigenvectors,
349 const Eigen::VectorXd& reference,
352 if (eigenvalues.size() == 0)
return 0;
354 Eigen::Index lowest_index = 0;
355 eigenvalues.minCoeff(&lowest_index);
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)));
362 eigenvectors.cols() != eigenvalues.size() ||
363 eigenvectors.rows() != reference.size() || !reference.allFinite() ||
364 reference.norm() == 0.0) {
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) {
382 eigenvalues.size()) ||
383 !eigenvectors.col(i).allFinite()) {
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))) {
393 selected_overlap = overlap;
396 if (selected_index >= 0)
return selected_index;
402 Eigen::Index canonical = -1;
403 for (Eigen::Index i = 0; i < eigenvalues.size(); ++i) {
405 eigenvalues.size()) ||
406 !eigenvectors.col(i).allFinite())
410 eigenvectors.col(canonical)))
413 if (canonical >= 0)
return canonical;
423 preserve_initial_reference) {
424 return initial_reference;
426 return current_orientation;
431const char* dimerTraceElementSymbol(
int atomic_number)
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)]
439uint64_t dimerTraceTrajId(
const std::string& phase)
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;
451readcon::RKRConFrame* buildDimerTraceFrame(
452 const gpr::Observation& obs,
const std::string& phase,
size_t idx,
453 const gpr::AtomsConfiguration& atoms_config,
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;
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;
471 "{\"energy\": %.17g, \"frame_index\": %zu, \"phase\": \"%s\"}", energy,
475 readcon::RKRConFrameBuilder* builder =
476 readcon::rkr_frame_new(cell, angles,
"Generated by gprd", meta,
"",
"");
477 if (!builder)
return nullptr;
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",
485 const bool have_forces = obs.
G.rows() > 0 && obs.
G.cols() >= 3 * natoms &&
486 obs.
G.row(0).allFinite();
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);
492 flat.data(),
static_cast<std::size_t
>(natoms));
493 if (std::isfinite(fmax))
494 (void)readcon::rkr_frame_builder_set_scalar_metadata(builder,
499 for (Eigen::Index a = 0; a < natoms && ok; ++a) {
502 z =
static_cast<int>(atoms_config.
atomicNrs(0, a));
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));
513 const double* force =
nullptr;
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);
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,
529 readcon::free_rkr_frame_builder(builder);
532 readcon::RKRConFrame* frame = readcon::rkr_frame_builder_build(builder);
533 if (!frame)
return nullptr;
541 bool path_leashed_recovery,
bool oracle_certified,
double best_oracle_force,
542 double trial_oracle_force)
noexcept
544 if (!path_leashed_recovery || !oracle_certified ||
545 !std::isfinite(best_oracle_force)) {
548 return std::isfinite(trial_oracle_force) &&
549 trial_oracle_force < best_oracle_force
565 cell_dimensions[0] = {15.3455999999999992, 0., 0.};
566 cell_dimensions[1] = {0., 21.7020000000000017, 0.};
567 cell_dimensions[2] = {0., 0., 100.0000000000000000};
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;
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;
587 rgmin_trans_ = std::make_unique<gpr::optim::RgminStep>();
600 if (external_gp !=
nullptr) {
604 owned_gpr_model_.reset();
605 gpr_model = external_gp;
606 uses_external_gp_ =
true;
609 owned_gpr_model_ = std::make_unique<gpr::GaussianProcessRegression>();
610 gpr_model = owned_gpr_model_.get();
611 uses_external_gp_ =
false;
613 if (wall_clock_limit_) gpr_model->setWallClockLimit(wall_clock_limit_);
616void AtomicDimer::clear()
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);
635 middle_point_init.
clear();
638 refit_oracle_batch_.
clear();
639 curvature_requires_full_refit_ =
false;
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();
652 max_iter_init_rot.setZero();
653 max_iter_new_pairs.setZero();
654 max_iter_relax_rot.setZero();
656 evaluate_image1_each_phase_ =
false;
659 num_bigiter_initparam = 0;
660 num_bigiter_initloc = 0;
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;
672 owned_gpr_model_.reset();
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;
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;
700void AtomicDimer::applyLikelihoodNoiseFloorAfterRefit()
702 if (!std::isfinite(likelihood_noise_floor_sigma2_) ||
703 !(likelihood_noise_floor_sigma2_ > 0.0)) {
706 (void)gpr_model->applyLikelihoodNoiseVarianceFloor(
707 likelihood_noise_floor_sigma2_, all_obs);
710bool AtomicDimer::keepsAbsoluteEnergies() const noexcept
712 return uses_external_gp_ || preserve_seed_kernel_ ||
713 (gpr_model !=
nullptr && (gpr_model->getUseZBLPriorMean() ||
714 gpr_model->getUseFFPriorMean()));
717void AtomicDimer::reseedAttachedModelIfWarmStartInfeasible()
723 if (!uses_external_gp_ || gpr_model ==
nullptr ||
724 !gpr_model->lastWarmStartInfeasible())
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);
731 applyLikelihoodNoiseFloorAfterRefit();
734std::vector<bool> AtomicDimer::hyperparameterRowPool()
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())
751 aux::Distance distance;
755 const Eigen::Index rows = all_obs.R.rows();
756 if (dist.size() != rows || !dist.allFinite())
return pool;
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;
767 log_man <<
"Hyperparameter subset pool: " << members <<
" of " << rows
768 <<
" rows within the search footprint (pair-distance radius "
773void AtomicDimer::synchronizeObservedData()
775 broadcastObservation(all_obs);
776#ifdef GPR_LINALG_SCALAPACK
779 if (mpiWorld(rank, nprocs)) {
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];
793void AtomicDimer::updateVarianceSubsetFootprint(
const std::vector<bool>& pool,
794 bool preserve_support)
796 if (!gpr_model->varianceSubsetFootprint())
return;
797 std::vector<int> ids;
798 if (preserve_support && !pool.empty()) {
799 ids = gpr_model->varianceSubsetConfigurationIds();
802 if (ids.empty())
return;
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));
816 throw std::invalid_argument(
817 "saddle secant curvature seed does not support the BFGS method");
818 secant_config_ = config;
820 secant_force_samples_.clear();
822 secant_pairs_checked_ = 0;
824 gpr_model->clearSecantQuadraticPrior();
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(),
843 if (gpr_model !=
nullptr)
848void AtomicDimer::syncSecantQuadraticPrior()
856 if (secant_force_samples_.empty())
857 throw std::logic_error(
858 "secant quadratic mean has no true-force stream to "
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,
867 throw std::logic_error(
868 "secant quadratic mean lost its physical prior");
874 gpr_model->setSecantQuadraticPrior(
879 gpr_model->setSecantQuadraticPrior(secant_hessian_.referencePosition(),
880 secant_hessian_.referenceGradient(),
881 secant_hessian_.hessian(),
882 secant_hessian_.referenceEnergy());
885void AtomicDimer::rememberSecantForceSample(
const Eigen::VectorXd& position,
886 const Eigen::VectorXd& gradient,
889 if (!secant_config_.quadratic_prior_mean)
return;
890 gpr::optim::SecantForceSample sample;
894 secant_force_samples_.push_back(std::move(sample));
897Eigen::VectorXd AtomicDimer::secantQuadraticHessianAction(
898 const Eigen::VectorXd& direction)
const
900 if (gpr_model ==
nullptr || !gpr_model->secantQuadraticPriorActive())
901 return Eigen::VectorXd::Zero(direction.size());
902 return gpr_model->secantQuadraticHessian() * direction;
905void AtomicDimer::recordTrueForceSecant(
const gpr::Observation& observation,
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));
925void AtomicDimer::purchaseSecantConsistency(pot::PotentialWrapper& potential)
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)
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;
938 at_reference.row(0) = secant_hessian_.referencePosition().transpose();
939 Eigen::VectorXd posterior_action;
940 if (!gpr_model->isDecomposedSuccessfully() &&
941 !gpr_model->hasActivePosterior())
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 "
948 const gpr::optim::SecantConsistency consistency =
949 secant_hessian_.consistency(
950 posterior_action, secant_config_.consistency_relative_tolerance);
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());
966 (secant_hessian_.referencePosition() +
967 secant_config_.finite_difference_step * consistency.
direction)
969 secant_probe_in_progress_ =
true;
970 AccurateObservationResult
measured{
false,
false};
974 measured = evaluateAccurateObservation(probe, potential,
977 secant_probe_in_progress_ =
false;
980 secant_probe_in_progress_ =
false;
983 ++secant_counts_.hvp_calls;
988void AtomicDimer::seedOrientationFromSecant(
gpr::Coord& orient)
const
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())
995 const gpr::optim::SecantSeed seed =
998 std::cout <<
"[secant-seed] orientation keeps its direction: "
1002 orient.row(0) = (seed.
direction * current.norm()).transpose();
1005void AtomicDimer::optimizeGPRModel()
1007 syncSecantQuadraticPrior();
1011 gpr_model->setRgminWarmStart(
true);
1012 if (gpr_model->getSexpAtCovarianceFunction().usesManifoldChart()) {
1013 refreshGPRModelFixedTheta();
1014 markGPRModelOptimizedForObservedData();
1017 const auto start = std::chrono::steady_clock::now();
1018 const std::vector<bool> pool = hyperparameterRowPool();
1019 updateVarianceSubsetFootprint(pool);
1020 gpr_model->setOptimizationRowPool(pool);
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);
1031 gpr_model->setOptimizationRequiredRows(std::move(required));
1032 struct FitRowsLease {
1033 gpr::GaussianProcessRegression& model;
1039 } fit_rows_lease{*gpr_model};
1040 gpr_model->optimize(all_obs);
1041 markGPRModelOptimizedForObservedData();
1042 if (!profile_phase_timing_)
return;
1044 gp_optimize_seconds_ +=
1045 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
1047 ++gp_optimize_calls_;
1052 training_policy_owner_.reset();
1053 training_policy_ = policy;
1057 std::shared_ptr<const gpr::policy::TrainingPolicy> policy)
1059 training_policy_owner_ = std::move(policy);
1060 training_policy_ = training_policy_owner_.get();
1064 DimerOracleProbeRole role)
1066 if (training_policy_ ==
nullptr || gpr_model ==
nullptr ||
1067 gpr_model->
failedOptim() || obs.
R.rows() == 0 || obs.
R.cols() == 0)
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();
1077 if (variance_probe_scratch_.
G.size() > 0) {
1078 force_variance = maxPredictiveForceVariance(variance_probe_scratch_.
G,
1079 convergence_force_norm);
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());
1094 state.
n_coords =
static_cast<int>(positions.size());
1095 state.
gp = gpr_model;
1099bool AtomicDimer::policyRetainObservations()
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_) {
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 =
1113 const std::vector<int> accepted =
1116 policy_retained_owner_ = training_policy_;
1117 policy_retained_all_obs_revision_ = all_obs_revision_;
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);
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) {
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_;
1156void AtomicDimer::refitGPRModel(
bool reinitialize,
1157 const gpr::Observation& witness,
1159 bool measured_trial_rejected)
1161 syncSecantQuadraticPrior();
1163 training_policy_ !=
nullptr && policyRetainObservations();
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_;
1173 gpr_model->clearModeRefitHint();
1174 if (witness.
R.rows() == 1 && witness.
R.allFinite())
1175 hyperparameter_pool_reference_ = witness.
R;
1180 const bool fitted_on_full_evidence =
1181 preserve_seed_kernel_ || uses_external_gp_;
1184 if (!pruned && !reinitialize && !curvature_requires_full_refit_ &&
1185 !measured_trial_rejected && fitted_on_full_evidence &&
1186 retainFittedKernelForConsistentRows()) {
1187 applyLikelihoodNoiseFloorAfterRefit();
1190 bool restricted_refit =
false;
1191 if (!reinitialize && !curvature_requires_full_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);
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();
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();
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);
1231 gpr::policy::SearchState state;
1233 state.
oracle_calls =
static_cast<int>(getNumEvaluations());
1238 state.
gp = gpr_model;
1240 *training_policy_, state)) {
1243 reinitialize, reinitialize,
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();
1255 *training_policy_, state);
1256 gpr_model->clearModeRefitHint();
1257 if (all_obs.R.rows() == 0) {
1258 gpr_model->invalidateTrainingFactorCache();
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);
1269 markGPRModelOptimizedForObservedData();
1273 gpr_model->clearModeRefitHint();
1274 applyLikelihoodNoiseFloorAfterRefit();
1275 reseedAttachedModelIfWarmStartInfeasible();
1276 recordContradictionRefitOutcome(theta_before, noise_before);
1277 curvature_requires_full_refit_ =
false;
1280bool AtomicDimer::retainFittedKernelForConsistentRows()
1290 if (gpr_model ==
nullptr || all_obs.R.rows() == 0 ||
1291 !gpr_model->hasBeenOptimized())
1295 if (refit_oracle_batch_.R.rows() == 0 &&
1296 hasOptimizedCurrentObservedData() &&
1297 gpr_model->isDecomposedSuccessfully())
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;
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";
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 "
1330 << futile_refit_evidence_nats_
1331 <<
" nats returned the same hyperparameters; a "
1334 <<
" nats conditions the fitted kernel instead.\n";
1335 refreshGPRModelFixedTheta();
1336 if (!gpr_model->isDecomposedSuccessfully())
return false;
1337 markGPRModelOptimizedForObservedData();
1340 pending_contradiction_evidence_nats_ = evidence_nats;
1343 refreshGPRModelFixedTheta();
1344 if (!gpr_model->isDecomposedSuccessfully())
return false;
1345 markGPRModelOptimizedForObservedData();
1349bool AtomicDimer::contradictionRefitWouldBeFutile(
double evidence_nats)
const
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_;
1363void AtomicDimer::recordContradictionRefitOutcome(
1364 const Eigen::VectorXd& theta_before,
double noise_before)
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();
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();
1381 const double step_tolerance = gpr_model->fitStepTolerance();
1382 const double unchanged_shift =
1383 std::isfinite(step_tolerance) && step_tolerance > 0.0 ? step_tolerance
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();
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";
1401void AtomicDimer::refreshGPRModelFixedTheta()
1403 if (gpr_model ==
nullptr || all_obs.R.rows() == 0)
return;
1404 const auto start = std::chrono::steady_clock::now();
1407 if (gpr_model->varianceSubsetFootprint())
1408 updateVarianceSubsetFootprint(hyperparameterRowPool(),
true);
1418 const bool own_model = !uses_external_gp_;
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) &&
1428 gpr_model->conditionActivePosterior(all_obs,
nullptr)))
1429 gpr_model->updateModelWithFullData(all_obs);
1430 ++fixed_theta_refresh_calls_;
1431 if (!profile_phase_timing_)
return;
1433 gp_fixed_theta_refresh_seconds_ +=
1434 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
1438bool AtomicDimer::refreshGPRModelFixedThetaIfObjectiveStationary()
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))
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,
1450 if (!refreshed)
return false;
1451 if (gpr_model->varianceSubsetFootprint())
1452 updateVarianceSubsetFootprint(hyperparameterRowPool(),
true);
1454 markGPRModelOptimizedForObservedData();
1455 ++fixed_theta_refresh_calls_;
1456 if (!profile_phase_timing_)
return true;
1458 gp_fixed_theta_refresh_seconds_ +=
1459 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
1464void AtomicDimer::calculateApproximatePotential(gpr::Observation& obs)
1466 const auto start = std::chrono::steady_clock::now();
1468 gpr::ScopedPredictTimer predict_timer;
1469 gpr_model->calculatePotentialDispatched(obs);
1470 if (local_potential_reference_ !=
nullptr) {
1471 auto& reference = *local_potential_reference_;
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();
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 =
1484 for (Eigen::Index row = 0; row < obs.
R.rows(); ++row) {
1485 const double energy_change = obs.
E(0, row) - predicted.E(0, 0);
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));
1494 const double seconds =
1495 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
1497 gp_predict_seconds_ += seconds;
1498 gp_predict_mean_seconds_ += seconds;
1499 ++gp_predict_calls_;
1500 ++gp_predict_mean_calls_;
1503void AtomicDimer::calculateApproximateVariance(gpr::Observation& obs)
1505 const auto start = std::chrono::steady_clock::now();
1507 gpr::ScopedPredictTimer predict_timer;
1508 gpr_model->calculateVarianceDispatched(obs);
1510 const double seconds =
1511 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
1513 gp_predict_seconds_ += seconds;
1514 gp_predict_variance_seconds_ += seconds;
1515 ++gp_predict_calls_;
1516 ++gp_predict_variance_calls_;
1519void AtomicDimer::logPhaseTimingSummary(
double elapsed_seconds)
1521 if (!profile_phase_timing_)
return;
1523 const double search_control_seconds =
1524 elapsed_seconds - accurate_potential_seconds_ - gp_optimize_seconds_ -
1525 gp_fixed_theta_refresh_seconds_ - gp_predict_seconds_ -
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_
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_
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
1555bool AtomicDimer::isAtomsConfigurationCorrect()
1570void AtomicDimer::updateLocation(
const gpr::Coord orient,
1574 new_point = middle_point + orient * dimer_sep;
1580 const double max_value = forceNormForConvergence(middle_point);
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 <<
")";
1595bool AtomicDimer::recordMeasuredModeCertificate(
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())
1612 Eigen::MatrixXd physical;
1617 measured.setRotationBasis(physical);
1621 latest_mode_curvature_ =
1622 measured.calculateCurvature(gradients, orientation);
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;
1634 final_rotation_residual_ = std::numeric_limits<double>::infinity();
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)
1643 (physical * (physical.transpose() * difference.transpose()))
1646 const double residual = forceNormForConvergence(difference);
1647 if (std::isfinite(residual)) final_rotation_residual_ = residual;
1654 const double angle_tolerance = stop_citeria_dimer.angle_rotation;
1658 if (!std::isfinite(latest_mode_curvature_) ||
1659 !(latest_mode_curvature_ < -latest_mode_curvature_resolution_))
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));
1669 return angle_certified || measured_rotation_stationary_;
1675 (external_terminal_certificate_ &&
1676 std::isfinite(latest_mode_curvature_) &&
1677 latest_mode_curvature_ < -latest_mode_curvature_resolution_);
1683 double surrogate_curvature)
1685 latest_mode_curvature_resolution_ = 0.0;
1687 surrogate_curvature))
1689 if (orientation.rows() != 1 || midpoint.
G.rows() != 1 ||
1690 midpoint.
G.cols() != orientation.cols() ||
1691 !(std::isfinite(dimer_sep) && dimer_sep > 0.0))
1693 const Eigen::RowVectorXd axis =
1694 orientation.row(0) /
1695 std::max(orientation.row(0).norm(), std::numeric_limits<double>::min());
1697 far_image.
R = midpoint.
R + 2.0 * dimer_sep * axis;
1698 evaluateAccurateEnergyAndForce(far_image, potential,
1700 broadcastObservation(far_image);
1701 synchronizeObservedData();
1702 if (!far_image.
G.allFinite() || far_image.
G.cols() != orientation.cols())
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_ =
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 "
1716 << latest_mode_curvature_resolution_ <<
" (surrogate "
1717 << surrogate_curvature <<
").\n";
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);
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();
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_);
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);
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);
1758 const auto evaluate = [&](gpr::Observation& candidate) {
1759 if (!evaluateAccurateProbe(candidate, potential))
1760 throw std::runtime_error(
"measured terminal dimer rotation failed");
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);
1771 const auto certify = [&]() {
1772 broadcastDenseMatrix(orientation);
1773 broadcastObservation(image1);
1774 synchronizeObservedData();
1775 return recordMeasuredModeCertificate(midpoint, orientation, image1);
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;
1782 orientation = axis.transpose();
1783 const gpr::Coord location = midpoint.
R + dimer_sep * orientation;
1785 image1.G.rows() != 1 || image1.G.cols() != dimension ||
1786 !image1.G.allFinite()) {
1787 image1.R = location;
1789 append(axis, image1);
1792 append(axis, image1);
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();
1804 append(direction, endpoint);
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;
1814 image1.R = location;
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)
1825 recovery = midpoint;
1826 if (measured_mode) measured_mode->resize(0, 0);
1827 if (!want_second_negative_mode_)
return true;
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;
1839 if (additional_mode_.size() == 0)
return true;
1841 const Eigen::MatrixXd physical =
1843 Eigen::VectorXd axis = orientation.row(0).transpose().normalized();
1844 Eigen::VectorXd transverse = additional_mode_;
1846 index_search_directions_, physical);
1847 if (transported.cols() == 2) {
1848 axis = transported.col(0);
1849 transverse = transported.col(1);
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);
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) ||
1866 std::sqrt(std::numeric_limits<double>::epsilon())) {
1867 curvature_requires_full_refit_ =
true;
1870 axis = projected_axis / axis_norm;
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;
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()))
1885 transverse /= transverse_norm;
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());
1898 const auto measure_retained = [&](gpr::Observation& observation) {
1900 evaluateAccurateEnergyAndForce(observation, potential,
1902 broadcastObservation(observation);
1903 synchronizeObservedData();
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();
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() &&
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;
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;
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())
1935 const auto copy_probe = [&](gpr::Observation& target,
gpr::Index_t row) {
1937 target.
copyRow(0, probes, row);
1939 copy_probe(plus, 0);
1940 copy_probe(minus, 1);
1941 if (owned_axis_plus)
1944 copy_probe(axis_plus, 2);
1945 copy_probe(axis_minus, probes.
R.rows() - 1);
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);
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);
1959 Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> spectrum =
1960 ritzSpectrum(action);
1961 if (spectrum.info() != Eigen::Success ||
1962 !spectrum.eigenvalues().allFinite())
1964 log_man <<
"Second negative mode: measured subspace curvatures "
1965 << spectrum.eigenvalues().transpose() <<
" (surrogate second "
1966 << additional_gp_curvature_ <<
").\n";
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;
1987 anharmonic_scale)) {
1988 refined_transverse =
true;
1989 Eigen::MatrixXd coarse = action;
1990 double fine_step = separation;
1992 for (
int refinement = 0; refinement < 2 && !
resolved; ++refinement) {
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;
2002 measure(fine_probes);
2003 if (fine_probes.
G.rows() != 4 ||
2004 fine_probes.
G.cols() != midpoint.
R.cols() ||
2005 !fine_probes.
G.allFinite())
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))
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())
2023 refined.resolution, anharmonic_scale);
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"
2045 coarse = std::move(fine);
2049 if (!resolved) positive_transverse =
true;
2055 Eigen::MatrixXd unstable = basis * spectrum.eigenvectors();
2056 Eigen::VectorXd escape = unstable.col(1);
2060 const auto flat_curvature = [&](
const Eigen::VectorXd& cartesian) {
2062 index_frequency_resolution_, cartesian,
atoms_config.atomic_masses);
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;
2072 const Eigen::Index column_limit =
2073 complete_stencil_follows ? std::min(dimension, 2 * basis.cols())
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() &&
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() &&
2102 curvature_prior = surrogate_spectrum_.modes *
2103 surrogate_spectrum_.curvatures.asDiagonal() *
2104 surrogate_spectrum_.modes.transpose();
2106 Eigen::MatrixXd prior = Eigen::MatrixXd::Zero(dimension, dimension);
2107 if (curvature_prior.rows() == midpoint.
R.cols())
2108 prior = physical.transpose() * curvature_prior * physical;
2110 gpr::track::JsonRecord record;
2111 record.
add(
"oracle_calls",
static_cast<long>(getNumEvaluations()))
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);
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();
2127 const double eps = std::numeric_limits<double>::epsilon();
2128 const double roundoff_scale =
2129 eps * std::max(action.norm(), midpoint.
G.norm());
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()) /
2142 .max(roundoff_scale)
2144 if (!error.allFinite())
return std::nullopt;
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())
2159 if (!error.allFinite())
return std::nullopt;
2162 struct ColumnStencil {
2163 Eigen::VectorXd cartesian;
2164 Eigen::VectorXd coarse_action;
2165 Eigen::VectorXd even_residual;
2166 Eigen::VectorXd refined_action;
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)
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(),
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();
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});
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();
2199 return probes.
G.rows() == 2 &&
2200 probes.
G.cols() == midpoint.
R.cols() && probes.
G.allFinite();
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() /
2210 const Eigen::VectorXd even =
2211 (0.5 * (probes.
G.row(0) + probes.
G.row(1)) - midpoint.
G.row(0))
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)
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});
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;
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;
2249 measured_basis, measured_action);
2255 const bool lowest_negative =
2257 measured_lowest_mode =
measured.modes.col(0);
2258 if (complete_stencil_follows && lowest_negative && measured_mode) {
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;
2271 const Eigen::MatrixXd pair = physical *
measured.modes.leftCols(2);
2277 double coarse_pair_error = 0.0;
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);
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) ||
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;
2304 pair_rows.append(probes);
2305 return Eigen::MatrixXd(probes.G);
2308 if (!
refined.valid)
return false;
2309 log_man <<
"Second negative mode: refined measured Ritz "
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))) {
2323 measured_negative_pair =
refined.modes;
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)
2336 physical * block * physical.transpose();
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()));
2351 verdict = IndexVerdict::Escape;
2354 negative_ritz_refinement.
rejected(measured, refined);
2356 if (complete_stencil_follows && measured_count >= column_limit) {
2357 index_search_directions_ = pair;
2365 prior, measured_basis, measured_action);
2367 model_scale * prior, measured_basis, measured_action);
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 *
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 &&
2387 -std::max(completed_resolution, second_flat) &&
2388 second.unmeasured.size() == dimension) {
2389 if (!measure_column(second.unmeasured))
return false;
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 -
2411 const double residual_norm = residual.norm();
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();
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)
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 &&
2437 std::sqrt(std::numeric_limits<double>::epsilon()) *
2440 next = residual / outside;
2443 if (next.size() == dimension) {
2444 if (!measure_column(next))
return false;
2448 if (complete_stencil_follows) {
2449 index_search_directions_ = pair;
2452 if (!lowest_negative) {
2453 log_man <<
"Measured dimer spectrum: lowest measured "
2456 <<
" is not negative; no saddle here.\n";
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(
2475 const Eigen::MatrixXd full =
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)
2490 (measured_basis.transpose() * direction).eval();
2491 if (direction.norm() > 0.0) {
2493 <<
"Measured dimer spectrum: the completion "
2494 "holds a second eigenvalue "
2495 << whole.eigenvalues()(1)
2496 <<
"; measuring its softest unmeasured "
2498 if (!measure_column(direction.normalized()))
2505 verdict = IndexVerdict::IndexOne;
2507 if (completed.rows() == dimension) {
2508 last_certificate_hessian_ =
2509 physical * completed * physical.transpose();
2510 last_certificate_positions_ = midpoint.
R;
2512 if (verdict == IndexVerdict::IndexOne) {
2516 const Eigen::MatrixXd rotation_physical =
2517 std::isfinite(transition_param.rotrem_thresh)
2521 : Eigen::MatrixXd::Identity(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;
2531 const Eigen::MatrixXd rotation_actions =
2533 midpoint.
R, midpoint.
G, directions, actions,
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;
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;
2550 index_search_directions_.resize(0, 0);
2553 unstable = std::move(measured_negative_pair);
2554 escape = unstable.col(1);
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
2563 if (midpoint.
E.size() == 0 || !std::isfinite(midpoint.
E(0, 0)))
2569 if (escapeByOrderOneSaddleSession(midpoint, potential, recovery)) {
2570 log_man <<
"Second negative mode: measured the order-one surrogate "
2572 << (recovery.
R - midpoint.
R).norm()
2573 <<
" displacement for GP conditioning.\n";
2578 curvature_requires_full_refit_ = curvature_requires_full_refit_ ||
2579 !gpr_model->activePosteriorRefitsEnabled();
2589 descendMeasuredNegativeMode(midpoint, escape, separation, step, potential,
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)
2602 mpiWorld(rank, nprocs);
2603 separation = broadcastDouble(separation);
2604 step = broadcastDouble(step);
2608 const auto propose = [&](
double displacement,
const gpr::Coord& previous,
2609 gpr::Observation& observation) {
2610 bool retracted =
true;
2612 observation.
R = midpoint.
R + displacement * escape.transpose();
2613 gpr::LBFGSInfo step_info;
2616 (void)limitTranslationGeometry(midpoint.
R, step_info,
2618 if (midpoint.
R.cols() >= 6 &&
2619 !retractTranslationGeometry(midpoint.
R, observation.
R)) {
2620 observation.
R = midpoint.
R;
2623 (void)limitTranslationGeometry(midpoint.
R, step_info,
2627 broadcastDenseMatrix(observation.
R);
2628 return broadcastBool(retracted && observation.
R.allFinite() &&
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));
2638 const auto measure_retained = [&](gpr::Observation& observation) {
2639 evaluateAccurateEnergyAndForce(observation, potential,
2641 broadcastObservation(observation);
2642 synchronizeObservedData();
2644 bool escaped =
false;
2645 last_escape_descent_calls_ = 0;
2646 for (
double length = step; !escaped && length > separation * 1e-3;
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)) {
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;
2668 if (!distinct_trial)
break;
2671 recovery = midpoint;
2672 log_man <<
"Second negative mode: every measured trial was uphill; "
2673 "no escape retained.\n";
2676 if (measured_trial_trust_ &&
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);
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";
2693rgsaddle_status_t AtomicDimer::orderOneSurface(
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);
2713bool AtomicDimer::escapeByOrderOneSaddleSession(
2714 const gpr::Observation& midpoint, pot::PotentialWrapper& potential,
2715 gpr::Observation& recovery)
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);
2722 auto& client = *kappa_dimer_client_;
2723 if (!client.hasSellaSaddle() || midpoint.
R.rows() != 1 ||
2724 gpr_model ==
nullptr)
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);
2736 const Eigen::VectorXd start = midpoint.
R.row(0).transpose();
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;
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);
2751 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
2752 hessian = 0.5 * (escape_hessian_ + escape_hessian_.transpose());
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
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());
2766 if (index1 ==
nullptr &&
2767 !fallback.
bind(client, n_atoms, start.data(), masses.data(),
2768 stop_citeria_dimer.force, 2,
2772 if (index1 !=
nullptr)
2773 return client.index1Step(index1, &AtomicDimer::orderOneSurface,
2775 return fallback.
step(&AtomicDimer::orderOneSurface,
this,
out);
2777 const auto session_position = [&](
double*
out) {
2778 if (index1 !=
nullptr)
return client.index1Position(index1,
out) == 0;
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())
2794 candidate.row(0) = position.transpose();
2796 if (isInterAtomicDistanceTooBig(candidate, all_obs.R, outside))
break;
2797 accepted = position;
2798 if (report.status == 1 || report.max_force <= stop_citeria_dimer.force)
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();
2806 evaluateAccurateEnergyAndForce(recovery, potential,
2808 broadcastObservation(recovery);
2809 synchronizeObservedData();
2810 return recovery.
G.allFinite();
2814 const Eigen::MatrixXd& cartesian_hessian,
const Eigen::VectorXd& kick,
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)
2824 if (measured_rows.
R.rows() > 0 && measured_rows.
G.allFinite()) {
2830 retainStructuralObservation(rows);
2831 synchronizeObservedData();
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();
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);
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());
2851 if (!escapeByOrderOneSaddleSession(start, potential, recovery) ||
2855 curvature_requires_full_refit_ =
2856 curvature_requires_full_refit_ ||
2857 !gpr_model->activePosteriorRefitsEnabled();
2863 centre.
R = midpoint.
R;
2864 evaluateAccurateEnergyAndForce(centre, potential,
2866 if (centre.
E.size() == 0 || !std::isfinite(centre.
E(0, 0)))
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
2872 const double sign_choice =
2873 plus_side.
E(0, 0) <= minus_side.
E(0, 0) ? 1.0 : -1.0;
2874 bool escaped =
false;
2878 for (
double length = step; !escaped; length *= 0.5) {
2879 bool resolved =
false;
2880 for (
double sign: {sign_choice, -sign_choice}) {
2882 trial.
R = midpoint.
R + sign * length * direction.transpose();
2887 evaluateAccurateEnergyAndForce(trial, potential,
2889 if (trial.
E.size() > 0 && trial.
G.allFinite() &&
2890 trial.
E(0, 0) < centre.
E(0, 0)) {
2893 for (
double next = 2.0 * length;; next *= 2.0) {
2896 midpoint.
R + sign * next * direction.transpose();
2898 if (isInterAtomicDistanceTooBig(further.
R, all_obs.R,
2901 evaluateAccurateEnergyAndForce(
2902 further, potential,
false);
2903 if (!(further.
E.size() > 0 && further.
G.allFinite() &&
2904 further.
E(0, 0) < recovery.
E(0, 0)))
2911 if (!resolved)
break;
2913 if (!escaped)
return false;
2914 broadcastObservation(recovery);
2915 synchronizeObservedData();
2917 middle_point_init = recovery;
2918 retainMeasuredNegativeSubspace(cartesian_hessian, recovery.
R);
2921 log_man <<
"Higher-order restart: complete stencil refused the "
2922 "converged midpoint; order-one search moved "
2923 << (recovery.
R - midpoint.
R).norm() <<
".\n";
2930 const Eigen::Index dof = origin.size();
2931 if (dof < 6 || dof % 3 != 0 || gpr_model ==
nullptr || !origin.allFinite())
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());
2945 nullptr, resolution);
2953 last_refinement_reached_index_one_ =
false;
2956 const double unresolved =
2957 std::isfinite(resolution) && resolution > 0.0 ? resolution : 0.0;
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)
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) {
2975 geometry.row(0) = positions.transpose();
2983 Eigen::MatrixXd model = cartesian_model.cwiseProduct(inverse_mass_weight);
2984 if (secant_config_.seed_curvature) {
2987 model, secant_hessian_, inverse_mass_weight,
2990 std::cout <<
"[secant-seed] measured walk keeps the surrogate "
2996 const auto probe = [&](
const Eigen::VectorXd& position,
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();
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);
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;
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) {
3084 for (Eigen::Index trials = 0;
3086 !oracleBudgetSpent();
3088 const Eigen::VectorXd
x = current.
R.row(0).transpose();
3089 const Eigen::MatrixXd basis = vibrational(
x);
3090 const Eigen::Index n = basis.cols();
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();
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;
3112 if (!resolve())
break;
3120 const auto refresh = [&]() {
3123 if (!(dimer_sep > 0.0)) {
3124 refresh_due =
false;
3125 measured_here =
true;
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;
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))
3147 .cwiseQuotient(root);
3148 const double length = mode.dot(s);
3149 if (!
y.allFinite() || !(length > 0.0) || !std::isfinite(length))
3151 measured_basis.col(j) = mode;
3152 measured_actions.col(j) =
y / length;
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;
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";
3172 const auto index_one_candidate = [&]() {
3173 return steps > 0 && curvature(0) < 0.0 && curvature(1) > 0.0 &&
3179 if ((refresh_due || index_one_candidate()) && !measured_here) {
3180 if (!refresh())
break;
3182 lowest = basis * modes.col(0);
3183 if (index_one_candidate()) {
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)
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();
3215 sampled = probe(points.col(j), at);
3216 if (sampled) rows.row(j) = at.G.row(0);
3218 return sampled ? rows : Eigen::MatrixXd();
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 =
3229 if (measured.rows() == dof && measured.allFinite()) {
3230 model = std::move(measured);
3231 measured_here =
true;
3233 if (!resolve())
break;
3234 lowest = basis * modes.col(0);
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 "
3250 << lowest_other <<
"); "
3251 << (refused ?
"one beyond the first is negative, "
3252 "the walk continues.\n"
3253 :
"none beyond the first is "
3255 if (refused) pair_refused =
true;
3265 if (!pair_refused && index_one_candidate()) {
3269 pair_refused =
false;
3274 const Eigen::VectorXd gradient =
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;
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;
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) {
3301 radius = radius_cap;
3303 curvature, projected, cartesian_modes, radius);
3304 if (!proposal.valid)
break;
3306 std::min(radius_cap, atomic_cap(proposal.cartesian_step));
3309 const bool clamped = proposal.boundary;
3310 const Eigen::VectorXd weighted = weighted_modes * proposal.eigen_step;
3311 const Eigen::VectorXd& displacement = proposal.cartesian_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();
3328 if (!probe(
x + displacement, trial,
3329 raw_candidate !=
nullptr ? &trial_raw :
nullptr))
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())
3342 cartesian_change, cartesian_prediction);
3345 const double measured_energy_change = trial.
E(0, 0) - current.
E(0, 0);
3350 const double defect = std::max(
3351 0.0, std::abs(measured_energy_change - predicted_energy_change) -
3353 const double ratio =
3355 : std::abs(predicted_energy_change) > 0.0
3356 ? 1.0 - defect / std::abs(predicted_energy_change)
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";
3381 cap_scale = std::max(1.0, cap_scale * trust_config.
shrink_factor);
3388 log_man <<
"Measured partitioned RFO: the radius collapsed "
3389 "to coordinate resolution after "
3390 << rejected <<
" rejected steps; the walk ends.\n";
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";
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;
3418 }
else if (complete_stencil && std::isfinite(gradient_defect) &&
3419 gradient_defect <= tolerance) {
3427 bofill(weighted, change);
3429 if (raw_candidate !=
nullptr) current_raw = std::move(trial_raw);
3431 measured_here =
false;
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();
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."
3464 ?
", radius collapsed; the search continues from here."
3465 :
", index one not reached.")
3472 const Eigen::MatrixXd& certified_cartesian_hessian,
3473 const Eigen::MatrixXd& certified_mass_weighted_basis,
3474 bool first_order_certificate)
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())
3511 relative_center = raw_center;
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_))
3527 Eigen::VectorXd masses;
3531 }
catch (
const std::invalid_argument&) {
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;
3554 const Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd>
3555 spectrum(0.5 * (reduced + reduced.transpose()), gram);
3556 if (spectrum.info() != Eigen::Success ||
3557 !spectrum.eigenvalues().allFinite())
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))
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;
3582 if (orient_init.rows() == 1 && orient_init.cols() == dimension &&
3583 orient_init.allFinite() && orient_init.row(0).dot(mode) < 0.0)
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))
3590 orientation.resize(1, dimension);
3591 orientation.row(0) = mode.transpose();
3595 int accepted = prepare() ? 1 : 0;
3596#if defined(GPR_LINALG_SCALAPACK) || defined(GPR_HAVE_MPI)
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)
3603 if (accepted == 0)
return false;
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;
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);
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;
3636void AtomicDimer::retainMeasuredNegativeSubspace(
3637 const Eigen::MatrixXd& cartesian_hessian,
const gpr::Coord& position)
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) {
3653 index_search_directions_ =
3654 physical * measured_spectrum.eigenvectors().leftCols(2);
3672 const Eigen::MatrixXd& cartesian_hessian)
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())))
3683 if (measured_rows.
R.rows() > 0 && measured_rows.
G.allFinite()) {
3689 retainStructuralObservation(rows);
3690 synchronizeObservedData();
3693 moved.
R.resize(1, dof);
3695 (final_position + length * direction.normalized()).transpose();
3696 evaluateAccurateEnergyAndForce(moved, potential,
3698 if (moved.
E.size() == 0 || !std::isfinite(moved.
E(0, 0)) ||
3699 !moved.
G.allFinite())
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);
3712 middle_point_final = moved;
3713 if (forceNormForConvergence(moved) < stop_citeria_dimer.force) {
3714 final_converged_ =
true;
3715 relaxation_termination_reason_ =
3718 log_man <<
"Weak-mode restart: the complete stencil cannot certify the "
3719 "weak modes positive; continuing "
3720 << length <<
" along the softest one.\n";
3724void AtomicDimer::resolveSurrogateNegativeModesBeforePhase(
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))
3743 const Eigen::Index span =
3744 projectedCartesianBasis(midpoint.
R, midpoint.
R.cols(),
atoms_config)
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))
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) ||
3763 std::sqrt(std::numeric_limits<double>::epsilon()))
3765 transverse /= transverse_norm;
3770 const double resolved_overlap =
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 "
3786 measured_directions.push_back(transverse);
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,
3794 broadcastObservation(*probe);
3796 synchronizeObservedData();
3797 if (!plus.
G.allFinite() || !minus.
G.allFinite() ||
3798 plus.
G.cols() != midpoint.
R.cols() ||
3799 minus.
G.cols() != midpoint.
R.cols())
3801 const double measured_curvature =
3802 (plus.
G.row(0) - minus.
G.row(0)).dot(transverse.transpose()) /
3804 log_man <<
"Surrogate negative mode check: "
3805 << last_negative_mode_count_
3806 <<
" surrogate negative modes at the phase start; measured "
3808 << measured_curvature <<
" along the second surrogate mode "
3809 <<
"(surrogate " << additional_gp_curvature_ <<
").\n";
3810 if (!std::isfinite(measured_curvature) || measured_curvature < 0.0)
3815 curvature_requires_full_refit_ =
true;
3816 refitGPRModel(
false, plus, mode.first);
3820void AtomicDimer::resolveFlatResidualDirection(
const gpr::Observation& midpoint,
3822 pot::PotentialWrapper& potential)
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);
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;
3845 measured_negative_directions_.clear();
3846 measured_negative_reference_ = midpoint.
R;
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;
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,
3860 broadcastObservation(*probe);
3862 synchronizeObservedData();
3863 if (!plus.
G.allFinite() || !minus.
G.allFinite() ||
3864 plus.
G.cols() != midpoint.
R.cols() ||
3865 minus.
G.cols() != midpoint.
R.cols())
3867 const double measured_curvature =
3868 (plus.
G.row(0) - minus.
G.row(0)).dot(direction.transpose()) /
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);
3879 if (surrogate_curvature < 0.0) curvature_requires_full_refit_ =
true;
3880 refitGPRModel(
false, plus, orientation);
3883bool AtomicDimer::projectedTrustRegionStep(
const gpr::Coord& R,
3887 if (measured_trial_trust_)
3888 radius = std::min(radius, measured_trial_trust_->radius());
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())
3913 if (!(R.row(0) - spectrum.R.row(0)).isZero(0.0) &&
3914 !R.row(0).isApprox(spectrum.R.row(0), 1.0e-12))
3917 measured_negative_directions_.clear();
3918 measured_negative_reference_.resize(0, 0);
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;
3927 pending_flat_direction_.resize(0);
3928 pending_flat_curvature_ = std::numeric_limits<double>::quiet_NaN();
3931 pending_flat_direction_ = spectrum.modes.col(solved.
request);
3932 pending_flat_curvature_ = spectrum.curvatures(solved.
request);
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)
3948bool AtomicDimer::restartLocalTranslation(
const gpr::Coord& R,
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))
3958 double radius = transition_param.max_step_length;
3959 if (measured_trial_trust_)
3960 radius = std::min(radius, measured_trial_trust_->radius());
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();
3970 curvature = eigenvalue;
3971 log_man <<
"Local force-root step: length=" << step.stableNorm()
3972 <<
" radius=" << radius <<
".\n";
3976double AtomicDimer::directionalCurvatureUncertainty(
3977 const gpr::Coord& R,
const Eigen::VectorXd& direction)
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();
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));
3997 long double roundoff = 0.0L;
3999 gpr::ScopedPredictTimer timer;
4001 gpr_model->calculateObservationFunctionalVariance(stencil, weights);
4002 if (std::isfinite(variance) && variance < 0.0L) {
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;
4018 const double seconds =
4019 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
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());
4031void AtomicDimer::prepareIndexOneProjection(
const gpr::Coord& R)
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))
4043 for (Eigen::Index k = 0; k < spectrum.curvatures.size(); ++k) {
4044 if (k == spectrum.mode_index || !(spectrum.curvatures(k) < 0.0))
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_;
4052 index_one_clamped_modes_.emplace_back(spectrum.curvatures(k), mode);
4056void AtomicDimer::applyIndexOneProjection(
const Eigen::VectorXd& direction,
4057 Eigen::VectorXd& action)
const
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;
4068double AtomicDimer::forceNormForConvergence(
4069 const Eigen::Ref<const Eigen::RowVectorXd>& gradient)
const
4074double AtomicDimer::forceNormForConvergence(
4075 const Eigen::Ref<const Eigen::RowVectorXd>& positions,
4076 const Eigen::Ref<const Eigen::RowVectorXd>& gradient)
const
4079 positions.size() != gradient.size() || positions.size() == 0 ||
4080 positions.size() % 3 != 0 || !positions.allFinite()) {
4081 return forceNormForConvergence(gradient);
4084 geometry.row(0) = positions;
4085 Eigen::VectorXd projected = gradient.transpose();
4087 const Eigen::RowVectorXd projected_row = projected.transpose();
4088 return forceNormForConvergence(projected_row);
4091double AtomicDimer::forceNormForConvergence(
const gpr::Observation& obs)
const
4093 if (obs.
R.rows() < 1 || obs.
G.rows() < 1 || obs.
R.cols() != obs.
G.cols()) {
4094 return std::numeric_limits<double>::infinity();
4096 return forceNormForConvergence(obs.
R.row(0), obs.
G.row(0));
4099double AtomicDimer::surrogateForceTolerance(
4100 const gpr::Observation& oracle_middle_point)
const
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)) {
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);
4112double AtomicDimer::bestObservedForceNorm()
const
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)));
4128 dimer.bindRgminTranslation(rgmin_trans_.get());
4131 bool is_convergence_rached =
false;
4133 G01_loc = middle_point.
G;
4136 dimer.rotateForce(G01_loc, orient, F_rot);
4138 double omega =
dimer.estimateRotationalAngle(orient, G01_loc, F_rot);
4140 if (omega <= stop_citeria_dimer.angle_rotation)
4141 is_convergence_rached =
true;
4143 is_convergence_rached =
false;
4145 return is_convergence_rached;
4150 const double stop_criteria)
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())
4156 if (!orient.allFinite() || !approx_obs.
G.allFinite())
return false;
4159 dimer.bindRgminTranslation(rgmin_trans_.get());
4161 dimer.rotateForce(approx_obs.
G, orient, F_rot);
4162 const double omega =
4163 dimer.estimateRotationalAngle(orient, approx_obs.
G, F_rot);
4165 return std::isfinite(omega) && omega <= stop_criteria;
4174 dimer.bindRgminTranslation(rgmin_trans_.get());
4180 if (uncertainty_aware_rotation_ && gpr_model !=
nullptr &&
4181 middle_point.
R.rows() == 1 && middle_point.
R.cols() > 0) {
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());
4197 double curv_dummy = 0;
4198 bool terminate_loop =
false;
4202 orient_old = orient;
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) {
4216 const bool have_prepared_hssvd =
4217 gpr_model->prepareMeanHessianVectorHssvd(middle_point.
R,
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,
4224 return gpr_model->calculateMeanHessianVectorDispatched(
4225 middle_point.
R, dx, hv);
4228 if (candidate.R.rows() != 1 ||
4229 candidate.R.cols() != middle_point.
R.cols() ||
4230 !candidate.R.allFinite())
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();
4241 double trial_curv = 0.0;
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;
4254 if (!used_analytic_hessian) {
4256 stop_criteria,
false, all_obs, gpr_model, rot_info, orient,
4257 curv_dummy, observed);
4258 endpoint_is_measured =
true;
4261 if (observed.
R.size() != 0) {
4264 approx_obs.
R(1, n) =
4265 middle_point.
R(0, n) + orient(0, n) * dimer_sep;
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);
4280 calculateApproximatePotential(reduced_obs);
4284 approx_obs.
R(1, j) = reduced_obs.
R(0, j);
4285 approx_obs.
G(1, j) = reduced_obs.
G(0, j);
4287 approx_obs.
E(0, 1) = reduced_obs.
E(0, 0);
4290 checkRotationalConvergence(orient, orient_old, stop_criteria);
4292 terminate_loop =
true;
4293 log_man <<
"Dimer rotation converged (omega < T_anglerot); "
4294 "skipping image-1 update\n";
4297 return terminate_loop;
4300bool AtomicDimer::checkRotationalConvergence(
const gpr::Coord& orient,
4302 const double stop_criteria)
4304 const Eigen::Map<const Eigen::VectorXd> v(orient.data(), orient.size());
4305 const Eigen::Map<const Eigen::VectorXd> v_old(orient_old.data(),
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;
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;
4320bool AtomicDimer::isRotationCurvatureInformative(
4321 const double curvature)
const noexcept
4323 return std::isfinite(curvature) && curvature < 0.0;
4326double AtomicDimer::exactEmdDuplicateThreshold(
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());
4337 if (!std::isfinite(beta) || beta < 0.0)
4338 throw std::invalid_argument(
4339 "kappa dimer beta must be finite and nonnegative");
4341 kappa_dimer_beta_ = 0.0;
4342 kappa_dimer_client_.reset();
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);
4353 kappa_dimer_beta_ = beta;
4354 if (rgmin_trans_) rgmin_trans_->forget();
4357void AtomicDimer::resetTranslationHistory(
gpr::LBFGSInfo& history)
4362 if (rgmin_trans_) rgmin_trans_->
forget();
4368 const double curvature,
4372 dimer.setProjectRotations(
4374 dimer.bindRgminTranslation(rgmin_trans_.get());
4378 G01_approx_negative *= -1.;
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))
4387 dimer.translate(middle_point.
R, orient, G01_approx_negative, curvature,
4388 transition_param, trans_info, R_new);
4391 const Eigen::Index dof = middle_point.
R.cols();
4392 Eigen::MatrixXd excluded(dof, 0);
4397 const Eigen::VectorXd gradient = approx_obs.
G.row(0).transpose();
4409 const bool refine = curvature < 0.0;
4410 if (refine != kappa_dimer_refining_) resetTranslationHistory(trans_info);
4411 kappa_dimer_refining_ = 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))
4418 dimer.translate(middle_point.
R, orient, G01_approx_negative, curvature,
4419 transition_param, trans_info, R_new);
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);
4430 const auto callback = [](
void*
user, int64_t n,
const double* v,
4431 double* hv) ->
int {
4432 auto& apply = *
static_cast<decltype(action)*
>(
user);
4434 Eigen::VectorXd result;
4435 if (!apply(Eigen::Map<const Eigen::VectorXd>(v, n), result) ||
4436 result.size() != n || !result.allFinite())
4438 Eigen::Map<Eigen::VectorXd>(hv, n) = result;
4445 const std::uint32_t kappa_abi_minor =
4446 std::max(kappa_dimer_client_->abiMinor(),
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);
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;
4473 dimer.translate(middle_point.
R, orient, G01_approx_negative, curvature,
4474 transition_param, trans_info, R_new);
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,
4489 bool atoms_were_updated =
false;
4493 log_man <<
"Frozen:: "
4498 <<
"Moving:: " <<
atoms_config.atoms_mov.positions.size()
4499 <<
" Total:: " <<
atoms_config.positions.size() <<
"\n";
4502 if (std::isfinite(actdist_fro)) {
4503 atoms_were_updated =
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";
4514 log_man <<
"More frozen atoms activated. Syncing GPR.\n";
4523 resetTranslationHistory(trans_info);
4529 return atoms_were_updated;
4532void AtomicDimer::setMeasuredTrialAnchor(
const gpr::Coord& measured)
4534 measured_trial_anchor_ = measured;
4538void AtomicDimer::shrinkMeasuredTrialTrust(
double displacement,
4541 if (!measured_trial_trust_) {
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);
4554 measured_trial_trust_->updateRadiusFromRhoValue(0.0);
4555 setMeasuredTrialAnchor(accepted);
4558void AtomicDimer::recordOracleTrialFailure(
const std::string& what)
4560 ++consecutive_oracle_failures_;
4561 log_man <<
"True-PES evaluation failed (" << consecutive_oracle_failures_
4563 <<
" in a row): " << what <<
"; rejecting the trial.\n";
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 " +
4572bool AtomicDimer::limitMeasuredTrial(
const gpr::Coord& current,
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())
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())
4589 proposed.row(0) = bounded.transpose();
4593std::vector<int> AtomicDimer::contactDomainAtomicNumbers(
4594 Eigen::Index moving_count, Eigen::Index frozen_active_count)
const
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)
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));
4608 moving.push_back(
z);
4610 frozen.push_back(
z);
4612 if (
static_cast<Eigen::Index
>(moving.size()) != moving_count)
4615 if (
static_cast<Eigen::Index
>(frozen.size()) == frozen_active_count)
4616 numbers.insert(numbers.end(), frozen.begin(), frozen.end());
4620bool AtomicDimer::limitTranslation(
const gpr::Coord& R,
4621 gpr::LBFGSInfo& trans_info,
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);
4634bool AtomicDimer::limitTranslationGeometry(
const gpr::Coord& R,
4635 gpr::LBFGSInfo& trans_info,
4638 aux::Distance distance;
4643 double step_coeff = 0.;
4645 bool step_length_is_larger_than_limit =
false;
4650 step_length_atomwise.resize(R.rows(), R.cols() / 3);
4651 step_length_atomwise.setZero();
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) +=
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);
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;
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) {
4688 R_new = R + (R_new - R) * step_coeff;
4690 resetTranslationHistory(trans_info);
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;
4712 if (contact_reference_geometries_.cols() == R.cols()) {
4713 std::vector<Eigen::VectorXd> references;
4715 static_cast<std::size_t
>(contact_reference_geometries_.rows()));
4716 for (Eigen::Index i = 0; i < contact_reference_geometries_.rows();
4718 references.push_back(
4719 assemble(contact_reference_geometries_.row(i).transpose()));
4720 floor.calibrateToGeometries(references, cell, moving_count);
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,
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;
4735 return step_length_is_larger_than_limit;
4739 bool* measured_boundary)
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;
4747bool AtomicDimer::retractTranslationGeometry(
const gpr::Coord& R,
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 &&
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()) {
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);
4771 for (
int atom = 0; atom < n_atoms; ++atom) {
4772 moving[
static_cast<std::size_t
>(atom)] =
4780 if (primitives.empty()) {
4784 const gpr::geometry::InternalCoordinateSet coords(
4785 n_atoms, std::move(moving), std::move(primitives), cell);
4786 const Eigen::VectorXd retracted =
4788 if (retracted.size() != positions.size() || !retracted.allFinite()) {
4789 log_man <<
"Internal-coordinate retraction failed; the trial "
4790 "was not replaced.\n";
4794 if ((retracted.array() == positions.array()).all()) {
4798 R_new.row(0) = retracted.transpose();
4800 }
catch (
const gpr::geometry::InternalCoordinateRetractionFailed&) {
4801 log_man <<
"Internal-coordinate retraction failed; the trial "
4802 "was not replaced.\n";
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";
4810 }
catch (
const std::invalid_argument&) {
4811 log_man <<
"Internal-coordinate retraction failed; the trial "
4812 "was not replaced.\n";
4815 }
catch (
const std::runtime_error&) {
4816 log_man <<
"Internal-coordinate retraction failed; the trial "
4817 "was not replaced.\n";
4823double AtomicDimer::shortestKernelLengthScale() const noexcept
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);
4834 return std::isfinite(shortest) ? shortest
4835 : std::numeric_limits<double>::quiet_NaN();
4838void AtomicDimer::recordPredictedMeasuredAgreement(
4839 const gpr::Observation& predicted,
const gpr::Observation& measured)
4841 if (predicted.
E.size() == 0 ||
measured.E.size() == 0 ||
4842 predicted.
G.rows() < 1 ||
measured.G.rows() < 1 ||
4845 const double energy_error = std::abs(predicted.
E(0, 0) -
measured.E(0, 0));
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));
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))
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;
4862AtomicDimer::InterAtomicTrustDistance
4863AtomicDimer::evaluateInterAtomicTrustDistance(
const gpr::Coord& R_new,
4866 InterAtomicTrustDistance trust;
4867 aux::Distance distance;
4869 if (early_params._use_adaptive_threshold) {
4870 const int num_data_points =
static_cast<int>(all_obs.E.size());
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);
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));
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));
4887 trust.threshold = std::min(earned_thresh, physical_limit);
4890 trust.threshold = early_params._threshold;
4893 switch (early_params._dist_metric) {
4896 trust.threshold = fabs(
log(ratio_at_limit));
4908 throw(
"Shouldn't be here");
4913 trust.threshold, shortestKernelLengthScale(), model_force_error_,
4914 model_force_scale_, model_energy_error_, model_energy_scale_);
4916 trust.distance = dist.minCoeff();
4920bool AtomicDimer::isInterAtomicDistanceTooBig(
const gpr::Coord& R_new,
4924 const InterAtomicTrustDistance trust =
4925 evaluateInterAtomicTrustDistance(R_new, R_all);
4926 const bool res = trust.distance > trust.threshold;
4932 log_man <<
"NOTE: got " << trust.distance <<
" compared to "
4933 << trust.threshold <<
".\n";
4937bool AtomicDimer::projectInterAtomicTrustBoundary(
const gpr::Coord& R_current,
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;
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;
4958 gpr::TrustRadius trust_policy;
4962 const Eigen::VectorXd current = R_current.row(0).transpose();
4963 const Eigen::VectorXd trial = R_trial.row(0).transpose();
4964 Eigen::VectorXd projected;
4966 current, trial, trial_trust.threshold, projected)) {
4967 R_projected = R_current;
4970 R_projected.resize(1, projected.size());
4971 R_projected.row(0) = projected.transpose();
4982 return num_of_gen_potential_calls;
4985void AtomicDimer::checkIfMaxIterReachedAndPrintWarning(
4987 const std::string& message)
4992 if (iter_counter == iter_limit) {
4993 log_man <<
"WARNING: Maximum number of iterations " << iter_counter
4994 <<
" is reached during the " << message <<
".\n";
4998void AtomicDimer::defineStartPath(
5002 gpr::Observation& middle_point,
gpr::Coord& orient)
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";
5011 const bool has_latest_converged_dimer = R_latest_conv.size() != 0;
5012 const bool has_stored_stop_point = R_previous.size() != 0;
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 "
5026 middle_point.
R = middle_point_init.R;
5027 orient = orient_init_gpr;
5028 log_man <<
"Started relaxation phase from the initial location.\n";
5032double AtomicDimer::performRotationAndTranslationWithGPR(
5033 const double stop_dimer_gp, gpr::Observation& middle_point,
5037 const size_t& outer_iter_idx,
bool& require_midpoint_oracle,
5039 const gpr::Observation* measured_reference)
5041 LocalPotentialReference local_reference;
5042 local_reference.measured = measured_reference;
5043 struct RestoreReference {
5044 LocalPotentialReference*& slot;
5045 LocalPotentialReference* previous;
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;
5058 gpr::LBFGSInfo rot_info;
5059 gpr::LBFGSInfo trans_info;
5060 gpr::Observation approx_obs;
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 =
5071 double action_curvature,
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();
5095 resetTranslationHistory(trans_info);
5104 double force_cycle_preceding = std::numeric_limits<double>::infinity();
5105 bool translation_restarted_at_current_point =
false;
5107 double previous_inner_curvature = std::numeric_limits<double>::quiet_NaN();
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;
5119 for (inner_iter = 0;
5123 log_man <<
" Inner relaxation iteration: " << inner_iter <<
"\n";
5127 approx_obs.
R = middle_point.
R;
5128 updateLocation(orient, middle_point.
R, temp);
5130 calculateApproximatePotential(approx_obs);
5132 const double force_now =
5133 forceNormForConvergence(middle_point.
R.row(0), approx_obs.
G.row(0));
5137 if (force_now < stop_dimer_gp) {
5138 curvature = performSurrogateRotation(middle_point, approx_obs,
5140 R_new = middle_point.
R;
5141 record_first_action(
5145 R_previous = middle_point.
R;
5146 orient_previous = orient;
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()
5165 << gpr_model->getSexpAtCovarianceFunction()
5166 .getLengthScaleRef()
5169 << gpr_model->getSexpAtCovarianceFunction()
5170 .getLengthScaleRef()
5173 << (E_zero_level.size() > 0 ? E_zero_level(0, 0) : 0.0)
5175 << (middle_point.
E.size() > 0 ? middle_point.
E(0, 0) : 0.0)
5177 << (all_obs.E.size() > 0 ? all_obs.E.mean() : 0.0) <<
").\n";
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(),
5194 if (!assume_many_iterations) {
5195 R_previous = middle_point.
R;
5196 orient_previous = orient;
5198 log_man <<
"Stopped relaxation phase: maximum number of inner "
5200 << inner_iter + 1 <<
" reached.\n";
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);
5221 if (!std::isfinite(curvature) || !R_new.allFinite()) {
5222 log_man <<
"Stopped relaxation phase: non-finite curvature ("
5224 <<
") or non-finite step from the GP "
5226 << inner_iter + 1 <<
" inner iterations.\n";
5227 if (!assume_many_iterations) {
5228 R_previous = middle_point.
R;
5229 orient_previous = orient;
5238 log_man <<
"updateActiveFrozenAtoms\n";
5239 optimized_all_obs_revision_ = kUnoptimizedObservationRevision;
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";
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;
5263 log_man <<
"Stopped the relaxation phase after " << inner_iter + 1
5264 <<
" inner iterations: internal-coordinate retraction "
5265 "failed; rejected the Cartesian trial.\n";
5275 (R_cycle_preceding.size() != 0) ? &R_cycle_preceding :
nullptr;
5276 const DimerRelaxationCycleCertificate cycle =
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;
5285 record_first_action(
5290 R_previous = middle_point.
R;
5291 orient_previous = orient;
5292 log_man <<
"Stopped the relaxation phase after "
5294 <<
" inner iterations: condition-driven dimer map "
5299 <<
" geometry cycle; retained lower-force member for "
5300 "oracle acquisition.\n";
5303 const gpr::Coord inner_step = R_new - middle_point.
R;
5304 if (previous_inner_step.size() != 0 &&
5306 previous_inner_step,
5307 previous_inner_curvature)) {
5308 record_first_action(
5313 R_previous = middle_point.
R;
5314 orient_previous = orient;
5315 log_man <<
"Stopped the relaxation phase after "
5317 <<
" inner iterations: the projected trust step "
5318 "repeated at the stable-basis cutoff.\n";
5321 previous_inner_step = inner_step;
5322 previous_inner_curvature = curvature;
5349 if (isInterAtomicDistanceTooBig(R_new, es_reference, num_es1)) {
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,
5357 log_man <<
"Projected relaxation step to inter-atomic trust "
5359 << projected_trust.distance <<
" compared to "
5360 << projected_trust.threshold <<
".\n";
5362 R_previous = middle_point.
R;
5363 orient_previous = orient;
5364 record_first_action(
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";
5379 const auto translated_force_residual = [&](
const auto& gradient_row) {
5381 force.row(0) = -gradient_row;
5384 progress_dimer.translateForce(force, orient, translated_force);
5385 return translated_force.norm();
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_);
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 =
5422 const bool measured_boundary =
5423 measured_translation_boundary || measured_retraction_boundary;
5425 measured_boundary, proposed_force_variance,
5426 posterior_action_force_scale);
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;
5442 const auto slope_start = std::chrono::steady_clock::now();
5443 Eigen::VectorXd hstep;
5444 bool have_action =
false;
5446 gpr::ScopedPredictTimer timer;
5447 const auto hessian =
5448 gpr_model->prepareMeanHessian(middle_point.
R);
5451 hessian((R_new - middle_point.
R).row(0).transpose(),
5453 hstep.size() == middle_point.
R.cols() && hstep.allFinite();
5455 residual_slope = approx_obs.
G.row(0).dot(hstep);
5458 std::isfinite(residual_slope) &&
5459 residual_slope >= 0.0) {
5464 const auto& modes = surrogate_spectrum_.modes;
5465 if (modes.rows() == middle_point.
R.cols() &&
5467 transverse_instability =
5468 directionsSpanTwoNegativeCurvatures(
5469 hessian, middle_point.
R, modes.col(0),
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(),
5481 const double slope_seconds =
5482 std::chrono::duration<double>(std::chrono::steady_clock::now() -
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;
5491 if (proposal_action ==
5496 const double slope = proposal_residual_slope();
5497 if (std::isfinite(slope) && slope >= 0.0 && inner_iter > 0 &&
5498 !translation_restarted_at_current_point) {
5502 resetTranslationHistory(trans_info);
5506 translation_restarted_at_current_point =
true;
5507 log_man <<
"Restarted local dimer translation after "
5508 "nonnegative force-residual slope "
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();
5525 middle_point.
R, R_new, approx_obs.
G.topRows(1), orient,
5526 curvature, energy_change);
5527 if (merit.accepted) {
5528 const bool shortened =
5530 R_new = std::move(merit.positions);
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);
5551 curvature, force_now, local_force_tolerance,
5552 proposed_force_variance,
5553 posterior_action_force_scale) ==
5554 DimerProposalGlobalizationAction::
5556 ? DimerProposalGlobalizationAction::
5558 : DimerProposalGlobalizationAction::
5560 log_man <<
"Trusted transverse dimer step satisfies "
5561 "saddle merit descent (change="
5563 <<
", evaluations=" << merit.evaluations
5564 <<
", shortened=" << shortened <<
").\n";
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));
5578 DimerRelaxationBacktrackResult backtrack;
5579 if (proposal_action ==
5582 curvature, current_residual)) {
5584 middle_point.
R, R_new, current_residual, evaluate_residual);
5588 proposal_action, curvature, current_residual,
5589 backtrack.accepted);
5593 double proposed_residual = std::numeric_limits<double>::infinity();
5595 std::isfinite(curvature) && curvature < 0.0) {
5596 gpr::Observation proposed;
5598 calculateApproximatePotential(proposed);
5599 if (proposed.
G.rows() > 0 &&
5600 proposed.
G.cols() == middle_point.
R.cols() &&
5601 proposed.
G.row(0).allFinite())
5603 translated_force_residual(proposed.
G.row(0));
5604 if (last_step_descends_measured_negative_ &&
5605 std::isfinite(proposed_residual)) {
5610 log_man <<
"Trusted step descends along a measured negative "
5611 "transverse direction (current="
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)) {
5621 proposed_force_variance, posterior_action_force_scale);
5622 }
else if (slope < 0.0) {
5625 middle_point.
R + 0.5 * (R_new - middle_point.
R),
5626 current_residual, evaluate_residual);
5629 curvature, current_residual, backtrack.accepted),
5630 proposed_force_variance, posterior_action_force_scale);
5632 log_man <<
"Trusted global dimer step has nonnegative "
5633 "force-residual slope "
5634 << slope <<
" (current=" << current_residual
5635 <<
", proposed=" << proposed_residual <<
").\n";
5639 if (residual_action ==
5641 const bool shortened =
5643 R_new = std::move(backtrack.positions);
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) ==
5666 resetTranslationHistory(trans_info);
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";
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;
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";
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;
5716 if (stop_after_first_action)
break;
5718 if (debug_level ==
DEBUG_L3) writeLatticeData(middle_point);
5721 if (debug_level ==
DEBUG_L2) writeLatticeData(middle_point);
5724 if (std::isfinite(curvature)) latest_mode_curvature_ = curvature;
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)) {
5747 gpr::Coord orient = initial_orientation / initial_orientation.norm();
5755 bool require_midpoint_oracle =
false;
5756 const double stop_dimer_gp = surrogateForceTolerance(oracle_middle_point);
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 0, require_midpoint_oracle, &action,
5762 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_ = {};
5775 const std::string& addl_group,
const size_t& idx)
5777 if (!hdf5_trace_enabled_)
return;
5778#ifdef GPR_LINALG_SCALAPACK
5781 MPI_Initialized(&mpi_up);
5784 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
5785 if (rank != 0)
return;
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";
5810#ifdef USE_READCON_DB
5811void AtomicDimer::setTraceCorpus(
const std::string& db_path)
5813 trace_corpus_.reset();
5814 trace_con_path_.clear();
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();
5829 const std::string& phase,
size_t idx)
5831#ifdef USE_READCON_DB
5832 if (trace_corpus_) {
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(
5843 uint32_t n_frames = 0;
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};
5856 readcon::rkr_writer_extend(staging_writer, frames, 1) ==
5857 readcon::RKR_STATUS_SUCCESS;
5860 readcon::free_rkr_writer(staging_writer);
5862 st = rkrdb_extend_trajectory(trace_corpus_->id(), traj,
5863 staging_path.c_str(),
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());
5874 const readcon::RKRConFrame* frames[] = {frame};
5875 (void)readcon::rkr_writer_extend(writer, frames, 1);
5876 readcon::free_rkr_writer(writer);
5879 readcon::free_rkr_frame(frame);
5880 if (st != RKRDB_OK) {
5881 std::cerr <<
"[dimer] trace corpus extend skipped\n";
5883 }
catch (
const std::exception& e) {
5884 std::cerr <<
"[dimer] trace corpus write skipped: " << e.what()
5891 writeHDF5(obs, phase, idx);
5905 std::string full_file_name_E;
5906 std::string full_file_name_R;
5907 std::string full_file_name_G;
5914 orig_coord(1) -= debug_output_info.
offset;
5915 orig_coord(2) -= debug_output_info.
offset;
5916 current_coord = orig_coord;
5919 Jmax = debug_output_info.
offset * 2. / debug_output_info.
dy + 1;
5920 Kmax = debug_output_info.
offset * 2. / debug_output_info.
dz + 1;
5923 std::filesystem::create_directories(debug_output_info.
out_dir);
5925 log_man <<
"...Writing output files: " << file_counter <<
"\n";
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());
5939 current_coord(1) = orig_coord(1) + j * debug_output_info.
dy;
5940 current_coord(2) = orig_coord(2);
5942 tmp_obs = middle_point;
5943 current_coord(2) = orig_coord(2) + k * debug_output_info.
dz;
5946 calculateApproximatePotential(tmp_obs);
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());
5959 debug_output_info.out_dir +
"/" + debug_output_info.file_name_E +
5960 std::to_string(file_counter) +
"." + debug_output_info.file_extension;
5963 debug_output_info.out_dir +
"/" + debug_output_info.file_name_R +
5964 std::to_string(file_counter) +
"." + debug_output_info.file_extension;
5967 debug_output_info.out_dir +
"/" + debug_output_info.file_name_G +
5968 std::to_string(file_counter) +
"." + debug_output_info.file_extension;
5970 file_man.
writeXYZFile(full_file_name_R, loc_grid, std::ios::app);
5972 file_man.
writeXYZFile(full_file_name_G, loc_G, std::ios::app);
5978double AtomicDimer::performSurrogateRotation(gpr::Observation& middle_point,
5979 gpr::Observation& approx_obs,
5981 gpr::LBFGSInfo& rot_info)
5983 double curvature = 0.;
5984 if (!use_hssvd_analytic_curvature_) {
5988 surrogate_spectrum_.valid =
false;
5989 index_one_clamped_modes_.clear();
5992 bool hssvd_mode_ready =
false;
5994 gpr::Observation hssvd_approx_obs;
5995 gpr::LBFGSInfo hssvd_rot_info;
5996 double hssvd_ritz_curvature = std::numeric_limits<double>::quiet_NaN();
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);
6009 orient_init, orient, hssvd_mode_selection_policy_,
6010 preserve_initial_alignment_reference_);
6012 const std::pair<gpr::Coord, double> hssvd_mode_estimate =
6013 finite_stencil_rotated
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
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)) /
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
6038 gpr::field::flatDot(hssvd_mode_reference, hssvd_mode)) /
6039 reference_alignment_norm
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);
6054 orient = aligned_hssvd_mode;
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);
6068 approx_obs.
R = middle_point.
R;
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;
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);
6092 calculateApproximatePotential(approx_obs);
6096 calculateApproximatePotential(approx_obs);
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";
6110 log_man <<
"Installed HS-SVD lowest-curvature fallback; no "
6111 "negative reference-connected mode";
6113 log_man <<
" (reference overlap=" << reference_mode_overlap
6114 <<
", continuation overlap=" << seed_mode_overlap
6115 <<
", curvature=" << hssvd_ritz_curvature <<
").\n";
6117 log_man <<
"Installed HS-SVD minimum mode for dimer rotation.\n";
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);
6131 if (!terminate_loop) {
6132 orient = hssvd_orient;
6133 approx_obs = hssvd_approx_obs;
6134 rot_info = hssvd_rot_info;
6136 }
else if (!finite_stencil_rotated) {
6138 inner_iter_rot < max_iter_relax_rot.inner; ++inner_iter_rot) {
6140 log_man <<
" Inner rotational iteration: " << inner_iter_rot
6142 bool terminate_loop =
6143 rotateDimer(stop_citeria_gpr.angle_rotation, orient, rot_info,
6144 middle_point, approx_obs);
6146 if (terminate_loop)
break;
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 =
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;
6170 calculateCurvature(orient, approx_obs, use_hssvd_analytic_curvature_,
6171 cached_hssvd_curvature);
6176double AtomicDimer::performRotationAndTranslationPure(
6181 const double curvature =
6182 performSurrogateRotation(middle_point, approx_obs, orient, rot_info);
6184 if (std::isfinite(curvature))
6185 translateDimer(middle_point, orient, approx_obs, curvature, trans_info,
6191gpr::Coord AtomicDimer::lowestModeFromGradientJacobian(
6194 if (gradient_jacobian.rows() != gradient_jacobian.cols() ||
6195 gradient_jacobian.rows() == 0)
6198 const Eigen::Index dof = gradient_jacobian.cols();
6199 const Eigen::MatrixXd Q = projectedCartesianBasis(R, dof, atoms_config);
6200 if (Q.cols() == 0)
return {};
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 {};
6210 return rowModeFromVector(Q * es.eigenvectors().col(0));
6213std::pair<gpr::Coord, double> AtomicDimer::estimateLowestModeAndCurvatureFromGP(
6215 SurrogateSpectrumRequest request)
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> {
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();
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();
6236 bool have_prepared_hssvd =
6237 gpr_model->prepareMeanHessianVectorHssvd(R, prepared_hssvd);
6238 const auto scoped_hessian =
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,
6247 return scoped_hessian && scoped_hessian(q_cart, hv_cart);
6250 auto projected_seed = [&](
const gpr::Coord* seed) -> Eigen::VectorXd {
6251 if (seed ==
nullptr || seed->rows() != 1 || seed->cols() != dof ||
6253 return Eigen::VectorXd{};
6254 Eigen::VectorXd q = Q.transpose() * seed->transpose();
6255 if (!q.allFinite())
return Eigen::VectorXd{};
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());
6268 auto full_subspace_solve = [&]() -> std::pair<gpr::Coord, double> {
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) {
6278 if (!apply_hssvd_hessian(Q.col(c), hv) || hv.size() != dof ||
6280 return empty_mode();
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();
6293 Eigen::VectorXd evals = es.eigenvalues();
6294 Eigen::MatrixXd evecs = es.eigenvectors();
6298 evals, evecs, q0, hssvd_mode_selection_policy_);
6299 if (!resolve_full_spectrum)
6300 return {rowModeFromVector(Q * evecs.col(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)
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);
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_
6341 gpr::Coord mode = rowModeFromVector(Q * evecs.col(mode_index));
6342 if (mode.size() != dof)
return empty_mode();
6343 return {mode, evals(mode_index)};
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);
6353 return full_subspace_solve();
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);
6361 return full_subspace_solve();
6363 if (sub_dim <= 2)
return full_subspace_solve();
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())
6372 out_sub = Q.transpose() * hv_cart;
6373 return out_sub.allFinite();
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);
6389 mode_angle_budget = std::min(
6390 stop_citeria_gpr.angle_rotation,
6391 2.0 * stop_citeria_gpr.angle_rotation / rotation_iterations);
6393 eigenvector_angle_tol =
6394 std::sin(std::min(mode_angle_budget, right_angle));
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);
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);
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();
6424 rr_options.
max_subspace = std::min(sub_dim, configured_subspace);
6427 eigenvalue_relative_residual_tol;
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};
6439 return full_subspace_solve();
6445 return estimateLowestModeAndCurvatureFromGP(R, seed_orient).first;
6454 const int* atomicNrs;
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)};
6463 mid_point.
E.resize(mid_point.
R.rows(), 1);
6464 mid_point.
G.resize(mid_point.
R.rows(), mid_point.
R.cols());
6470 R = mid_point.
R.data();
6473 F = mid_point.
G.data();
6476 U = mid_point.
E.data();
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) {
6487 moving_species.push_back(
atoms_config.atomicNrs(0, atom));
6489 atomicNrs = moving_species.data();
6498 potential.
force(N, R, atomicNrs, F, U,
nullptr , box);
6503 double step,
int& calls)
6506 if (!(step > 0.0) || !std::isfinite(step))
return false;
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);
6517 const auto counted = [&](
const auto& evaluate) {
6519 const bool ok = evaluate();
6520 calls +=
static_cast<int>(getNumEvaluations() - before);
6525 double measured_curvature = curvature_final;
6526 const auto measure = [&]() {
6530 vibrational_stencil_, center, masses, periodic, anchored);
6531 const Eigen::Index count = directions.cols();
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());
6539 probes.
R.resize(2 * count + (center_held ? 0 : 1), dof);
6540 probes.
R.topRows(2 * count) =
6543 if (!center_held) probes.
R.row(2 * count) = center.transpose();
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;
6551 log_man <<
"Force-stop certificate: stencil failed: " << failure
6555 broadcastObservation(probes);
6556 Eigen::MatrixXd actions(dof, count);
6557 for (Eigen::Index k = 0; k < count; ++k)
6559 (probes.
G.row(2 * k) - probes.
G.row(2 * k + 1)).transpose() /
6561 const Eigen::VectorXd center_gradient =
6562 center_held && count < dof
6563 ? Eigen::VectorXd(middle_point_final.G.row(0).transpose())
6566 : Eigen::VectorXd(probes.
G.row(2 * count).transpose()));
6567 const Eigen::MatrixXd columns =
6569 directions, actions);
6570 if (columns.rows() != dof) {
6571 log_man <<
"Force-stop certificate: Hessian columns cannot be "
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;
6586 log_man <<
"Force-stop certificate: " << latest.
negative
6587 <<
" negative, " << latest.
unresolved <<
" unresolved, "
6588 << latest.
positive <<
" positive modes (resolution "
6591 measured.first_order = latest.
pass;
6592 measured.higher_order = latest.
negative > 1;
6595 const auto move_to = [&](
const Eigen::VectorXd& point) {
6597 moved.
R = point.transpose();
6598 if (!counted([&]() {
return evaluateAccurateProbe(moved, potential); }))
6600 broadcastObservation(moved);
6601 middle_point_final = moved;
6602 middle_point_init = moved;
6611 if (latest.
step.size() != dof)
return -1;
6615 if (outcome.needs_min_mode_escape && latest.
step.size() == dof &&
6616 latest.
step.norm() > 0.0) {
6620 double length = latest.
step.norm();
6621 Eigen::VectorXd direction = latest.
step / length;
6622 for (
int escape = 0; outcome.needs_min_mode_escape &&
6628 measure, [&]() {
return -1; }, plan);
6629 if (latest.
step.size() == dof && latest.
step.norm() > 0.0)
6630 direction = latest.
step / latest.
step.norm();
6633 const bool certified =
6635 forceNormForConvergence(middle_point_final) < stop_citeria_dimer.force;
6636 if (certified) curvature_final = measured_curvature;
6640bool AtomicDimer::requireOracleBudget(Eigen::Index rows)
6643 if (max_oracle_calls_ == 0 || rows <= 0)
return true;
6645 if (used < max_oracle_calls_ &&
6646 static_cast<gpr::Index_t>(rows) <= max_oracle_calls_ - used)
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)");
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_)
6662 const auto before = getNumEvaluations();
6664 bool certified =
false;
6667 certifyStoppedForce(potential, force_stop_certificate_step_, calls);
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";
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";
6687 force_stop_certificate_calls_ =
6688 static_cast<int>(getNumEvaluations() - before);
6689 force_stop_certified_ = certified;
6691 log_man <<
"Force-stop certificate: one negative mode at the "
6692 "returned midpoint ("
6693 << calls <<
" oracle calls).\n";
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";
6705void AtomicDimer::evaluateAccurateEnergyAndForceAtMidPoint(
6714 atoms_config, cell_dimensions, obs, general_potential,
6715 num_of_gen_potential_calls, oracle_batch_chunk_);
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;
6732 const auto start = std::chrono::steady_clock::now();
6735 if (!requireOracleBudget(middle_point.
R.rows()))
6736 throw std::runtime_error(
"the oracle budget is spent");
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: ") +
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 "
6748 archiveObservations(middle_point);
6749 if (profile_phase_timing_) {
6750 accurate_potential_seconds_ +=
6751 std::chrono::duration<double>(std::chrono::steady_clock::now() -
6754 ++accurate_potential_calls_;
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();
6766 recordTrueForceSecant(middle_point,
6767 supplied_measurement
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())
6779 observations_changed |= (all_obs.E.row(row).array() !=
6780 middle_point.
E.row(0).array())
6782 (all_obs.G.row(row).array() !=
6783 middle_point.
G.row(0).array())
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;
6791 if (!retained_seed) {
6792 all_obs.append(middle_point);
6793 observations_changed =
true;
6797 if (observations_changed) {
6798 if (gpr_model->activePosteriorRefitsEnabled())
6799 refit_oracle_batch_.append(middle_point);
6800 markObservedDataChanged();
6804void AtomicDimer::recordImspeQueryHistory(
const gpr::Coord& R_query)
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;
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_;
6820bool AtomicDimer::computeImspeAdmissionScore(
const gpr::Coord& R_query,
6822 double& relative_gain,
6823 const bool allow_hssvd_local)
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)
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)));
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;
6846 rows.push_back(std::move(row));
6849 for (
int i = 0; i < imspe_query_history_count_; ++i) {
6851 hist.row(0) = imspe_query_history_.row(i);
6854 push_row(middle_point_init.R);
6858 estimateLowestModeAndCurvatureFromGP(R_query,
nullptr,
6859 SurrogateSpectrumRequest::Spectrum)
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;
6868 if (rows.empty())
return false;
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>();
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;
6883 reduction = gpr_model->calculateObservationForceVarianceReduction(
6884 chain_pos, query_idx, target_queries, sigma_n2, allow_hssvd_local);
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);
6894bool AtomicDimer::maybeSoftSkipViaImspe(
const gpr::Coord& R_query)
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;
6902 double relative_gain = 0.0;
6904 computeImspeAdmissionScore(R_query, score, relative_gain,
true);
6905 recordImspeQueryHistory(R_query);
6907 if (scored && score < variance_gate_.imspe_soft_threshold) {
6908 ++imspe_soft_skipped_calls_;
6914double AtomicDimer::effectiveEmdDedupThreshold()
const
6919 double threshold = emd_dedup_threshold_;
6920 if (gpr_model ==
nullptr)
return threshold;
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;
6944 if (!gpr_model->getHssvdBackend()) {
6945 if (d_min > 0.0) threshold = std::max(threshold, d_min);
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);
6965 if (d_min > 0.0) eff = std::max(eff, d_min);
6969double AtomicDimer::initialRotationStopCriterion()
const
6971 const double criterion = stop_citeria_dimer.angle_rotation;
6972 return (criterion > 0.0 && std::isfinite(criterion)) ? criterion : 0.0;
6975bool AtomicDimer::shouldSkipOracleByImspeAdmission(
const gpr::Coord& R_query)
6977 if (gpr_model ==
nullptr || R_query.rows() != 1 || all_obs.R.rows() == 0)
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))
6990 double relative_gain = 0.0;
6991 if (!computeImspeAdmissionScore(R_query, score, relative_gain,
true))
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)
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";
7018bool AtomicDimer::shouldSkipMidpointOracleByEmdNear(
const gpr::Observation& obs)
7021 if (R_query.rows() != 1 || all_obs.R.rows() == 0)
return false;
7025 distance.
dist_emd(R_query, all_obs.R, atoms_config, dist);
7026 if (dist.size() == 0)
return false;
7028 const double min_emd = dist.minCoeff();
7029 if (!std::isfinite(min_emd) || min_emd >= effectiveEmdDedupThreshold())
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";
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";
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";
7066 DimerOracleProbeRole role)
7086 if (gpr_model ==
nullptr || gpr_model->failedOptim())
return false;
7087 const auto suppress_call = [&]() {
7088 if (training_policy_ ==
nullptr ||
7089 !policySuppressesAccurateCall(obs, role))
7091 calculateApproximatePotential(obs);
7092 ++variance_skipped_accurate_calls_;
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_;
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);
7113 double tau = variance_gate_.accept_tau;
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;
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;
7128 tau = tau_rel * magn_sigma2;
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;
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;
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;
7164 if (var_max >= tau) {
7174 if (allow_imspe_soft_skip && maybeSoftSkipViaImspe(obs.
R)) {
7175 calculateApproximatePotential(obs);
7178 if (suppress_call())
return true;
7184 calculateApproximatePotential(obs);
7185 ++variance_skipped_accurate_calls_;
7189bool AtomicDimer::appendObservationIfInformative(
const gpr::Observation& obs)
7191 if (training_policy_ !=
nullptr && !policy_admission_passthrough_ &&
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)
7200 if (row < obs.
G.rows()) point.
gradient = obs.
G.row(row).transpose();
7201 candidates.push_back(std::move(point));
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;
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);
7226 if (
out == 0)
return false;
7228 kept.
R.conservativeResize(
out, kept.
R.cols());
7229 kept.
E.conservativeResize(
out, kept.
E.cols());
7230 kept.
G.conservativeResize(
out, kept.
G.cols());
7232 struct Passthrough {
7234 explicit Passthrough(
bool& flag) : flag(flag)
7242 } passthrough(policy_admission_passthrough_);
7243 return appendObservationIfInformative(kept);
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;
7263 distance.
dist_emd(obs.
R, all_obs.R, atoms_config, dist);
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;
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 "
7304 << min_emd <<
" < " << effectiveEmdDedupThreshold()
7305 <<
", force residual " << residual_norm <<
" > "
7306 << stop_citeria_dimer.force <<
").\n";
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;
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";
7343 const bool imspe_informative =
7344 !exact_degenerate &&
7345 computeImspeAdmissionScore(obs.
R, score, relative_gain,
true) &&
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;
7365 const double magn_for_gain =
7366 (gpr_model !=
nullptr)
7367 ? gpr_model->getSexpAtCovarianceFunction().getMagnSigma2()
7369 const double rel_gain_floor =
7370 (magn_for_gain > 0.0 && std::isfinite(magn_for_gain))
7371 ? sigma_n2 / magn_for_gain
7373 const bool exact_informative =
7374 imspe_informative &&
7375 (!needs_exact_confirmation ||
7376 computeImspeAdmissionScore(obs.
R, exact_score, exact_relative_gain,
7378 exact_score > sigma_n2 && std::isfinite(exact_relative_gain) &&
7379 exact_relative_gain > rel_gain_floor;
7381 if (!exact_informative) {
7390 if (coalesceObservationIntoNearestEmdRepresentative(obs)) {
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";
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";
7417bool AtomicDimer::coalesceObservationIntoNearestEmdRepresentative(
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())
7428 distance.
dist_emd(obs.
R, all_obs.R, atoms_config, dist);
7429 if (dist.size() == 0)
return false;
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))
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;
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);
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";
7462void AtomicDimer::appendConvergenceCertificateObservation(
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";
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";
7486 last_nonterminal_certificate_r_.resize(0);
7488 bool exact_duplicate =
false;
7489 if (all_obs.R.rows() > 0) {
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);
7499 if (exact_duplicate) {
7500 log_man <<
"Final convergence certificate: true midpoint witness "
7501 "already present in training set.\n";
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 "
7513bool AtomicDimer::evaluateAccurateEnergyAndForce(
7515 bool apply_emd_dedup)
7517 return evaluateAccurateObservation(obs, general_potential, apply_emd_dedup)
7526 measured.R = positions;
7528 broadcastDenseMatrix(measured.R);
7529 const Eigen::Index atoms =
atoms_config.is_frozen.size();
7530 bool valid = measured.R.rows() > 0 && atoms > 0 &&
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);
7542 valid ? std::string{}
7543 :
"curvature probe batch has invalid coordinates or exceeds "
7544 "the remaining oracle budget",
7547 std::string failure;
7548 if (!acquireAccurateProbe(measured, potential, 1, failure)) {
7549 log_man <<
"Curvature probe batch failed: " << failure <<
"\n";
7552 raw = std::move(measured);
7553 broadcastObservation(raw);
7557bool AtomicDimer::evaluateAccurateProbe(
7560 return evaluateAccurateProbe(obs, general_potential,
nullptr);
7563bool AtomicDimer::evaluateAccurateProbe(
7568 std::string failure;
7569 if (!acquireAccurateProbe(obs, general_potential, oracle_batch_chunk_,
7571 recordOracleTrialFailure(
"probe: " + failure);
7574 consecutive_oracle_failures_ = 0;
7575 if (raw_observation !=
nullptr) *raw_observation = obs;
7578 recordTrueForceSecant(obs);
7579 return obs.
E.allFinite() && obs.
G.allFinite();
7584 Eigen::Index batch_chunk,
7585 std::string& failure)
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";
7595 const auto start = std::chrono::steady_clock::now();
7596 const auto calls_before = num_of_gen_potential_calls;
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();
7608 if (!obs.
E.allFinite() || !obs.
G.allFinite()) {
7609 failure =
"non-finite energy or force";
7612 archiveObservations(obs);
7613 if (profile_phase_timing_) {
7614 accurate_potential_seconds_ +=
7615 std::chrono::duration<double>(std::chrono::steady_clock::now() -
7618 accurate_potential_calls_ += num_of_gen_potential_calls - calls_before;
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;
7633AtomicDimer::AccurateObservationResult AtomicDimer::evaluateAccurateObservation(
7635 bool apply_emd_dedup)
7644 atoms_config, cell_dimensions, o, general_potential,
7645 num_of_gen_potential_calls, oracle_batch_chunk_);
7648 const auto start = std::chrono::steady_clock::now();
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};
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};
7666 }
catch (
const std::exception& error) {
7667 return rejectTrial(error.what());
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() -
7678 ++accurate_potential_calls_;
7681 recordTrueForceSecant(obs);
7682 if (!apply_emd_dedup) {
7684 retainStructuralObservation(obs);
7685 return {
true,
true};
7687 if (gpr_model->activePosteriorRefitsEnabled())
7688 refit_oracle_batch_.append(obs);
7693 return {
true, appendObservationIfInformative(obs)};
7696bool AtomicDimer::image1CarriesOracleGradient()
const
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())
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)
7710 if ((all_obs.G.row(row) - image1.G.row(0)).squaredNorm() == 0.0)
7725 const double stop_citeria_gpr_init = initialRotationStopCriterion();
7727 for (outer_iter = 0; outer_iter < max_iter_init_rot.outer; ++outer_iter) {
7729 log_man <<
"Outer rotational iteration: " << outer_iter <<
"\n";
7733 if (image1CarriesOracleGradient() &&
7734 isRotationalConvergenceReached(orient, middle_point)) {
7735 log_man <<
"Rotated the initial dimer in " << outer_iter + 1
7737 " iterations (total number of image evaluations: "
7738 << getNumEvaluations() <<
").\n";
7742 if (!use_gpr_initial_rotations_) {
7748 double proposed_curvature = 0.0;
7750 evaluateAccurateEnergyAndForce(candidate, potential,
7752 return candidate.
G.allFinite() && candidate.
E.allFinite();
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,
7760 throw std::runtime_error(
7761 "accurate initial dimer rotation failed");
7763 orient = proposed_orientation;
7764 updateLocation(orient, middle_point.
R, image1.R);
7767 evaluateAccurateEnergyAndForce(image1, potential,
7769 gradients = middle_point.
G;
7771 latest_mode_curvature_ =
7772 rotation.calculateCurvature(gradients, orient);
7774 measured_pair.
append(image1);
7775 writeTraceFrame(measured_pair,
"initial_rotations",
7776 static_cast<size_t>(outer_iter));
7780 if (curvature_requires_full_refit_ ||
7781 !hasOptimizedCurrentObservedData()) {
7785 (!uses_external_gp_ && !preserve_seed_kernel_ &&
7786 !gpr_model->hasBeenOptimized()) ||
7787 atoms_config.
n_pt != gpr_model->getSexpAtCovarianceFunction()
7788 .getLengthScaleRef()
7790 refitGPRModel(reseed, middle_point, orient);
7791 }
else if (profile_phase_timing_) {
7792 log_man <<
"GP optimize skipped: observation data unchanged.\n";
7795 orient_old = orient;
7796 orient = orient_init;
7798 approx_obs.
R = middle_point.
R;
7799 updateLocation(orient, middle_point.
R, temp);
7801 calculateApproximatePotential(approx_obs);
7802 writeTraceFrame(approx_obs,
"initial_rotations",
7803 static_cast<size_t>(outer_iter));
7810 for (inner_iter = 0; inner_iter < max_iter_init_rot.inner;
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;
7819 checkIfMaxIterReachedAndPrintWarning(
7820 inner_iter, max_iter_init_rot.inner,
"dimer rotation");
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 "
7828 << stop_citeria_gpr_init
7829 <<
"), but not on the true PES (stop criteria = "
7830 << stop_citeria_dimer.angle_rotation <<
").\n";
7833 if (outer_iter > 0) {
7834 if (checkRotationalConvergence(
7836 stop_citeria_dimer.angle_rotation)) {
7837 log_man <<
"Rotated the initial dimer in " << outer_iter + 1
7838 <<
" outer iterations (total number of image "
7840 << getNumEvaluations() <<
".\n";
7844 updateLocation(orient, middle_point.
R, image1.R);
7845 if (!maybeSkipAccurateViaVariance(
7846 image1, DimerOracleProbeRole::StructuralImage1)) {
7848 evaluateAccurateEnergyAndForce(image1, potential,
7853 checkIfMaxIterReachedAndPrintWarning(outer_iter, max_iter_init_rot.outer,
7854 "initial rotations");
7857void AtomicDimer::recordContactReferences(
const gpr::Observation& middle_point)
7859 seed_min_interatomic_ = std::numeric_limits<double>::quiet_NaN();
7860 if (middle_point.
R.cols() > 0) {
7864 if (dist.size() > 0) seed_min_interatomic_ = dist.minCoeff();
7869 if (middle_point.
R.rows() > 0)
7870 contact_reference_geometries_ = middle_point.
R.topRows(1);
7872 contact_reference_geometries_.resize(0, 0);
7875std::pair<double, gpr::Coord> AtomicDimer::performGPRIterations(
7886 double stop_dimer_gp = 0.;
7890 double curvature = 0.;
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);
7906 double progress_reference_force = best_oracle_force;
7909 best_oracle_midpoint = middle_point;
7911 measured_trial_trust_.reset();
7912 measured_trial_anchor_.resize(0, 0);
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;
7925 bool certified_index_complete =
false;
7926 const auto resolve_terminal_index =
7928 if (external_terminal_certificate_ && !higher_order_restart_ &&
7929 complete_stencil_follows)
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();
7942 if ((preliminary || certified_index_complete) &&
7943 identical(certified_index_midpoint.
R, middle_point.
R) &&
7944 identical(certified_index_midpoint.
G, middle_point.
G))
7947 if (!resolveAdditionalNegativeMode(middle_point, orient, potential,
7948 recovery, &measured_mode,
7951 certified_index_midpoint = middle_point;
7952 certified_index_complete = !preliminary;
7955 const bool mode_ready =
7956 preliminary ? terminalModeIsReady() : measuredModeIsCertified();
7957 if (!mode_ready && measured_mode.size() == orient.size() &&
7958 measured_mode.allFinite()) {
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;
7975 orient = measured_mode;
7976 updateLocation(orient, middle_point.
R, image1.R);
7977 evaluateAccurateEnergyAndForce(image1, potential,
7979 broadcastObservation(image1);
7980 synchronizeObservedData();
7981 recordMeasuredModeCertificate(middle_point, orient, image1);
7985 const auto retain_measured_recovery =
7987 refit_oracle_midpoint = recovery;
7988 accepted_oracle_midpoint = recovery;
7991 measured_index_zero_hessian_.resize(0, 0);
7992 measured_index_zero_midpoint_.resize(0, 0);
7994 best_oracle_force = forceNormForConvergence(recovery);
7995 progress_reference_force = best_oracle_force;
7996 best_oracle_midpoint = recovery;
7997 best_oracle_orientation = orient;
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);
8007 measured_rotation_basis_.resize(0, 0);
8009 for (outer_iter = 0;
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;
8024 totalIterations = outer_iter + 1;
8026 <<
"Outer relaxation iteration: " << outer_iter
8027 <<
" (oracle_calls=" << getNumEvaluations() <<
")"
8041 <<
" pt_pair_contract="
8050 <<
" pt_anchor_asm="
8052 <<
" pt_anchor_factor="
8063 <<
" gp_mean_total=" << gp_predict_mean_seconds_
8064 <<
" gp_variance_total=" << gp_predict_variance_seconds_
8065 <<
" gp_mode_total=" << gp_mode_seconds_
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_)
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",
8115 if (measured_rotation_pending) {
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;
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";
8138 const bool can_expand =
8140 measured_rotation_basis_, measured_rotation_physical_,
8141 (image1.G.row(0) - middle_point.
G.row(0)).transpose() /
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_);
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);
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;
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 "
8184 <<
"); resolving the index with the measured mode.\n";
8187 if (certified && isFinalConvergenceReached(
8188 middle_point, stop_citeria_dimer.force)) {
8189 retainStructuralObservation(image1);
8190 synchronizeObservedData();
8192 if (resolve_terminal_index(recovery)) {
8193 curvature = latest_mode_curvature_;
8194 if (!terminalModeIsReady()) {
8197 R_latest_conv = middle_point.
R;
8198 orient_latest_conv = orient;
8199 final_converged_ =
true;
8200 relaxation_termination_reason_ =
8201 DimerRelaxationTerminationReason::ForceConverged;
8206 retain_measured_recovery(recovery);
8208 measured_rotation_pending =
false;
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;
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";
8238 retainStructuralObservation(image1);
8239 synchronizeObservedData();
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()
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";
8261 stop_dimer_gp = surrogateForceTolerance(middle_point);
8263 middle_point.
R = middle_point_init.R;
8264 orient = orient_init_gpr;
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;
8273 defineStartPath(R_latest_conv, orient_latest_conv, orient_init_gpr,
8274 outer_iter, R_previous, orient_previous,
8275 middle_point, orient);
8278 resolveFlatResidualDirection(middle_point, orient, potential);
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 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;
8309 predicted_endpoint.
R = middle_point.
R;
8310 calculateApproximatePotential(predicted_endpoint);
8312 if (!path_leashed_recovery) {
8314 predicted_reference.
R = accepted_oracle_midpoint.
R;
8315 calculateApproximatePotential(predicted_reference);
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) {
8328 const auto evaluation =
8329 evaluateAccurateObservation(trial, potential);
8330 midpoint_appended = evaluation.appended;
8331 if (evaluation.measured) {
8332 middle_point = std::move(trial);
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;
8348 midpoint_appended = broadcastBool(midpoint_appended);
8349 broadcastObservation(middle_point);
8350 synchronizeObservedData();
8352 bool rotation_uninformative =
8353 alignment_abort_tol_ > 0.0 &&
8354 !isRotationCurvatureInformative(curvature);
8355 const bool degenerate_midpoint_probe =
8356 shouldProbeImage1ForDegenerateMidpoint();
8358 bool final_force_converged =
8359 isFinalConvergenceReached(middle_point, stop_citeria_dimer.force);
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);
8375 final_force_converged = broadcastBool(final_force_converged);
8376 broadcastObservation(middle_point);
8377 synchronizeObservedData();
8382 if (midpoint_oracle_certified) {
8383 recordPredictedMeasuredAgreement(predicted_endpoint, middle_point);
8384 refit_oracle_midpoint = middle_point;
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 "
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;
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) {
8411 const double dmin = dist.size() > 0
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, "
8423 relaxation_termination_reason_ =
8424 DimerRelaxationTerminationReason::InteratomicCollapse;
8428 const bool measured_descent_certified =
8429 midpoint_oracle_certified && std::isfinite(trial_oracle_force) &&
8430 trial_oracle_force < best_oracle_force;
8432 double phase_reference_alignment =
8433 std::numeric_limits<double>::quiet_NaN();
8434 if (orient.cols() > 0 && orient.cols() == alignment_reference.cols()) {
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;
8448 DimerPhaseRecord rec;
8449 rec.position = middle_point.
R;
8450 rec.gradient = middle_point.
G;
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);
8460 if (energy_ceiling_rejected) {
8466 if (want_second_negative_mode_ &&
8467 !resolve_terminal_index(recovery,
false) &&
8469 retain_measured_recovery(recovery);
8472 log_man <<
"Measured-energy ceiling: stationary candidate "
8473 "requires path recovery.\n";
8474 relaxation_termination_reason_ =
8475 DimerRelaxationTerminationReason::MeasuredNonDescent;
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 "
8491 middle_point = best_oracle_midpoint;
8492 orient = best_oracle_orientation;
8493 relaxation_termination_reason_ =
8494 DimerRelaxationTerminationReason::MeasuredNonDescent;
8497 if (measured_descent_certified) {
8498 best_oracle_force = trial_oracle_force;
8499 best_oracle_midpoint = middle_point;
8500 best_oracle_orientation = orient;
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()) {
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;
8526 middle_point.
G - accepted_oracle_midpoint.
G;
8528 forceNormForConvergence(middle_point.
R.row(0), error);
8529 measured_change = forceNormForConvergence(middle_point.
R.row(0),
8532 const double reference_force =
8533 forceNormForConvergence(accepted_oracle_midpoint);
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";
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_)
8552 last_trial_force_variance_ =
8553 std::numeric_limits<double>::quiet_NaN();
8554 if (!final_force_converged && trial_moved &&
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;
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_) {
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);
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;
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);
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) {
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();
8645 gpr_model->calculateObservationPosteriorCovariance(
8646 queries, covariance,
false);
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";
8660 const double variance_seconds =
8661 std::chrono::duration<double>(
8662 std::chrono::steady_clock::now() -
8665 gp_predict_seconds_ += variance_seconds;
8666 gp_predict_variance_seconds_ += variance_seconds;
8667 ++gp_predict_calls_;
8668 ++gp_predict_variance_calls_;
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();
8693 transition_param.max_step_length, length_scale,
8694 change_error_norm, change_force_scale, energy_error,
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(
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()
8720 accepted_oracle_midpoint = middle_point;
8727 const bool surrogate_did_not_move =
8728 R_phase_start.size() == middle_point.
R.size() &&
8730 const bool probe_coalesced = consecutive_degenerate_probes_ > 0;
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)) {
8740 resetTranslationHistory(step_info);
8744 translateDimer(middle_point, orient, middle_point, curvature,
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;
8753 if (R_step.size() == middle_point.
R.size() && R_step.allFinite() &&
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 "
8762 << curvature <<
", displacement "
8763 << (R_step - middle_point.
R).norm() <<
").\n";
8768 evaluateAccurateEnergyAndForce(rescue, potential,
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);
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;
8788 bool final_image1_measured =
false;
8789 if (final_force_converged) {
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";
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";
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);
8837 broadcastObservation(image1);
8838 synchronizeObservedData();
8840 if (rotation_uninformative) {
8841 ++consecutive_uninformative_rotations_;
8843 consecutive_uninformative_rotations_ = 0;
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 "
8863 <<
" relaxation phases; the surrogate cannot move the "
8864 "dimer here. Not converged.\n";
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 "
8874 <<
" phases; aborting burst, handing back to NEB.\n";
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 "
8895 <<
" phases; aborting burst, handing back to NEB.\n";
8902 if (alignment_abort_tol_ > 0.0 &&
8903 std::isfinite(phase_reference_alignment)) {
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
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";
8933 totalIterations = outer_iter + 1;
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 "
8947 return {curvature, orient};
8952 struct RequireImprovingFallback {
8958 if (model ==
nullptr)
return;
8962 ~RequireImprovingFallback()
8964 if (model !=
nullptr)
8967 RequireImprovingFallback(
const RequireImprovingFallback&) =
delete;
8968 RequireImprovingFallback& operator=(
const RequireImprovingFallback&) =
8970 } require_improving_fallback(gpr_model);
8977 std::chrono::duration<double> elp_time;
8978 auto start = std::chrono::steady_clock::now();
8979 std::pair<double, gpr::Coord> eigen_data;
8981 if (!isAtomsConfigurationCorrect()) {
8982 final_converged_ =
false;
8983 relaxation_termination_reason_ =
8986 <<
"Error! The structure of atoms configuration is incorrect!\n";
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);
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;
9018 middle_point.
R = middle_point_init.R;
9019 orient = orient_init;
9021 force_stop_certified_ =
false;
9022 force_stop_certificate_calls_ = 0;
9024 budget_stop_orientation_.resize(0, 0);
9025 struct BudgetUnwinds {
9027 explicit BudgetUnwinds(
bool& f) : flag(f)
9035 } budget_unwinds(oracle_budget_unwinds_);
9038 evaluateAccurateEnergyAndForceAtMidPoint(middle_point,
9043 const bool force_converged_at_start =
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 "
9053 eigen_data.first = latest_mode_curvature_;
9054 eigen_data.second = orient;
9056 if (max_iter_init_rot.outer > 0) {
9058 updateLocation(orient, middle_point.
R, image1.R);
9061 evaluateAccurateEnergyAndForce(image1, general_potential,
9065 performInitialRotations(middle_point, orient,
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);
9074 evaluateAccurateEnergyAndForce(image1, general_potential,
9076 log_man <<
"Evaluated image 1 of the dimer for the initial GP "
9081 performGPRIterations(middle_point, orient, general_potential);
9087 if (budget_stop_midpoint_.R.size() > 0) {
9088 middle_point = budget_stop_midpoint_;
9089 orient = budget_stop_orientation_;
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());
9103 gpr::Coord::Constant(1, middle_point.
R.cols(),
9104 std::numeric_limits<double>::quiet_NaN());
9109 if (budget_stop_midpoint_.R.size() > 0) {
9110 middle_point = budget_stop_midpoint_;
9111 orient = budget_stop_orientation_;
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()) {
9123 middle_point.
E = gpr::FieldMatrixd::Constant(
9124 1, 1, std::numeric_limits<double>::quiet_NaN());
9126 gpr::Coord::Constant(1, middle_point.
R.cols(),
9127 std::numeric_limits<double>::quiet_NaN());
9131 assignFinalResults(middle_point, eigen_data);
9132 certifyExecuteForceStop(general_potential);
9136 log_man <<
"Call statistics:\n";
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;
9151 log_man << summary.str();
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';
9164 if (budget_stop_midpoint_.R.size() > 0) {
9165 middle_point_final = budget_stop_midpoint_;
9166 orient_final = budget_stop_orientation_;
9168 final_converged_ =
false;
9169 relaxation_termination_reason_ =