Loading...
Searching...
No Matches
gpr::neb::LocalCartesianGP Class Reference

Squared-exponential Gaussian process with partial gradients. More...

#include <gpr/neb/LocalGP.h>

Public Member Functions

 LocalCartesianGP (Eigen::Index input_dim, std::vector< Eigen::Index > gradient_dofs)
Eigen::Index inputDim () const noexcept
Eigen::Index gradientDim () const noexcept
const std::vector< Eigen::Index > & gradientDofs () const noexcept
int size () const noexcept
void setNoise (double energy_sigma, double gradient_sigma)
 Standard deviation of the energy and gradient channels.
void setWindow (int max_observations)
void setLengthScaleBounds (double lower, double upper)
 Admissible length scale range in input units.
void setHyperparameters (double signal_variance, double length_scale)
 Seed hyperparameters before the first fit.
void setHyperparametersFromData (double factor)
bool add (const Eigen::VectorXd &x, double energy, const Eigen::VectorXd &local_gradient, double duplicate_distance=1e-7)
 Append an observation.
double fit (int max_iterations, const std::function< bool()> &stop_requested={})
void condition ()
bool ready () const noexcept
void predict (const Eigen::VectorXd &x, double &energy, Eigen::VectorXd &local_gradient) const
 Posterior mean energy and gradient on the gradient coordinates.
double energyVariance (const Eigen::VectorXd &x) const
 Posterior energy variance at x.
double signalVariance () const noexcept
double lengthScale () const noexcept
double mean () const noexcept
double negativeLogMarginalLikelihood () const
 Negative log marginal likelihood at the current hyperparameters.
double objective (const Eigen::Vector2d &theta, Eigen::Vector2d &gradient) const

Detailed Description

Squared-exponential Gaussian process with partial gradients.

The input is the full Cartesian vector of a band image, so two images that differ only in their substrate are distinct inputs and the data stay consistent. Every observation supplies the energy and the gradient on a fixed subset of coordinates, the atoms that carry the band's motion, so an observation adds one row per local coordinate plus one. The kernel is isotropic with one length scale, the mean is the highest retained energy, and the noise is fixed per channel. The factorisation grows by appended rows between window evictions.

Definition at line 28 of file LocalGP.h.

Constructor & Destructor Documentation

◆ LocalCartesianGP()

gpr::neb::LocalCartesianGP::LocalCartesianGP ( Eigen::Index input_dim,
std::vector< Eigen::Index > gradient_dofs )

Definition at line 18 of file LocalGP.cpp.

20 : input_dim_(input_dim),
21 dim_(static_cast<Eigen::Index>(gradient_dofs.size())),
22 dofs_(std::move(gradient_dofs))
23{
24}

Member Function Documentation

◆ add()

bool gpr::neb::LocalCartesianGP::add ( const Eigen::VectorXd & x,
double energy,
const Eigen::VectorXd & local_gradient,
double duplicate_distance = 1e-7 )

Append an observation.

x is the full input and local_gradient the gradient on the gradient coordinates. An input within duplicate_distance of a retained observation replaces that observation. Nonfinite values are rejected and the model is unchanged.

Definition at line 95 of file LocalGP.cpp.

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}
@ x
Definition Enums.h:28

◆ condition()

void gpr::neb::LocalCartesianGP::condition ( )

Condition the posterior on the retained observations with the current hyperparameters, appending rows when the retained set only grew since the last conditioning.

Definition at line 389 of file LocalGP.cpp.

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}

◆ energyVariance()

double gpr::neb::LocalCartesianGP::energyVariance ( const Eigen::VectorXd & x) const

Posterior energy variance at x.

Definition at line 438 of file LocalGP.cpp.

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}
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
double variance(const Weights &w, const Matrix &covariance)

◆ fit()

double gpr::neb::LocalCartesianGP::fit ( int max_iterations,
const std::function< bool()> & stop_requested = {} )

Maximise the marginal likelihood over (signal variance, length scale) with at most max_iterations quasi-Newton iterations, then condition. Returns the negative log marginal likelihood.

Definition at line 255 of file LocalGP.cpp.

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}
std::size_t memory
Definition RgminLbfgs.h:30
void minimize(Eigen::VectorXd &x, EvalGrad eval_grad)
std::size_t maxiter
Definition RgminLbfgs.h:28
double negativeLogMarginalLikelihood() const
Negative log marginal likelihood at the current hyperparameters.
Definition LocalGP.cpp:249
double objective(const Eigen::Vector2d &theta, Eigen::Vector2d &gradient) const
Definition LocalGP.cpp:210

