Loading...
Searching...
No Matches
LocalGP.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "LocalGP.h"
6
7#include <algorithm>
8#include <cmath>
9#include <limits>
10
12#include "../ml/PhaseTimers.h"
13#include "../ml/RgminLbfgs.h"
14
15namespace gpr {
16namespace neb {
17
19 std::vector<Eigen::Index> gradient_dofs)
20 : input_dim_(input_dim),
21 dim_(static_cast<Eigen::Index>(gradient_dofs.size())),
22 dofs_(std::move(gradient_dofs))
23{
24}
25
26void LocalCartesianGP::setNoise(double energy_sigma, double gradient_sigma)
27{
28 noise_energy_ = std::max(energy_sigma, 1e-8);
29 noise_gradient_ = std::max(gradient_sigma, 1e-8);
30 conditioned_ = false;
31 structure_changed_ = true;
32}
33
34void LocalCartesianGP::setWindow(int max_observations)
35{
36 window_ = std::max(2, max_observations);
37 if (static_cast<int>(obs_.size()) > window_) {
38 while (static_cast<int>(obs_.size()) > window_)
39 obs_.pop_front();
40 structure_changed_ = true;
41 conditioned_ = false;
42 }
43}
44
45void LocalCartesianGP::setLengthScaleBounds(double lower, double upper)
46{
47 ell_lower_ = std::max(lower, 1e-4);
48 ell_upper_ = std::max(upper, ell_lower_ * 2.0);
49 const double clamped = std::clamp(ell_, ell_lower_, ell_upper_);
50 if (clamped != ell_) {
51 ell_ = clamped;
52 structure_changed_ = true;
53 conditioned_ = false;
54 }
55}
56
57void LocalCartesianGP::setHyperparameters(double signal_variance,
58 double length_scale)
59{
60 if (std::isfinite(signal_variance) && signal_variance > 0.0)
61 sf2_ = signal_variance;
62 if (std::isfinite(length_scale) && length_scale > 0.0)
63 ell_ = std::clamp(length_scale, ell_lower_, ell_upper_);
64 conditioned_ = false;
65 structure_changed_ = true;
66}
67
69{
70 if (obs_.size() < 2) return;
71 std::vector<double> nearest;
72 nearest.reserve(obs_.size());
73 double e_min = std::numeric_limits<double>::infinity();
74 double e_max = -std::numeric_limits<double>::infinity();
75 for (std::size_t a = 0; a < obs_.size(); ++a) {
76 double best = std::numeric_limits<double>::infinity();
77 for (std::size_t b = 0; b < obs_.size(); ++b) {
78 if (a == b) continue;
79 best = std::min(best, (obs_[a].x - obs_[b].x).norm());
80 }
81 if (std::isfinite(best) && best > 0.0) nearest.push_back(best);
82 e_min = std::min(e_min, obs_[a].energy);
83 e_max = std::max(e_max, obs_[a].energy);
84 }
85 if (nearest.empty()) return;
86 std::nth_element(nearest.begin(),
87 nearest.begin() + static_cast<long>(nearest.size() / 2),
88 nearest.end());
89 const double spacing = nearest[nearest.size() / 2];
90 const double half_spread = 0.5 * (e_max - e_min);
91 setHyperparameters(std::max(half_spread * half_spread, 1e-3),
92 std::max(factor, 1.0) * spacing);
93}
94
95bool LocalCartesianGP::add(const Eigen::VectorXd& x, double energy,
96 const Eigen::VectorXd& local_gradient,
97 double duplicate_distance)
98{
99 if (x.size() != input_dim_ || local_gradient.size() != dim_) return false;
100 if (!std::isfinite(energy) || !x.allFinite() || !local_gradient.allFinite())
101 return false;
102 Eigen::VectorXd local(dim_);
103 for (Eigen::Index k = 0; k < dim_; ++k)
104 local(k) = x(dofs_[static_cast<std::size_t>(k)]);
105 for (auto& o: obs_) {
106 if ((o.x - x).norm() <= duplicate_distance) {
107 o.x = x;
108 o.local = local;
109 o.energy = energy;
110 o.gradient = local_gradient;
111 conditioned_ = false;
112 structure_changed_ = true;
113 return true;
114 }
115 }
116 obs_.push_back({x, local, energy, local_gradient});
117 if (static_cast<int>(obs_.size()) > window_) {
118 const int drop = std::max(1, window_ / 4);
119 for (int k = 0; k < drop && obs_.size() > 1; ++k)
120 obs_.pop_front();
121 structure_changed_ = true;
122 }
123 conditioned_ = false;
124 return true;
125}
126
127double LocalCartesianGP::meanStatistic() const
128{
129 // The constant mean sits at the highest retained energy: a band's
130 // images lie below the saddle, and a prior that returns to the barrier
131 // height away from the data keeps a polish step from drifting into
132 // unobserved low-energy regions.
133 double m = -std::numeric_limits<double>::infinity();
134 for (const auto& o: obs_)
135 m = std::max(m, o.energy);
136 return std::isfinite(m) ? m : 0.0;
137}
138
139Eigen::VectorXd LocalCartesianGP::targets() const
140{
141 Eigen::VectorXd y(rows());
142 const double m = meanStatistic();
143 Eigen::Index r = 0;
144 for (const auto& o: obs_) {
145 y(r) = o.energy - m;
146 y.segment(r + 1, dim_) = o.gradient;
147 r += block();
148 }
149 return y;
150}
151
152void LocalCartesianGP::kernelBlock(const Observation& a, const Observation& b,
153 double sf2, double ell,
154 Eigen::Ref<Eigen::MatrixXd> out,
155 Eigen::MatrixXd* dout) const
156{
157 const double inv2 = 1.0 / (ell * ell);
158 const double inv4 = inv2 * inv2;
159 const double q = (a.x - b.x).squaredNorm() * inv2;
160 const double k = sf2 * std::exp(-0.5 * q);
161 const Eigen::VectorXd r = a.local - b.local;
162 out(0, 0) = k;
163 out.row(0).segment(1, dim_) = (k * inv2) * r.transpose();
164 out.col(0).segment(1, dim_) = (-k * inv2) * r;
165 out.block(1, 1, dim_, dim_) = (-k * inv4) * (r * r.transpose());
166 out.block(1, 1, dim_, dim_).diagonal().array() += k * inv2;
167 if (dout) {
168 Eigen::MatrixXd& d = *dout;
169 d.resize(block(), block());
170 d(0, 0) = k * q;
171 d.row(0).segment(1, dim_) = (k * (q - 2.0) * inv2) * r.transpose();
172 d.col(0).segment(1, dim_) = (-k * (q - 2.0) * inv2) * r;
173 d.block(1, 1, dim_, dim_) =
174 (-k * (q - 4.0) * inv4) * (r * r.transpose());
175 d.block(1, 1, dim_, dim_).diagonal().array() += k * (q - 2.0) * inv2;
176 }
177}
178
179void LocalCartesianGP::assemble(double sf2, double ell, Eigen::MatrixXd& K,
180 Eigen::MatrixXd* dK_dlogell) const
181{
182 const Eigen::Index n = rows();
183 const Eigen::Index b = block();
184 K.setZero(n, n);
185 if (dK_dlogell) dK_dlogell->setZero(n, n);
186 const Eigen::Index count = static_cast<Eigen::Index>(obs_.size());
187 Eigen::MatrixXd dblock;
188 for (Eigen::Index a = 0; a < count; ++a) {
189 for (Eigen::Index c = a; c < count; ++c) {
190 kernelBlock(obs_[static_cast<std::size_t>(a)],
191 obs_[static_cast<std::size_t>(c)], sf2, ell,
192 K.block(a * b, c * b, b, b),
193 dK_dlogell ? &dblock : nullptr);
194 if (dK_dlogell) dK_dlogell->block(a * b, c * b, b, b) = dblock;
195 if (c != a) {
196 K.block(c * b, a * b, b, b) =
197 K.block(a * b, c * b, b, b).transpose();
198 if (dK_dlogell)
199 dK_dlogell->block(c * b, a * b, b, b) = dblock.transpose();
200 }
201 }
202 }
203 for (Eigen::Index a = 0; a < count; ++a) {
204 K(a * b, a * b) += noise_energy_ * noise_energy_;
205 for (Eigen::Index i = 1; i < b; ++i)
206 K(a * b + i, a * b + i) += noise_gradient_ * noise_gradient_;
207 }
208}
209
210double LocalCartesianGP::objective(const Eigen::Vector2d& theta,
211 Eigen::Vector2d& gradient) const
212{
213 const double sf2 = std::exp(theta(0));
214 const double ell = std::exp(theta(1));
215 const Eigen::Index n = rows();
216 Eigen::MatrixXd K, dK;
217 assemble(sf2, ell, K, &dK);
218 Eigen::LLT<Eigen::MatrixXd> llt(K);
219 if (llt.info() != Eigen::Success) {
220 gradient.setZero();
221 return std::numeric_limits<double>::infinity();
222 }
223 const Eigen::VectorXd y = targets();
224 const Eigen::VectorXd alpha = llt.solve(y);
225 const Eigen::MatrixXd L = llt.matrixL();
226 double logdet = 0.0;
227 for (Eigen::Index i = 0; i < n; ++i)
228 logdet += 2.0 * std::log(L(i, i));
229 const double nlml = 0.5 * y.dot(alpha) + 0.5 * logdet +
230 0.5 * static_cast<double>(n) * std::log(2.0 * M_PI);
231 const Eigen::MatrixXd Kinv = llt.solve(Eigen::MatrixXd::Identity(n, n));
232 // d/dlog sf2: the kernel part of K scales with sf2, the noise does not.
233 Eigen::MatrixXd dKs = K;
234 const Eigen::Index b = block();
235 for (Eigen::Index a = 0; a < static_cast<Eigen::Index>(obs_.size()); ++a) {
236 dKs(a * b, a * b) -= noise_energy_ * noise_energy_;
237 for (Eigen::Index i = 1; i < b; ++i)
238 dKs(a * b + i, a * b + i) -= noise_gradient_ * noise_gradient_;
239 }
240 const auto grad_for = [&](const Eigen::MatrixXd& dKm) {
241 return -0.5 * alpha.dot(dKm * alpha) +
242 0.5 * (Kinv.cwiseProduct(dKm)).sum();
243 };
244 gradient(0) = grad_for(dKs);
245 gradient(1) = grad_for(dK);
246 return nlml;
247}
248
250{
251 Eigen::Vector2d g;
252 return objective(Eigen::Vector2d(std::log(sf2_), std::log(ell_)), g);
253}
254
255double LocalCartesianGP::fit(int max_iterations,
256 const std::function<bool()>& stop_requested)
257{
258 const auto require_budget = [&] {
259 if (stop_requested && stop_requested()) throw WallClockLimitReached{};
260 };
261 require_budget();
262 if (obs_.size() < 2) {
263 condition();
264 return std::numeric_limits<double>::quiet_NaN();
265 }
266 const double lo = std::log(ell_lower_);
267 const double hi = std::log(ell_upper_);
268 const double sf_lo = std::log(1e-8);
269 const double sf_hi = std::log(1e6);
270 // A quadratic wall outside the admissible box keeps the unconstrained
271 // quasi-Newton iterates inside it without a second solver.
272 const auto penalised = [&](const Eigen::VectorXd& w, double& value,
273 Eigen::VectorXd& grad) {
274 require_budget();
275 Eigen::Vector2d theta(w(0), w(1));
276 Eigen::Vector2d g;
277 value = objective(theta, g);
278 grad.resize(2);
279 grad << g(0), g(1);
280 constexpr double wall = 1e3;
281 const auto box = [&](int i, double a, double b) {
282 if (theta(i) < a) {
283 value += wall * (a - theta(i)) * (a - theta(i));
284 grad(i) += -2.0 * wall * (a - theta(i));
285 } else if (theta(i) > b) {
286 value += wall * (theta(i) - b) * (theta(i) - b);
287 grad(i) += 2.0 * wall * (theta(i) - b);
288 }
289 };
290 box(0, sf_lo, sf_hi);
291 box(1, lo, hi);
292 if (!std::isfinite(value)) {
293 value = 1e300;
294 grad.setZero();
295 }
296 };
297 Eigen::VectorXd w(2);
298 w << std::log(sf2_), std::log(ell_);
299 const double start = negativeLogMarginalLikelihood();
300 if (max_iterations > 0) {
301 funcmin::RgminLbfgs solver;
302 solver.maxiter = static_cast<std::size_t>(max_iterations);
303 solver.gtol = 1e-4;
304 solver.memory = 8;
305 solver.minimize(w, penalised);
306 require_budget();
307 }
308 require_budget();
309 const double sf2 = std::exp(std::clamp(w(0), sf_lo, sf_hi));
310 const double ell = std::exp(std::clamp(w(1), lo, hi));
311 const double before_sf2 = sf2_, before_ell = ell_;
312 sf2_ = sf2;
313 ell_ = ell;
314 const double after = negativeLogMarginalLikelihood();
315 // The fit never leaves the model worse than its warm start.
316 if (!(after <= start) || !std::isfinite(after)) {
317 sf2_ = before_sf2;
318 ell_ = before_ell;
319 }
320 structure_changed_ = true;
321 conditioned_ = false;
322 require_budget();
323 condition();
324 require_budget();
326}
327
328void LocalCartesianGP::fullCondition()
329{
330 Eigen::MatrixXd K;
331 assemble(sf2_, ell_, K, nullptr);
332 Eigen::LLT<Eigen::MatrixXd> llt(K);
333 if (llt.info() != Eigen::Success) {
334 conditioned_ = false;
335 factored_obs_ = 0;
336 return;
337 }
338 L_ = llt.matrixL();
339 factored_obs_ = static_cast<Eigen::Index>(obs_.size());
340 structure_changed_ = false;
341 mean_ = meanStatistic();
342 alpha_ = L_.transpose().triangularView<Eigen::Upper>().solve(
343 L_.triangularView<Eigen::Lower>().solve(targets()));
344 conditioned_ = alpha_.allFinite();
345}
346
347bool LocalCartesianGP::appendCondition()
348{
349 const Eigen::Index b = block();
350 const Eigen::Index n_old = factored_obs_ * b;
351 const Eigen::Index count = static_cast<Eigen::Index>(obs_.size());
352 const Eigen::Index n_new = (count - factored_obs_) * b;
353 if (n_new <= 0 || n_old <= 0 || L_.rows() != n_old) return false;
354 Eigen::MatrixXd Kno(n_new, n_old), Knn(n_new, n_new);
355 for (Eigen::Index a = factored_obs_; a < count; ++a) {
356 const Eigen::Index ra = (a - factored_obs_) * b;
357 for (Eigen::Index c = 0; c < factored_obs_; ++c)
358 kernelBlock(obs_[static_cast<std::size_t>(a)],
359 obs_[static_cast<std::size_t>(c)], sf2_, ell_,
360 Kno.block(ra, c * b, b, b), nullptr);
361 for (Eigen::Index c = factored_obs_; c < count; ++c)
362 kernelBlock(obs_[static_cast<std::size_t>(a)],
363 obs_[static_cast<std::size_t>(c)], sf2_, ell_,
364 Knn.block(ra, (c - factored_obs_) * b, b, b), nullptr);
365 Knn(ra, ra) += noise_energy_ * noise_energy_;
366 for (Eigen::Index i = 1; i < b; ++i)
367 Knn(ra + i, ra + i) += noise_gradient_ * noise_gradient_;
368 }
369 // L_new = [L 0; B C] with B = Kno L^{-T} and C C^T = Knn - B B^T.
370 const Eigen::MatrixXd B =
371 L_.triangularView<Eigen::Lower>().solve(Kno.transpose()).transpose();
372 const Eigen::MatrixXd S = Knn - B * B.transpose();
373 Eigen::LLT<Eigen::MatrixXd> llt(S);
374 if (llt.info() != Eigen::Success) return false;
375 Eigen::MatrixXd L(n_old + n_new, n_old + n_new);
376 L.setZero();
377 L.topLeftCorner(n_old, n_old) = L_;
378 L.bottomLeftCorner(n_new, n_old) = B;
379 L.bottomRightCorner(n_new, n_new) = llt.matrixL();
380 L_.swap(L);
381 factored_obs_ = count;
382 mean_ = meanStatistic();
383 alpha_ = L_.transpose().triangularView<Eigen::Upper>().solve(
384 L_.triangularView<Eigen::Lower>().solve(targets()));
385 conditioned_ = alpha_.allFinite();
386 return conditioned_;
387}
388
390{
391 conditioned_ = false;
392 if (obs_.empty()) return;
393 if (!structure_changed_ && factored_obs_ > 0 &&
394 factored_obs_ <= static_cast<Eigen::Index>(obs_.size())) {
395 if (factored_obs_ == static_cast<Eigen::Index>(obs_.size())) {
396 mean_ = meanStatistic();
397 alpha_ = L_.transpose().triangularView<Eigen::Upper>().solve(
398 L_.triangularView<Eigen::Lower>().solve(targets()));
399 conditioned_ = alpha_.allFinite();
400 return;
401 }
402 if (appendCondition()) return;
403 }
404 fullCondition();
405}
406
407void LocalCartesianGP::crossBlock(const Eigen::VectorXd& x,
408 Eigen::MatrixXd& Kx) const
409{
410 // Rows: energy and local gradient at x; columns: every retained row.
411 const Eigen::Index b = block();
412 Kx.resize(b, rows());
413 Observation probe;
414 probe.x = x;
415 probe.local.resize(dim_);
416 for (Eigen::Index k = 0; k < dim_; ++k)
417 probe.local(k) = x(dofs_[static_cast<std::size_t>(k)]);
418 Eigen::Index c = 0;
419 for (const auto& o: obs_) {
420 kernelBlock(probe, o, sf2_, ell_, Kx.block(0, c, b, b), nullptr);
421 c += b;
422 }
423}
424
425void LocalCartesianGP::predict(const Eigen::VectorXd& x, double& energy,
426 Eigen::VectorXd& local_gradient) const
427{
428 local_gradient.setZero(dim_);
429 energy = mean_;
430 if (!conditioned_ || x.size() != input_dim_) return;
431 Eigen::MatrixXd Kx;
432 crossBlock(x, Kx);
433 const Eigen::VectorXd f = Kx * alpha_;
434 energy = mean_ + f(0);
435 local_gradient = f.segment(1, dim_);
436}
437
438double LocalCartesianGP::energyVariance(const Eigen::VectorXd& x) const
439{
440 if (!conditioned_ || x.size() != input_dim_) return sf2_;
441 Eigen::MatrixXd Kx;
442 crossBlock(x, Kx);
443 const Eigen::VectorXd kstar = Kx.row(0).transpose();
444 const Eigen::VectorXd v = L_.triangularView<Eigen::Lower>().solve(kstar);
446 return std::max(sf2_ - v.squaredNorm(), 0.0);
447 linalg::ExactSum pivot;
448 pivot.add(sf2_);
449 for (Eigen::Index row = 0; row < v.size(); ++row)
450 pivot.addProduct(-v(row), v(row));
451 double variance = pivot.value();
453 variance, sf2_,
454 variance < 0.0 ? linalg::denseCholeskySchurRelativeError(L_) : 0.0);
455 return variance;
456}
457
458} // namespace neb
459} // namespace gpr
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
Correctly rounded Schur-complement diagonals from Cholesky solves.
L-BFGS waist through rgmin. The loop lives in Rust.
Definition RgminLbfgs.h:25
std::size_t memory
Definition RgminLbfgs.h:30
void minimize(Eigen::VectorXd &x, EvalGrad eval_grad)
std::size_t maxiter
Definition RgminLbfgs.h:28
void addProduct(double a, double b) noexcept
Definition ExactSum.h:70
void add(double x) noexcept
Definition ExactSum.h:54
double value() const noexcept
The exact sum rounded once to the nearest double, ties to even.
Definition ExactSum.h:190
double energyVariance(const Eigen::VectorXd &x) const
Posterior energy variance at x.
Definition LocalGP.cpp:438
double negativeLogMarginalLikelihood() const
Negative log marginal likelihood at the current hyperparameters.
Definition LocalGP.cpp:249
int size() const noexcept
Definition LocalGP.h:45
void setHyperparameters(double signal_variance, double length_scale)
Seed hyperparameters before the first fit.
Definition LocalGP.cpp:57
void setLengthScaleBounds(double lower, double upper)
Admissible length scale range in input units.
Definition LocalGP.cpp:45
LocalCartesianGP(Eigen::Index input_dim, std::vector< Eigen::Index > gradient_dofs)
Definition LocalGP.cpp:18
double fit(int max_iterations, const std::function< bool()> &stop_requested={})
Definition LocalGP.cpp:255
void setNoise(double energy_sigma, double gradient_sigma)
Standard deviation of the energy and gradient channels.
Definition LocalGP.cpp:26
void setWindow(int max_observations)
Definition LocalGP.cpp:34
void setHyperparametersFromData(double factor)
Definition LocalGP.cpp:68
double objective(const Eigen::Vector2d &theta, Eigen::Vector2d &gradient) const
Definition LocalGP.cpp:210
void predict(const Eigen::VectorXd &x, double &energy, Eigen::VectorXd &local_gradient) const
Posterior mean energy and gradient on the gradient coordinates.
Definition LocalGP.cpp:425
bool add(const Eigen::VectorXd &x, double energy, const Eigen::VectorXd &local_gradient, double duplicate_distance=1e-7)
Append an observation.
Definition LocalGP.cpp:95
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
void requireStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance)
Accept one stable posterior variance or throw.
Definition ExactSchur.h:131
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40
double denseCholeskySchurRelativeError(const Eigen::MatrixBase< Derived > &factor)
choleskySchurRelativeError of a dense lower Cholesky factor.
Definition ExactSchur.h:362
The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition,...
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
STL namespace.
Observation data: energy, gradient and positions.