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))
28 noise_energy_ = std::max(energy_sigma, 1e-8);
29 noise_gradient_ = std::max(gradient_sigma, 1e-8);
31 structure_changed_ =
true;
36 window_ = std::max(2, max_observations);
37 if (
static_cast<int>(obs_.size()) > window_) {
38 while (
static_cast<int>(obs_.size()) > window_)
40 structure_changed_ =
true;
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_) {
52 structure_changed_ =
true;
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_);
65 structure_changed_ =
true;
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) {
79 best = std::min(best, (obs_[a].
x - obs_[b].
x).norm());
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);
85 if (nearest.empty())
return;
86 std::nth_element(nearest.begin(),
87 nearest.begin() +
static_cast<long>(nearest.size() / 2),
89 const double spacing = nearest[nearest.size() / 2];
90 const double half_spread = 0.5 * (e_max - e_min);
92 std::max(factor, 1.0) * spacing);
96 const Eigen::VectorXd& local_gradient,
97 double duplicate_distance)
99 if (
x.size() != input_dim_ || local_gradient.size() != dim_)
return false;
100 if (!std::isfinite(energy) || !
x.allFinite() || !local_gradient.allFinite())
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) {
110 o.gradient = local_gradient;
111 conditioned_ =
false;
112 structure_changed_ =
true;
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)
121 structure_changed_ =
true;
123 conditioned_ =
false;
127double LocalCartesianGP::meanStatistic()
const
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;
139Eigen::VectorXd LocalCartesianGP::targets()
const
141 Eigen::VectorXd
y(rows());
142 const double m = meanStatistic();
144 for (
const auto& o: obs_) {
146 y.segment(r + 1, dim_) = o.gradient;
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
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;
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;
168 Eigen::MatrixXd& d = *dout;
169 d.resize(block(), block());
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;
179void LocalCartesianGP::assemble(
double sf2,
double ell, Eigen::MatrixXd& K,
180 Eigen::MatrixXd* dK_dlogell)
const
182 const Eigen::Index n = rows();
183 const Eigen::Index b = block();
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;
196 K.block(c * b, a * b, b, b) =
197 K.block(a * b, c * b, b, b).transpose();
199 dK_dlogell->block(c * b, a * b, b, b) = dblock.transpose();
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_;
211 Eigen::Vector2d& gradient)
const
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) {
221 return std::numeric_limits<double>::infinity();
223 const Eigen::VectorXd
y = targets();
224 const Eigen::VectorXd alpha = llt.solve(
y);
225 const Eigen::MatrixXd L = llt.matrixL();
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));
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_;
240 const auto grad_for = [&](
const Eigen::MatrixXd& dKm) {
241 return -0.5 * alpha.dot(dKm * alpha) +
242 0.5 * (Kinv.cwiseProduct(dKm)).sum();
244 gradient(0) = grad_for(dKs);
245 gradient(1) = grad_for(dK);
252 return objective(Eigen::Vector2d(std::log(sf2_), std::log(ell_)), g);
256 const std::function<
bool()>& stop_requested)
258 const auto require_budget = [&] {
262 if (obs_.size() < 2) {
264 return std::numeric_limits<double>::quiet_NaN();
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);
272 const auto penalised = [&](
const Eigen::VectorXd& w,
double& value,
273 Eigen::VectorXd& grad) {
275 Eigen::Vector2d theta(w(0), w(1));
280 constexpr double wall = 1e3;
281 const auto box = [&](
int i,
double a,
double b) {
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);
290 box(0, sf_lo, sf_hi);
292 if (!std::isfinite(value)) {
297 Eigen::VectorXd w(2);
298 w << std::log(sf2_), std::log(ell_);
300 if (max_iterations > 0) {
302 solver.
maxiter =
static_cast<std::size_t
>(max_iterations);
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_;
316 if (!(after <= start) || !std::isfinite(after)) {
320 structure_changed_ =
true;
321 conditioned_ =
false;
328void LocalCartesianGP::fullCondition()
331 assemble(sf2_, ell_, K,
nullptr);
332 Eigen::LLT<Eigen::MatrixXd> llt(K);
333 if (llt.info() != Eigen::Success) {
334 conditioned_ =
false;
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();
347bool LocalCartesianGP::appendCondition()
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_;
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);
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();
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();
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();
402 if (appendCondition())
return;
407void LocalCartesianGP::crossBlock(
const Eigen::VectorXd&
x,
408 Eigen::MatrixXd& Kx)
const
411 const Eigen::Index b = block();
412 Kx.resize(b, rows());
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)]);
419 for (
const auto& o: obs_) {
420 kernelBlock(probe, o, sf2_, ell_, Kx.block(0, c, b, b),
nullptr);
426 Eigen::VectorXd& local_gradient)
const
428 local_gradient.setZero(dim_);
430 if (!conditioned_ ||
x.size() != input_dim_)
return;
433 const Eigen::VectorXd f = Kx * alpha_;
434 energy = mean_ + f(0);
435 local_gradient = f.segment(1, dim_);
440 if (!conditioned_ ||
x.size() != input_dim_)
return sf2_;
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);
449 for (Eigen::Index row = 0; row < v.size(); ++row)
451 double variance = pivot.
value();
Correctly rounded Schur-complement diagonals from Cholesky solves.
L-BFGS waist through rgmin. The loop lives in Rust.
void minimize(Eigen::VectorXd &x, EvalGrad eval_grad)
void addProduct(double a, double b) noexcept
void add(double x) noexcept
double value() const noexcept
The exact sum rounded once to the nearest double, ties to even.
double energyVariance(const Eigen::VectorXd &x) const
Posterior energy variance at x.
double negativeLogMarginalLikelihood() const
Negative log marginal likelihood at the current hyperparameters.
int size() const noexcept
void setHyperparameters(double signal_variance, double length_scale)
Seed hyperparameters before the first fit.
void setLengthScaleBounds(double lower, double upper)
Admissible length scale range in input units.
LocalCartesianGP(Eigen::Index input_dim, std::vector< Eigen::Index > gradient_dofs)
double fit(int max_iterations, const std::function< bool()> &stop_requested={})
void setNoise(double energy_sigma, double gradient_sigma)
Standard deviation of the energy and gradient channels.
void setWindow(int max_observations)
void setHyperparametersFromData(double factor)
double objective(const Eigen::Vector2d &theta, Eigen::Vector2d &gradient) const
void predict(const Eigen::VectorXd &x, double &energy, Eigen::VectorXd &local_gradient) const
Posterior mean energy and gradient on the gradient coordinates.
bool add(const Eigen::VectorXd &x, double energy, const Eigen::VectorXd &local_gradient, double duplicate_distance=1e-7)
Append an observation.
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.
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
double denseCholeskySchurRelativeError(const Eigen::MatrixBase< Derived > &factor)
choleskySchurRelativeError of a dense lower Cholesky factor.
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.
Observation data: energy, gradient and positions.