Loading...
Searching...
No Matches
GaussianProcessRegression.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/*
6 * GaussianProcessRegression.cpp
7 *
8 * Created on: 3 Nov 2020
9 * Author: Maxim Masterov
10 * Company: SURFSara
11 */
12
14
15#include <cstdio>
16
21#include "PhaseTimers.h"
22
23#ifdef GPR_PREDICT_VIA_PCG
25#endif
26
31#include "JointObservation.h"
32#include "LaplaceINLA.h"
33#include "NoiseGridSearch.h"
34#include "gp/Helpers.h"
36#include "gp/OptimizerState.h"
37#include "gpr/Enums.h"
40#include "gpr/linalg/Backend.h"
51#ifdef GPR_LINALG_SCALAPACK
52#include <mpi.h>
53
55#endif
56
57#define EIGEN_NO_DEBUG
58#include <Eigen/Core>
59#include <algorithm>
60#include <array>
61#include <cfloat>
62#include <chrono>
63#include <cmath>
64#include <cstdlib>
65#include <functional>
66#include <limits>
67#include <stdexcept>
68#include <string>
69#include <type_traits>
70#include <unordered_set>
71#include <vector>
72
76
77namespace gpr {
78
79void GaussianProcessRegression::configureDistributedTrainingGrid() noexcept
80{
81#ifdef GPR_LINALG_SCALAPACK
82 // The training paths pass the observation stride to initialize; it
83 // describes the derivative layout. SLATE and the reproducible tile
84 // kernels compute on the automatic computation tile unless the caller
85 // chooses a block, and the ScaLAPACK library routines keep the stride.
86 backend().distributed().configure(scalapack_block_size_, scalapack_nprow_,
87 /*computation_tile=*/true);
88#endif
89}
90
91using namespace detail;
92
93// Definitions of LaplacePosteriorStamp, LaplacePosteriorSignature,
94// LaplacePosteriorState, and SliceLaplaceState live in
95// gp/LaplacePosteriorTypes.h (included above).
96
98 : optimizer_state_(std::make_unique<OptimizerState>()),
99 backend_context_(std::make_shared<linalg::BackendContext>())
100{
101 hssvd_basis_ = StableBasisND(backend_context_);
102 sigma2 = 1e-7;
103 jitter_sigma2 = 1e-6;
104 optimization_alg = INLA_opt;
105 report_level = 0;
106
107 lik_gaussian = std::make_unique<LikGaussian>();
108 const_cov_fun = std::make_unique<ConstantCF>();
109 sexpat_cov_func = std::make_unique<SexpatCF>();
110
113 num_of_potential_calls = 0;
114 failedOptimizer = false;
115 fps_options.history = 5;
116 fps_options.latest_points = 2;
117 fps_options.metric = DistanceMetricType::EMD;
118 selectHyperparameterOptimizer(hyperparameter_optimization_mode_);
119}
120
122
124 std::shared_ptr<const KernelOperator> kernel)
125{
126 optimizer_state_->mean_hessian.map_kernel = std::move(kernel);
127}
128
130 bool override) noexcept
131{
132 optimizer_state_->mean_hessian.map_kernel_overrides_hssvd = override;
133}
134
136 MeanHessianPreparation background, bool background_exact,
137 MeanHessianPreparation residual, bool residual_exact)
138{
139 if (!active_posterior_ || !background) return false;
140 auto& hook = optimizer_state_->mean_hessian;
141 hook.active_posterior_actions = true;
142 hook.background = std::move(background);
143 hook.background_exact = background_exact;
144 hook.residual = std::move(residual);
145 hook.residual_exact = residual_exact;
146 return true;
147}
148
150 bool fail) const noexcept
151{
152 optimizer_state_->mean_hessian.hssvd_block_apply_fails = fail;
153}
154
156 const noexcept
157{
158 optimizer_state_->mean_hessian.dispatched_map_hessian_actions = 0;
159}
160
161std::size_t
163 const noexcept
164{
165 return optimizer_state_->mean_hessian.dispatched_map_hessian_actions;
166}
167
169 const Eigen::VectorXd& point, const Eigen::MatrixXd& hessian)
170{
171 if (!optimizer_state_) return;
172 auto& entries = optimizer_state_->conditioned_hessians;
173 for (auto& entry: entries) {
174 if (entry.point.size() == point.size() &&
175 (entry.point - point).lpNorm<Eigen::Infinity>() <=
176 1e-12 * std::max(1.0, point.lpNorm<Eigen::Infinity>())) {
177 entry.point = point;
178 entry.hessian = hessian;
179 return;
180 }
181 }
182 entries.push_back({point, hessian});
183}
184
186{
187 if (optimizer_state_) optimizer_state_->conditioned_hessians.clear();
188}
189
191 const Eigen::VectorXd& point, Eigen::MatrixXd& hessian_out) const
192{
193 if (!optimizer_state_) return false;
194 const auto& entries = optimizer_state_->conditioned_hessians;
195 for (auto it = entries.rbegin(); it != entries.rend(); ++it) {
196 if (it->point.size() == point.size() &&
197 (it->point - point).lpNorm<Eigen::Infinity>() <=
198 1e-12 * std::max(1.0, point.lpNorm<Eigen::Infinity>())) {
199 hessian_out = it->hessian;
200 return true;
201 }
202 }
203 return false;
204}
205
207 std::shared_ptr<const linalg::MpiCommunicator> communication)
209{
210 backend_context_ = std::make_shared<linalg::BackendContext>(communication);
211 rff_model_ = RFFModel(std::move(communication));
212 hssvd_basis_ = StableBasisND(backend_context_);
213}
214
215static_assert(RGMIN_LBFGS == 3,
216 "rgmin_method_ stores RGMIN_LBFGS as the integer 3");
217
218void GaussianProcessRegression::setRgminMethod(rgmin_method_t method) noexcept
219{
220 rgmin_method_ = method;
221 rgmin_method_set_ = true;
222 if (auto* optimizer =
223 std::get_if<funcmin::RgminOpt>(&optimizer_state_->optimizer))
224 optimizer->setMethod(method);
225}
226
228 const noexcept
229{
230 const auto& optimizer = optimizer_state_->optimizer;
231 if (std::holds_alternative<funcmin::RgminScg>(optimizer) ||
232 std::holds_alternative<funcmin::RgminOpt>(optimizer))
233 return "rgmin";
234#ifdef USE_CERES
235 if (std::holds_alternative<funcmin::Ceres>(optimizer)) return "ceres";
236#endif
237 return "builtin";
238}
239
240void GaussianProcessRegression::selectHyperparameterOptimizer(
241 HyperparameterOptimizationMode mode) noexcept
242{
243 hyperparameter_optimization_mode_ = mode;
244 scg_stalled_ = false;
245 scg_stall_scope_ = {};
246 optimization_alg =
250 optimizer_state_->optimizer.emplace<funcmin::RgminOpt>();
251 std::get<funcmin::RgminOpt>(optimizer_state_->optimizer)
253 rgmin_method_set_
254 ? static_cast<rgmin_method_t>(rgmin_method_)
255 : RGMIN_LBFGS);
256 } else {
257 optimizer_state_->optimizer.emplace<funcmin::RgminScg>();
258 }
259}
260
262 HyperparameterOptimizationMode mode) noexcept
263{
264 hyperparameter_mode_override_ = mode;
265 selectHyperparameterOptimizer(mode);
266 ++laplace_model_revision_;
267}
268
269void GaussianProcessRegression::invalidateLikelihoodNoiseDependentState()
270{
271 // A caller-supplied physical Hessian is not a likelihood-noise cache.
272 // gpr_htst_half keeps using it after set_sigma2.
273 full_cartesian_training_dimension_ = -1;
274 if (atomic_environment_posterior_)
275 atomic_environment_posterior_->invalidate();
276 ++laplace_model_revision_;
277 laplace_posterior_.reset();
278 slice_laplace_state_.reset();
279 invalidateObjectiveStationarityHessian();
280 objective_stationarity_bb_dimension_ = 0;
281 objective_stationarity_bb_inverse_scale_ = 0.0;
282 objective_stationarity_bb_valid_ = false;
283 inla_warm_theta_.resize(0);
284 inla_warm_inverse_hessian_.resize(0, 0);
285 inla_warm_valid_ = false;
286 clearHssvdBasisState();
287 hssvd_objective_trace_via_cholesky_ = false;
288
291 C.resize(0, 0);
293 a.resize(0);
294 b.resize(0);
295 rff_features_ = 0;
296 rff_replaces_exact_ = false;
297
298#ifdef GPR_LINALG_SCALAPACK
299 auto& distributed_state = backend().distributed();
300 if (distributed_state.cached_L_owned_by(this)) {
301 distributed_state.invalidate_L();
302 }
303 distributed_state.invalidate_inv();
304 training_cholesky_is_distributed_ = false;
305 parked_training_cholesky_.clear();
306#endif
307}
308
311 double physical_sigma2, const Observation* full_observation)
312{
313 if (!std::isfinite(physical_sigma2) || !(physical_sigma2 > 0.0) ||
314 lik_gaussian == nullptr) {
316 }
317
318 const double training_sigma2 =
319 physicalToTrainingNoiseVariance(physical_sigma2);
320 if (!std::isfinite(training_sigma2) || !(training_sigma2 > 0.0)) {
322 }
323
324 const double current_training_sigma2 = lik_gaussian->getSigma2();
325 const bool representations_match =
326 std::isfinite(sigma2) && sigma2 == physical_sigma2 &&
327 std::isfinite(current_training_sigma2) &&
328 current_training_sigma2 == training_sigma2;
329 if (representations_match) {
331 }
332
333 const bool rebuild_layered_rff =
334 rff_features_ > 0 && !rff_replaces_exact_ && rff_model_.isBuilt();
335 lik_gaussian->setSigma2(training_sigma2);
336 sigma2 = physical_sigma2;
337 if (atomic_environment_model_ && atomic_environment_parameters_.size() >= 2)
338 atomic_environment_parameters_.tail(2).setConstant(
339 std::log(physical_sigma2));
340 invalidateLikelihoodNoiseDependentState();
341
342 if (full_observation == nullptr) {
344 }
345
346 updateModelWithFullData(*full_observation);
347 // buildRFFModel fits the residual of every prior mean, so no prior keeps
348 // the layered features from being rebuilt on the new noise.
349 if (rebuild_layered_rff && !rff_replaces_exact_ &&
350 is_decomposed_succesfully && rff_features_requested_ > 0 &&
351 full_observation->E.size() > 0) {
352 buildRFFModel(*full_observation, rff_features_requested_);
353 }
355}
356
358 double floor_sigma2, const Observation& full_observation)
359{
360 if (!std::isfinite(floor_sigma2) || !(floor_sigma2 > 0.0) ||
361 lik_gaussian == nullptr) {
362 return false;
363 }
364
365 const double current_training_sigma2 = lik_gaussian->getSigma2();
366 double effective_physical_sigma2 = floor_sigma2;
367 if (std::isfinite(current_training_sigma2) &&
368 current_training_sigma2 > 0.0) {
369 const double current_physical_sigma2 =
370 trainingToPhysicalNoiseVariance(current_training_sigma2);
371 if (std::isfinite(current_physical_sigma2) &&
372 current_physical_sigma2 > effective_physical_sigma2) {
373 effective_physical_sigma2 = current_physical_sigma2;
374 }
375 }
376
377 return setLikelihoodNoiseVariance(effective_physical_sigma2,
378 full_observation) ==
380}
381
382void GaussianProcessRegression::recordEnergyProfileSplit(
383 const double covariance_seconds, const double factor_seconds,
384 const double posterior_seconds) noexcept
385{
386 ++profile_split_totals_.energy_calls;
387 profile_split_totals_.energy_covariance_seconds += covariance_seconds;
388 profile_split_totals_.energy_factor_seconds += factor_seconds;
389 profile_split_totals_.energy_posterior_seconds += posterior_seconds;
390}
391
392void GaussianProcessRegression::recordGradientProfileSplit(
393 const double alpha_seconds, const double inverse_seconds,
394 const double const_seconds, const double sexpat_seconds) noexcept
395{
396 ++profile_split_totals_.gradient_calls;
397 profile_split_totals_.gradient_alpha_seconds += alpha_seconds;
398 profile_split_totals_.gradient_inverse_seconds += inverse_seconds;
399 profile_split_totals_.gradient_const_seconds += const_seconds;
400 profile_split_totals_.gradient_sexpat_seconds += sexpat_seconds;
401}
402
404{
405 if (profile_split_totals_.energy_calls == 0 &&
406 profile_split_totals_.gradient_calls == 0) {
407 return;
408 }
409
410#ifdef GPR_LINALG_SCALAPACK
411 if (!backend().distributed().is_root()) return;
412#endif
413
414 log_man << "GP profile split summary:\n";
415 log_man << " Energy objective: covariance="
416 << profile_split_totals_.energy_covariance_seconds
417 << "s factor=" << profile_split_totals_.energy_factor_seconds
418 << "s posterior=" << profile_split_totals_.energy_posterior_seconds
419 << "s energy_calls=" << profile_split_totals_.energy_calls << "\n";
420 log_man << " Gradient objective: alpha_solve="
421 << profile_split_totals_.gradient_alpha_seconds
422 << "s inverse_cache="
423 << profile_split_totals_.gradient_inverse_seconds
424 << "s const_cf=" << profile_split_totals_.gradient_const_seconds
425 << "s sexpat_cf=" << profile_split_totals_.gradient_sexpat_seconds
426 << "s gradient_calls=" << profile_split_totals_.gradient_calls
427 << "\n";
428}
429
431 const Eigen::VectorXd& x_ind)
432{
433#ifdef GPR_LINALG_SCALAPACK
434 // Match the observation-tile size so the trainstep gradient can take the
435 // observation-tiled fast path (one row per stored channel). Grid
436 // shape stays the DistributedState default (near-square): a forced 1D
437 // nprow=nprocs grid was measured to anti-scale the pure-CPU HostTask
438 // trainstep at np>=8 relative to the square grid.
439 const int tile_size =
440 static_cast<int>(detail::storedObservationChannelCount(x_ind));
441 if (tile_size > 0) backend().distributed().initialize(tile_size);
443#else
445#endif
446}
447
449 const Eigen::VectorXd& x_ind)
450{
451 if (x_ind.size() == 0) {
454 return;
455 }
458 static_cast<Eigen::Index>(training_permutation_.perm.size()) ==
459 x_ind.size();
460}
461
466
468{
469 if (sexpat_cov_func == nullptr) return 0;
470 return 1 + sexpat_cov_func->getLengthScaleRef().size();
471}
472
473bool GaussianProcessRegression::hasTrailingLikelihoodNoiseParameter(
474 const Eigen::VectorXd& w) const
475{
476 const Eigen::Index n_cov = covarianceParameterCount();
477 return n_cov > 0 && w.size() > n_cov;
478}
479
481 const noexcept
482{
483 return theta_includes_likelihood_noise_;
484}
485
487{
488 const double lik_noise =
489 lik_gaussian != nullptr ? lik_gaussian->getSigma2() : 0.0;
490 return (lik_noise > 0.0) ? lik_noise
491 : physicalToTrainingNoiseVariance(sigma2);
492}
493
495{
496 if (sexpat_cov_func == nullptr) return {};
497 Eigen::VectorXd theta = sexpat_cov_func->combineParameters();
498 if (!theta_includes_likelihood_noise_) return theta;
499
500 const double noise = likelihoodNoiseVariance();
501 if (!(noise > 0.0)) return {};
502
503 Eigen::VectorXd packed(theta.size() + 1);
504 packed.head(theta.size()) = theta;
505 packed(packed.size() - 1) = numerics::log(noise);
506 return packed;
507}
508
510{
511 detail::validateRigidNullDeflationConfiguration(enabled,
512 principled_nugget_);
513 if (enabled == use_rigid_null_deflation_) return;
516 clearHssvdBasisState();
517 hssvd_basis_ = StableBasisND{};
519 active_posterior_.reset();
520 ++laplace_model_revision_;
521}
522
524{
525 detail::validateRigidNullDeflationConfiguration(use_rigid_null_deflation_,
526 use);
527 principled_nugget_ = use;
528}
529
530void GaussianProcessRegression::appendLikelihoodNoiseGradient(
531 const Eigen::VectorXd& alpha, const EigenMatrix& invC,
532 const EigenMatrix& L_factor, const bool use_solve_based_trace,
533 FieldMatrixd& gdata, FieldMatrixd& gprior,
534 const detail::RigidDeflationState* deflation_override) const
535{
536 if (!theta_includes_likelihood_noise_ || alpha.size() == 0) return;
537
538 const detail::RigidDeflationState& active_deflation =
539 deflation_override != nullptr ? *deflation_override : rigid_deflation_;
540
541 // A dense factor takes the rank-local Eigen trace below, so this
542 // flag only selects the collective cache trace.
543#if !defined(GPR_LINALG_SCALAPACK)
544 (void)use_solve_based_trace;
545#endif
546 const double noise = likelihoodNoiseVariance();
547 if (!(noise > 0.0)) return;
548
549 double trace_inv = std::numeric_limits<double>::quiet_NaN();
550 if (hssvd_trace_basis_ != nullptr &&
551 hssvd_trace_weighted_basis_ != nullptr &&
552 (hssvd_trace_inv_noise_ > 0.0 || hssvd_trace_direct_inverse_) &&
553 hssvd_trace_basis_->rows() == alpha.size() &&
554 hssvd_trace_weighted_basis_->rows() == alpha.size() &&
555 hssvd_trace_basis_->cols() == hssvd_trace_weighted_basis_->cols()) {
556 const double shrink_sum =
557 (hssvd_trace_basis_->array() * hssvd_trace_weighted_basis_->array())
558 .sum();
559 trace_inv = hssvd_trace_direct_inverse_
560 ? shrink_sum
561 : hssvd_trace_inv_noise_ *
562 (static_cast<double>(alpha.size()) - shrink_sum);
563 } else if (hutch_trace_W_ != nullptr && hutch_trace_Z_ != nullptr &&
564 hutch_trace_W_->rows() == alpha.size() &&
565 hutch_trace_Z_->rows() == alpha.size() &&
566 hutch_trace_W_->cols() == hutch_trace_Z_->cols() &&
567 hutch_trace_W_->cols() > 0) {
568 trace_inv = (hutch_trace_W_->array() * hutch_trace_Z_->array()).sum() /
569 static_cast<double>(hutch_trace_W_->cols());
570 } else if (active_deflation.isActiveForFullOrder(alpha.size()) &&
571 L_factor.rows() == active_deflation.deflated_rows &&
572 L_factor.cols() == active_deflation.deflated_rows &&
573 L_factor.size() != 0) {
574 trace_inv = linalg::dense_factor_inverse_trace(L_factor) +
575 active_deflation.rigid_inv_trace;
576 } else if (L_factor.rows() == alpha.size() &&
577 L_factor.cols() == alpha.size() && L_factor.size() != 0) {
578 // A dense factor is rank-local. Eigen's triangular solve does
579 // not scatter it into DistributedState::cache_L. The ScaLAPACK
580 // and SLATE solves do, and they are collective across ranks that
581 // may be holding different SVGD particles.
582 trace_inv = linalg::dense_factor_inverse_trace(L_factor);
583#if defined(GPR_LINALG_SCALAPACK)
584 } else if (use_solve_based_trace && L_factor.size() == 0) {
585 // The distributed factor lives in the process cache. Every rank
586 // enters this collective together; a dense rank-local factor
587 // must not.
588 trace_inv =
589 backend().trace_inverse(L_factor, static_cast<int>(alpha.size()));
590#endif
591#ifndef GPR_LINALG_CHOLMOD
592 } else if (invC.rows() == invC.cols() && invC.rows() == alpha.size()) {
593 trace_inv = invC.trace();
594#else
595 } else {
596 (void)invC;
597 (void)use_solve_based_trace;
598#endif
599 }
600 if (!std::isfinite(trace_inv)) return;
601
602 const double alpha_sq =
603 active_deflation.isActiveForFullOrder(alpha.size())
604 ? (alpha.squaredNorm() + active_deflation.rigid_alpha_sq_norm)
605 : alpha.squaredNorm();
606 appendScalarColumn(gdata, 0.5 * noise * (trace_inv - alpha_sq));
607 appendScalarColumn(gprior, 0.0);
608}
609
616
618 const Eigen::VectorXd& input) const
619{
620 if (!hasTrainingPermutation()) return input;
622}
623
625 const Eigen::VectorXd& input) const
626{
627 if (!hasTrainingPermutation()) return input;
629}
630
636
637void GaussianProcessRegression::configureZBLPriorMean(
638 const AtomsConfiguration& conf_info)
639{
640 if (!use_zbl_prior_mean_) {
641 zbl_prior_mean_.reset();
642 return;
643 }
644
645 auto prior = std::make_unique<priors::ZBLPriorMean>(conf_info);
646 if (prior->active()) {
647 zbl_prior_mean_ = std::move(prior);
648 } else {
649 zbl_prior_mean_.reset();
650 }
651}
652
655{
657 state.ties = length_scale_ties_;
658 state.enabled = use_length_scale_ties_;
659 return state;
660}
661
663 const LengthScaleFitState& state)
664{
665 if (length_scale_ties_ == state.ties &&
666 use_length_scale_ties_ == state.enabled)
667 return;
668 if (state.ties.valid &&
669 (state.ties.parent != atoms_config.pair_type_parent ||
670 state.ties.base_count != atoms_config.n_base_pt)) {
671 throw std::invalid_argument(
672 "length-scale fit state requires the same chemical pair types");
673 }
674 length_scale_ties_ = state.ties;
675 use_length_scale_ties_ = state.enabled;
676 if (sexpat_cov_func)
677 sexpat_cov_func->setLengthScalePriorWeights(Eigen::VectorXd());
679 ++laplace_model_revision_;
680 laplace_posterior_.reset();
681 // Curvature pairs are expressed in the parameter groups of their fit.
683}
684
686{
687 if (enabled == use_length_scale_ties_) return;
688 auto state = lengthScaleFitState();
689 state.enabled = enabled;
691}
692
694 const AtomsConfiguration& configuration)
695{
696 length_scale_ties_ = LengthScaleTies{};
697 if (sexpat_cov_func != nullptr)
698 sexpat_cov_func->setLengthScalePriorWeights(Eigen::VectorXd());
699 const auto& parent = configuration.pair_type_parent;
700 if (configuration.n_base_pt == 0 || parent.empty() ||
701 static_cast<Index_t>(parent.size()) != configuration.n_pt)
702 return;
703 for (const auto base: parent)
704 if (base >= configuration.n_base_pt) return;
705 length_scale_ties_.parent = parent;
706 length_scale_ties_.released.assign(parent.size(), false);
707 length_scale_ties_.evidence.assign(parent.size(), 0.0);
708 length_scale_ties_.base_count = configuration.n_base_pt;
709 length_scale_ties_.valid = true;
711}
712
714{
715 auto& ties = length_scale_ties_;
716 if (!ties.valid) return;
717 // Index_t is unsigned: the count itself marks a base without a leader.
718 const Index_t none = ties.count();
719 ties.leader.assign(ties.parent.size(), none);
720 std::vector<Index_t> first(static_cast<std::size_t>(ties.base_count), none);
721 for (std::size_t t = 0; t < ties.parent.size(); ++t) {
722 if (ties.released[t]) {
723 ties.leader[t] = static_cast<Index_t>(t);
724 continue;
725 }
726 auto& lead = first[static_cast<std::size_t>(ties.parent[t])];
727 if (lead == none) lead = static_cast<Index_t>(t);
728 ties.leader[t] = lead;
729 }
730 // The covariance function's own prior counts each group once.
731 if (sexpat_cov_func != nullptr && use_length_scale_ties_) {
732 Eigen::VectorXd weight(ties.count());
733 for (Index_t t = 0; t < ties.count(); ++t)
734 weight(t) = ties.leader[t] == t ? 1.0 : 0.0;
735 sexpat_cov_func->setLengthScalePriorWeights(weight);
736 }
737}
738
740 Eigen::VectorXd& theta) const
741{
742 const auto& ties = length_scale_ties_;
743 if (!use_length_scale_ties_ || !ties.valid ||
744 theta.size() < 1 + ties.count())
745 return;
746 for (Index_t t = 0; t < ties.count(); ++t)
747 theta(1 + t) = theta(1 + ties.leader[static_cast<std::size_t>(t)]);
748}
749
751 Eigen::VectorXd& scales) const
752{
753 const auto& ties = length_scale_ties_;
754 if (!use_length_scale_ties_ || !ties.valid || scales.size() != ties.count())
755 return;
756 std::vector<double> variance(ties.parent.size(), 0.0);
757 std::vector<int> members(ties.parent.size(), 0);
758 for (Index_t t = 0; t < ties.count(); ++t) {
759 const auto lead = static_cast<std::size_t>(ties.leader[t]);
760 ++members[lead];
761 const double scale = scales(t);
762 if (std::isfinite(scale) && scale > 0.0)
763 variance[lead] += scale * scale;
764 }
765 for (Index_t t = 0; t < ties.count(); ++t) {
766 const auto lead = static_cast<std::size_t>(ties.leader[t]);
767 // A group of one keeps its scale bit for bit.
768 if (members[lead] == 1) continue;
769 scales(t) = std::sqrt(variance[lead]);
770 }
771}
772
774 Eigen::VectorXd& gradient) const
775{
776 // J^T g: each leader's entry becomes the sum over its group, the
777 // derivative of the objective restricted to the tied subspace; the
778 // members, held by the fit, carry none.
779 const auto& ties = length_scale_ties_;
780 if (!use_length_scale_ties_ || !ties.valid ||
781 gradient.size() < 1 + ties.count())
782 return;
783 std::vector<double> sum(ties.parent.size(), 0.0);
784 for (Index_t t = 0; t < ties.count(); ++t)
785 sum[static_cast<std::size_t>(ties.leader[t])] += gradient(1 + t);
786 for (Index_t t = 0; t < ties.count(); ++t)
787 gradient(1 + t) =
788 ties.leader[t] == t ? sum[static_cast<std::size_t>(t)] : 0.0;
789}
790
791void GaussianProcessRegression::configureFFPriorMean(
792 const AtomsConfiguration& conf_info)
793{
794 if (!use_ff_prior_mean_) {
795 ff_prior_mean_.reset();
796 return;
797 }
798
799 auto prior = std::make_unique<priors::MorsePriorMean>(conf_info);
800 if (prior->active()) {
801 ff_prior_mean_ = std::move(prior);
802 } else {
803 ff_prior_mean_.reset();
804 }
805}
806
808 const Eigen::VectorXd& position, const Eigen::VectorXd& gradient,
809 const Eigen::MatrixXd& hessian, double reference_energy)
810{
811 if (position.size() == 0 || gradient.size() != position.size() ||
812 hessian.rows() != position.size() ||
813 hessian.cols() != position.size() || !position.allFinite() ||
814 !gradient.allFinite() || !hessian.allFinite() ||
815 !std::isfinite(reference_energy))
816 throw std::invalid_argument(
817 "secant quadratic mean requires a finite matching Hessian");
818 secant_reference_position_ = position;
819 secant_reference_gradient_ = gradient;
820 secant_hessian_ = 0.5 * (hessian + hessian.transpose());
821 secant_reference_energy_ = reference_energy;
822 secant_quadratic_prior_active_ = true;
823}
824
826{
827 secant_quadratic_prior_active_ = false;
828 secant_reference_position_.resize(0);
829 secant_reference_gradient_.resize(0);
830 secant_hessian_.resize(0, 0);
831 secant_reference_energy_ = 0.0;
832}
833
836{
837 return {secant_quadratic_prior_active_, secant_reference_position_,
838 secant_reference_gradient_, secant_hessian_,
839 secant_reference_energy_};
840}
841
843 const SecantQuadraticPriorState& state)
844{
845 if (!state.active) {
847 return;
848 }
850 state.energy);
851}
852
854 const Eigen::VectorXd& position, double& energy,
855 Eigen::VectorXd& gradient) const
856{
857 if (position.size() == 0 || !position.allFinite())
858 throw std::invalid_argument(
859 "secant quadratic mean requires a finite geometry");
860 const auto accept = [&](double prior_energy,
861 const Eigen::RowVectorXd& prior_gradient,
862 const char* name) {
863 if (prior_gradient.size() != position.size() ||
864 !std::isfinite(prior_energy) || !prior_gradient.allFinite())
865 throw std::runtime_error(std::string(name) +
866 " prior mean has no finite gradient for "
867 "the secant");
868 energy = prior_energy;
869 gradient = prior_gradient.transpose();
870 };
871 if (ffPriorMeanActive()) {
872 const auto evaluation = ff_prior_mean_->evaluate(position.transpose());
873 accept(evaluation.energy, evaluation.gradient, "Morse");
874 return true;
875 }
876 if (zblPriorMeanActive()) {
877 const auto evaluation = zbl_prior_mean_->evaluate(position.transpose());
878 accept(evaluation.energy, evaluation.gradient, "ZBL");
879 return true;
880 }
881 return false;
882}
883
885{
886 if (!secant_quadratic_prior_active_)
887 throw std::logic_error("secant quadratic mean is not active");
888 return secant_hessian_;
889}
890
892 const Eigen::VectorXd& position, const Eigen::VectorXd& direction,
893 Eigen::VectorXd& action) const
894{
895 if (direction.size() != position.size() || !position.allFinite() ||
896 !direction.allFinite())
897 throw std::invalid_argument(
898 "secant quadratic mean requires a finite Hessian direction");
899 action = Eigen::VectorXd::Zero(position.size());
900 if (ffPriorMeanActive())
902 ff_prior_mean_->hessianPairs(position.transpose()), direction);
903 else if (zblPriorMeanActive())
905 zbl_prior_mean_->hessianPairs(position.transpose()), direction);
906 if (!secant_quadratic_prior_active_) return;
907 if (secant_reference_position_.size() != position.size())
908 throw std::logic_error(
909 "secant quadratic mean requires a matching query");
910 action += secant_hessian_ * direction;
911}
912
913void GaussianProcessRegression::applySecantQuadraticPrior(
914 const Coord& positions, Eigen::Index energy_count,
915 Eigen::VectorXd& targets) const
916{
917 if (!secant_quadratic_prior_active_) return;
918 if (positions.rows() != energy_count ||
919 positions.cols() != secant_reference_position_.size() ||
920 targets.size() < energy_count + positions.rows() * positions.cols())
921 throw std::logic_error(
922 "secant quadratic mean cannot be applied to these targets");
923 for (Eigen::Index row = 0; row < positions.rows(); ++row) {
924 const Eigen::VectorXd displacement =
925 positions.row(row).transpose() - secant_reference_position_;
926 const Eigen::VectorXd gradient =
927 secant_reference_gradient_ + secant_hessian_ * displacement;
928 const double energy =
929 secant_reference_energy_ +
930 secant_reference_gradient_.dot(displacement) +
931 0.5 * displacement.dot(secant_hessian_ * displacement);
932 if (!std::isfinite(energy) || !gradient.allFinite())
933 throw std::runtime_error(
934 "secant quadratic mean produced a non-finite target");
935 targets(row) -= energy;
936 for (Eigen::Index component = 0; component < positions.cols();
937 ++component) {
938 const Eigen::Index target_index =
939 energy_count + row + component * positions.rows();
940 targets(target_index) -= gradient(component);
941 }
942 }
943 ++secant_quadratic_prior_uses_;
944}
945
946void GaussianProcessRegression::addSecantQuadraticPrior(
947 Observation& observation) const
948{
949 if (!secant_quadratic_prior_active_) return;
950 const bool write_energy_column =
951 observation.E.rows() == observation.R.rows() &&
952 observation.E.cols() >= 1;
953 const bool write_energy_row = observation.E.rows() == 1 &&
954 observation.E.cols() == observation.R.rows();
955 const bool write_gradient = observation.G.rows() == observation.R.rows() &&
956 observation.G.cols() == observation.R.cols();
957 if (observation.R.cols() != secant_reference_position_.size() ||
958 (observation.E.size() > 0 && !write_energy_column &&
959 !write_energy_row) ||
960 (observation.G.size() > 0 && !write_gradient))
961 throw std::logic_error(
962 "secant quadratic mean cannot be added to this observation");
963 const bool write_energy = write_energy_column || write_energy_row;
964 if (!write_energy && !write_gradient) return;
965 for (Eigen::Index row = 0; row < observation.R.rows(); ++row) {
966 const Eigen::VectorXd displacement =
967 observation.R.row(row).transpose() - secant_reference_position_;
968 const Eigen::VectorXd gradient =
969 secant_reference_gradient_ + secant_hessian_ * displacement;
970 const double energy =
971 secant_reference_energy_ +
972 secant_reference_gradient_.dot(displacement) +
973 0.5 * displacement.dot(secant_hessian_ * displacement);
974 if (!std::isfinite(energy) || !gradient.allFinite())
975 throw std::runtime_error(
976 "secant quadratic mean produced a non-finite prediction");
977 if (write_energy_column)
978 observation.E(row, 0) += energy;
979 else if (write_energy_row)
980 observation.E(0, row) += energy;
981 if (write_gradient) observation.G.row(row) += gradient.transpose();
982 }
983 ++secant_quadratic_prior_uses_;
984}
985
986void GaussianProcessRegression::addPhysicalPriorToObservation(
987 Observation& observation) const
988{
989 if (!ffPriorMeanActive() && !zblPriorMeanActive()) return;
990 const bool write_energy_column =
991 observation.E.rows() == observation.R.rows() &&
992 observation.E.cols() >= 1;
993 const bool write_energy_row = observation.E.rows() == 1 &&
994 observation.E.cols() == observation.R.rows();
995 const bool write_gradient = observation.G.rows() == observation.R.rows() &&
996 observation.G.cols() == observation.R.cols();
997 if ((observation.E.size() > 0 && !write_energy_column &&
998 !write_energy_row) ||
999 (observation.G.size() > 0 && !write_gradient))
1000 throw std::logic_error(
1001 "physical prior mean cannot be added to this observation");
1002 const bool write_energy = write_energy_column || write_energy_row;
1003 if (!write_energy && !write_gradient) return;
1004 for (Eigen::Index row = 0; row < observation.R.rows(); ++row) {
1005 double energy = 0.0;
1006 Eigen::VectorXd gradient;
1007 if (!samplePhysicalPriorMean(observation.R.row(row).transpose(), energy,
1008 gradient))
1009 throw std::logic_error(
1010 "physical prior mean disappeared during composition");
1011 if (write_energy_column)
1012 observation.E(row, 0) += energy;
1013 else if (write_energy_row)
1014 observation.E(0, row) += energy;
1015 if (write_gradient) observation.G.row(row) += gradient.transpose();
1016 }
1017}
1018
1019void GaussianProcessRegression::subtractPriorMeanFromTargets(
1020 const Coord& positions, Eigen::Index energy_count,
1021 Eigen::VectorXd& targets) const
1022{
1023 if (secant_quadratic_prior_active_)
1024 applySecantQuadraticPrior(positions, energy_count, targets);
1025 if (ffPriorMeanActive()) {
1026 ff_prior_mean_->subtractFromTargets(positions, energy_count, targets);
1027 return;
1028 }
1029 if (!zblPriorMeanActive()) return;
1030 zbl_prior_mean_->subtractFromTargets(positions, energy_count, targets);
1031}
1032
1033void GaussianProcessRegression::addPriorMeanToObservation(
1034 Observation& observation) const
1035{
1036 if (secant_quadratic_prior_active_) {
1037 addSecantQuadraticPrior(observation);
1038 addPhysicalPriorToObservation(observation);
1039 return;
1040 }
1041 if (ffPriorMeanActive()) {
1042 ff_prior_mean_->addToObservation(observation);
1043 return;
1044 }
1045 if (!zblPriorMeanActive()) return;
1046 zbl_prior_mean_->addToObservation(observation);
1047}
1048
1050 const Eigen::VectorXd& positions, double& energy,
1051 Eigen::VectorXd& gradient) const
1052{
1053 energy = 0.0;
1054 gradient = Eigen::VectorXd::Zero(positions.size());
1055 if (secant_quadratic_prior_active_) {
1056 if (positions.size() != secant_reference_position_.size() ||
1057 !positions.allFinite())
1058 throw std::logic_error(
1059 "secant quadratic mean requires a matching query");
1060 const Eigen::VectorXd displacement =
1061 positions - secant_reference_position_;
1062 gradient = secant_reference_gradient_ + secant_hessian_ * displacement;
1063 energy = secant_reference_energy_ +
1064 secant_reference_gradient_.dot(displacement) +
1065 0.5 * displacement.dot(secant_hessian_ * displacement);
1066 if (!std::isfinite(energy) || !gradient.allFinite())
1067 throw std::runtime_error(
1068 "secant quadratic mean produced a non-finite target");
1069 ++secant_quadratic_prior_uses_;
1070 if (ffPriorMeanActive()) {
1071 const auto evaluation =
1072 ff_prior_mean_->evaluate(positions.transpose());
1073 energy += evaluation.energy;
1074 gradient += evaluation.gradient.transpose();
1075 return;
1076 }
1077 if (!zblPriorMeanActive()) return;
1078 const auto evaluation =
1079 zbl_prior_mean_->evaluate(positions.transpose());
1080 energy += evaluation.energy;
1081 gradient += evaluation.gradient.transpose();
1082 return;
1083 }
1084 if (ffPriorMeanActive()) {
1085 const auto evaluation = ff_prior_mean_->evaluate(positions.transpose());
1086 energy = evaluation.energy;
1087 gradient = evaluation.gradient.transpose();
1088 return;
1089 }
1090 if (!zblPriorMeanActive()) return;
1091 const auto evaluation = zbl_prior_mean_->evaluate(positions.transpose());
1092 energy = evaluation.energy;
1093 gradient = evaluation.gradient.transpose();
1094}
1095
1096void GaussianProcessRegression::residualEnergyStatistics(
1097 const Observation& observation, double& mean, double& variance) const
1098{
1099 double maximum = 0.0;
1100 residualEnergyStatistics(observation, mean, variance, maximum);
1101}
1102
1103void GaussianProcessRegression::residualEnergyStatistics(
1104 const Observation& observation, double& mean, double& variance,
1105 double& maximum) const
1106{
1107 mean = 0.0;
1108 variance = 0.0;
1109 maximum = 0.0;
1110 const Eigen::Index n = observation.E.size();
1111 if (n <= 0) return;
1112
1113 double sum = 0.0;
1114 double sumsq = 0.0;
1115 maximum = -std::numeric_limits<double>::infinity();
1116 const bool rows_match = observation.R.rows() == n;
1117 const bool subtract_secant =
1118 secant_quadratic_prior_active_ && rows_match &&
1119 observation.R.cols() == secant_reference_position_.size();
1120 const bool subtract_ff = ffPriorMeanActive() && rows_match;
1121 const bool subtract_zbl =
1122 !subtract_ff && zblPriorMeanActive() && rows_match;
1123 for (Eigen::Index i = 0; i < n; ++i) {
1124 double energy = observation.E(i);
1125 if (subtract_secant) {
1126 const Eigen::VectorXd displacement =
1127 observation.R.row(i).transpose() - secant_reference_position_;
1128 energy -= secant_reference_energy_ +
1129 secant_reference_gradient_.dot(displacement) +
1130 0.5 * displacement.dot(secant_hessian_ * displacement);
1131 }
1132 if (subtract_ff)
1133 energy -= ff_prior_mean_->energy(observation.R.row(i));
1134 else if (subtract_zbl)
1135 energy -= zbl_prior_mean_->energy(observation.R.row(i));
1136 sum += energy;
1137 sumsq += energy * energy;
1138 maximum = std::max(maximum, energy);
1139 }
1140 mean = sum / static_cast<double>(n);
1141 if (n > 1) {
1142 const double centered_sumsq =
1143 sumsq - (sum * sum) / static_cast<double>(n);
1144 variance = centered_sumsq > 0.0
1145 ? centered_sumsq / static_cast<double>(n - 1)
1146 : 0.0;
1147 }
1148}
1149
1156
1158 const AtomsConfiguration& conf_info)
1159{
1161 if (atomic_environment_model_) invalidateLikelihoodNoiseDependentState();
1162 atomic_environment_cutoff_ = std::isfinite(parameters.actdist_fro.value) &&
1163 parameters.actdist_fro.value > 0.0
1164 ? parameters.actdist_fro.value
1165 : 4.0;
1166 this->atoms_config = conf_info;
1167 configureLengthScaleTies(conf_info);
1168 if (parameters.gp_nonperiodic.value) {
1169 std::fill(std::begin(this->atoms_config.cell),
1170 std::end(this->atoms_config.cell), 0.0);
1171 } else if (geometry::cellIsZero(this->atoms_config.cell)) {
1172 geometry::copyMicLattice(this->atoms_config.cell,
1173 parameters.cell_dimensions.value);
1174 }
1175 // Open axes carry zero rows, which every PairBox reads as open.
1176 geometry::zeroOpenAxes(this->atoms_config.cell,
1177 {parameters.cell_periodic.value[0] != 0,
1178 parameters.cell_periodic.value[1] != 0,
1179 parameters.cell_periodic.value[2] != 0});
1180 configureZBLPriorMean(this->atoms_config);
1181 configureFFPriorMean(this->atoms_config);
1182 fps_options.history = parameters.fps_history.value;
1183 fps_options.metric = parameters.fps_metric.value;
1184 // Classic joint [E, F] profiles evaluate PriorSqrtt, which divides by nu,
1185 // and both profiles read s2 for prior scales.
1186 if (usesClassicJointEnergyForcePrior(model_profile_) &&
1187 (!sexpat_cov_func || !sexpat_cov_func->useLogNormalMagnPrior())) {
1189 parameters.prior_nu.value);
1190 }
1192 parameters.prior_s2.value);
1193 PriorBase prior_parameters;
1194
1195 use_precision_ = parameters.use_precision.value;
1196 sigma2 = parameters.gp_sigma2.value;
1197 jitter_sigma2 = parameters.jitter_sigma2.value;
1198 report_level = parameters.report_level.value;
1199 linalg::CusolverEighLib::setVerbose(report_level >= 3);
1200 use_alpha_k_predict_mean_ = parameters.use_alpha_k_predict_mean.value;
1201 use_alpha_k_laplace_mean_ = parameters.use_alpha_k_laplace_mean.value;
1202 laplace_skip_scg_threshold_ = parameters.laplace_skip_scg_threshold.value;
1203 use_training_geometry_handle_ =
1205 detail::validateRigidNullDeflationConfiguration(
1206 parameters.use_rigid_null_deflation.value, principled_nugget_);
1208 rigid_deflation_.reset();
1210 profile_predict_mean_ = parameters.profile_predict_mean.value;
1211 profile_energy_split_ = parameters.profile_energy_split.value;
1212 profile_gradient_split_ = parameters.profile_gradient_split.value;
1213 log_training_geometry_ = parameters.log_training_geometry.value;
1214 log_rank_block_cholesky_ = false;
1215 if (parameters.log_rank_block_cholesky.value) {
1216 std::fprintf(stderr,
1217 "warning: logRankBlockCholesky is deprecated and "
1218 "ignored; rank-block Cholesky logging was removed\n");
1219 }
1220 scalapack_block_size_ = parameters.scalapack_block_size.value;
1221 scalapack_nprow_ = parameters.scalapack_nprow.value;
1222 cutlass_plugin_path_ = parameters.cutlass_plugin_path.value;
1223 configureDistributedTrainingGrid();
1224 linalg::cutlass::setPluginPath(cutlass_plugin_path_);
1225
1226 if (hyperparameter_mode_override_.has_value()) {
1227 setHyperparameterOptimizationMode(*hyperparameter_mode_override_);
1228 } else {
1229 const auto mode = parameters.optimization_alg.value == "INLA_opt"
1231 : parameters.optimization_alg.value == "MAP_LBFGS_opt"
1234 selectHyperparameterOptimizer(mode);
1235#ifdef USE_CERES
1236 if (parameters.optimization_alg.value == "Ceres_opt")
1237 optimizer_state_->optimizer.emplace<funcmin::Ceres>();
1238#endif
1239 }
1240
1241 // Initialize Gaussian likelihood
1242 prior_parameters.setMu(parameters.prior_mu.value);
1243 prior_parameters.setNu(parameters.prior_nu.value);
1244 prior_parameters.setS2(parameters.prior_s2.value);
1245 lik_gaussian->setSigma2(parameters.sigma2.value);
1246
1247 // Initialize constant covariance function
1248 // Field<double> lengthScale; <----- ? is it calculated or is in initial
1249 // data?
1250
1251 sexpat_cov_func->setMagnSigma2(parameters.magnSigma2.value);
1252 sexpat_cov_func->setConfInfo(this->atoms_config);
1253 auto& length_scales = sexpat_cov_func->getLengthScaleRef();
1254 if (!sexpat_cov_func->usesManifoldChart() &&
1255 length_scales.size() != conf_info.n_pt) {
1256 // The parameter domain follows the pair map even before a fit or
1257 // imported kernel supplies its physical length scales.
1258 length_scales = FieldMatrixd::Ones(1, conf_info.n_pt);
1259 }
1260 sexpat_cov_func->setPriorParametersSqrtt(prior_parameters);
1261 sexpat_cov_func->setPriorParametersGaussian(prior_parameters);
1262 sexpat_cov_func->setPriorParametersLogNormal(prior_parameters);
1263
1264 // Initialize constant covariance function
1265 const_cov_fun->setConstSigma2(parameters.constSigma2.value);
1266
1267 const bool check_derivative = parameters.check_derivative.value == "true";
1268 scg_opt_settings.common.check_derivative = check_derivative;
1269 scg_opt_settings.common.report_level = parameters.report_level.value;
1270 scg_opt_settings.common.max_iter = parameters.max_iter.value;
1271 scg_opt_settings.common.tolerance_func = parameters.tolerance_func.value;
1272 scg_opt_settings.common.tolerance_sol = parameters.tolerance_sol.value;
1273 scg_opt_settings.lambda_limit = parameters.lambda_limit.value;
1274 scg_opt_settings.lambda = parameters.lambda.value;
1275 scg_opt_settings.curvature_mode =
1276 parseScgCurvatureMode(parameters.curvature_mode.value);
1277
1278 ceres_opt_settings.common.check_derivative = check_derivative;
1279 ceres_opt_settings.common.report_level = parameters.report_level.value;
1280 ceres_opt_settings.common.max_iter = parameters.max_iter.value;
1281 ceres_opt_settings.common.tolerance_func = parameters.tolerance_func.value;
1282 ceres_opt_settings.common.tolerance_sol = parameters.tolerance_sol.value;
1283
1285 scg_stalled_ = false;
1286 scg_stall_scope_ = {};
1287 initialized_ = true;
1288 ++laplace_model_revision_;
1289 laplace_posterior_.reset();
1290}
1291
1293{
1294 if (usesClassicJointEnergyForcePrior(profile) && initialized_ &&
1295 sexpat_cov_func && !sexpat_cov_func->useLogNormalMagnPrior()) {
1297 "prior", "nu", sexpat_cov_func->getPriorParametersSqrtt().getNu());
1298 }
1299 if (atomic_environment_model_ && model_profile_ != profile)
1300 invalidateLikelihoodNoiseDependentState();
1301 model_profile_ = profile;
1302 scg_opt_settings.model_profile = profile;
1303
1304 if (sexpat_cov_func) {
1305 sexpat_cov_func->setModelProfile(profile);
1306 }
1307
1308 if (!usesClassicJointEnergyForcePrior(profile)) {
1309 // EXTENDED: leave solver, objective, normalization, and prior
1310 // knobs under their existing independent controls.
1311 return;
1312 }
1313
1314 // Classic joint [E, F] profiles (CHEMGP, GPRD_ZBL): published Sexpat prior
1315 // density on raw targets with NLML/SCG. Clear experimental local/
1316 // RFF/PC overlays. A live InternalCoordinateChart stays attached so the
1317 // global tensor can be ManifoldEnergyForceKernel. Keep HS-SVD dual factor
1318 // if the caller enabled it.
1319 // Caller retains principled-nugget / ls-prior: forcing both off left the
1320 // classic posterior overconfident (Baker05 chain_var~1e-7 while true force
1321 // rose 1.3->2.1 under rejected recovery). 01-03 force_pass used NLML;
1322 // nugget defaults on in main_neb and is needed on larger Baker cells.
1330 if (sexpat_cov_func && (sexpat_cov_func->usesManifoldChart() ||
1331 sexpat_cov_func->usesGeodesicHeatKernel()))
1332 configureExactCompositeKernel();
1333 // Refits use the objective stationarity test (Newton decrement under
1334 // SCG's solution tolerance), and fits stop at that same step scale.
1335 setFitStepStop(true);
1337
1338 // Residual ZBL prior mean stays an independent CLI/config flag: the
1339 // frozen gprd_zbl input.dat defaults leave it off; enabling it is a
1340 // deliberate residual-mean choice on top of the classic kernel.
1341 ++laplace_model_revision_;
1342 laplace_posterior_.reset();
1343}
1344
1345// Per-pairtype descriptor spread (see the declaration in
1346// GaussianProcessRegression.h for the physical meaning). Shared by
1347// setHyperparameters (length-scale seeding) and
1348// performHyperparameterOptimization (scale-free MAP lengthscale-prior
1349// anchor rho0, see MapObjective.h) so there is one computation, not two
1350// that could silently drift apart.
1352 const Coord& R, const AtomsConfiguration& conf_info, Eigen::VectorXd& ls_k)
1353{
1354 return InverseDistanceDescriptor::pairtypeMotionScales(R, conf_info, ls_k);
1355}
1356
1358 const AtomsConfiguration& conf_info, const Eigen::VectorXd& ls_k,
1359 double own_s2_log)
1360{
1361 if (population_prior_.empty() || sexpat_cov_func == nullptr ||
1362 conf_info.n_pt <= 0)
1363 return;
1364 const auto entries = population_prior_.perPairtype(conf_info);
1365 const Eigen::Index count = conf_info.n_pt + 1;
1366 Eigen::VectorXd mu_log = sexpat_cov_func->hierarchicalPriorMu();
1367 if (mu_log.size() != count) {
1368 // No prior of the run's own: the population supplies the anchored
1369 // types, the others carry no term (a zero width) and the
1370 // amplitude keeps its own prior.
1371 mu_log = Eigen::VectorXd::Zero(count);
1372 const double magn = sexpat_cov_func->getMagnSigma2();
1373 mu_log(0) =
1374 std::isfinite(magn) && magn > 0.0 ? numerics::log(magn) : 0.0;
1375 for (Index_t k = 0; k < conf_info.n_pt; ++k) {
1376 const double lk = k < ls_k.size() ? ls_k(k) : 0.0;
1377 mu_log(k + 1) =
1378 std::isfinite(lk) && lk > 0.0 ? numerics::log(lk) : 0.0;
1379 }
1380 }
1381 Eigen::VectorXd s2_log_per = Eigen::VectorXd::Constant(count, own_s2_log);
1382 if (!(own_s2_log > 0.0)) s2_log_per(0) = 0.0;
1383 std::vector<char> anchored(static_cast<std::size_t>(conf_info.n_pt), 0);
1384 Index_t anchored_count = 0;
1385 for (Index_t k = 0; k < conf_info.n_pt; ++k) {
1386 const auto* entry = entries[static_cast<std::size_t>(k)];
1387 if (entry == nullptr || !(entry->log_length_sigma > 0.0)) continue;
1388 mu_log(k + 1) = entry->log_length_mu;
1389 s2_log_per(k + 1) = entry->log_length_sigma * entry->log_length_sigma;
1390 anchored[static_cast<std::size_t>(k)] = 1;
1391 ++anchored_count;
1392 }
1393 if (anchored_count == 0) return;
1394 sexpat_cov_func->setHierarchicalPrior(mu_log, own_s2_log, s2_log_per);
1395 sexpat_cov_func->setHierarchicalAnchorMask(std::move(anchored));
1396 if (!population_prior_reported_ && report_level >= 1) {
1397 log_man << "Population prior: " << anchored_count << " of "
1398 << conf_info.n_pt
1399 << " pair types anchored at the campaign's length scales.\n";
1400 population_prior_reported_ = true;
1401 }
1402}
1403
1404// calculation for R_all2 should be moved out
1406 const Observation& all_obs, const AtomsConfiguration& conf_info,
1407 const bool update_sexpat_cf_param, const bool update_const_cf_param,
1408 const bool update_sqrt_prior_param)
1409{
1411 detail::requireJointTrainingObservation(
1412 all_obs, "GaussianProcessRegression::setHyperparameters",
1413 /*allow_empty=*/true);
1414 if (atomic_environment_model_) {
1415 updateConfiguration(conf_info);
1417 invalidateLikelihoodNoiseDependentState();
1418 return;
1419 }
1421 !update_sexpat_cf_param && !update_const_cf_param &&
1422 !update_sqrt_prior_param && canConditionActivePosterior(all_obs)) {
1423 active_refit_setup_skipped_ = true;
1424 return;
1425 }
1428 active_posterior_.reset();
1429 const bool fixed_chart =
1430 sexpat_cov_func != nullptr && sexpat_cov_func->usesManifoldChart();
1431 const bool update_sexpat = update_sexpat_cf_param && !fixed_chart;
1432 const bool update_constant = update_const_cf_param && !fixed_chart;
1433 const bool update_sqrt_prior = update_sqrt_prior_param && !fixed_chart;
1434 if (update_sexpat || update_constant || update_sqrt_prior) {
1435 invalidateObjectiveStationarityHessian();
1436 }
1437 configureZBLPriorMean(conf_info);
1438 configureFFPriorMean(conf_info);
1439
1440 PriorBase prior_parameters;
1441
1442 const bool has_energy = all_obs.E.size() > 0;
1443 const bool has_positions = all_obs.R.rows() > 0 && all_obs.R.cols() > 0;
1444 // The energy mean is the constant prior mean, needed in BOTH branches:
1445 // a zero-mean GP on raw absolute energies reverts every extrapolation
1446 // toward 0 eV absolute and inflates the signal-variance seed to
1447 // mean(y^2) ~ E_abs^2.
1448 const bool needs_output_statistics = true;
1449 const bool needs_prior_scale_update =
1450 sexpat_cov_func != nullptr && !fixed_chart;
1451
1452 // Every later use of the kernel assumes it is allocated. Reject a
1453 // missing one before the first dereference, including the classic
1454 // nu check below.
1455 if (sexpat_cov_func == nullptr) {
1456 throw std::invalid_argument(
1457 "Sexpat covariance function is not allocated");
1458 }
1459
1460#ifndef NDEBUG
1461 gpr::assertMsg(const_cov_fun != nullptr,
1462 "Object of constant covariance function is not allocated!");
1463 gpr::assertMsg(sexpat_cov_func != nullptr,
1464 "Object of sexpAt covariance function is not allocated!");
1465#endif
1466
1467 // OUTPUT standardization (transform-at-the-GP-boundary): the GP trains on
1468 // standardized targets E~=(E-mean_E)/sigma_E and the Cartesian gradient
1469 // G~=G/sigma_E (= grad_R of the standardized energy; derived in
1470 // scripts/derive_gp_normalization.py). y_mean_/y_scale_ un-normalize
1471 // predictions. The signal scale is the unbiased target variance when a
1472 // Bayesian hyperparameter bracketing path needs it.
1473 const double physical_likelihood_variance =
1474 lik_gaussian != nullptr
1475 ? trainingToPhysicalNoiseVariance(lik_gaussian->getSigma2())
1476 : 0.0;
1477 const double physical_signal_variance =
1478 trainingToPhysicalNoiseVariance(sexpat_cov_func->getMagnSigma2());
1479 const double physical_constant_variance =
1480 trainingToPhysicalNoiseVariance(const_cov_fun->getConstSigma2());
1481 const double previous_output_scale = y_scale_;
1482 double mean_y = 0.0;
1483 double target_variance = 0.0;
1484 double sigma_E = 0.0;
1485 if (needs_output_statistics && has_energy) {
1486 double max_y = 0.0;
1487 residualEnergyStatistics(all_obs, mean_y, target_variance, max_y);
1488 if (prior_mean_statistic_ == PriorMeanStatistic::Maximum &&
1489 std::isfinite(max_y))
1490 mean_y = max_y;
1491 }
1492 if (needs_output_statistics && has_energy && all_obs.E.size() > 1) {
1493 if (std::isfinite(target_variance) && target_variance > 0.0)
1494 sigma_E = std::sqrt(target_variance);
1495 }
1496 // The floor depends on the training rows only: the energy scale the
1497 // gradient data imply bounds the amplification of the standardized
1498 // gradient targets. It is covariant under an energy rescaling E -> cE
1499 // (the gradient scale and sigma_E both scale by c) and invariant under a
1500 // geometry rescaling R -> aR (|G| scales by 1/a, the spread by a).
1501 double scale_floor = 0.0;
1502 if (output_scale_floor_ && has_energy && all_obs.R.rows() > 1 &&
1503 all_obs.G.rows() == all_obs.R.rows() && all_obs.G.cols() > 0 &&
1504 jitter_sigma2 > 0.0 && std::isfinite(jitter_sigma2)) {
1505 double gradient_sumsq = 0.0;
1506 Eigen::Index gradient_rows = 0;
1507 for (Eigen::Index row = 0; row < all_obs.G.rows(); ++row) {
1508 const double squared = all_obs.G.row(row).squaredNorm();
1509 if (!std::isfinite(squared)) continue;
1510 gradient_sumsq += squared;
1511 ++gradient_rows;
1512 }
1513 const Eigen::VectorXd centroid = all_obs.R.colwise().mean();
1514 double spread_sumsq = 0.0;
1515 for (Eigen::Index row = 0; row < all_obs.R.rows(); ++row)
1516 spread_sumsq +=
1517 (all_obs.R.row(row).transpose() - centroid).squaredNorm();
1518 const double candidate =
1519 std::sqrt(jitter_sigma2) *
1520 std::sqrt(
1521 gradient_sumsq /
1522 static_cast<double>(std::max<Eigen::Index>(gradient_rows, 1))) *
1523 std::sqrt(spread_sumsq / static_cast<double>(all_obs.R.rows()));
1524 if (std::isfinite(candidate) && candidate > 0.0)
1525 scale_floor = candidate;
1526 }
1527 const bool have_scale =
1528 (std::isfinite(sigma_E) && sigma_E > 0.0) || scale_floor > 0.0;
1529 // Config-gated: the HS-SVD stable basis solves at cond=1 regardless of
1530 // target scale, so output standardization is optional there. Leaving raw
1531 // targets (y_scale_=1, y_mean_=0) exposes whether the prediction
1532 // cancellation actually harms the forces on the HS-SVD path.
1533 if (disable_output_normalization_) {
1534 // The flag disables SCALE standardization only (the HS-SVD stable
1535 // basis solves at cond=1 regardless of target scale). Mean
1536 // centering is a different object: the constant prior mean. The
1537 // constant-offset kernel is zeroed below under the assumption the
1538 // targets are centered, so the mean must be centered here too.
1539 //
1540 // FROZEN after the first data-bearing fit: any constant m is a
1541 // valid prior mean (posterior mean = m + k^T alpha); what matters
1542 // is that every row in the model is centered by the SAME m. The
1543 // HS-SVD basis appends rows incrementally between full rebuilds,
1544 // so a per-refit drifting mean labels same-region rows with
1545 // different targets -- an O(eV) drift against a 1e-2 eV noise
1546 // scale is a thousand-sigma self-contradiction the optimizer can
1547 // only explain by inflating the signal variance.
1548 if (!y_mean_frozen_ && has_energy) {
1549 y_mean_ = mean_y;
1550 y_mean_frozen_ = true;
1551 }
1552 y_scale_ = 1.0;
1553 } else {
1554 y_mean_ = mean_y;
1555 y_scale_ = have_scale ? std::max(sigma_E, scale_floor) : 1.0;
1556 }
1557
1558 if (lik_gaussian != nullptr &&
1559 std::isfinite(physical_likelihood_variance) &&
1560 physical_likelihood_variance >= 0.0) {
1561 const double training_variance =
1562 physicalToTrainingNoiseVariance(physical_likelihood_variance);
1563 if (training_variance != lik_gaussian->getSigma2()) {
1564 // Likelihood variance follows the same output transformation as
1565 // energies and Cartesian gradients, preserving its physical units.
1566 lik_gaussian->setSigma2(training_variance);
1567 invalidateLikelihoodNoiseDependentState();
1568 }
1569 }
1570
1571 const double output_scale_ratio = previous_output_scale / y_scale_;
1572 sexpat_cov_func->rescaleGeodesicHeatCovariance(output_scale_ratio *
1573 output_scale_ratio);
1574
1575 // A warm kernel retains its covariance in physical output units.
1576 // Signal and constant variances follow the same transform as noise.
1577 if (!(update_sexpat && update_constant)) {
1578 sexpat_cov_func->setMagnSigma2(
1579 physicalToTrainingNoiseVariance(physical_signal_variance));
1580 }
1581 if (!update_constant) {
1582 const_cov_fun->setConstSigma2(
1583 physicalToTrainingNoiseVariance(physical_constant_variance));
1584 }
1585
1586 if (update_constant) {
1587 // Energy is mean-centred by the y_mean_ transform, so the GP models a
1588 // zero-mean residual; the constant-offset kernel contributes nothing.
1589 const_cov_fun->setConstSigma2(0.0);
1590 }
1591
1592 if (update_sexpat) {
1593 if (update_constant) {
1594 // Standardized output -> unit signal variance.
1595 sexpat_cov_func->setMagnSigma2(1.0);
1596 }
1597 sexpat_cov_func->getLengthScaleRef().resize(1, conf_info.n_pt);
1598
1599 // INPUT standardization in the kernel's OWN inverse-distance feature
1600 // space (BoTorch/GPyTorch standard: scale inputs so the SE
1601 // length-scale prior is correct). Per pairtype l_k = std of descriptor
1602 // dimension k over the training set. This is the dimensionally correct
1603 // length scale (a Cartesian scale like sigma_E/sigma_G is the wrong
1604 // units for a descriptor-space kernel). The descriptor spread depends
1605 // on the sampled geometries, NOT the NEB image count, so l_k is
1606 // image-count-free and carries no Cartesian range divisor.
1607 // rho0_k anchor (per-pairtype descriptor std): shared with
1608 // performHyperparameterOptimization's scale-free MAP lengthscale
1609 // prior via computePairtypeDescriptorScale (see MapObjective.h).
1610 Eigen::VectorXd ls_k;
1611 bool have_descriptor_scale =
1612 computePairtypeDescriptorScale(all_obs.R, conf_info, ls_k);
1613 if (have_descriptor_scale) poolDescriptorScaleByTies(ls_k);
1614 // Data-derived width of the two-sided length-scale prior
1615 // (use_ls_prior_): the mean squared coefficient of variation of the
1616 // descriptors, i.e. the data's own relative log-scale spread. No magic
1617 // number.
1618 double ls_prior_s2_log = 0.0;
1619 if (has_positions && all_obs.R.rows() > 0) {
1620 Eigen::VectorXd phi;
1621 std::vector<Eigen::VectorXd> phi_rows;
1622 phi_rows.reserve(static_cast<size_t>(all_obs.R.rows()));
1623 for (Eigen::Index r = 0; r < all_obs.R.rows(); ++r) {
1624 Coord xr = all_obs.R.row(r);
1625 InverseDistanceDescriptor::compute(xr, conf_info, phi);
1626 phi_rows.push_back(phi);
1627 }
1628 // Prior width = var(log pairwise descriptor distance): the actual
1629 // spread of length scales present in the band, NOT the per-pairtype
1630 // descriptor-value CV^2. CV^2 collapses for a rigid simple system
1631 // (01 HCN) -> pins l -> flat posterior variance -> the acquisition
1632 // admits near-duplicates to the wall cap. Pairwise distances stay
1633 // informative even when each descriptor value barely varies. Data-
1634 // derived, no magic number.
1635 double dlog_sum = 0.0, dlog_sq = 0.0;
1636 long npair = 0;
1637 for (size_t a = 0; a < phi_rows.size(); ++a)
1638 for (size_t b = a + 1; b < phi_rows.size(); ++b) {
1639 const double d = (phi_rows[a] - phi_rows[b]).norm();
1640 if (d > 0.0 && std::isfinite(d)) {
1641 const double ld = numerics::log(d);
1642 dlog_sum += ld;
1643 dlog_sq += ld * ld;
1644 ++npair;
1645 }
1646 }
1647 if (npair > 1) {
1648 const double m = dlog_sum / static_cast<double>(npair);
1649 const double v = dlog_sq / static_cast<double>(npair) - m * m;
1650 if (std::isfinite(v) && v > 0.0) ls_prior_s2_log = v;
1651 }
1652 }
1653
1654 // Each pair type keeps its measured descriptor motion. Types with
1655 // no sampled motion use the inverse covalent bond length because
1656 // the kernel acts on 1/r, in inverse Angstrom.
1657 const priors::CovalentBondPrior bond_prior(conf_info);
1658 const Eigen::VectorXd chemical_scales =
1659 bond_prior.lengthScalePerPairtype().cwiseInverse();
1660 if (ls_k.size() != conf_info.n_pt) ls_k = chemical_scales;
1661 for (Index_t k = 0; k < conf_info.n_pt; ++k) {
1662 if (!std::isfinite(ls_k(k)) || ls_k(k) <= 0.0)
1663 ls_k(k) = chemical_scales(k);
1664 else if (ls_seed_chemical_floor_ &&
1665 std::isfinite(chemical_scales(k)) &&
1666 chemical_scales(k) > 0.0)
1667 ls_k(k) = std::max(ls_k(k), chemical_scales(k));
1668 sexpat_cov_func->getLengthScaleRef()(0, k) = ls_k(k);
1669 }
1670 if (conf_info.n_pt > 0) {
1671 // One scale per fitted parameter: each tie group counts once.
1672 const auto& ties = length_scale_ties_;
1673 if (ties.valid && ties.count() == conf_info.n_pt) {
1674 double sum = 0.0;
1675 int groups = 0;
1676 for (Index_t k = 0; k < conf_info.n_pt; ++k) {
1677 if (ties.leader[k] != k) continue;
1678 sum += ls_k(k);
1679 ++groups;
1680 }
1681 seed_length_scale_ = sum / static_cast<double>(groups);
1682 } else {
1683 seed_length_scale_ = ls_k.mean();
1684 }
1685 }
1686
1687 // use_ls_prior_: TWO-SIDED log-Gaussian length-scale prior centred on
1688 // the chemistry scale rho0_k (per-pairtype descriptor std) with width
1689 // ls_prior_s2_log = var(log pairwise descriptor distance), computed
1690 // above. It penalises BOTH collapse (l<<rho0 -> posterior variance
1691 // pins at prior, system 20) and over-smoothing (l>>rho0 -> mislocated
1692 // saddle/drift, system 10), with NO magic tail probability. Reuses
1693 // the hierarchical-Gaussian prior (log(theta) ~ N(mu_log, s2_log I));
1694 // mu_log[0]=log(magnSigma2) anchors the amplitude at the robust
1695 // energy spread. The log-distance width stays informative even on a
1696 // rigid simple system whose per-descriptor CV collapses (01 HCN),
1697 // because pairwise row distances span the fine-step-to-full-path
1698 // ratio structure. Opt-in via use_ls_prior_ (--ls-prior).
1699 const bool use_ls_prior =
1700 use_ls_prior_ && conf_info.n_pt > 0 && have_descriptor_scale &&
1701 ls_prior_s2_log > 0.0 && std::isfinite(ls_prior_s2_log);
1702 if (use_ls_prior) {
1703 Eigen::VectorXd mu_log(conf_info.n_pt + 1);
1704 // Anchor the magnSigma2 (signal-variance) prior MEAN to the data's
1705 // energy spread -- a STABLE scale -- not the drifting current
1706 // magnSigma2. Re-centering the prior on getMagnSigma2() each refit
1707 // imposes no constraint on the amplitude: SCG ratchets magnSigma2
1708 // up on a rough PES and the posterior variance (proportional to
1709 // magnSigma2) blows up unboundedly (system 20: max posterior var ->
1710 // 1e5, the band steps into extrapolation and never relaxes so the
1711 // CI never activates). var(observed energies) is the textbook GP
1712 // signal- variance scale and is data-derived (no magic number); the
1713 // prior now pulls the amplitude back toward the data scale instead
1714 // of chasing it. Falls back to the current magnSigma2 only if the
1715 // energy spread is unavailable/degenerate. ROBUST energy signal
1716 // variance (sigma = 1.4826 * MAD), matching the SCG magnSigma2
1717 // ceiling: a plain Var(E) is inflated by the transient clash
1718 // geometries the band samples during active learning, which would
1719 // push the magnSigma2 prior mean up and let the posterior variance
1720 // blow up. The MAD tracks the barrier-scale spread of the reaction
1721 // path and ignores the clash tail. No tunable.
1722 std::vector<double> evals;
1723 evals.reserve(static_cast<std::size_t>(all_obs.E.size()));
1724 for (Eigen::Index r = 0; r < all_obs.E.rows(); ++r)
1725 for (Eigen::Index c = 0; c < all_obs.E.cols(); ++c) {
1726 const double ev = all_obs.E(r, c);
1727 if (std::isfinite(ev)) evals.push_back(ev);
1728 }
1729 const long e_n = static_cast<long>(evals.size());
1730 double signal_var = 0.0;
1731 if (e_n > 1) {
1732 std::vector<double> s = evals;
1733 std::sort(s.begin(), s.end());
1734 const auto med = [](std::vector<double>& v) {
1735 const std::size_t m = v.size();
1736 return (m % 2) ? v[m / 2] : 0.5 * (v[m / 2 - 1] + v[m / 2]);
1737 };
1738 const double e_median = med(s);
1739 std::vector<double> ad(evals.size());
1740 for (std::size_t i = 0; i < evals.size(); ++i)
1741 ad[i] = std::abs(evals[i] - e_median);
1742 std::sort(ad.begin(), ad.end());
1743 const double mad = med(ad);
1744 const double robust_var = (1.4826 * mad) * (1.4826 * mad);
1745 // When more than half the energies tie, as the two
1746 // symmetry-equivalent endpoints of a three-row band do, the
1747 // MAD is their round-off. A robust spread inside the
1748 // likelihood noise does not resolve the signal, so the plain
1749 // variance anchors it.
1750 const double noise_variance =
1751 std::isfinite(physical_likelihood_variance)
1752 ? std::max(physical_likelihood_variance, 0.0)
1753 : 0.0;
1754 if (std::isfinite(robust_var) && robust_var > noise_variance) {
1755 signal_var = robust_var;
1756 } else {
1757 double e_mean = 0.0;
1758 for (double v: evals)
1759 e_mean += v;
1760 e_mean /= static_cast<double>(e_n);
1761 for (double v: evals)
1762 signal_var += (v - e_mean) * (v - e_mean);
1763 signal_var /= static_cast<double>(e_n);
1764 }
1765 }
1766 const double ms2 = sexpat_cov_func->getMagnSigma2();
1767 mu_log(0) =
1768 (std::isfinite(signal_var) && signal_var > 0.0)
1769 ? numerics::log(signal_var)
1770 : ((std::isfinite(ms2) && ms2 > 0.0) ? numerics::log(ms2)
1771 : 0.0);
1772 // Anchor the length-scale prior MEAN to the STABLE per-pairtype
1773 // descriptor std ls_k(k) (the data's own natural length scale,
1774 // computed above as the seed), NOT the drifting current length
1775 // scale. Re-centering mu_log on getLengthScaleRef() each refit
1776 // imposed no constraint: SCG ratchets l upward on the sparse early
1777 // band, the surface over-smooths, the posterior variance collapses
1778 // to ~1e-4 (confidently wrong) and the band wanders to a spurious
1779 // high saddle (hard Baker cells 04/09/16/20). ls_k is the length-
1780 // scale analogue of the var(energies) magnSigma2 anchor above:
1781 // data-derived, no magic number, measured from the actual band
1782 // (including strained/partial saddle bonds).
1783 for (Index_t k = 0; k < conf_info.n_pt; ++k) {
1784 const double lk = ls_k(k);
1785 mu_log(k + 1) =
1786 (std::isfinite(lk) && lk > 0.0) ? numerics::log(lk) : 0.0;
1787 }
1788 sexpat_cov_func->clearPcLengthScalePrior();
1789 sexpat_cov_func->setHierarchicalPrior(mu_log, ls_prior_s2_log);
1790 } else {
1791 sexpat_cov_func->clearHierarchicalPrior();
1792 sexpat_cov_func->clearPcLengthScalePrior();
1793 }
1794 // The population prior (the campaign's fits of the same element
1795 // pair) anchors the pair types it has seen at its location with
1796 // its width, the hierarchy's second level, whether or not the
1797 // run's own hierarchical prior is in force: the anchored types
1798 // carry a log-Gaussian in every prior branch of the kernel
1799 // (setHierarchicalAnchorMask), the others keep what they had.
1800 applyPopulationPrior(conf_info, ls_k,
1801 use_ls_prior ? ls_prior_s2_log : 0.0);
1802 }
1803
1804 // nu is the configured degrees of freedom of the classic Student-t
1805 // prior, not a data-seeded hyperparameter. The magnitude density
1806 // divides by it whenever that prior is active, including when this
1807 // call does not rescale s2. Only a classic profile evaluates that
1808 // density, so a non-positive nu is rejected there rather than
1809 // replaced. An extended model, and a classic model on the log-normal
1810 // magnitude prior, keeps its unused prior untouched. The covariance
1811 // function was rejected above when missing, before this dereference.
1812 if (usesClassicJointEnergyForcePrior(model_profile_) &&
1813 !sexpat_cov_func->useLogNormalMagnPrior()) {
1815 "Student-t prior", "nu",
1816 sexpat_cov_func->getPriorParametersSqrtt().getNu());
1817 }
1818
1819 if (update_sqrt_prior && std::isfinite(target_variance) &&
1820 target_variance > 0.0) {
1821 prior_parameters = sexpat_cov_func->getPriorParametersSqrtt();
1822 prior_parameters.setS2(target_variance);
1823 sexpat_cov_func->setPriorParametersSqrtt(prior_parameters);
1824 }
1825
1826 if (needs_prior_scale_update && std::isfinite(seed_length_scale_) &&
1827 seed_length_scale_ > 0.0) {
1828 prior_parameters = sexpat_cov_func->getPriorParametersGaussian();
1829 prior_parameters.setS2(seed_length_scale_ * seed_length_scale_);
1830 sexpat_cov_func->setPriorParametersGaussian(prior_parameters);
1831 }
1832
1833 ++laplace_model_revision_;
1834 laplace_posterior_.reset();
1835}
1836
1838GaussianProcessRegression::currentLaplacePosteriorStamp() const
1839{
1840 LaplacePosteriorStamp stamp;
1841 stamp.model_revision = laplace_model_revision_;
1842 stamp.theta_includes_likelihood_noise = theta_includes_likelihood_noise_;
1843 stamp.model_profile = model_profile_;
1844 stamp.zbl_mean = use_zbl_prior_mean_;
1845 stamp.ff_mean = use_ff_prior_mean_;
1846 stamp.sigma2_value = sigma2;
1847 stamp.likelihood_sigma2 = lik_gaussian ? lik_gaussian->getSigma2() : 0.0;
1848 stamp.jitter_sigma2_value = jitter_sigma2;
1849 stamp.theta_star = packInlaHyperparameters();
1850 stamp.const_parameters =
1851 const_cov_fun ? const_cov_fun->combineParameters() : Eigen::VectorXd{};
1852 stamp.lik_parameters =
1853 lik_gaussian ? lik_gaussian->combineParameters() : Eigen::VectorXd{};
1854 if (sexpat_cov_func) {
1855 stamp.chart = sexpat_cov_func->manifoldChart();
1856 stamp.heat = sexpat_cov_func->geodesicHeatKernel();
1857 stamp.sexpat_gaussian_prior = priorParametersVector(
1858 sexpat_cov_func->getPriorParametersGaussian());
1859 stamp.sexpat_sqrtt_prior =
1860 priorParametersVector(sexpat_cov_func->getPriorParametersSqrtt());
1861 stamp.sexpat_pair_cutoff = sexpat_cov_func->getConfInfo().pair_cutoff;
1862 stamp.sexpat_pair_cutoff_width =
1863 sexpat_cov_func->getConfInfo().pair_cutoff_width;
1864 }
1865 stamp.R_rows = R_matrix.rows();
1866 stamp.R_cols = R_matrix.cols();
1867 stamp.R_indices_size = R_indices.size();
1868 stamp.y_train_size = energy_and_gradient.size();
1869 stamp.atom_n_pt = atoms_config.n_pt;
1870
1871#ifdef GPR_LINALG_SCALAPACK
1872 int mpi_init = 0;
1873 MPI_Initialized(&mpi_init);
1874 if (mpi_init) {
1875 MPI_Comm_rank(mpiContext().comm, &stamp.mpi_rank);
1876 MPI_Comm_size(mpiContext().comm, &stamp.mpi_size);
1877 }
1878#endif
1879
1880 return stamp;
1881}
1882
1884GaussianProcessRegression::currentLaplacePosteriorSignature(
1885 const LaplacePosteriorStamp& stamp) const
1886{
1887 ++laplace_posterior_signature_builds_for_testing_;
1888 LaplacePosteriorSignature signature;
1889 signature.stamp = stamp;
1890 signature.mpi_rank = stamp.mpi_rank;
1891 signature.mpi_size = stamp.mpi_size;
1892 signature.theta_includes_likelihood_noise =
1893 stamp.theta_includes_likelihood_noise;
1894 signature.sigma2_value = stamp.sigma2_value;
1895 signature.likelihood_sigma2 = stamp.likelihood_sigma2;
1896 signature.jitter_sigma2_value = stamp.jitter_sigma2_value;
1897 signature.theta_star = stamp.theta_star;
1898 signature.const_parameters = stamp.const_parameters;
1899 signature.lik_parameters = stamp.lik_parameters;
1900 signature.sexpat_gaussian_prior = stamp.sexpat_gaussian_prior;
1901 signature.sexpat_sqrtt_prior = stamp.sexpat_sqrtt_prior;
1902 signature.R_matrix_snapshot = R_matrix;
1903 signature.R_indices_snapshot = R_indices;
1904 signature.y_train = energy_and_gradient;
1905 signature.atom_positions = atoms_config.positions;
1906 signature.atom_is_frozen = atoms_config.is_frozen;
1907 signature.atom_id = atoms_config.id;
1908 signature.atom_atomic_nrs = atoms_config.atomicNrs;
1909 signature.atom_type = atoms_config.type;
1910 signature.atom_pairtype = atoms_config.pairtype;
1911 signature.atom_n_pt = atoms_config.n_pt;
1912 signature.atoms_froz_active_positions =
1913 atoms_config.atoms_froz_active.positions;
1914 signature.atoms_froz_active_type = atoms_config.atoms_froz_active.type;
1915 signature.atoms_froz_inactive_positions =
1916 atoms_config.atoms_froz_inactive.positions;
1917 signature.atoms_froz_inactive_type = atoms_config.atoms_froz_inactive.type;
1918 signature.atoms_mov_positions = atoms_config.atoms_mov.positions;
1919 signature.atoms_mov_type = atoms_config.atoms_mov.type;
1920
1921 return signature;
1922}
1923
1925GaussianProcessRegression::currentLaplacePosteriorSignature() const
1926{
1927 return currentLaplacePosteriorSignature(currentLaplacePosteriorStamp());
1928}
1929
1930bool GaussianProcessRegression::recallCachedVarianceSolve(Observation& query)
1931{
1932 if (query.R.rows() <= 0 || query.R.cols() <= 0) return false;
1933 const double calibration = reportedVarianceCalibrationFactor();
1934 for (auto it = variance_solve_cache_.rbegin();
1935 it != variance_solve_cache_.rend(); ++it) {
1936 const auto& cached = *it;
1937 const double sigma2 =
1938 lik_gaussian != nullptr ? lik_gaussian->getSigma2() : 0.0;
1939 const std::uint64_t noise_revision =
1940 lik_gaussian != nullptr ? lik_gaussian->geometryNoiseRevision() : 0;
1941 if (cached.epoch != factor_epoch_ ||
1942 cached.active != static_cast<bool>(active_posterior_) ||
1943 cached.hssvd != use_hssvd_backend_ ||
1944 cached.stable_variance !=
1946 cached.rff != rff_replaces_exact_ ||
1947 cached.convention != variance_convention_ ||
1948 cached.mode != uncertainty_mode_ ||
1949 cached.precision != use_precision_ ||
1950 cached.subset_footprint != variance_subset_footprint_ ||
1951 cached.subset_configurations != variance_subset_configurations_ ||
1952 cached.subset_ids != variance_subset_forced_ids_ ||
1953 cached.sigma2 != sigma2 ||
1954 cached.geometry_noise_revision != noise_revision ||
1955 cached.output_scale != y_scale_ ||
1956 cached.calibration != calibration ||
1957 cached.positions.rows() != query.R.rows() ||
1958 cached.positions.cols() != query.R.cols() ||
1959 !(cached.positions.array() == query.R.array()).all())
1960 continue;
1961 query.E = cached.energy;
1962 query.G = cached.gradient;
1963 ++variance_solve_cache_hits_for_testing_;
1964 return true;
1965 }
1966 return false;
1967}
1968
1969void GaussianProcessRegression::storeCachedVarianceSolve(
1970 const Observation& query)
1971{
1972 if (query.R.rows() <= 0 || query.E.size() == 0 || query.G.size() == 0 ||
1973 !query.E.allFinite() || !query.G.allFinite())
1974 return;
1975 CachedVarianceSolve cached;
1976 cached.epoch = factor_epoch_;
1977 cached.output_scale = y_scale_;
1978 cached.calibration = reportedVarianceCalibrationFactor();
1979 cached.convention = variance_convention_;
1980 cached.mode = uncertainty_mode_;
1981 cached.active = static_cast<bool>(active_posterior_);
1982 cached.hssvd = use_hssvd_backend_;
1983 cached.stable_variance = linalg::stablePosteriorVarianceEnabled();
1984 cached.rff = rff_replaces_exact_;
1985 cached.precision = use_precision_;
1986 cached.subset_footprint = variance_subset_footprint_;
1987 cached.subset_configurations = variance_subset_configurations_;
1988 cached.subset_ids = variance_subset_forced_ids_;
1989 cached.sigma2 = lik_gaussian != nullptr ? lik_gaussian->getSigma2() : 0.0;
1990 cached.geometry_noise_revision =
1991 lik_gaussian != nullptr ? lik_gaussian->geometryNoiseRevision() : 0;
1992 cached.positions = query.R;
1993 cached.energy = query.E;
1994 cached.gradient = query.G;
1995 variance_solve_cache_.push_back(std::move(cached));
1996 if (variance_solve_cache_.size() > 8)
1997 variance_solve_cache_.erase(variance_solve_cache_.begin());
1998}
1999
2001{
2002 ScopedPredictTimer predict_timer;
2003 if (recallCachedVarianceSolve(image1)) return;
2004 ScopedVarianceTimer variance_timer;
2005 if (atomic_environment_model_) {
2006 calculateAtomicEnvironmentVariance(image1);
2007 return;
2008 }
2009 if (active_posterior_) {
2010 calculateActivePosteriorVariance(image1);
2011 return;
2012 }
2013 // RFF-replace path: above the design cutoff the exact dual-kernel
2014 // eigensolve was skipped (rff_replaces_exact_), so the RFF Bayesian
2015 // linear-regression posterior is the only model -- take the variance
2016 // from it. Gated on rff_replaces_exact_ so below-cutoff systems fall
2017 // through to the exact dispatch unchanged.
2018 if (rff_replaces_exact_ && rff_model_.isBuilt()) {
2019 calculateVarianceRFF(image1);
2020 return;
2021 }
2022 // MAP variance uses the fitted stable basis and its physical output
2023 // units. Integrated modes include hyperparameter uncertainty through
2024 // their own posterior operators.
2025 if (uncertainty_mode_ == UncertaintyMode::MAP && canUseHssvdVariance()) {
2026 calculateVarianceHssvd(image1);
2027 return;
2028 }
2029 switch (uncertainty_mode_) {
2031 calculateVarianceSVGD(image1);
2032 break;
2035 // Empirical Bayes uses MAP for the mean (fast, no Taylor
2036 // correction risk on small data) but the LAPLACE mixture
2037 // for the variance, which is the calibrated Bayesian
2038 // estimate including hyperparameter uncertainty. This is the
2039 // standard EB approach (Carlin & Louis 2008; INLA's
2040 // approx hyperpar.dist mode), and is the right default for
2041 // small-data regimes where the TCOV correction on the mean
2042 // is unreliable but the K-grid mixture variance is still
2043 // informative.
2045 break;
2047 if (use_delta_method_) {
2048 calculateVarianceLaplaceDelta(image1);
2049 } else {
2051 }
2052 break;
2054 calculateVarianceBMA(image1);
2055 break;
2057 default:
2058 ensurePosteriorFactorForPrediction();
2059 calculateVariance(image1);
2060 break;
2061 }
2062 // Un-normalize posterior variance from standardized to physical units:
2063 // var(E) = y_scale_^2 var(E~), var(grad) = y_scale_^2 var(grad~).
2064 if (y_scale_ != 1.0) {
2065 const double s2 = y_scale_ * y_scale_;
2066 if (image1.E.size() > 0) image1.E.array() *= s2;
2067 if (image1.G.size() > 0) image1.G.array() *= s2;
2068 }
2069 storeCachedVarianceSolve(image1);
2070}
2071
2073 const Eigen::VectorXd& mu_log, double s2_log)
2074{
2075 if (sexpat_cov_func != nullptr) {
2076 sexpat_cov_func->setHierarchicalPrior(mu_log, s2_log);
2077 }
2078}
2079
2081{
2082 if (sexpat_cov_func != nullptr) {
2083 sexpat_cov_func->clearHierarchicalPrior();
2084 }
2085}
2086
2088 const GaussianProcessRegression& source)
2089{
2090 restoreOutputTransform(source.y_mean_, source.y_scale_,
2091 source.y_mean_frozen_);
2092}
2093
2095 double scale,
2096 bool frozen_mean)
2097{
2098 if (!std::isfinite(mean) || !std::isfinite(scale) || !(scale > 0.0)) {
2099 throw std::invalid_argument(
2100 "GP output transform requires a finite mean and positive scale");
2101 }
2102 if (y_mean_ == mean && y_scale_ == scale && y_mean_frozen_ == frozen_mean) {
2103 return;
2104 }
2105
2106 y_mean_ = mean;
2107 y_scale_ = scale;
2108 y_mean_frozen_ = frozen_mean;
2109 invalidateLikelihoodNoiseDependentState();
2110}
2111
2112void GaussianProcessRegression::setParameters(const Eigen::VectorXd& w)
2113{
2114 if (w.rows() == 0) return;
2115 if (atomic_environment_model_) invalidateLikelihoodNoiseDependentState();
2116 pending_hyperparameter_posterior_ = {};
2117
2118#ifndef NDEBUG
2119 gpr::assertMsg(sexpat_cov_func != nullptr,
2120 "Object of Gausian likelihood is not allocated!");
2121 gpr::assertMsg(const_cov_fun != nullptr,
2122 "Object of Gausian likelihood is not allocated!");
2123 gpr::assertMsg(lik_gaussian != nullptr,
2124 "Object of Gausian likelihood is not allocated!");
2125#endif
2126
2127 last_objective_theta_.resize(0);
2128 sexpat_cov_func->setParameters(w);
2129 const_cov_fun->setParameters(w);
2130 lik_gaussian->setParameters(w);
2131 theta_includes_likelihood_noise_ = hasTrailingLikelihoodNoiseParameter(w);
2132 if (theta_includes_likelihood_noise_) {
2133 const double noise = numerics::exp(w(w.rows() - 1));
2134 sigma2 = trainingToPhysicalNoiseVariance(noise);
2135 lik_gaussian->setSigma2(noise);
2136 }
2137}
2138
2140 std::shared_ptr<const geometry::InternalCoordinateChart> chart,
2141 double length_scale)
2142{
2143 if (!sexpat_cov_func) {
2144 throw std::logic_error(
2145 "internal coordinate chart requires an initialized GP");
2146 }
2147 sexpat_cov_func->setManifoldChart(std::move(chart), length_scale);
2148 configureExactCompositeKernel();
2149}
2150
2151void GaussianProcessRegression::configureExactCompositeKernel()
2152{
2153 if (!base_kernel_execution_config_.has_value()) {
2154 base_kernel_execution_config_ = BaseKernelExecutionConfig{
2155 use_hssvd_backend_,
2156 use_hssvd_objective_contractions_,
2157 use_alpha_k_predict_mean_,
2158 use_alpha_k_laplace_mean_,
2159 use_training_geometry_handle_,
2160 rff_features_requested_,
2161 uncertainty_mode_,
2162 rff_auto_,
2163 rff_force_tol_fraction_,
2164 };
2165 }
2166 use_hssvd_backend_ = false;
2167 use_hssvd_objective_contractions_ = false;
2168 use_alpha_k_predict_mean_ = false;
2169 use_alpha_k_laplace_mean_ = false;
2170 use_training_geometry_handle_ = false;
2171 rff_features_requested_ = 0;
2172 rff_auto_ = false;
2173 rff_features_ = 0;
2174 rff_standardized_targets_ = false;
2175 rff_replaces_exact_ = false;
2176 uncertainty_mode_ = UncertaintyMode::MAP;
2177 active_training_geom_ = nullptr;
2178 clearHssvdBasisState();
2180 ++laplace_model_revision_;
2181 laplace_posterior_.reset();
2182}
2183
2184void GaussianProcessRegression::restoreBaseKernelExecutionConfig()
2185{
2186 if (!base_kernel_execution_config_.has_value()) return;
2187 const BaseKernelExecutionConfig config = *base_kernel_execution_config_;
2188 base_kernel_execution_config_.reset();
2189 use_hssvd_backend_ = config.use_hssvd_backend;
2190 use_hssvd_objective_contractions_ = config.use_hssvd_objective_contractions;
2191 use_alpha_k_predict_mean_ = config.use_alpha_k_predict_mean;
2192 use_alpha_k_laplace_mean_ = config.use_alpha_k_laplace_mean;
2193 use_training_geometry_handle_ = config.use_training_geometry_handle;
2194 rff_features_requested_ = config.rff_features_requested;
2195 rff_auto_ = config.rff_auto;
2196 rff_force_tol_fraction_ = config.rff_force_tol_fraction;
2197 rff_features_ = 0;
2198 rff_standardized_targets_ = false;
2199 rff_replaces_exact_ = false;
2200 uncertainty_mode_ = config.uncertainty_mode;
2201 active_training_geom_ = nullptr;
2202 clearHssvdBasisState();
2204 ++laplace_model_revision_;
2205 laplace_posterior_.reset();
2206}
2207
2209 std::shared_ptr<const GeodesicHeatEnergyForceKernel> kernel)
2210{
2211 if (!sexpat_cov_func)
2212 throw std::logic_error(
2213 "geodesic heat prior requires an initialized GP");
2214 sexpat_cov_func->setGeodesicHeatKernel(std::move(kernel));
2215 if (sexpat_cov_func->usesManifoldChart() ||
2216 sexpat_cov_func->usesGeodesicHeatKernel())
2217 configureExactCompositeKernel();
2218 else
2219 restoreBaseKernelExecutionConfig();
2220}
2221
2223{
2224 if (sexpat_cov_func)
2225 setGeodesicHeatPrior(nullptr);
2226 else
2227 restoreBaseKernelExecutionConfig();
2228}
2229
2231 const Coord& reference_path, const Observation& training_data)
2232{
2233 detail::requireJointTrainingObservation(
2234 training_data, "GaussianProcessRegression::fitGeodesicHeatPrior");
2235 if (!sexpat_cov_func) {
2236 throw std::logic_error(
2237 "geodesic heat prior requires an initialized GP");
2238 }
2239 // An amplitude fit holds the heat metric fixed independently of fitted
2240 // base lengths. The first attachment derives only its initial metric.
2241 const auto retained_heat = sexpat_cov_func->geodesicHeatKernel();
2242 const FieldMatrixd heat_lengths =
2243 retained_heat ? retained_heat->atomisticLengthScales()
2244 : sexpat_cov_func->getAtomisticLengthScaleRef();
2247 EigenMatrix training_rows;
2248 Eigen::VectorXd training_indices;
2249 Eigen::VectorXd targets;
2251 training_data.R, training_rows, training_indices);
2252 auxiliary.assembleVectorFromEnergyAndGradient(training_data, targets);
2253 subtractPriorMeanFromTargets(training_data.R, training_data.E.size(),
2254 targets);
2255 standardizeTargets(targets, training_data.E.size());
2256
2257 EigenMatrix base_covariance;
2258 evaluateTrainingCovarianceMatrix(training_rows, training_indices,
2259 base_covariance,
2260 /*serial_per_rank=*/true);
2261 const GeodesicHeatEnergyForceKernel unit_geodesic(
2262 reference_path, atoms_config, heat_lengths,
2263 /*covariance_weight=*/1.0);
2264 const EigenMatrix unit_geodesic_features =
2265 unit_geodesic.jointEnergyGradientFeatures(training_data.R);
2266 double weight = 0.0;
2267 if (kernelNuggetCoefficient(training_rows.rows()) > 0.0) {
2268 EigenMatrix unit_geodesic_covariance =
2269 unit_geodesic_features * unit_geodesic_features.transpose();
2270 applyKernelNugget(unit_geodesic_covariance, training_rows.rows());
2272 base_covariance, unit_geodesic_covariance, targets);
2273 } else {
2275 base_covariance, unit_geodesic_features, targets);
2276 }
2277 if (report_level >= 2) {
2278 std::fprintf(stderr,
2279 "[GPR_TRACE_GEODESIC] rows=%lld path=%lld weight=%.17g "
2280 "mean=%.17g scale=%.17g\n",
2281 static_cast<long long>(training_data.R.rows()),
2282 static_cast<long long>(reference_path.rows()), weight,
2283 y_mean_, y_scale_);
2284 }
2285
2286 if (weight > 0.0) {
2288 std::make_shared<const GeodesicHeatEnergyForceKernel>(
2289 unit_geodesic.withCovarianceWeight(weight)));
2290 }
2291 updateModelWithFullData(training_data);
2292 return weight;
2293}
2294
2295std::optional<double>
2297 const geometry::InternalCoordinateChart& chart) const
2298{
2299 if (!sexpat_cov_func || !chart.valid() ||
2300 sexpat_cov_func->getLengthScaleRef().size() <= 0) {
2301 return std::nullopt;
2302 }
2303 // Allocated unit lengths reserve parameter slots. A data-derived seed or
2304 // a fitted background supplies the physical metric for a local chart.
2305 if (!(seed_length_scale_ > 0.0) && !has_been_optimized_ &&
2306 full_fit_observations_.R.rows() == 0) {
2307 return std::nullopt;
2308 }
2309 const Eigen::Index dimensions = chart.anchor().size();
2310 const Eigen::Index rank = chart.rank();
2311 if (dimensions <= 0 || rank <= 0 ||
2312 chart.tangentBasis().rows() != dimensions) {
2313 return std::nullopt;
2314 }
2315
2316 EigenMatrix positions(1, dimensions);
2317 positions.row(0) = chart.anchor().transpose();
2318 // The chart length belongs to the base component. An independently
2319 // weighted heat covariance cannot change its force-variance match.
2320 EigenMatrix prior;
2321 if (sexpat_cov_func->usesManifoldChart())
2322 prior =
2323 sexpat_cov_func->manifoldJointEnergyGradientCovariance(positions);
2324 else
2325 prior =
2326 Sexpat(*sexpat_cov_func).jointEnergyGradientCovariance(positions);
2327 if (prior.rows() != dimensions + 1 || prior.cols() != dimensions + 1 ||
2328 !prior.allFinite()) {
2329 return std::nullopt;
2330 }
2331
2332 const EigenMatrix force_covariance =
2333 prior.block(1, 1, dimensions, dimensions);
2334 const EigenMatrix tangent_covariance = chart.tangentBasis().transpose() *
2335 force_covariance *
2336 chart.tangentBasis();
2337 const double tangent_trace = tangent_covariance.trace();
2338 const double signal_variance = sexpat_cov_func->getMagnSigma2();
2339 if (!(tangent_trace > 0.0) || !std::isfinite(tangent_trace) ||
2340 !(signal_variance > 0.0) || !std::isfinite(signal_variance)) {
2341 return std::nullopt;
2342 }
2343 const double length_squared =
2344 signal_variance * static_cast<double>(rank) / tangent_trace;
2345 if (!(length_squared > 0.0) || !std::isfinite(length_squared)) {
2346 return std::nullopt;
2347 }
2348 return std::sqrt(length_squared);
2349}
2350
2352 const Eigen::VectorXd& w, const EigenMatrix& x,
2353 const Eigen::VectorXd& x_ind, const Eigen::VectorXd& y)
2354{
2355 if (!detail::logParametersAreRepresentable(w)) {
2356 return std::numeric_limits<double>::infinity();
2357 }
2358 setParameters(w);
2359
2360 const Eigen::Index n = x.rows();
2361 if (n <= 0 || y.rows() != n) {
2362 return std::numeric_limits<double>::quiet_NaN();
2363 }
2364
2365 EigenMatrix C_local;
2366 evaluateTrainingCovarianceMatrix(x, x_ind, C_local,
2367 /*serial_per_rank=*/true);
2368 if (jitter_sigma2 > 0.0) C_local.diagonal().array() += jitter_sigma2;
2369
2370 Eigen::LLT<EigenMatrix> llt(C_local);
2371 if (llt.info() != Eigen::Success) {
2372 return std::numeric_limits<double>::quiet_NaN();
2373 }
2374
2375 const auto& matrix_llt = llt.matrixLLT();
2376 const auto lower = matrix_llt.template triangularView<Eigen::Lower>();
2377 const Eigen::VectorXd b_local = lower.solve(y);
2378 const double y_dot_alpha = b_local.squaredNorm();
2379 const double log_det = 2.0 * matrix_llt.diagonal().array().log().sum();
2380
2381 const double e_data =
2382 0.5 * (static_cast<double>(n) * numerics::log(2.0 * M_PI) + log_det +
2383 y_dot_alpha);
2384 double e_prior = 0.0;
2385 if (const_cov_fun) e_prior -= const_cov_fun->calculateLogPrior();
2386 if (sexpat_cov_func) e_prior -= sexpat_cov_func->calculateLogPrior();
2387 if (lik_gaussian) e_prior -= lik_gaussian->evaluateLogPrior();
2388
2389 const double energy = e_data + e_prior;
2390 return std::isfinite(energy) ? energy
2391 : std::numeric_limits<double>::quiet_NaN();
2392}
2393
2394} /* namespace gpr */
Linear algebra abstraction layer for GPR hot-path operations.
Full Bayesian posterior marginal GP/TP (FBPMGP).
Runtime-dlopen'd cuSOLVER dense symmetric eigensolver (syevd).
Optional CUTLASS GEMM facade for rank-local dense products.
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
@ SCG_opt
Definition Enums.h:30
@ INLA_opt
Definition Enums.h:30
Eigendecomposition-based log marginal likelihood evaluation.
Preconditioned conjugate gradient (PCG) solver for symmetric positive-definite systems....
Abstract operator interface for K^{-1} actions used by Laplace Hessian probe loops and Williams-Rasmu...
INLA-style Laplace approximation of the GP/TP hyperparameter posterior.
Tiny value type describing the MPI dispatch context for a probe loop.
Exponential grid search for noise hyperparameter optimization.
MPI-aware dispatcher for the Hutchinson-style probe loop used by the Laplace Hessian assembler and th...
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.
Wrapper for the Ceres Solver for robust nonlinear optimization.
Definition Ceres.h:22
void setMethod(rgmin::Method m) noexcept
Definition RgminOpt.h:49
void tieLengthScaleParameters(Eigen::VectorXd &theta) const
Sets every tied member to its leader's log length (theta(1 + t)).
linalg::BackendContext & backend() const
void setObjectiveStationaritySkipAuto(bool use) noexcept
virtual void calculateVariance(Observation &image1)
Compute predictive variance for energy and gradient. Corresponds to MATLAB get_variance....
Definition Variance.cpp:353
LengthScaleFitState lengthScaleFitState() const
Eigen::VectorXd permuteTrainingVector(const Eigen::VectorXd &input) const
void calculateVarianceLaplace(Observation &image1)
std::size_t getDispatchedMapMeanHessianActionsForTesting() const noexcept
Count of exact MAP Hessian actions built by dispatch.
void addLayeredPriorHessianAction(const Eigen::VectorXd &position, const Eigen::VectorXd &direction, Eigen::VectorXd &action) const
H_prior(x) v + H_q v, with either term absent when that mean is off.
LikelihoodNoiseVarianceUpdate setLikelihoodNoiseVariance(double physical_sigma2, const Observation *full_observation=nullptr)
Set the likelihood noise variance in physical output units.
void poolDescriptorScaleByTies(Eigen::VectorXd &scales) const
void prepareTrainingPermutationLocal(const Eigen::VectorXd &x_ind)
void calculateVarianceBMA(Observation &image1)
Definition BMA.cpp:133
void calculateVarianceRFF(Observation &image)
Definition RFF.cpp:70
void setGeodesicHeatPrior(std::shared_ptr< const GeodesicHeatEnergyForceKernel > kernel)
bool installActivePosteriorHessianActionsForTesting(MeanHessianPreparation background, bool background_exact, MeanHessianPreparation residual, bool residual_exact)
Replace the active posterior's Hessian actions for one test.
void setParameters(const GPRSetup &parameters)
Set parameters of the GPR model.
Eigen::VectorXd unpermuteTrainingVector(const Eigen::VectorXd &input) const
void calculateVarianceSVGD(Observation &image1)
Definition SVGD.cpp:167
void buildRFFModel(const Observation &training_data, int D_rff)
Definition RFF.cpp:17
void setSecantQuadraticPrior(const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, const Eigen::MatrixXd &hessian, double reference_energy)
void setHyperparameterObjectiveMode(HyperparameterObjectiveMode mode) noexcept
const Eigen::MatrixXd & secantQuadraticHessian() const
detail::RigidDeflationState rigid_deflation_
void setFitStepStop(bool use) noexcept
Whether the auto stationarity mode also ends each fit at its scale.
EigenMatrix permuteTrainingRows(const EigenMatrix &input) const
void setInternalCoordinateChart(std::shared_ptr< const geometry::InternalCoordinateChart > chart, double length_scale)
void setHssvdLocalPosteriorActiveSetSize(int size) noexcept
void calculateVarianceDispatched(Observation &image1)
bool hasPendingResidualModelRefit() const noexcept
void synchronizeOutputTransformFrom(const GaussianProcessRegression &source)
static bool computePairtypeDescriptorScale(const Coord &R, const AtomsConfiguration &conf_info, Eigen::VectorXd &ls_k)
Per-pairtype motion scale rho0_k = sqrt(sum_f var(1/r_f)). Each pair feature is centered across confi...
bool currentThetaIncludesLikelihoodNoise() const noexcept
SecantQuadraticPriorState retainSecantQuadraticPrior() const
std::function< MeanHessianAction(const Eigen::VectorXd &)> MeanHessianPreparation
EigenMatrix rowsInTrainingFactorLayout(const EigenMatrix &input) const
bool hasPendingActivePosteriorRefit() const noexcept
void evaluatePriorMeanTargets(const Eigen::VectorXd &positions, double &energy, Eigen::VectorXd &gradient) const
Prior-mean targets for a virtual (conditioning-only) observation at ~positions~.
void calculateVarianceLaplaceSlice(Observation &image1)
void calculateVarianceHssvd(Observation &image1)
void refreshLengthScaleLeaders()
Recomputes the leaders from the released flags.
double reportedVarianceCalibrationFactor() const noexcept
void resetDispatchedMapMeanHessianActionsForTesting() const noexcept
Reset the count of exact MAP Hessian actions built by dispatch.
void reduceTiedLengthScaleGradient(Eigen::VectorXd &gradient) const
double fitGeodesicHeatPrior(const Coord &reference_path, const Observation &training_data)
std::unique_ptr< SexpatCF > sexpat_cov_func
void setDisableOutputNormalization(bool d) noexcept
void setRigidNullDeflation(bool enabled)
Opt-in rigid-motion nullspace deflation for free systems.
void setHierarchicalPrior(const Eigen::VectorXd &mu_log, double s2_log)
void setHssvdHessianBlockApplyFailsForTesting(bool fail) const noexcept
Make the dense HS-SVD block apply fail for one test.
void setModelProfile(GPModelProfile profile)
void setHyperparameterOptimizationMode(HyperparameterOptimizationMode mode) noexcept
void initialize(const InputParameters &parameters, const AtomsConfiguration &conf_info)
Initialize GPR class.
void prepareTrainingPermutation(const Eigen::VectorXd &x_ind)
void setRgminMethod(rgmin_method_t m) noexcept
void setMapMeanKernelForTesting(std::shared_ptr< const KernelOperator > kernel)
Install the kernel used as the MAP mean expansion.
void setConditionedHessian(const Eigen::VectorXd &point, const Eigen::MatrixXd &hessian)
RigidDeflationDiagnostic rigid_deflation_diag_
void updateModelWithFullData(const Observation &full_observation)
EigenMatrix symmetricMatrixInTrainingFactorLayout(const EigenMatrix &input) const
void forgetRgminSessions() noexcept
void updateConfiguration(const AtomsConfiguration &conf_info)
Update the internal atoms configuration. Use this when the set of active/frozen atoms changes dynamic...
std::optional< double > inferInternalCoordinateLengthScale(const geometry::InternalCoordinateChart &chart) const
const char * getHyperparameterOptimizerBackend() const noexcept
double evaluateEnergyLocalOnly(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
void applyPopulationPrior(const AtomsConfiguration &conf_info, const Eigen::VectorXd &ls_k, double own_s2_log)
void restoreOutputTransform(double mean, double scale, bool frozen_mean)
Restore output coordinates alongside a kernel represented in them.
void setHyperparameters(const Observation &all_obs, const AtomsConfiguration &conf_info, const bool update_sexpat_cf_param=true, const bool update_const_cf_param=true, const bool update_sqrt_prior_param=true)
Set up hyperparameters for GPR.
void setHssvdLocalActiveSetSize(int size) noexcept
bool applyLikelihoodNoiseVarianceFloor(double floor_sigma2, const Observation &full_observation)
Raise the Gaussian likelihood noise variance to a floor.
bool findConditionedHessian(const Eigen::VectorXd &point, Eigen::MatrixXd &hessian_out) const
void restoreSecantQuadraticPrior(const SecantQuadraticPriorState &state)
void configureLengthScaleTies(const AtomsConfiguration &configuration)
bool samplePhysicalPriorMean(const Eigen::VectorXd &position, double &energy, Eigen::VectorXd &gradient) const
void evaluateTrainingCovarianceMatrix(const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool serial_per_rank=false, bool include_constant=true, bool include_noise=true)
Evaluate training covariance matrix (gp_cov + noise covariance).
void restoreLengthScaleFitState(const LengthScaleFitState &state)
void setMapMeanKernelOverridesHssvdForTesting(bool override) noexcept
Make an installed MAP test kernel take precedence over HS-SVD.
static double selectWeightFromFeatures(const Eigen::MatrixXd &base_covariance, const Eigen::MatrixXd &unit_geodesic_features, const Eigen::VectorXd &standardized_targets)
static double selectWeight(const Eigen::MatrixXd &base_covariance, const Eigen::MatrixXd &unit_geodesic_covariance, const Eigen::VectorXd &standardized_targets)
GeodesicHeatEnergyForceKernel withCovarianceWeight(double weight) const
Eigen::MatrixXd jointEnergyGradientFeatures(const Coord &positions) const
static bool pairtypeMotionScales(const Coord &positions, const AtomsConfiguration &configuration, Eigen::VectorXd &scales)
static void compute(const Coord &x, const AtomsConfiguration &conf_info, Eigen::VectorXd &phi)
Compute phi(x) for a single configuration.
virtual Eigen::MatrixXd jointEnergyGradientCovariance(const Eigen::MatrixXd &positions) const
Joint covariance in Observation order [E; G_col0; ...; G_colD-1].
Class of prior parameters.
Definition PriorBase.h:23
void setMu(const double value)
Definition PriorBase.h:63
void setS2(const double value)
Definition PriorBase.h:68
void setNu(const double value)
Definition PriorBase.h:73
Random Fourier Features (RFF) approximation to the SE kernel.
Definition RFFModel.h:51
const Eigen::VectorXd & anchor() const noexcept override
Eigen::Index rank() const noexcept override
const Eigen::MatrixXd & tangentBasis() const noexcept override
static void setVerbose(bool verbose) noexcept
Eigen::VectorXd lengthScalePerPairtype() const
bool cellIsZero(const double cell[9]) noexcept
Isolated molecule: every entry of the ASE-style 3x3 cell is zero.
Definition MinImage.h:22
void zeroOpenAxes(double cell[9], const std::array< bool, 3 > &periodic) noexcept
Definition MinImage.h:136
bool copyMicLattice(double dest[9], const double src[9]) noexcept
Copy src onto dest only when src is a MIC lattice.
Definition MinImage.h:68
void setPluginPath(std::string path)
Definition CutlassGemm.h:48
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
double dense_factor_inverse_trace(const EigenMatrix &L)
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40
double log(double x) noexcept
double exp(double x) noexcept
Eigen::MatrixXd applyPriorHessianPairs(const std::vector< PriorHessianPair > &pairs, const Eigen::MatrixBase< Derived > &directions)
Apply physical prior curvature without forming a dense Hessian.
double variance(const Weights &w, const Matrix &covariance)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
void requirePositiveFinitePriorParameter(const char *density, const char *name, double value)
Definition PriorScale.h:17
Eigen::VectorXd permuteVector(const Eigen::VectorXd &input, const StructuredPermutation &p)
Eigen::VectorXd unpermuteVector(const Eigen::VectorXd &input, const StructuredPermutation &p)
FieldMatrixd Coord
Definition Macros.h:35
bool usesClassicJointEnergyForcePrior(GPModelProfile profile) noexcept
Definition Structures.h:206
uint32_t Index_t
Definition Macros.h:17
EigenMatrix permuteMatrixRows(const EigenMatrix &input, const StructuredPermutation &p)
EigenMatrix permuteSymmetricMatrix(const EigenMatrix &input, const StructuredPermutation &p)
StructuredPermutation buildObservationTiledPermutation(const Eigen::VectorXd &ind_Ddim)
GPModelProfile
Definition Structures.h:201
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
HyperparameterOptimizationMode
Definition Enums.h:56
STL namespace.
Stores configurations of all atoms in the system.
Definition Structures.h:832
std::vector< Index_t > pair_type_parent
Definition Structures.h:854
Index_t n_base_pt
Number of base pair types (0: none).
Definition Structures.h:855
std::vector< Index_t > parent
fine pair type -> base pair type
Structure of the input parameters. All input parameters are pairs of string names and values.
Definition Structures.h:370
KeyValuePair< bool > log_rank_block_cholesky
Definition Structures.h:635
KeyValuePair< double > prior_s2
Definition Structures.h:650
KeyValuePair< double > laplace_skip_scg_threshold
Definition Structures.h:623
KeyValuePair< int > max_iter
Definition Structures.h:674
KeyValuePair< bool > use_rigid_null_deflation
Definition Structures.h:627
KeyValuePair< std::string > optimization_alg
Definition Structures.h:614
KeyValuePair< double[9]> cell_dimensions
Definition Structures.h:605
KeyValuePair< double > lambda
Definition Structures.h:678
KeyValuePair< int > fps_history
Definition Structures.h:665
KeyValuePair< double > prior_nu
Definition Structures.h:649
KeyValuePair< int > report_level
Definition Structures.h:673
KeyValuePair< int > scalapack_nprow
Definition Structures.h:638
KeyValuePair< double > jitter_sigma2
Definition Structures.h:613
KeyValuePair< int > scalapack_block_size
Definition Structures.h:637
KeyValuePair< int > gp_nonperiodic
Definition Structures.h:603
KeyValuePair< DistanceMetricType > fps_metric
Definition Structures.h:663
KeyValuePair< bool > use_training_geometry_handle
Definition Structures.h:625
KeyValuePair< bool > profile_gradient_split
Definition Structures.h:631
KeyValuePair< double > actdist_fro
Definition Structures.h:379
KeyValuePair< double > constSigma2
Definition Structures.h:618
KeyValuePair< double > lambda_limit
Definition Structures.h:677
KeyValuePair< double > tolerance_func
Definition Structures.h:675
KeyValuePair< bool > use_precision
Definition Structures.h:566
KeyValuePair< std::string > check_derivative
Definition Structures.h:672
KeyValuePair< std::string > cutlass_plugin_path
Definition Structures.h:639
KeyValuePair< bool > profile_energy_split
Definition Structures.h:630
KeyValuePair< bool > log_training_geometry
Definition Structures.h:634
KeyValuePair< bool > use_alpha_k_laplace_mean
Definition Structures.h:621
KeyValuePair< bool > use_alpha_k_predict_mean
Definition Structures.h:619
KeyValuePair< double > tolerance_sol
Definition Structures.h:676
KeyValuePair< double > prior_mu
Definition Structures.h:648
KeyValuePair< double > sigma2
Definition Structures.h:616
KeyValuePair< std::string > curvature_mode
Definition Structures.h:679
KeyValuePair< bool > profile_predict_mean
Definition Structures.h:629
KeyValuePair< double > magnSigma2
Definition Structures.h:617
KeyValuePair< double > gp_sigma2
Definition Structures.h:612
Observation data: energy, gradient and positions.
FieldMatrixd E
static double setup_seconds