25#if defined(__has_include)
26#if !__has_include(<rgmin.h>)
27#error "gpridge requires rgmin include/rgmin.h"
32#include <rgmin/optimize.hpp>
39using detail::inlaClipToLogBox;
43inline double* destTensorData(DLManagedTensorVersioned* t)
45 return reinterpret_cast<double*
>(
46 static_cast<uint8_t*
>(t->dl_tensor.data) +
47 static_cast<std::size_t
>(t->dl_tensor.byte_offset));
51 GaussianProcessRegression* gp =
nullptr;
53 const Eigen::VectorXd* x_ind =
nullptr;
54 const Eigen::VectorXd* y =
nullptr;
55 const TrainingKernelGeometry* geom =
nullptr;
57 Eigen::VectorXd cached_theta;
58 Eigen::VectorXd cached_grad;
59 Eigen::MatrixXd cached_hessian;
60 double cached_energy = 0.0;
61 bool cache_ok =
false;
62 bool factor_ok =
false;
63 bool hessian_ok =
false;
64 funcmin::RgminCallbackFailure failure;
66 void evalAt(
const Eigen::VectorXd& theta)
68 if (gp !=
nullptr && gp->wallClockLimitReached())
69 throw WallClockLimitReached{};
70 if (cache_ok && cached_theta.size() == theta.size() &&
71 (cached_theta - theta).lpNorm<Eigen::Infinity>() == 0.0) {
77 cached_grad.resize(theta.size());
80 EnergyAndGradient eg(cached_energy, cached_grad);
81 if (geom !=
nullptr) {
82 gp->evaluateEnergyAndGradientFromGeometry(theta, *geom, *x, *x_ind,
85 gp->evaluateEnergyAndGradient(theta, *x, *x_ind, *y, eg);
87 cached_grad = eg.gradient;
90 std::isfinite(cached_energy) && gp->isDecomposedSuccessfully() &&
91 cached_grad.size() == theta.size() && cached_grad.allFinite();
95rgmin_status_t inlaEvalGrad(
void*
user,
const DLManagedTensorVersioned*
x,
97 DLManagedTensorVersioned* grad_out)
noexcept
99 auto* ctx =
static_cast<InlaDestCtx*
>(
user);
101 *value_out = std::numeric_limits<double>::infinity();
102 gout.setConstant(std::numeric_limits<double>::quiet_NaN());
103 return ctx->failure.invoke(
"INLA objective", [&] {
105 if (!ctx->factor_ok)
return RGMIN_SUCCESS;
106 *value_out = ctx->cached_energy;
107 gout = ctx->cached_grad;
108 return RGMIN_SUCCESS;
112rgmin_status_t inlaHess(
void*
user,
const DLManagedTensorVersioned*
x,
113 DLManagedTensorVersioned* hess_out)
noexcept
115 auto* ctx =
static_cast<InlaDestCtx*
>(
user);
117 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
118 hout(destTensorData(hess_out), ctx->p, ctx->p);
119 hout.setConstant(std::numeric_limits<double>::quiet_NaN());
120 return ctx->failure.invoke(
"INLA Hessian", [&] {
123 const bool assembled = ctx->factor_ok &&
124 ctx->gp->assembleExactHessian(
125 *ctx->x_ind, *ctx->x, *ctx->y, ctx->p, H) &&
126 H.rows() == ctx->p && H.cols() == ctx->p &&
129 ctx->cached_hessian = H;
130 ctx->hessian_ok =
true;
132 H = Eigen::MatrixXd::Identity(ctx->p, ctx->p);
133 ctx->hessian_ok =
false;
136 return RGMIN_SUCCESS;
144 double floor = std::max(1.0e-6, range_x * 1.0e-3);
145 if (!ls_seed_chemical_floor_ || !std::isfinite(floor))
return floor;
147 const Eigen::VectorXd chemical =
149 double covalent = 0.0;
150 for (Eigen::Index k = 0; k < chemical.size(); ++k) {
151 if (!std::isfinite(chemical(k)) || !(chemical(k) > 0.0))
continue;
153 covalent == 0.0 ? chemical(k) : std::min(covalent, chemical(k));
155 if (covalent > 0.0) floor = std::max(floor, covalent);
166 const Eigen::VectorXd& theta_seed)
const
168 const Eigen::Index columns =
x.cols();
169 Eigen::Index energies = columns > 0 ?
y.size() / columns : 0;
170 if (!(energies > 0 && energies <
y.size() &&
171 energies * columns ==
y.size()))
173 const Eigen::Index covariance_parameters =
174 hasTrailingLikelihoodNoiseParameter(theta_seed) ? theta_seed.size() - 1
177 x, energies,
y, theta_seed.head(covariance_parameters)));
181 const Eigen::VectorXd& theta_seed,
const double min_lengthscale,
182 const double max_log_magn_sigma2, Eigen::VectorXd& lower,
183 Eigen::VectorXd& upper)
const
189 lower.resize(theta_seed.size());
190 upper.resize(theta_seed.size());
194 const double amplitude_scale2 =
195 (amplitude_prior.
getS2() > 0.0) ? amplitude_prior.
getS2() : 1.0;
196 lower(0) = std::log(std::max(1.0e-12, 1.0e-6 * amplitude_scale2));
197 upper(0) = max_log_magn_sigma2;
198 if (lower(0) >= upper(0)) lower(0) = upper(0) - std::log(1.0e6);
202 const double prior_length_scale =
203 (length_prior.
getS2() > 0.0) ? std::sqrt(length_prior.
getS2()) : 1.0;
204 const double length_center = std::abs(length_prior.
getMu());
205 const double lower_length = std::max(1.0e-6, min_lengthscale);
206 const double upper_length =
207 std::max({10.0 * lower_length,
208 length_center + 30.0 * prior_length_scale, 1.0e-2});
210 const bool has_noise = hasTrailingLikelihoodNoiseParameter(theta_seed);
211 const Eigen::Index length_end =
212 has_noise ? theta_seed.size() - 1 : theta_seed.size();
213 for (Eigen::Index i = 1; i < length_end; ++i) {
214 lower(i) = std::log(lower_length);
215 upper(i) = std::log(upper_length);
216 if (lower(i) >= upper(i)) lower(i) = upper(i) - std::log(1.0e6);
220 const Eigen::Index noise_idx = theta_seed.size() - 1;
221 const double seed_noise = std::exp(theta_seed(noise_idx));
222 const double lower_noise =
223 std::max(1.0e-12, std::min(seed_noise * 1.0e-4, 1.0e-8));
224 const double upper_noise =
225 std::max({1.0e-2, seed_noise * 1.0e4, lower_noise * 1.0e6});
226 lower(noise_idx) = std::log(lower_noise);
227 upper(noise_idx) = std::log(upper_noise);
228 if (lower(noise_idx) >= upper(noise_idx)) {
229 lower(noise_idx) = upper(noise_idx) - std::log(1.0e6);
236 const Eigen::VectorXd&
y, Eigen::VectorXd& theta_mode,
239 theta_mode.resize(0);
246 if (theta_seed.size() == 0 || !theta_seed.allFinite())
return false;
250 unit_lengthscale.setConstant(1.0);
251 const double range_x = distance.
range_at(
x, atoms_config, unit_lengthscale);
253 Eigen::VectorXd lower;
254 Eigen::VectorXd upper;
258 const int p =
static_cast<int>(theta_seed.size());
259 if (lower.size() != p || upper.size() != p)
return false;
261 auto clip_to_bounds = [&](
const Eigen::VectorXd& theta) {
262 return inlaClipToLogBox(theta, lower, upper);
267 const bool can_warm_start = inla_warm_valid_ &&
268 inla_warm_theta_.size() == p &&
269 inla_warm_theta_.allFinite();
270 Eigen::VectorXd theta =
271 clip_to_bounds(can_warm_start ? inla_warm_theta_ : theta_seed);
272 if (theta.size() != p || !theta.allFinite())
return false;
273 if (can_warm_start) {
274 ++inla_warm_start_hits_for_testing_;
276 ++inla_warm_start_misses_for_testing_;
279 constexpr int kMaxIterations = 10;
280 constexpr double kGradientTolerance = 1.0e-4;
281 constexpr double kTrustRadius = 3.0;
283 std::vector<double> wbuf(
static_cast<std::size_t
>(p));
284 Eigen::Map<Eigen::VectorXd>(wbuf.data(), p) = theta;
287 rgmin_tensor_borrow_cpu_f64(wbuf.data(), wbuf.size()));
288 if (!xt)
return false;
295 ctx.geom = training_geom;
299 ctrl.maxiter =
static_cast<std::size_t
>(kMaxIterations);
300 ctrl.gtol = kGradientTolerance;
306 Eigen::VectorXd best_theta = theta;
307 double best_phi = std::numeric_limits<double>::infinity();
308 Eigen::MatrixXd inverse_hessian = Eigen::MatrixXd::Identity(p, p);
309 ctx.failure.invoke(
"INLA initial objective", [&] {
311 return RGMIN_SUCCESS;
313 if (ctx.failure.failed() || !ctx.factor_ok) {
314 ctx.failure.report();
317 best_phi = ctx.cached_energy;
319 rgmin::Solver session(rgmin::Method::Rfo, ctrl,
320 static_cast<std::size_t
>(p));
321 session.set_accept(RGMIN_ACCEPT_ENERGY);
322 if (session.set_highs(
true) != 0 ||
323 session.set_box(lower.data(), upper.data(),
324 static_cast<std::size_t
>(p)) != 0) {
327 session.set_trust(kTrustRadius);
329 rgmin::Report report{};
330 for (
int iter = 0; iter < kMaxIterations; ++iter) {
332 last_inla_iterations_ =
static_cast<std::size_t
>(iter + 1);
334 session.step_hess_fg(&inlaEvalGrad, &inlaHess, &ctx, xt.get());
335 if (ctx.failure.failed()) {
336 ctx.failure.report();
339 Eigen::Map<const Eigen::VectorXd> walked(wbuf.data(), p);
340 if (walked.size() == p && walked.allFinite() &&
341 std::isfinite(report.value) && report.value < best_phi) {
342 best_phi = report.value;
345 if (report.grad_norm <=
346 kGradientTolerance * (1.0 + std::abs(report.value))) {
351 ctx.failure.report();
356 if (best_theta.size() != p || !best_theta.allFinite()) {
359 for (
int i = 0; i < p; ++i) {
360 if (best_theta(i) < lower(i) - 1.0e-12 ||
361 best_theta(i) > upper(i) + 1.0e-12) {
366 if (!std::isfinite(best_phi) || best_theta.size() != p ||
367 !best_theta.allFinite()) {
376 theta_mode = best_theta;
377 if (retain_fitted_hyperparameter_density_) {
383 const Eigen::Index configurations = (x_ind.array() == 0.0).count();
384 const Eigen::Index dimensions =
385 static_cast<Eigen::Index
>(x_ind.maxCoeff());
387 if (dimensions > 0 && dimensions <=
x.cols())
388 fit_positions =
x.topLeftCorner(configurations, dimensions);
390 density_config, 1.0,
false);
392 if (best_theta.size() == p && best_theta.allFinite() &&
393 inverse_hessian.rows() == p && inverse_hessian.cols() == p &&
394 inverse_hessian.allFinite()) {
395 inla_warm_theta_ = best_theta;
396 inla_warm_inverse_hessian_ = inverse_hessian;
397 inla_warm_valid_ =
true;
405 failedOptimizer =
false;
408 failedOptimizer =
true;
409 last_fit_stop_reason_ =
"wall-clock limit";
418 Eigen::VectorXd opt_R_indices;
419 Eigen::VectorXd opt_energy_and_gradient;
421 opt_R_matrix, opt_R_indices);
423 opt_energy_and_gradient);
424 subtractPriorMeanFromTargets(optimization_observation.
R,
425 optimization_observation.
E.size(),
426 opt_energy_and_gradient);
427 standardizeTargets(opt_energy_and_gradient,
428 optimization_observation.
E.size());
443 optimization_observation.
R);
451 const bool inla_geom_ready =
455 inla_geom_ready ? &inla_geom :
nullptr;
457 Eigen::VectorXd theta_mode;
459 opt_energy_and_gradient,
460 theta_mode, inla_geom_ptr);
467 failedOptimizer =
true;
470 last_fit_stop_reason_ =
"wall-clock limit";
479 failedOptimizer =
true;
480 last_fit_stop_reason_ =
"wall-clock limit";
486 failedOptimizer =
true;
INLA-style Laplace approximation of the GP/TP hyperparameter posterior.
Some auxiliary functions.
void assembleVectorFromEnergyAndGradient(const gpr::Observation &observation, Eigen::VectorXd &vector)
Combine Energy and gradient into a single Eigen vector.
void assembleMatrixOfRepetitiveCoordinates(const gpr::Coord &coord, gpr::EigenMatrix &matrix, Eigen::VectorXd &ind)
Assemble Eigen matrix with repetitive rows based on provided set of coordinates R.
Methods to calculate distances between atoms.
double range_at(const gpr::Coord &positions, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale)
Observation selectOptimizationSubset(const Observation &full_observation) const
Select a hyperparameter-optimization subset via FPS-EMD.
double evaluateEnergy(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
void setParameters(const GPRSetup ¶meters)
Set parameters of the GPR model.
bool prepareTrainingKernelGeometry(const EigenMatrix &x, const Eigen::VectorXd &x_ind, TrainingKernelGeometry &out, bool reused=false) const
bool is_decomposed_succesfully
bool computeInlaPosteriorMode(const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &theta_mode, const TrainingKernelGeometry *training_geom)
bool wallClockLimitReached() const
Collective on the model's process group for distributed fitters.
void calculateInlaModeLogBounds(const Eigen::VectorXd &theta_seed, double min_lengthscale, double max_log_magn_sigma2, Eigen::VectorXd &lower, Eigen::VectorXd &upper) const
std::unique_ptr< SexpatCF > sexpat_cov_func
Eigen::VectorXd packInlaHyperparameters() const
void captureFittedHyperparameterDensity(const Coord &positions, const Eigen::VectorXd &targets, const Eigen::VectorXd &theta, const funcmin::MapObjectiveConfig &penalty, double target_scale, bool use_ties)
void optimizeLaplaceINLA(const Observation &observation)
void updateModelWithFullData(const Observation &full_observation)
bool canUseTrainingGeometryObjective() const noexcept
double inlaMinimumLengthScale(double range_x) const
double inlaMaxLogMagnSigma2(const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &theta_seed) const
Class of prior parameters.
Eigen::VectorXd lengthScalePerPairtype() const
eon_relax_band_t eon_relax_surface_fn void * user
double mapMaxLogMagnSigma2(double signal_variance) noexcept
Eigen::Map< const Eigen::VectorXd > tensorToVec(const DLManagedTensorVersioned *tensor)
std::unique_ptr< DLManagedTensorVersioned, RgminTensorDeleter > RgminTensorHandle
double mapRobustSignalVarianceAnchor(const gpr::EigenMatrix &x, Eigen::Index n_e, const Eigen::VectorXd &y, const Eigen::VectorXd &w)
void requireCompatibleLibrary()
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
double barrier_strength
Already capped with min(current_barrier_strength, 0.5) by the caller.
Eigen::VectorXd parameter_lower
Eigen::VectorXd parameter_upper
gpr::MapPriorWeightMode weight_mode
Observation data: energy, gradient and positions.