Loading...
Searching...
No Matches
SaddlePolish.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4#include "SaddlePolish.h"
5
6#include <Eigen/Eigenvalues>
7#include <Eigen/Geometry>
8#include <Eigen/QR>
9#include <algorithm>
10#include <cmath>
11#include <cstdlib>
12#include <iostream>
13#include <limits>
14#include <vector>
15
21#include "NEBPath.h"
22
23namespace gpr {
24namespace neb {
25
26namespace {
27
29Eigen::VectorXd surrogateGradient(ActiveLearningSession& session,
30 const Eigen::VectorXd& x)
31{
32 gpr::Observation probe;
33 probe.R.resize(1, x.size());
34 probe.R.row(0) = x.transpose();
35 session.gp.calculatePotentialDispatched(probe);
36 if (probe.G.rows() < 1 || probe.G.cols() != x.size()) {
37 return Eigen::VectorXd();
38 }
39 return probe.G.row(0).transpose();
40}
41
45Eigen::MatrixXd surrogateHessian(ActiveLearningSession& session,
46 const Eigen::VectorXd& x)
47{
48 Eigen::MatrixXd H;
49 if (!session.gp.calculateMeanHessian(x.transpose(), H)) return {};
50 return 0.5 * (H + H.transpose());
51}
52
56Eigen::VectorXd newtonSaddleStep(const Eigen::MatrixXd& H,
57 const Eigen::VectorXd& g,
58 const Eigen::VectorXd& x,
59 const AtomsConfiguration& configuration,
60 double* quadratic_correction)
61{
62 const Eigen::MatrixXd Q = detail::saddlePolishBasis(x, configuration);
63 if (H.rows() != x.size() || H.cols() != x.size() || g.size() != x.size() ||
64 Q.rows() != x.size() || Q.cols() == 0) {
65 if (quadratic_correction != nullptr) *quadratic_correction = 0.0;
66 return Eigen::VectorXd::Zero(g.size());
67 }
68 const Eigen::MatrixXd Hq = Q.transpose() * H * Q;
69 const Eigen::VectorXd gq = Q.transpose() * g;
70 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(0.5 *
71 (Hq + Hq.transpose()));
72 const Eigen::VectorXd lambda = es.eigenvalues();
73 const Eigen::MatrixXd V = es.eigenvectors();
74 if (lambda.size() == 0 || !lambda.allFinite() || !gq.allFinite() ||
75 es.info() != Eigen::Success) {
76 if (quadratic_correction != nullptr) *quadratic_correction = 0.0;
77 return Eigen::VectorXd::Zero(g.size());
78 }
79 const double lambda_max = lambda.cwiseAbs().maxCoeff();
80 const double cutoff = std::numeric_limits<double>::epsilon() *
81 static_cast<double>(H.rows()) * lambda_max;
82 Eigen::VectorXd step_q = Eigen::VectorXd::Zero(Q.cols());
83 double correction = 0.0;
84 for (Eigen::Index i = 0; i < lambda.size(); ++i) {
85 if (std::abs(lambda(i)) <= cutoff) continue;
86 const double c = V.col(i).dot(gq);
87 step_q -= (c / lambda(i)) * V.col(i);
88 correction -= 0.5 * c * c / lambda(i);
89 }
90 if (quadratic_correction) *quadratic_correction = correction;
91 return Q * step_q;
92}
93
94} // namespace
95
96Eigen::MatrixXd detail::saddlePolishBasis(
97 const Eigen::VectorXd& positions,
98 const gpr::AtomsConfiguration& configuration)
99{
100 const Eigen::Index dimension = positions.size();
101 if (dimension == 0 || dimension % 3 != 0)
102 return Eigen::MatrixXd(dimension, 0);
103 const Eigen::Index atoms = dimension / 3;
104 if (configuration.is_frozen.size() == 0 &&
105 configuration.positions.size() == 0 &&
106 configuration.atoms_froz_active.positions.size() == 0 &&
107 configuration.atoms_froz_inactive.positions.size() == 0 &&
108 !gpr::geometry::cellIsMicLattice(configuration.cell)) {
109 return Eigen::MatrixXd::Identity(dimension, dimension);
110 }
111 if (configuration.positions.size() != 0 &&
112 configuration.positions.cols() != dimension)
113 throw std::invalid_argument(
114 "saddle polish position/configuration dimensions differ");
115 if (configuration.is_frozen.size() != atoms)
116 throw std::invalid_argument(
117 "saddle polish requires one mobility flag per atom");
118
119 bool all_free = true;
120 Eigen::Index free_atoms = 0;
121 for (Eigen::Index atom = 0; atom < atoms; ++atom) {
122 if (configuration.is_frozen(atom) == MOVING_ATOM) {
123 ++free_atoms;
124 } else {
125 all_free = false;
126 }
127 }
128 if (all_free) {
129 gpr::Coord geometry(1, dimension);
130 geometry.row(0) = positions.transpose();
132 geometry, configuration, true,
134 }
135
136 Eigen::MatrixXd basis = Eigen::MatrixXd::Zero(dimension, 3 * free_atoms);
137 Eigen::Index column = 0;
138 for (Eigen::Index atom = 0; atom < atoms; ++atom) {
139 if (configuration.is_frozen(atom) != MOVING_ATOM) continue;
140 for (Eigen::Index axis = 0; axis < 3; ++axis)
141 basis(3 * atom + axis, column++) = 1.0;
142 }
143 return basis;
144}
145
146double detail::saddlePolishForceMagnitude(
147 const Eigen::VectorXd& positions, const Eigen::VectorXd& gradient,
148 const gpr::AtomsConfiguration& configuration)
149{
150 if (positions.size() != gradient.size())
151 return std::numeric_limits<double>::infinity();
152 const Eigen::MatrixXd basis =
153 detail::saddlePolishBasis(positions, configuration);
154 if (basis.rows() != gradient.size())
155 return std::numeric_limits<double>::infinity();
156 if (basis.cols() == 0) return 0.0;
157 const Eigen::VectorXd projected = basis * (basis.transpose() * gradient);
158 return saddleForceMagnitude(projected);
159}
160
161namespace {
162double surrogateEnergy(ActiveLearningSession& session, const Eigen::VectorXd& x)
163{
164 gpr::Observation probe;
165 probe.R.resize(1, x.size());
166 probe.R.row(0) = x.transpose();
167 session.gp.calculatePotentialDispatched(probe);
168 return (probe.E.size() > 0) ? probe.E(0, 0)
169 : std::numeric_limits<double>::quiet_NaN();
170}
171double surrogateEnergyVariance(ActiveLearningSession& session,
172 const Eigen::VectorXd& x)
173{
174 gpr::Observation probe;
175 probe.R.resize(1, x.size());
176 probe.R.row(0) = x.transpose();
177 probe.E.resize(1, 1);
178 probe.G.resize(1, x.size());
179 session.gp.calculateVarianceDispatched(probe);
180 return (probe.E.size() > 0) ? probe.E(0, 0)
181 : std::numeric_limits<double>::quiet_NaN();
182}
183
184Eigen::VectorXd surrogateEnergyVarianceGradient(ActiveLearningSession& session,
185 const Eigen::VectorXd& x)
186{
187 gpr::EigenMatrix covariance;
188 session.gp.calculateObservationPosteriorCovariance(x.transpose(),
189 covariance);
190 if (covariance.rows() != x.size() + 1 ||
191 covariance.cols() != x.size() + 1 || !covariance.allFinite())
192 return {};
193 // Differentiating both arguments on the covariance diagonal gives
194 // grad Var[E(x)] = 2 Cov[E(x), grad E(x)].
195 return 2.0 * covariance.row(0).tail(x.size()).transpose();
196}
197} // namespace
198
200 const NEBPath& path,
201 double force_tol)
202{
203 // The chord midpoint of two images on a curved path cuts the corner of
204 // the valley and climbs its wall, so its surrogate energy exceeds both
205 // images with no ridge between them (04_ch3o: four refinement passes
206 // and 72 oracle rows spent on such corner cuts). The question is whether
207 // the surrogate minimum-energy path between the images rises above the
208 // climbing image, so the midpoint is relaxed on the surrogate in the
209 // hyperplane perpendicular to the chord, descent with an Armijo
210 // backtracking line search and no oracle call, until the in-plane force
211 // is below the band tolerance. A ridge the band straddles keeps that
212 // valley-floor point above the climbing image; a corner cut drops it to
213 // the floor. The point may not wander further than one chord length
214 // from the midpoint, beyond which it no longer describes this segment,
215 // and a trial point is taken only where the surrogate is trusted: its
216 // posterior energy variance no larger than the model noise floor (the
217 // acquisition floor of the search) or than the variance at the chord
218 // midpoint it started from, so the descent never moves into territory
219 // the model knows less well than its starting point. Descent on an
220 // untrusted surrogate finds its holes (a synthetic valley fit dropped
221 // 250 eV within 0.1 A of the training grid). The descent stops as soon
222 // as the point is no higher than the climbing image: the question is
223 // answered there.
225 const int n = path.numImages();
226 const int ci = detail::climbingStopImage(path);
227 if (n < 3 || ci <= 0 || ci >= n - 1) return out;
228 const double e_ci = path.image(ci).energy;
229 if (!std::isfinite(e_ci)) return out;
230 const double tol =
231 (std::isfinite(force_tol) && force_tol > 0.0) ? force_tol : 0.0;
232 constexpr int kMaxRelaxSteps = 200;
233 constexpr int kMaxBacktracks = 24;
234 constexpr double kArmijo = 1e-4;
235 constexpr double kEnergyConfidence = 2.0;
236 const double variance_floor = std::max(0.0, session.gp.getSigma2());
237 out.evaluated = true;
238 out.holds = true;
239 out.excess = -std::numeric_limits<double>::infinity();
240 double worst_upper_excess = -std::numeric_limits<double>::infinity();
241 const double nan = std::numeric_limits<double>::quiet_NaN();
242 out.segment_excess.assign(static_cast<std::size_t>(n - 1), nan);
243 out.segment_raw_excess.assign(static_cast<std::size_t>(n - 1), nan);
244 out.segment_variance.assign(static_cast<std::size_t>(n - 1), nan);
245 out.segment_position.assign(static_cast<std::size_t>(n - 1),
246 Eigen::VectorXd());
247 for (int i = 0; i + 1 < n; ++i) {
248 const Eigen::VectorXd& a = path.image(i).positions;
249 const Eigen::VectorXd& b = path.image(i + 1).positions;
250 if (a.size() != b.size() || a.size() == 0) continue;
251 Eigen::VectorXd tau = b - a;
252 const double chord = tau.norm();
253 if (!(chord > 0.0) || !std::isfinite(chord)) continue;
254 tau /= chord;
255 const Eigen::VectorXd mid = 0.5 * (a + b);
256 Eigen::VectorXd x = mid;
257 double e = surrogateEnergy(session, x);
258 if (!std::isfinite(e)) continue;
259 const double e_raw = e;
260 const double v_mid = surrogateEnergyVariance(session, mid);
261 const double trust_cap = std::isfinite(v_mid)
262 ? std::max(variance_floor, v_mid)
263 : variance_floor;
264 double step = 0.5 * chord;
265 const auto descend_from_observed_rows = [&]() {
266 // A short-range posterior can be flat between its observations.
267 // Project nearby observed geometries into the segment plane to
268 // propose a descent where the local mean gradient is uninformative.
269 const auto& rows = session.training_obs.R;
270 if (rows.cols() != x.size()) return false;
271 std::vector<std::pair<double, Eigen::Index>> candidates;
272 const auto projected = [&](Eigen::Index row) -> Eigen::VectorXd {
273 const Eigen::VectorXd offset = rows.row(row).transpose() - mid;
274 return mid + offset - tau.dot(offset) * tau;
275 };
276 for (Eigen::Index row = 0; row < rows.rows(); ++row) {
277 const Eigen::VectorXd trial = projected(row);
278 if (trial.allFinite() && (trial - mid).norm() <= chord &&
279 !(trial.array() == x.array()).all())
280 candidates.emplace_back((trial - x).squaredNorm(), row);
281 }
282 std::sort(candidates.begin(), candidates.end());
283 for (const auto& candidate: candidates) {
284 const Eigen::VectorXd trial = projected(candidate.second);
285 const double trial_energy = surrogateEnergy(session, trial);
286 if (!std::isfinite(trial_energy) || !(trial_energy < e))
287 continue;
288 const double variance = surrogateEnergyVariance(session, trial);
289 if (!std::isfinite(variance) || variance > trust_cap) continue;
290 x = trial;
291 e = trial_energy;
292 step = 0.5 * chord;
293 return true;
294 }
295 return false;
296 };
297 for (int it = 0; it < kMaxRelaxSteps && tol > 0.0 && e > e_ci; ++it) {
298 const Eigen::VectorXd g = surrogateGradient(session, x);
299 if (g.size() != x.size() || !g.allFinite()) break;
300 Eigen::VectorXd f = -(g - g.dot(tau) * tau);
301 const double fn = f.norm();
302 if (!(fn > tol)) {
303 if (descend_from_observed_rows()) continue;
304 break;
305 }
306 f /= fn;
307 bool accepted = false;
308 const double initial_step = step;
309 bool rejected_by_variance = false;
310 for (int direction = 0; direction < 2 && !accepted; ++direction) {
311 if (direction == 1) {
312 if (!rejected_by_variance) break;
313 Eigen::VectorXd normal =
314 surrogateEnergyVarianceGradient(session, x);
315 if (normal.size() != x.size() || !normal.allFinite()) break;
316 normal -= normal.dot(tau) * tau;
317 const double normal_norm = normal.norm();
318 if (std::getenv("GPR_MIDPOINT_DEBUG"))
319 std::cerr << "[midpoint] seg=" << i
320 << " energy_direction=" << f.transpose()
321 << " variance_gradient=" << normal.transpose()
322 << " cap=" << trust_cap << std::endl;
323 if (!(normal_norm > 0.0)) break;
324 normal /= normal_norm;
325 // The bisector of energy descent and variance descent
326 // decreases both functions to first order. At an active
327 // variance boundary, reducing the length of an outward
328 // energy gradient alone cannot produce a feasible step.
329 f -= normal;
330 const double feasible_norm = f.norm();
331 if (!(feasible_norm >
332 std::sqrt(std::numeric_limits<double>::epsilon())))
333 break;
334 f /= feasible_norm;
335 step = initial_step;
336 }
337 const double descent = -g.dot(f);
338 if (!(descent > 0.0)) break;
339 for (int ls = 0; ls < kMaxBacktracks; ++ls) {
340 const Eigen::VectorXd xt = x + step * f;
341 if ((xt.array() == x.array()).all()) break;
342 if ((xt - mid).norm() > chord) {
343 step *= 0.5;
344 continue;
345 }
346 const double et = surrogateEnergy(session, xt);
347 const double vt = surrogateEnergyVariance(session, xt);
348 const bool trusted = std::isfinite(vt) && vt <= trust_cap;
349 if (std::getenv("GPR_MIDPOINT_DEBUG") &&
350 (ls == 0 || ls + 1 == kMaxBacktracks))
351 std::cerr << "[midpoint] seg=" << i
352 << " direction=" << direction << " ls=" << ls
353 << " step=" << step << " e=" << e
354 << " trial=" << et << " variance=" << vt
355 << " cap=" << trust_cap
356 << " descent=" << descent << std::endl;
357 rejected_by_variance = rejected_by_variance || !trusted;
358 if (trusted && std::isfinite(et) && et < e &&
359 et <= e - kArmijo * step * descent) {
360 x = xt;
361 e = et;
362 accepted = true;
363 step = std::min(2.0 * step, chord);
364 break;
365 }
366 step *= 0.5;
367 }
368 }
369 if (!accepted) {
370 if (descend_from_observed_rows()) continue;
371 break;
372 }
373 if (std::getenv("GPR_MIDPOINT_DEBUG")) {
374 std::cerr << "[midpoint] seg=" << i << " it=" << it
375 << " e=" << e << " fn=" << fn << " step=" << step
376 << " disp=" << (x - mid).norm() << " chord=" << chord
377 << std::endl;
378 }
379 }
380 if (std::getenv("GPR_MIDPOINT_DEBUG")) {
381 std::cerr
382 << "[midpoint] seg=" << i << " final e=" << e
383 << " e_ci=" << e_ci
384 << " e_raw=" << surrogateEnergy(session, mid)
385 << " variance=" << surrogateEnergyVariance(session, x)
386 << " magn="
388 << " lengths="
390 << std::endl;
391 }
392 const double excess = e - e_ci;
393 const double v_x = surrogateEnergyVariance(session, x);
394 // A mean below the climbing image cannot certify an unsampled gap
395 // whose posterior still permits a higher barrier. The measured
396 // certificate resolves these two-standard-deviation upper bounds.
397 const double uncertainty =
398 std::isfinite(v_x)
399 ? kEnergyConfidence *
400 std::sqrt(std::max(0.0, v_x - variance_floor))
401 : std::numeric_limits<double>::infinity();
402 const double upper_excess = excess + uncertainty;
403 out.segment_excess[static_cast<std::size_t>(i)] = excess;
404 out.segment_raw_excess[static_cast<std::size_t>(i)] = e_raw - e_ci;
405 out.segment_variance[static_cast<std::size_t>(i)] = v_x;
406 out.segment_position[static_cast<std::size_t>(i)] = x;
407 if (upper_excess > worst_upper_excess) {
408 worst_upper_excess = upper_excess;
409 out.excess = excess;
410 out.raw_excess = e_raw - e_ci;
411 out.worst_segment = i;
412 out.worst_position = x;
413 out.worst_variance = v_x;
414 }
415 if (upper_excess > 0.0) out.holds = false;
416 }
417 if (!std::isfinite(out.excess)) out.excess = 0.0;
418 return out;
419}
420
422 ActiveLearningSession& session, const NEBPath& path, double force_tol,
423 NEBOracle& oracle, int max_measurements, int* oracle_calls)
424{
426 certifyBandMidpoints(session, path, force_tol);
427 int measured = 0;
428 // A measured energy above the climbing image does not prove a ridge:
429 // the surrogate-relaxed point need not be the true in-plane minimum.
430 // The row corrects the surrogate and the certificate is re-run; the
431 // refusal stands only when the corrected surrogate still shows the
432 // ridge (04_ch3o: one measured excess of 0.097 eV read as a ridge
433 // would have bought a refinement pass the certificate did not need).
434 // Each row carries the true gradient at the relaxed point, so the
435 // loop is a measured in-plane descent: the corrected surrogate relaxes
436 // to a new point and that is measured next, up to max_measurements
437 // rows (one per segment). Only an exactly repeated position is stuck
438 // (04_ch3o: a 1e-3 A radius stopped the descent after two rows 0.1 eV
439 // above the climbing image and bought a refinement pass instead).
440 std::vector<Eigen::VectorXd> measured_at;
441 auto already_measured = [&](const Eigen::VectorXd& x) {
442 for (const auto& m: measured_at)
443 if (m.size() == x.size() && (m - x).norm() < 1e-6) return true;
444 return false;
445 };
446 bool any_measured_above = false;
447 Eigen::VectorXd measured_above_position;
448 while (mid.evaluated && !mid.holds && measured < max_measurements &&
449 mid.worst_segment >= 0 && mid.worst_position.size() > 0 &&
450 mid.worst_position.allFinite() &&
451 !already_measured(mid.worst_position)) {
452 const int ci = detail::climbingStopImage(path);
453 const double e_ci = path.image(ci).energy;
454 const auto [e_true, g_true] =
455 detail::evaluateOieOraclePosition(mid.worst_position, oracle);
456 ++measured;
457 if (oracle_calls != nullptr) ++(*oracle_calls);
458 if (!std::isfinite(e_true) ||
459 g_true.size() != mid.worst_position.size() || !g_true.allFinite())
460 break;
461 measured_at.push_back(mid.worst_position);
462 session.appendObservation(mid.worst_position, e_true, g_true);
463 (void)session.refitGPIfTrainingChanged(/*reinit_seeds=*/false);
464 std::cout << "[ocineb] midpoint measured: seg=" << mid.worst_segment
465 << " e_true-e_ci=" << (e_true - e_ci)
466 << " surrogate_excess=" << mid.excess
467 << " variance=" << mid.worst_variance << std::endl;
468 if (e_true > e_ci) {
469 // A true-surface point above the climbing image is conclusive:
470 // the band missed the pass in this segment. Relaxing and
471 // measuring the midpoint again only spends the budget (dacp2:
472 // the certificate's own loop ran out the cell).
473 any_measured_above = true;
474 measured_above_position = mid.worst_position;
475 break;
476 }
477 mid = certifyBandMidpoints(session, path, force_tol);
478 }
479 if (mid.evaluated && !mid.holds) {
480 mid.true_ridge = any_measured_above;
481 mid.measured_position = measured_above_position;
482 mid.measurements = measured;
483 return mid;
484 }
485 // A hump the relaxation slid off: the raw chord midpoint lay above the
486 // climbing image and the relaxed point below it, in a region the
487 // surrogate has no row for. Verify the valley before trusting it.
488 const double noise_floor = std::max(0.0, session.gp.getSigma2());
489 std::vector<char> verified(mid.segment_excess.size(), 0);
490 while (mid.evaluated && mid.holds && measured < max_measurements) {
491 int target = -1;
492 double worst_raw = 0.0;
493 for (std::size_t i = 0; i < mid.segment_excess.size(); ++i) {
494 if (verified[i]) continue;
495 const double raw = mid.segment_raw_excess[i];
496 const double rel = mid.segment_excess[i];
497 const double var = mid.segment_variance[i];
498 if (!std::isfinite(raw) || !std::isfinite(rel) || !(raw > 0.0) ||
499 !(rel <= 0.0) || mid.segment_position[i].size() == 0)
500 continue;
501 if (std::isfinite(var) && var <= noise_floor) continue;
502 if (raw > worst_raw) {
503 worst_raw = raw;
504 target = static_cast<int>(i);
505 }
506 }
507 if (target < 0) break;
508 verified[static_cast<std::size_t>(target)] = 1;
509 const int ci = detail::climbingStopImage(path);
510 const double e_ci = path.image(ci).energy;
511 const Eigen::VectorXd x =
512 mid.segment_position[static_cast<std::size_t>(target)];
513 const auto [e_true, g_true] =
514 detail::evaluateOieOraclePosition(x, oracle);
515 ++measured;
516 if (oracle_calls != nullptr) ++(*oracle_calls);
517 if (!std::isfinite(e_true) || g_true.size() != x.size() ||
518 !g_true.allFinite())
519 break;
520 session.appendObservation(x, e_true, g_true);
521 (void)session.refitGPIfTrainingChanged(/*reinit_seeds=*/false);
522 std::cout << "[ocineb] midpoint verified: seg=" << target
523 << " raw_excess=" << worst_raw
524 << " e_true-e_ci=" << (e_true - e_ci) << " variance="
525 << mid.segment_variance[static_cast<std::size_t>(target)]
526 << std::endl;
527 if (e_true > e_ci) any_measured_above = true;
528 // The row corrects the surrogate; the certificate decides again.
529 const BandMidpointCertificate again =
530 certifyBandMidpoints(session, path, force_tol);
531 if (again.evaluated) {
532 mid = again;
533 if (mid.segment_excess.size() != verified.size())
534 verified.assign(mid.segment_excess.size(), 0);
535 }
536 if (!mid.holds) {
537 // A corrected surrogate that now refuses goes back through the
538 // refusal loop above only via the caller's next certificate
539 // call; report the refusal as measured.
540 mid.true_ridge = any_measured_above;
541 break;
542 }
543 }
544 mid.measurements = measured;
545 return mid;
546}
547
549 double refused_energy) const noexcept
550{
551 if (verified && std::isfinite(oracle_curvature1) &&
552 std::isfinite(oracle_curvature2) && oracle_curvature1 < 0.0 &&
553 oracle_curvature2 < 0.0 && std::isfinite(refused_energy)) {
554 return refused_energy;
555 }
556 return std::numeric_limits<double>::infinity();
557}
558
560 const NEBOracle& oracle, ActiveLearningSession& session,
561 const Eigen::VectorXd& x_ci, double e_ci, const Eigen::VectorXd& g_ci,
562 double hessian_fd_step, double max_move, double force_tol,
563 const NEBBatchOracle* batch_oracle, Eigen::Index batch_chunk)
564{
566 const Eigen::Index n = x_ci.size();
567 if (n < 3 || g_ci.size() != n || !(hessian_fd_step > 0.0) ||
568 !std::isfinite(hessian_fd_step) || !(force_tol > 0.0)) {
569 out.reason = "invalid input";
570 return out;
571 }
572 const Eigen::VectorXd x = detail::broadcastRootVector(x_ci);
573 const gpr::Coord positions_row = x.transpose();
574 const Eigen::MatrixXd Q =
575 gpr::optim::physicalCurvatureBasis(positions_row, session.atoms_config);
576 const Eigen::Index dimension = Q.cols();
577 if (dimension < 2) {
578 out.reason = "fewer than two non-rigid modes";
579 return out;
580 }
581
582 const double h = hessian_fd_step;
583 const Eigen::MatrixXd H = surrogateHessian(session, x);
584 if (H.rows() != n || !H.allFinite()) {
585 out.reason =
586 "surrogate Hessian unavailable (rows=" + std::to_string(H.rows()) +
587 ")";
588 return out;
589 }
590 const Eigen::MatrixXd surrogate = Q.transpose() * H * Q;
591 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(surrogate);
592 if (es.info() != Eigen::Success) {
593 out.reason = "eigensolver failed";
594 return out;
595 }
596 out.evaluated = true;
597 out.surrogate_lambda1 = es.eigenvalues()(0);
598 out.surrogate_lambda2 = es.eigenvalues()(1);
599
600 // The complete coarse stencil: two calls along every physical direction.
601 const int probes = 2 * static_cast<int>(dimension);
602 Eigen::MatrixXd positions(n, probes);
603 for (Eigen::Index j = 0; j < dimension; ++j) {
604 positions.col(2 * j) = x + h * Q.col(j);
605 positions.col(2 * j + 1) = x - h * Q.col(j);
606 }
607 const auto observations = detail::evaluateOwnedOraclePositions(
608 positions, oracle, batch_oracle, batch_chunk);
609 out.oracle_calls = probes;
610 bool valid = true;
611 for (int i = 0; i < probes; ++i) {
612 if (observations.valid[i]) {
613 session.appendObservation(positions.col(i), observations.energy[i],
614 observations.gradient.row(i).transpose());
615 } else {
616 valid = false;
617 }
618 }
619 if (!valid) {
620 out.reason = "oracle probe failed";
621 (void)session.refitGPIfTrainingChanged(false);
622 return out;
623 }
624 out.rounds = static_cast<int>(dimension);
625 out.verified = true;
626
627 // The measured columns carry the same error model as the dimer's index
628 // certificate: entry by entry, the even stencil residual over the step
629 // (the cubic force term the central difference cannot see) above the
630 // roundoff of the two gradients, mapped into the physical basis. The
631 // surrogate Hessian is the prior of the smoothed spectrum, and the
632 // stationarity floor of a mode, sqrt(2 max(b f, 0)) with b its cubic
633 // coefficient and f the residual gradient along it, is the curvature
634 // below which no stationary point of the measured sign exists.
635 const Eigen::MatrixXd Q_sq = Q.array().square().matrix();
636 const auto physical_variance =
637 [&](const Eigen::VectorXd& cartesian_error) -> Eigen::VectorXd {
638 return Q_sq.transpose() * cartesian_error.array().square().matrix();
639 };
640 const double eps = std::numeric_limits<double>::epsilon();
641 // The roundoff floor of a column, as in the dimer's certificate: the
642 // scale of the measured actions and of the gradient at the point.
643 double action_scale = g_ci.norm();
644 for (Eigen::Index j = 0; j < dimension; ++j)
645 action_scale =
646 std::max(action_scale, (observations.gradient.row(2 * j) -
647 observations.gradient.row(2 * j + 1))
648 .norm() /
649 (2.0 * h));
650 const double roundoff_scale = eps * action_scale;
651 const auto roundoff_error = [&](const Eigen::VectorXd& g_plus,
652 const Eigen::VectorXd& g_minus,
653 double step) -> Eigen::VectorXd {
654 if (!(step > 0.0) || !std::isfinite(step) ||
655 g_plus.size() != g_minus.size() || !g_plus.allFinite() ||
656 !g_minus.allFinite()) {
657 return Eigen::VectorXd::Zero(g_plus.size());
658 }
659 return (eps * (g_plus.array().abs() + g_minus.array().abs()) /
660 (2.0 * step))
661 .max(roundoff_scale)
662 .matrix()
663 .eval();
664 };
665 struct ColumnStencil {
666 Eigen::VectorXd coarse_action; // Cartesian central difference
667 Eigen::VectorXd even_residual;
668 };
669 std::vector<gpr::optim::MeasuredHessianColumn> columns;
670 std::vector<ColumnStencil> stencils;
671 Eigen::MatrixXd second_differences = Eigen::MatrixXd::Zero(n, dimension);
672 columns.reserve(static_cast<std::size_t>(dimension));
673 for (Eigen::Index j = 0; j < dimension; ++j) {
674 const Eigen::VectorXd g_plus =
675 observations.gradient.row(2 * j).transpose();
676 const Eigen::VectorXd g_minus =
677 observations.gradient.row(2 * j + 1).transpose();
678 const Eigen::VectorXd coarse = (g_plus - g_minus) / (2.0 * h);
679 const Eigen::VectorXd even = 0.5 * (g_plus + g_minus) - g_ci;
680 const Eigen::VectorXd roundoff = roundoff_error(g_plus, g_minus, h);
681 Eigen::VectorXd error;
682 if (!even.allFinite() || !(h > 0.0) || !std::isfinite(h)) {
683 error = Eigen::VectorXd::Zero(even.size());
684 } else {
685 error = (even.array().abs() / h).max(roundoff.array()).matrix();
686 }
687 columns.push_back({Eigen::VectorXd::Unit(dimension, j),
688 Q.transpose() * coarse, physical_variance(error),
689 false});
690 stencils.push_back({coarse, even});
691 second_differences.col(j) = (2.0 / (h * h)) * even;
692 }
693 // Refinement of a coarse column: two calls at half the step; the
694 // Richardson combination is exact through the quartic force term and
695 // the difference of the two stencils is the truncation the coarse
696 // column carried, entry by entry.
697 const auto refine_column = [&](Eigen::Index j) {
698 auto& column = columns[static_cast<std::size_t>(j)];
699 const auto& stencil = stencils[static_cast<std::size_t>(j)];
700 Eigen::MatrixXd pair(n, 2);
701 pair.col(0) = x + 0.5 * h * Q.col(j);
702 pair.col(1) = x - 0.5 * h * Q.col(j);
703 const auto probed = detail::evaluateOwnedOraclePositions(
704 pair, oracle, batch_oracle, batch_chunk);
705 out.oracle_calls += 2;
706 bool probed_valid = true;
707 for (int i = 0; i < 2; ++i) {
708 if (probed.valid[i])
709 session.appendObservation(pair.col(i), probed.energy[i],
710 probed.gradient.row(i).transpose());
711 else
712 probed_valid = false;
713 }
714 if (!probed_valid) return false;
715 const Eigen::VectorXd g_plus = probed.gradient.row(0).transpose();
716 const Eigen::VectorXd g_minus = probed.gradient.row(1).transpose();
717 const Eigen::VectorXd fine = (g_plus - g_minus) / h;
718 const Eigen::VectorXd refined =
719 (4.0 * fine - stencil.coarse_action) / 3.0;
720 const Eigen::VectorXd truncation = (stencil.coarse_action - fine) / 3.0;
721 column.action = Q.transpose() * refined;
722 column.variance = physical_variance(
723 truncation.array()
724 .abs()
725 .max(roundoff_error(g_plus, g_minus, 0.5 * h).array())
726 .matrix());
727 column.refined = true;
728 std::cout << "[ocineb] index certificate refined column " << j << ": "
729 << Q.col(j).dot(stencil.coarse_action) << " coarse, "
730 << Q.col(j).dot(refined) << " extrapolated, truncation "
731 << Q.col(j).dot(truncation) << std::endl;
732 return true;
733 };
734 const Eigen::VectorXd gradient_physical = Q.transpose() * g_ci;
736 const auto stationarity_floor = [&](Eigen::Index k) {
738 Q, second_differences, Q * smoothed.modes.col(k));
739 const double f = gradient_physical.dot(smoothed.modes.col(k));
740 return std::sqrt(2.0 * std::max(b * f, 0.0));
741 };
742 // The resolution of an eigenvalue of the Hessian at this point is its
743 // posterior spread: what the validation stencil measures and accepts
744 // on. The stationarity floor is reported, not applied (see the
745 // dimer's certificate). The irreducible resolution is the best
746 // precision a fully refined stencil reaches; a sign inside it is
747 // undecidable and no column is refined for it.
748 const auto resolution = [&](Eigen::Index k) { return smoothed.spreads(k); };
749 const auto irreducible = [&](Eigen::Index k) { return smoothed.floors(k); };
750 const auto decidable = [&](Eigen::Index k) {
751 const double curvature = smoothed.mean_curvatures(k);
752 return curvature * curvature > irreducible(k) * irreducible(k);
753 };
754 // The verdict on the point: index one; a resolved minimum or a
755 // resolved higher-index point, each with the mode to leave along; or
756 // a lowest curvature no stencil resolves.
757 enum class IndexVerdict {
758 Undecided,
759 IndexOne,
760 Minimum,
761 HigherIndex,
762 Unresolved,
763 Polish
764 };
765 IndexVerdict verdict = IndexVerdict::Undecided;
766 double resolution1 = std::numeric_limits<double>::infinity();
767 double resolution2 = std::numeric_limits<double>::infinity();
768 while (verdict == IndexVerdict::Undecided) {
770 surrogate, columns, smoothed.valid ? &smoothed : nullptr,
771 session.gp.mpiContext());
772 out.local_spectrum_samples = smoothed.local_samples;
773 if (!smoothed.valid) {
774 out.reason = "projected eigensolver failed";
775 (void)session.refitGPIfTrainingChanged(false);
776 return out;
777 }
778 resolution1 = resolution(0);
779 resolution2 = resolution(1);
780 // The eigenvalues of the posterior mean Hessian: deterministic,
781 // exact for an exact stencil, and within the sampled spread of
782 // the sorted-eigenvalue posterior's mean, which the resolution
783 // already covers.
784 out.oracle_curvature1 = smoothed.mean_curvatures(0);
785 out.oracle_curvature2 = smoothed.mean_curvatures(1);
786 out.mode1 = Q * smoothed.modes.col(0);
787 out.mode2 = Q * smoothed.modes.col(1);
788 out.residual1 = h * resolution1;
789 out.residual2 = h * resolution2;
790 std::cout << "[ocineb] index certificate at energy " << e_ci
791 << ": lowest curvature " << out.oracle_curvature1
792 << " (resolution " << resolution1 << "), second "
793 << out.oracle_curvature2 << " (resolution " << resolution2
794 << ", spread " << smoothed.spreads(1)
795 << ", stationarity floor " << stationarity_floor(1)
796 << ", irreducible " << irreducible(1) << "), calls "
797 << out.oracle_calls << std::endl;
798 if (!(out.oracle_curvature1 + resolution1 < 0.0)) {
799 if (out.oracle_curvature1 - resolution1 > 0.0) {
800 out.reason = "resolved minimum";
801 verdict = IndexVerdict::Minimum;
802 break;
803 }
804 // The lowest curvature is not resolved negative: refine the
805 // coarse column it overlaps most, when a stencil can decide it.
806 const Eigen::Index coarse =
807 decidable(0)
808 ? gpr::optim::coarseColumnToRefine(smoothed, columns, 0)
809 : -1;
810 if (coarse >= 0 && refine_column(coarse)) continue;
811 out.reason = "lowest curvature is unresolved";
812 verdict = IndexVerdict::Unresolved;
813 break;
814 }
815 if (out.oracle_curvature2 - resolution2 > 0.0) {
816 out.reason = "resolved positive second curvature";
817 out.positive_complement_lower_bound =
818 out.oracle_curvature2 - resolution2;
819 verdict = IndexVerdict::IndexOne;
820 break;
821 }
822 if (out.oracle_curvature2 + resolution2 < 0.0) {
823 // Index two at the point; the escape is worth its calls only
824 // when the stationary point has index two as well (the
825 // cubic model along the mode, see the dimer's certificate).
827 Q, second_differences, Q * smoothed.modes.col(1));
828 const double f = gradient_physical.dot(smoothed.modes.col(1));
829 const double sigma_f = h * smoothed.measured_spreads(1);
830 const double sigma_b = 2.0 * sigma_f / (h * h);
831 const auto stationary = gpr::optim::stationaryCurvaturePosterior(
832 out.oracle_curvature2, resolution2, f, sigma_f, b, sigma_b);
833 std::cout << "[ocineb] index certificate: second curvature at the "
834 "stationary point in ["
835 << stationary.lower << ", " << stationary.upper
836 << "], undetermined fraction " << stationary.undetermined
837 << ", force target " << stationary.force_target
838 << std::endl;
839 if (stationary.valid && !(stationary.upper < 0.0) &&
840 stationary.force_decidable &&
841 stationary.force_target < force_tol) {
842 out.polish_force_target = stationary.force_target;
843 out.reason =
844 "second curvature negative at the point, "
845 "undetermined at the stationary point";
846 verdict = IndexVerdict::Polish;
847 break;
848 }
849 out.reason = "resolved negative second curvature";
850 verdict = IndexVerdict::HigherIndex;
851 break;
852 }
853 // A refinement decides the sign only when the stencil error, not
854 // the irreducible resolution, hides it.
855 const Eigen::Index coarse =
856 decidable(1)
857 ? gpr::optim::coarseColumnToRefine(smoothed, columns, 1)
858 : -1;
859 if (coarse >= 0 && refine_column(coarse)) continue;
860 // Within the irreducible resolution of zero the second curvature's
861 // sign is beyond every affordable stencil: no certificate and no
862 // escape, as the validation stencil refuses an unresolved mode.
863 out.reason = "second curvature unresolved within " +
864 std::to_string(resolution2) + " of zero";
865 verdict = IndexVerdict::Unresolved;
866 }
867 out.certified = verdict == IndexVerdict::IndexOne;
868 // A certified index ends the search at this point: no query follows that
869 // the stencil rows could inform, and conditioning on them factors a
870 // covariance of the band's rows plus two per physical direction. The
871 // session's training revision records the appended rows, so a caller
872 // that continues conditions or refits before its next query. A refused
873 // index continues from this posterior and needs it now.
874 if (!out.certified) (void)session.refitGPIfTrainingChanged(false);
875 const bool escape = verdict == IndexVerdict::Minimum ||
876 verdict == IndexVerdict::HigherIndex;
877 if (out.certified || !(max_move > 0.0) || !escape) return out;
878
879 // Leave the higher-index stationary point along the offending mode
880 // (mode 2 when the second curvature is negative, mode 1 when the image
881 // is not even a saddle along its lowest mode), toward the side the
882 // surrogate ranks lower.
883 const Eigen::VectorXd& mode =
884 verdict == IndexVerdict::HigherIndex ? out.mode2 : out.mode1;
885 const Eigen::VectorXd xa = x + max_move * mode;
886 const Eigen::VectorXd xb = x - max_move * mode;
887 const double ea = surrogateEnergy(session, xa);
888 const double eb = surrogateEnergy(session, xb);
889 // The side the surrogate ranks lower; a side without a finite energy
890 // is never chosen over one with.
891 const bool prefer_b = std::isfinite(eb) && (!std::isfinite(ea) || eb < ea);
892 out.displaced_positions = prefer_b ? xb : xa;
893 return out;
894}
895
897 const NEBOracle& oracle, ActiveLearningSession& session,
898 const Eigen::VectorXd& x0, double e0, const Eigen::VectorXd& g0,
899 double force_tol, int max_steps, double max_move, double hessian_fd_step)
900{
902 out.positions = x0;
903 out.energy = e0;
904 out.gradient = g0;
905 if (x0.size() == 0 || g0.size() != x0.size() || !g0.allFinite() ||
906 !(force_tol > 0.0) || !(hessian_fd_step > 0.0)) {
907 return out;
908 }
909 out.initial_force_inf = g0.lpNorm<Eigen::Infinity>();
910 out.final_force_inf = out.initial_force_inf;
911 out.initial_max_atom_force =
912 detail::saddlePolishForceMagnitude(x0, g0, session.atoms_config);
913 out.final_max_atom_force = out.initial_max_atom_force;
914 out.converged = out.final_max_atom_force <= force_tol;
915 if (out.converged) return out;
916
917 Eigen::VectorXd x = x0, g = g0;
918 double e = e0;
919 for (int step = 0; step < max_steps; ++step) {
920 const Eigen::MatrixXd H = surrogateHessian(session, x);
921 if (H.size() == 0 || !H.allFinite()) break;
922 double correction = 0.0;
923 Eigen::VectorXd d =
924 newtonSaddleStep(H, g, x, session.atoms_config, &correction);
925 out.quadratic_correction = correction;
926 const double dmax = d.lpNorm<Eigen::Infinity>();
927 if (!(dmax > 0.0) || !std::isfinite(dmax)) break;
928 if (max_move > 0.0 && dmax > max_move) d *= max_move / dmax;
929
930 bool accepted = false;
931 const double f_before =
932 detail::saddlePolishForceMagnitude(x, g, session.atoms_config);
933 for (int halving = 0; halving < 2 && !accepted; ++halving) {
934 const Eigen::VectorXd x_try = x + d;
935 const auto [e_try, g_try] =
936 detail::evaluateOieOraclePosition(x_try, oracle);
937 ++out.oracle_calls;
938 if (g_try.size() == x.size() && g_try.allFinite()) {
939 session.appendObservation(x_try, e_try, g_try);
940 (void)session.refitGPIfTrainingChanged(false);
941 if (detail::saddlePolishForceMagnitude(
942 x_try, g_try, session.atoms_config) < f_before) {
943 x = x_try;
944 e = e_try;
945 g = g_try;
946 accepted = true;
947 }
948 }
949 if (!accepted) d *= 0.5;
950 }
951 if (!accepted) break;
952 ++out.steps;
953 out.positions = x;
954 out.energy = e;
955 out.gradient = g;
956 out.final_force_inf = g.lpNorm<Eigen::Infinity>();
957 out.final_max_atom_force =
958 detail::saddlePolishForceMagnitude(x, g, session.atoms_config);
959 if (out.final_max_atom_force <= force_tol) {
960 out.converged = true;
961 break;
962 }
963 }
964 // Report the correction the remaining force still hides at the final
965 // point, from the surrogate curvature there.
966 if (out.steps > 0 || out.oracle_calls > 0) {
967 const Eigen::MatrixXd H = surrogateHessian(session, out.positions);
968 if (H.size() > 0 && H.allFinite()) {
969 double correction = 0.0;
970 (void)newtonSaddleStep(H, out.gradient, out.positions,
971 session.atoms_config, &correction);
972 out.quadratic_correction = correction;
973 }
974 }
975 return out;
976}
977
978} // namespace neb
979} // namespace gpr
@ x
Definition Enums.h:28
@ MOVING_ATOM
Definition Enums.h:35
NEB path management: image chain, spring forces, climbing image.
The curvature of a mode at the stationary point the search converges to, from the cubic model along t...
double getMagnSigma2()
Definition SexpatCF.inl:53
FieldMatrixd & getLengthScaleRef()
Definition SexpatCF.inl:58
NEB path: chain of images between two endpoints.
Definition NEBPath.h:57
int numImages() const
Definition NEBPath.h:338
Image & image(int i)
Access image i.
Definition NEBPath.h:329
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
bool cellIsMicLattice(const double cell[9]) noexcept
Nonzero ASE 3x3 that is not the 25 A vacuum convention.
Definition MinImage.h:56
The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition,...
std::function< std::vector< std::pair< double, Eigen::VectorXd > >( const std::vector< Eigen::VectorXd > &positions)> NEBBatchOracle
Definition GPNEB.h:89
SaddlePolishResult polishSaddleOnSurrogate(const NEBOracle &oracle, ActiveLearningSession &session, const Eigen::VectorXd &x0, double e0, const Eigen::VectorXd &g0, double force_tol, int max_steps, double max_move, double hessian_fd_step)
std::function< std::pair< double, Eigen::VectorXd >( const Eigen::VectorXd &positions)> NEBOracle
Oracle function: positions -> (energy, gradient).
Definition GPNEB.h:82
BandMidpointCertificate certifyBandMidpoints(ActiveLearningSession &session, const NEBPath &path, double force_tol)
ClimbingImageIndexCertificate certifyClimbingImageIndex(const NEBOracle &oracle, ActiveLearningSession &session, const Eigen::VectorXd &x_ci, double e_ci, const Eigen::VectorXd &g_ci, double hessian_fd_step, double max_move, double force_tol, const NEBBatchOracle *batch_oracle, Eigen::Index batch_chunk)
BandMidpointCertificate certifyBandMidpointsMeasured(ActiveLearningSession &session, const NEBPath &path, double force_tol, NEBOracle &oracle, int max_measurements, int *oracle_calls)
double saddleForceMagnitude(const Eigen::VectorXd &gradient)
Definition NEBPath.cpp:25
Eigen::MatrixXd physicalCurvatureBasis(const gpr::Coord &positions, const gpr::AtomsConfiguration &config, bool exclude_rotations=true, RigidMotionMetric metric=RigidMotionMetric::MassWeighted)
double axisStencilDirectionalCubic(const Eigen::MatrixXd &axes, const Eigen::MatrixXd &second_differences, const Eigen::VectorXd &mode)
Eigen::Index coarseColumnToRefine(const SmoothedCurvatureSpectrum &spectrum, const std::vector< MeasuredHessianColumn > &columns, Eigen::Index k)
SmoothedCurvatureSpectrum smoothMeasuredCurvature(const Eigen::MatrixXd &prior, const std::vector< MeasuredHessianColumn > &columns, const SmoothedCurvatureSpectrum *previous=nullptr, const linalg::MpiContext &context=linalg::MpiContext::local())
StationaryCurvaturePosterior stationaryCurvaturePosterior(double c, double c_spread, double f, double f_spread, double b, double b_spread, Eigen::Index samples=detail::kSpectrumSamples)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
FieldMatrixd Coord
Definition Macros.h:35
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
AtomsPositionAndType atoms_froz_inactive
Info on inactive frozen atoms.
Definition Structures.h:843
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
Definition Structures.h:834
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841
Coord positions
Positions of all atoms in the system.
Definition Structures.h:833
FieldMatrixd E
gpr::Observation training_obs
Definition Session.h:246
bool refitGPIfTrainingChanged(bool reinit_seeds)
Definition Session.h:3301
gpr::GaussianProcessRegression gp
Definition Session.h:471
gpr::AtomsConfiguration atoms_config
Definition Session.h:1129
void appendObservation(const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient, ObservationRetention retention=ObservationRetention::RecordAcquisition, optim::SecantAccounting secant_accounting=optim::SecantAccounting::Count)
Definition Session.h:1574
double worst_variance
posterior variance there
int measurements
oracle rows bought by the measured variant
std::vector< double > segment_raw_excess
std::vector< Eigen::VectorXd > segment_position
std::vector< double > segment_variance
int worst_segment
segment with the highest energy upper bound
std::vector< double > segment_excess
Eigen::VectorXd worst_position
the relaxed midpoint of worst_segment
double excess
mean E_mid - E_ci for that segment (eV)
double escapeEnergyCeiling(double refused_energy) const noexcept
bool verified
the complete non-rigid subspace was evaluated
double energy
Definition NEBPath.h:41
Eigen::VectorXd positions
Definition NEBPath.h:40
Outcome of a saddle polish (see polishSaddleOnSurrogate).
Eigen::Index local_samples
Spectrum samples evaluated by this process.