◆ gradientDim()

Eigen::Index gpr::neb::LocalCartesianGP::gradientDim ( ) const
inlinenoexcept

Definition at line 37 of file LocalGP.h.

38 {
39 return dim_;
40 }

◆ gradientDofs()

const std::vector< Eigen::Index > & gpr::neb::LocalCartesianGP::gradientDofs ( ) const
inlinenoexcept

Definition at line 41 of file LocalGP.h.

42 {
43 return dofs_;
44 }

◆ inputDim()

Eigen::Index gpr::neb::LocalCartesianGP::inputDim ( ) const
inlinenoexcept

Definition at line 33 of file LocalGP.h.

34 {
35 return input_dim_;
36 }

◆ lengthScale()

double gpr::neb::LocalCartesianGP::lengthScale ( ) const
inlinenoexcept

Definition at line 101 of file LocalGP.h.

102 {
103 return ell_;
104 }

◆ mean()

double gpr::neb::LocalCartesianGP::mean ( ) const
inlinenoexcept

Definition at line 105 of file LocalGP.h.

106 {
107 return mean_;
108 }

◆ negativeLogMarginalLikelihood()

double gpr::neb::LocalCartesianGP::negativeLogMarginalLikelihood ( ) const

Negative log marginal likelihood at the current hyperparameters.

Definition at line 249 of file LocalGP.cpp.

250{
251 Eigen::Vector2d g;
252 return objective(Eigen::Vector2d(std::log(sf2_), std::log(ell_)), g);
253}

◆ objective()

double gpr::neb::LocalCartesianGP::objective ( const Eigen::Vector2d & theta,
Eigen::Vector2d & gradient ) const

Negative log marginal likelihood and its gradient with respect to (log signal variance, log length scale).

Definition at line 210 of file LocalGP.cpp.

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}
@ y
Definition Enums.h:28

◆ predict()

void gpr::neb::LocalCartesianGP::predict ( const Eigen::VectorXd & x,
double & energy,
Eigen::VectorXd & local_gradient ) const

Posterior mean energy and gradient on the gradient coordinates.

Definition at line 425 of file LocalGP.cpp.

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}

◆ ready()

bool gpr::neb::LocalCartesianGP::ready ( ) const
inlinenoexcept

Definition at line 86 of file LocalGP.h.

87 {
88 return conditioned_;
89 }

◆ setHyperparameters()

void gpr::neb::LocalCartesianGP::setHyperparameters ( double signal_variance,
double length_scale )

Seed hyperparameters before the first fit.

Definition at line 57 of file LocalGP.cpp.

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}

◆ setHyperparametersFromData()

void gpr::neb::LocalCartesianGP::setHyperparametersFromData ( double factor)

Length scale from the median nearest-neighbour spacing of the retained inputs times factor, and the signal variance from the spread of the retained energies.

Definition at line 68 of file LocalGP.cpp.

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}
void setHyperparameters(double signal_variance, double length_scale)
Seed hyperparameters before the first fit.
Definition LocalGP.cpp:57

◆ setLengthScaleBounds()

void gpr::neb::LocalCartesianGP::setLengthScaleBounds ( double lower,
double upper )

Admissible length scale range in input units.

Definition at line 45 of file LocalGP.cpp.

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}

◆ setNoise()

void gpr::neb::LocalCartesianGP::setNoise ( double energy_sigma,
double gradient_sigma )

Standard deviation of the energy and gradient channels.

Definition at line 26 of file LocalGP.cpp.

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}

◆ setWindow()

void gpr::neb::LocalCartesianGP::setWindow ( int max_observations)

Retain at most this many observations; the oldest quarter leaves together once the window overflows.

Definition at line 34 of file LocalGP.cpp.

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}

◆ signalVariance()

double gpr::neb::LocalCartesianGP::signalVariance ( ) const
inlinenoexcept

Definition at line 97 of file LocalGP.h.

98 {
99 return sf2_;
100 }

◆ size()

int gpr::neb::LocalCartesianGP::size ( ) const
inlinenoexcept

Definition at line 45 of file LocalGP.h.

46 {
47 return static_cast<int>(obs_.size());
48 }

The documentation for this class was generated from the following files: